/* ============================================================
   POST VERSIONS — cut stack & deliverables tracking
   Two layers: a version stack of cuts moving through review →
   approval, and a deliverables tracker (spec, format, due, status).
   Rolls up latest approved cut + deliverables shipped. Persisted.
   ============================================================ */

const POSTVER_KEY = 'silverlines.postver.' + (window.PROJ_ID || 'crimson') + '.v1';

const CUT_STATUS = {
  wip:      { label:'In progress',   tone:'neutral',  icon:'Loader' },
  internal: { label:'Internal review', tone:'electric', icon:'Eye' },
  client:   { label:'Client review', tone:'amber',    icon:'Send' },
  approved: { label:'Approved',      tone:'mint',     icon:'CircleCheck' },
};
const CUT_ORDER = ['wip', 'internal', 'client', 'approved'];
const DEL_STATUS = {
  pending:   { label:'Pending',   tone:'neutral', icon:'Circle' },
  inprog:    { label:'In post',   tone:'electric', icon:'Loader' },
  review:    { label:'In review', tone:'amber',   icon:'Eye' },
  delivered: { label:'Delivered', tone:'mint',    icon:'PackageCheck' },
};
const DEL_ORDER = ['pending', 'inprog', 'review', 'delivered'];

const POSTVER_SEED = {
  cuts: [
    { id:'c1', name:'v1 — Assembly',   dur:'1:42', status:'approved', by:'D. Mercer', date:'Jun 28', note:'Full assembly, no grade.' },
    { id:'c2', name:'v2 — Rough cut',  dur:'1:08', status:'approved', by:'D. Mercer', date:'Jul 02', note:'Story locked, temp music.' },
    { id:'c3', name:'v3 — Fine cut',   dur:'0:62', status:'client',   by:'D. Mercer', date:'Jul 06', note:'Sent to Aether for notes.' },
    { id:'c4', name:'v4 — Grade pass', dur:'0:60', status:'wip',      by:'Colorist',  date:'Jul 09', note:'Crimson grade in progress.' },
  ],
  dels: [
    { id:'d1', name:'Hero film',       fmt:':60 · 16:9 · ProRes', due:'Jul 12', status:'review' },
    { id:'d2', name:'Cutdown',         fmt:':30 · 16:9 · ProRes', due:'Jul 14', status:'inprog' },
    { id:'d3', name:'Social verticals',fmt:':15 ×6 · 9:16 · H.264', due:'Jul 16', status:'pending' },
    { id:'d4', name:'Stills package',  fmt:'12 frames · 4:5 · TIFF', due:'Jul 12', status:'delivered' },
  ],
};

function postverLoad() {
  const s = window.SLStore.get(POSTVER_KEY); if (s && Array.isArray(s.cuts)) return s;
  return window.PROJ_BLANK ? { cuts: [], dels: [] } : POSTVER_SEED;
}

