/* ============================================================
   CREW LOGISTICS — rates, deal memos & call times
   The money + paperwork layer under the Crew Directory: per-person
   day rate × days = cost, deal-memo status, and a default call time.
   Rolls up total crew cost and memo completion. This is the data the
   Budget can later pull crew lines from. Persisted per project.
   ============================================================ */

const CREWLOG_KEY = 'silverlines.crewlog.' + (window.PROJ_ID || 'crimson') + '.v1';

const MEMO = {
  none:   { label:'Not sent', tone:'neutral',  icon:'FileX' },
  sent:   { label:'Sent',     tone:'amber',    icon:'Send' },
  signed: { label:'Signed',   tone:'mint',     icon:'FileCheck' },
};
const MEMO_ORDER = ['none', 'sent', 'signed'];

const CREWLOG_SEED = [
  { dept:'Camera', color:'#5FB0E8', people:[
    { id:'c1', name:'Dahlia Mercer', role:'Director / DP', rate:1100, days:4, memo:'signed', call:'06:30', agency:'Frame & Field' },
    { id:'c2', name:'Theo Vance',    role:'1st AC',        rate:520,  days:4, memo:'signed', call:'06:30', agency:'—' },
    { id:'c3', name:'Mara Lindqvist',role:'2nd AC',        rate:420,  days:4, memo:'sent',   call:'06:30', agency:'—' },
    { id:'c4', name:'Sven Okafor',   role:'DIT',           rate:560,  days:4, memo:'none',   call:'06:00', agency:'—' },
  ]},
  { dept:'Lighting & Grip', color:'#F5A742', people:[
    { id:'g1', name:'Rafael Mendes', role:'Gaffer',     rate:620, days:4, memo:'signed', call:'06:00', agency:'—' },
    { id:'g2', name:'Iris Caldwell', role:'Key Grip',   rate:600, days:4, memo:'sent',   call:'06:00', agency:'—' },
    { id:'g3', name:'Joon Park',     role:'Best Boy',   rate:440, days:4, memo:'none',   call:'06:00', agency:'—' },
  ]},
  { dept:'Sound', color:'#9B8BE8', people:[
    { id:'s1', name:'Nadia Brooks',  role:'Production Sound', rate:680, days:3, memo:'signed', call:'07:00', agency:'Clearwave' },
  ]},
  { dept:'Art Department', color:'#22D48A', people:[
    { id:'a1', name:'Lucia Romano',  role:'Production Designer', rate:750, days:4, memo:'signed', call:'05:30', agency:'—' },
    { id:'a2', name:'Felix Andersen',role:'Art Director',        rate:520, days:4, memo:'sent',   call:'05:30', agency:'—' },
    { id:'a3', name:'Priya Nair',    role:'Props Master',        rate:460, days:4, memo:'none',   call:'05:30', agency:'—' },
  ]},
  { dept:'Production', color:'#FF6FA5', people:[
    { id:'p1', name:'Noor Haddad',   role:'Producer',     rate:900, days:4, memo:'signed', call:'05:30', agency:'—' },
    { id:'p2', name:'Marcus Hale',   role:'1st AD',       rate:720, days:4, memo:'signed', call:'05:30', agency:'—' },
    { id:'p3', name:'Elena Sokolova',role:'Production Coord', rate:480, days:4, memo:'sent', call:'05:30', agency:'—' },
  ]},
];

function crewlogLoad() {
  const s = window.SLStore.get(CREWLOG_KEY); if (Array.isArray(s) && s.length) return s;
  return window.PROJ_BLANK ? [] : CREWLOG_SEED;
}

const clCost = p => (+p.rate || 0) * (+p.days || 0);
const deptCost = d => d.people.reduce((a, p) => a + clCost(p), 0);

function CrewLogNum({ value, prefix = '', suffix = '', onChange, className = '' }) {
  return (
    <span className={className}>
      {prefix}<Edit value={value ? String(value) : ''} placeholder="0" className={className}
        onChange={v => { const n = parseFloat(String(v).replace(/[^0-9.]/g, '')); onChange(isNaN(n) ? 0 : n); }} />{suffix}
    </span>
  );
}