function PostVersionModule({ mobile, readOnly = false }) {
  const [doc, setDocState] = useState(postverLoad);
  const setDoc = next => setDocState(prev => {
    const v = typeof next === 'function' ? next(prev) : next;
    window.SLStore.set(POSTVER_KEY, v);
    return v;
  });

  const approved = doc.cuts.filter(c => c.status === 'approved');
  const latest = doc.cuts[doc.cuts.length - 1];
  const delivered = doc.dels.filter(d => d.status === 'delivered').length;

  const cutPatch = (id, p) => setDoc(d => ({ ...d, cuts: d.cuts.map(c => c.id === id ? { ...c, ...p } : c) }));
  const cutCycle = id => setDoc(d => ({ ...d, cuts: d.cuts.map(c => c.id !== id ? c : { ...c, status: CUT_ORDER[(CUT_ORDER.indexOf(c.status) + 1) % CUT_ORDER.length] }) }));
  const cutRemove = id => {
    const prev = doc; const cut = doc.cuts.find(c => c.id === id) || {};
    setDoc(d => ({ ...d, cuts: d.cuts.filter(c => c.id !== id) }));
    window.pushUndo && window.pushUndo(`Removed "${cut.name || 'cut'}"`, () => setDoc(prev));
  };
  const cutAdd = () => setDoc(d => ({ ...d, cuts: [...d.cuts, { id:'c' + Date.now(), name:'v' + (d.cuts.length + 1) + ' — New cut', dur:'0:00', status:'wip', by:'Editor', date:'TBD', note:'' }] }));
  const delPatch = (id, p) => setDoc(d => ({ ...d, dels: d.dels.map(x => x.id === id ? { ...x, ...p } : x) }));
  const delCycle = id => setDoc(d => ({ ...d, dels: d.dels.map(x => x.id !== id ? x : { ...x, status: DEL_ORDER[(DEL_ORDER.indexOf(x.status) + 1) % DEL_ORDER.length] }) }));
  const delRemove = id => {
    const prev = doc; const del = doc.dels.find(x => x.id === id) || {};
    setDoc(d => ({ ...d, dels: d.dels.filter(x => x.id !== id) }));
    window.pushUndo && window.pushUndo(`Removed "${del.name || 'deliverable'}"`, () => setDoc(prev));
  };
  const delAdd = () => setDoc(d => ({ ...d, dels: [...d.dels, { id:'d' + Date.now(), name:'New deliverable', fmt:'format', due:'TBD', status:'pending' }] }));

  return (
    <div className="fade-up">
      {!readOnly && <SectionTitle kicker="Post & Review · Versions" icon="Layers3" title="Post Versions"
        action={<div className="flex items-center gap-2.5">
          <Chip tone="mint"><Icon name="CircleCheck" size={12} /> {approved.length} approved</Chip>
          <Chip tone="electric"><Icon name="PackageCheck" size={12} /> {delivered}/{doc.dels.length} delivered</Chip>
        </div>} />}

      <div className={cx('grid items-start gap-5', mobile ? 'grid-cols-1' : 'grid-cols-12')}>
        {/* cut stack */}
        <div className={mobile ? '' : 'col-span-7'}>
          <Panel pad={false} className="overflow-hidden">
            <div className="flex items-center justify-between border-b border-line p-3.5">
              <div>
                <h3 className="font-display text-[15px] font-600 text-head">Version Stack</h3>
                <p className="text-[11.5px] text-zinc-500">{latest ? 'Latest: ' + latest.name : 'No cuts yet'}</p>
              </div>
              {!readOnly && <button onClick={cutAdd} className="flex items-center gap-1.5 rounded-lg bg-cta px-3 py-2 text-[12px] font-700 text-cta-ink hover:bg-cta-hover"><Icon name="Plus" size={14} /> New cut</button>}
            </div>
            <div className="relative p-3.5">
              <div className="absolute bottom-4 left-[26px] top-4 w-px bg-line" />
              <div className="space-y-2.5">
                {doc.cuts.map(c => {
                  const st = CUT_STATUS[c.status] || CUT_STATUS.wip;
                  return (
                    <div key={c.id} className="group/cut relative flex gap-3">
                      <span className={cx('relative z-10 mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border-2 border-ink-850', c.status === 'approved' ? 'bg-mint text-ink-950' : 'bg-ink-700 text-zinc-300')}><Icon name={st.icon} size={12} /></span>
                      <div className="min-w-0 flex-1 rounded-xl border border-line bg-ink-900 p-3">
                        <div className="flex items-center gap-2">
                          <span className="min-w-0 flex-1 truncate text-[13px] font-700 text-zinc-100"><Edit value={c.name} onChange={v => cutPatch(c.id, { name: v })} className="text-[13px] font-700" /></span>
                          <span className="font-mono text-[11px] text-zinc-500"><Edit value={c.dur} onChange={v => cutPatch(c.id, { dur: v })} className="font-mono text-[11px]" /></span>
                          <button onClick={() => !readOnly && cutCycle(c.id)} disabled={readOnly}><Chip tone={st.tone}><Icon name={st.icon} size={11} />{st.label}</Chip></button>
                          {!readOnly && <button onClick={() => cutRemove(c.id)} className="text-zinc-700 opacity-0 transition-all hover:text-[#FF4D6D] group-hover/cut:opacity-100"><Icon name="Trash2" size={13} /></button>}
                        </div>
                        <div className="mt-1 flex items-center gap-2 text-[11px] text-zinc-500">
                          <span className="inline-flex items-center gap-1"><Icon name="User" size={10} /><Edit value={c.by} onChange={v => cutPatch(c.id, { by: v })} className="text-[11px]" /></span>
                          <span className="text-zinc-700">·</span>
                          <span className="inline-flex items-center gap-1"><Icon name="Calendar" size={10} /><Edit value={c.date} onChange={v => cutPatch(c.id, { date: v })} className="text-[11px]" /></span>
                        </div>
                        <div className="mt-1 text-[11.5px] text-zinc-400"><Edit value={c.note} onChange={v => cutPatch(c.id, { note: v })} placeholder="Cut note…" multiline className="text-[11.5px]" /></div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </Panel>
        </div>

        {/* deliverables */}
        <div className={mobile ? '' : 'col-span-5'}>
          <Panel pad={false} className="overflow-hidden">
            <div className="flex items-center justify-between border-b border-line p-3.5">
              <h3 className="font-display text-[15px] font-600 text-head">Deliverables</h3>
              {!readOnly && <button onClick={delAdd} className="flex items-center gap-1.5 rounded-lg border border-line bg-ink-900 px-2.5 py-1.5 text-[12px] font-600 text-zinc-300 hover:text-zinc-100"><Icon name="Plus" size={13} /> Add</button>}
            </div>
            <div>
              {doc.dels.map(x => {
                const st = DEL_STATUS[x.status] || DEL_STATUS.pending;
                return (
                  <div key={x.id} className="group/del flex items-center gap-3 border-t border-line/70 px-3.5 py-2.5 first:border-t-0 hover:bg-ink-800">
                    <div className="min-w-0 flex-1">
                      <div className="truncate text-[13px] font-600 text-zinc-100"><Edit value={x.name} onChange={v => delPatch(x.id, { name: v })} className="text-[13px] font-600" /></div>
                      <div className="truncate font-mono text-[10.5px] text-zinc-500"><Edit value={x.fmt} onChange={v => delPatch(x.id, { fmt: v })} className="font-mono text-[10.5px]" /></div>
                    </div>
                    <div className="shrink-0 text-right">
                      <button onClick={() => !readOnly && delCycle(x.id)} disabled={readOnly}><Chip tone={st.tone}><Icon name={st.icon} size={11} />{st.label}</Chip></button>
                      <div className="mt-1 text-[10.5px] text-zinc-500">due <Edit value={x.due} onChange={v => delPatch(x.id, { due: v })} className="text-[10.5px]" /></div>
                    </div>
                    {!readOnly && <button onClick={() => delRemove(x.id)} className="shrink-0 text-zinc-700 opacity-0 transition-all hover:text-[#FF4D6D] group-hover/del:opacity-100"><Icon name="Trash2" size={13} /></button>}
                  </div>
                );
              })}
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}

window.PostVersionModule = PostVersionModule;