function CrewLogRow({ p, color, onPatch, onCycle, onRemove, readOnly }) {
  const m = MEMO[p.memo] || MEMO.none;
  return (
    <div className="group/cl flex items-center gap-3 border-t border-line/70 px-3.5 py-2.5 hover:bg-ink-800">
      <Avatar name={p.name} color={color} size={34} />
      <div className="min-w-0 flex-1">
        <div className="truncate text-[13px] font-600 text-zinc-100"><Edit value={p.name} onChange={v => onPatch({ name: v })} className="text-[13px] font-600" /></div>
        <div className="flex items-center gap-1.5 text-[11px] text-zinc-500">
          <Edit value={p.role} onChange={v => onPatch({ role: v })} className="text-[11px]" />
          {p.agency && p.agency !== '—' && <><span className="text-zinc-700">·</span><span>{p.agency}</span></>}
        </div>
      </div>
      {/* call time */}
      <div className="hidden w-[68px] shrink-0 text-center sm:block">
        <div className="text-[9px] uppercase tracking-[0.1em] text-zinc-600">Call</div>
        <div className="font-mono text-[12px] font-600 text-zinc-200"><Edit value={p.call} onChange={v => onPatch({ call: v })} align="center" className="font-mono text-[12px]" /></div>
      </div>
      {/* rate × days */}
      <div className="hidden shrink-0 items-center gap-1 font-mono text-[11.5px] text-zinc-500 sm:flex">
        <CrewLogNum value={p.rate} prefix={(CURRENCIES[curCode()] || CURRENCIES.USD).sym} onChange={v => onPatch({ rate: v })} className="text-zinc-300" /> ×
        <CrewLogNum value={p.days} suffix="d" onChange={v => onPatch({ days: v })} className="text-zinc-300" />
      </div>
      {/* cost */}
      <div className="w-[88px] shrink-0 text-right font-display text-[14px] font-700 text-head">{money(clCost(p))}</div>
      {/* deal memo */}
      <button onClick={() => !readOnly && onCycle()} disabled={readOnly} title="Cycle deal-memo status" className="w-[88px] shrink-0">
        <Chip tone={m.tone}><Icon name={m.icon} size={11} />{m.label}</Chip>
      </button>
      {!readOnly && (
        <button onClick={onRemove} title="Remove from crew"
          className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-zinc-700 opacity-0 transition-all hover:bg-[#FF4D6D]/12 hover:text-[#FF4D6D] group-hover/cl:opacity-100"><Icon name="UserMinus" size={13} /></button>
      )}
    </div>
  );
}

function CrewLogModule({ mobile, readOnly = false }) {
  const [depts, setDeptsState] = useState(crewlogLoad);
  const [pick, setPick] = useState(false);
  const [pq, setPq] = useState('');
  const setDepts = next => setDeptsState(prev => {
    const v = typeof next === 'function' ? next(prev) : next;
    window.SLStore.set(CREWLOG_KEY, v);
    return v;
  });
  /* pull a person from the workspace directory — prefilled with their per-production
     post (from assignmeta) + rate/agency, linked back by personId. */
  const DEPT_COLORS = ['#5FB0E8', '#F5A742', '#9B8BE8', '#22D48A', '#FF6FA5', '#BD2555', '#7CC4A0'];
  const addFromDirectory = person => {
    const code = (window.PROJECT && window.PROJECT.code) || '';
    const meta = ((window.SLStore.get('silverlines.assignmeta.v1', {}) || {})[code] || {})[person.id] || {};
    const rate = parseFloat(String(meta.rate || person.rate || '').replace(/[^0-9.]/g, '')) || 0;
    const deptName = person.dept || 'Crew';
    const rec = { id: 'dir-' + person.id + '-' + Date.now(), personId: person.id, name: person.name, role: meta.post || person.role, rate, days: 4, memo: 'none', call: '06:00', agency: person.agency || '—' };
    setDepts(ds => {
      const di = ds.findIndex(d => (d.dept || '').toLowerCase() === deptName.toLowerCase());
      if (di >= 0) return ds.map((d, i) => i !== di ? d : { ...d, people: [...d.people, rec] });
      return [...ds, { dept: deptName, color: DEPT_COLORS[ds.length % DEPT_COLORS.length], people: [rec] }];
    });
    window.toast(`${person.name} added to Crew Logistics${meta.post ? ' as ' + meta.post : ''}`, 'UserPlus');
  };
  const dirPeople = (() => {
    try {
      const inLog = new Set(depts.flatMap(d => d.people).map(p => (p.personId || '') + '|' + (p.name || '').toLowerCase()));
      const all = (typeof readPeopleDB === 'function' ? readPeopleDB() : (window.SLStore.get('silverlines.people.v1', []) || []));
      const ql = pq.trim().toLowerCase();
      return all.filter(p => !inLog.has((p.id || '') + '|' + (p.name || '').toLowerCase()) && !inLog.has('|' + (p.name || '').toLowerCase()))
        .filter(p => !ql || (p.name + ' ' + p.role + ' ' + p.dept).toLowerCase().includes(ql));
    } catch (e) { return []; }
  })();

  const all = depts.flatMap(d => d.people);
  const totalCost = all.reduce((a, p) => a + clCost(p), 0);
  const signed = all.filter(p => p.memo === 'signed').length;
  const sent = all.filter(p => p.memo === 'sent').length;
  const memoPct = all.length ? Math.round((signed / all.length) * 100) : 0;

  const patch = (di, id, p) => setDepts(ds => ds.map((d, i) => i !== di ? d : { ...d, people: d.people.map(x => x.id === id ? { ...x, ...p } : x) }));
  const cycle = (di, id) => setDepts(ds => ds.map((d, i) => i !== di ? d : { ...d, people: d.people.map(x => x.id !== id ? x : { ...x, memo: MEMO_ORDER[(MEMO_ORDER.indexOf(x.memo) + 1) % 3] }) }));
  const remove = (di, id) => setDepts(ds => ds.map((d, i) => i !== di ? d : { ...d, people: d.people.filter(x => x.id !== id) }));
  const add = di => setDepts(ds => ds.map((d, i) => i !== di ? d : { ...d, people: [...d.people, { id:'n' + Date.now(), name:'New crew', role:'Role', rate:0, days:4, memo:'none', call:'06:00', agency:'—' }] }));

  return (
    <div className="fade-up">
      {!readOnly && <SectionTitle kicker="Crew & departments · Logistics" icon="ReceiptText" title="Crew Logistics"
        action={<button onClick={() => setPick(p => !p)} className="flex items-center gap-2 rounded-xl border border-line bg-ink-900 px-3.5 py-2.5 text-[12.5px] font-700 text-zinc-200 transition-colors hover:border-electric/50 hover:text-electric-soft"><Icon name="BookUser" size={15} /> From directory</button>} />}

      {pick && !readOnly && (
        <Panel className="mb-5">
          <div className="mb-2 flex items-center gap-2">
            <Icon name="Search" size={14} className="shrink-0 text-zinc-500" />
            <input autoFocus value={pq} onChange={e => setPq(e.target.value)} placeholder="Search the crew directory…"
              className="min-w-0 flex-1 bg-transparent text-[12.5px] text-zinc-200 outline-none placeholder:text-zinc-600" />
            <button onClick={() => setPick(false)} className="text-zinc-500 hover:text-zinc-300"><Icon name="X" size={15} /></button>
          </div>
          <div className="max-h-[280px] space-y-1 overflow-y-auto">
            {dirPeople.length === 0 && <div className="px-2 py-4 text-center text-[12px] text-zinc-500">Everyone's already here — or the directory is empty.</div>}
            {dirPeople.map(person => (
              <button key={person.id} onClick={() => addFromDirectory(person)}
                className="flex w-full items-center gap-3 rounded-lg border border-line bg-ink-900 px-3 py-2 text-left transition-colors hover:border-electric/50">
                <Avatar name={person.name} color={person.color} size={30} />
                <div className="min-w-0 flex-1">
                  <div className="truncate text-[12.5px] font-600 text-zinc-100">{person.name}</div>
                  <div className="truncate text-[11px] text-zinc-500">{person.role} · {person.dept}</div>
                </div>
                <Icon name="Plus" size={14} className="shrink-0 text-electric-soft" />
              </button>
            ))}
          </div>
        </Panel>
      )}

      {/* rollup */}
      <Panel className="mb-5">
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
          <div>
            <div className="text-[11px] uppercase tracking-[0.12em] text-zinc-500">Crew cost</div>
            <div className="font-display text-[30px] font-700 leading-none text-head">{money(totalCost)}</div>
            <div className="mt-1 text-[11px] text-zinc-500">{all.length} people · {depts.length} depts</div>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-[0.12em] text-zinc-500">Deal memos signed</div>
            <div className="font-display text-[30px] font-700 leading-none text-mint">{signed}<span className="text-[16px] text-zinc-600">/{all.length}</span></div>
            <div className="mt-1 text-[11px] text-zinc-500">{sent} awaiting signature</div>
          </div>
          <div className="col-span-2">
            <div className="mb-1 flex items-center justify-between text-[11px] text-zinc-500"><span>Paperwork completion</span><span className="font-mono">{memoPct}%</span></div>
            <div className="h-2.5 overflow-hidden rounded-full bg-ink-700">
              <div className="h-full rounded-full bg-mint transition-all" style={{ width: memoPct + '%' }} />
            </div>
            {sent > 0 && <div className="mt-2 flex items-center gap-1.5 text-[11.5px] text-amber"><Icon name="Clock" size={12} />{sent} memo{sent > 1 ? 's' : ''} sent, waiting on signatures</div>}
          </div>
        </div>
      </Panel>

      {/* department tables */}
      <div className="space-y-4">
        {depts.length === 0 ? <EmptyState icon="ReceiptText" title="No crew yet" sub="Add crew and departments to track rates, deal memos and call times." /> : depts.map((d, di) => (
          <Panel key={d.dept} pad={false} className="overflow-hidden">
            <div className="flex items-center justify-between gap-3 border-b border-line p-3.5">
              <div className="flex items-center gap-2.5">
                <span className="flex h-8 w-8 items-center justify-center rounded-lg" style={{ background: d.color + '1f', color: d.color }}><Icon name="Users" size={16} /></span>
                <div>
                  <div className="text-[13.5px] font-700 text-zinc-100">{d.dept}</div>
                  <div className="text-[11px] text-zinc-500">{d.people.length} {d.people.length === 1 ? 'person' : 'people'}</div>
                </div>
              </div>
              <div className="text-right">
                <div className="text-[10px] uppercase tracking-[0.1em] text-zinc-500">Dept cost</div>
                <div className="font-display text-[20px] font-700 leading-none text-head">{money(deptCost(d))}</div>
              </div>
            </div>
            {d.people.map(p => (
              <CrewLogRow key={p.id} p={p} color={d.color} readOnly={readOnly}
                onPatch={x => patch(di, p.id, x)} onCycle={() => cycle(di, p.id)} onRemove={() => remove(di, p.id)} />
            ))}
            {!readOnly && (
              <button onClick={() => add(di)}
                className="flex w-full items-center justify-center gap-2 border-t border-line py-2.5 text-[12.5px] font-600 text-zinc-500 transition-colors hover:bg-ink-800 hover:text-electric-soft">
                <Icon name="UserPlus" size={14} /> Add crew to {d.dept}
              </button>
            )}
          </Panel>
        ))}
      </div>
    </div>
  );
}

window.CrewLogModule = CrewLogModule;
