/* ============================================================
   DPR — Daily Production Report
   One report per shoot day: scenes & pages completed vs planned,
   setups, call/wrap, schedule status and notes/incidents. Rolls up
   days wrapped and pages shot vs total. Persisted per project.
   ============================================================ */

const DPR_KEY = 'silverlines.dpr.' + (window.PROJ_ID || 'crimson') + '.v1';

const DPR_STATUS = {
  ahead:    { label:'Ahead',       tone:'mint',    icon:'TrendingUp' },
  onsched:  { label:'On schedule', tone:'electric', icon:'CircleCheck' },
  behind:   { label:'Behind',      tone:'amber',   icon:'TrendingDown' },
  upcoming: { label:'Upcoming',    tone:'neutral', icon:'Clock' },
};
const DPR_ORDER = ['upcoming', 'onsched', 'ahead', 'behind'];

const DPR_SEED = [
  { id:'d1', day:1, date:'Mon, Jun 22', call:'06:00', wrap:'18:40', scenesPlan:3, scenesDone:3, pages:'2 4/8', setups:14, status:'onsched', note:'Cockpit + tarmac complete. Lost 20 min to fog, recovered.' },
  { id:'d2', day:2, date:'Tue, Jun 23', call:'05:30', wrap:'19:10', scenesPlan:3, scenesDone:2, pages:'1 6/8', setups:11, status:'behind', note:'Runway permit window tight. Scene 21 pushed to Day 3.' },
  { id:'d3', day:3, date:'Wed, Jun 24', call:'06:00', wrap:'', scenesPlan:4, scenesDone:0, pages:'', setups:0, status:'upcoming', note:'Backlot tank + pickups from Day 2.' },
  { id:'d4', day:4, date:'Thu, Jun 25', call:'06:00', wrap:'', scenesPlan:2, scenesDone:0, pages:'', setups:0, status:'upcoming', note:'Hangar finale + VFX plates.' },
];

function dprLoad() {
  const s = window.SLStore.get(DPR_KEY);
  const list = (Array.isArray(s) && s.length) ? s : (window.PROJ_BLANK ? [] : DPR_SEED);
  /* migrate: a legacy hand-entered planned count becomes a manual override once,
     so historical reports are preserved while new days auto-plan from the board. */
  return list.map(d => (d.scenesPlanManual === undefined && +d.scenesPlan > 0) ? { ...d, scenesPlanManual: +d.scenesPlan } : d);
}

function DPRField({ label, value, onChange, mono, align = 'left' }) {
  return (
    <div>
      <div className="text-[9.5px] uppercase tracking-[0.1em] text-zinc-600">{label}</div>
      <div className={cx('text-[13px] font-600 text-zinc-200', mono && 'font-mono')}><Edit value={String(value)} onChange={onChange} align={align} placeholder="—" className={cx('text-[13px]', mono && 'font-mono')} /></div>
    </div>
  );
}

function DPRModule({ mobile, readOnly = false }) {
  const [days, setDaysState] = useState(dprLoad);
  const [sbScenes] = useStoryboard();
  const spotsForDay = n => [...new Set(sbScenes.filter(s => ((s.sched && s.sched.day) || 0) === n).map(sceneSpot))];
  /* planned scenes auto-derive from the stripboard (scenes assigned to that day);
     a manual entry overrides it, and the ✕ clears back to auto. */
  const plannedFor = n => sbScenes.filter(s => ((s.sched && s.sched.day) || 0) === n).length;
  const effPlan = d => (d.scenesPlanManual != null ? +d.scenesPlanManual : plannedFor(d.day));
  const setDays = next => setDaysState(prev => {
    const v = typeof next === 'function' ? next(prev) : next;
    window.SLStore.set(DPR_KEY, v);
    return v;
  });

  const wrapped = days.filter(d => d.scenesDone > 0 && d.wrap).length;
  const scenesDone = days.reduce((a, d) => a + (+d.scenesDone || 0), 0);
  const scenesPlan = days.reduce((a, d) => a + effPlan(d), 0);
  const setups = days.reduce((a, d) => a + (+d.setups || 0), 0);

  const patch = (id, p) => setDays(ds => ds.map(d => d.id === id ? { ...d, ...p } : d));
  const cycle = id => setDays(ds => ds.map(d => d.id !== id ? d : { ...d, status: DPR_ORDER[(DPR_ORDER.indexOf(d.status) + 1) % DPR_ORDER.length] }));
  const remove = id => {
    const prev = days; const day = days.find(d => d.id === id) || {};
    setDays(ds => ds.filter(d => d.id !== id));
    window.pushUndo && window.pushUndo(`Removed Day ${day.day || ''} report`, () => setDays(prev));
  };
  const add = () => setDays(ds => {
    const day = ds.reduce((m, d) => Math.max(m, +d.day || 0), 0) + 1;
    const cd = (window.SLStore.get('silverlines.callday.' + (window.PROJ_ID || 'crimson') + '.v1', {}) || {})[day] || {};
    const date = (typeof fmtDayDate === 'function') ? fmtDayDate(day) : 'TBD';
    return [...ds, { id:'d' + Date.now() + '-' + Math.random().toString(36).slice(2, 6), day, date, call: cd.callTime || '06:00', wrap:'', scenesPlanManual:null, scenesDone:0, pages:'', setups:0, status:'upcoming', note:'' }];
  });

  return (
    <div className="fade-up">
      {!readOnly && <SectionTitle kicker="Production · Reporting" icon="ClipboardCheck" title="Daily Production Report"
        action={<div className="flex items-center gap-2.5">
          <Chip tone="mint"><Icon name="CalendarCheck" size={12} /> {wrapped} days wrapped</Chip>
          {!readOnly && <button onClick={add} className="flex items-center gap-2 rounded-xl bg-cta px-3.5 py-2.5 text-[12.5px] font-700 text-cta-ink transition-colors hover:bg-cta-hover"><Icon name="Plus" size={15} /> Add day</button>}
        </div>} />}

      {/* rollup */}
      <Panel className="mb-5">
        <div className="grid grid-cols-3 gap-4">
          <div>
            <div className="text-[11px] uppercase tracking-[0.12em] text-zinc-500">Scenes completed</div>
            <div className="font-display text-[30px] font-700 leading-none text-head">{scenesDone}<span className="text-[16px] text-zinc-600">/{scenesPlan}</span></div>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-[0.12em] text-zinc-500">Total setups</div>
            <div className="font-display text-[30px] font-700 leading-none text-head">{setups}</div>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-[0.12em] text-zinc-500">Days wrapped</div>
            <div className="font-display text-[30px] font-700 leading-none text-mint">{wrapped}<span className="text-[16px] text-zinc-600">/{days.length}</span></div>
          </div>
        </div>
      </Panel>

      {/* per-day reports */}
      {days.length === 0 ? (
        <EmptyState icon="ClipboardCheck" title="No reports yet"
          sub="Add the first shoot day to start logging scenes, pages and setups against plan."
          action={!readOnly && <button onClick={add} className="flex items-center gap-2 rounded-xl bg-cta px-3.5 py-2.5 text-[12.5px] font-700 text-cta-ink transition-colors hover:bg-cta-hover"><Icon name="Plus" size={15} /> Add day</button>} />
      ) : (
      <div className="space-y-4">
        {days.map(d => {
          const st = DPR_STATUS[d.status] || DPR_STATUS.upcoming;
          const plan = effPlan(d);
          const done = (+d.scenesDone || 0) >= plan && plan > 0;
          return (
            <Panel key={d.id} 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={cx('flex h-9 w-9 items-center justify-center rounded-lg font-display text-[15px] font-700', done ? 'bg-mint/15 text-mint' : 'bg-ink-700 text-zinc-300')}>{d.day}</span>
                  <div>
                    <div className="text-[13.5px] font-700 text-zinc-100"><Edit value={d.date} onChange={v => patch(d.id, { date: v })} className="text-[13.5px] font-700" /></div>
                    <div className="text-[11px] text-zinc-500">Day {d.day}</div>
                    {spotsForDay(d.day).length > 0 && (
                      <div className="mt-1 flex flex-wrap items-center gap-1">
                        {spotsForDay(d.day).map(id => <SpotBadge key={id} spotId={id} />)}
                      </div>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button onClick={() => !readOnly && cycle(d.id)} disabled={readOnly}><Chip tone={st.tone}><Icon name={st.icon} size={11} />{st.label}</Chip></button>
                  {!readOnly && <button onClick={() => remove(d.id)} title="Remove day" className="flex h-7 w-7 items-center justify-center rounded-md text-zinc-700 transition-colors hover:bg-[#FF4D6D]/12 hover:text-[#FF4D6D]"><Icon name="Trash2" size={13} /></button>}
                </div>
              </div>
              <div className="grid grid-cols-3 gap-3 p-3.5 sm:grid-cols-6">
                <DPRField label="Call" value={d.call} mono onChange={v => patch(d.id, { call: v })} />
                <DPRField label="Wrap" value={d.wrap} mono onChange={v => patch(d.id, { wrap: v })} />
                <DPRField label="Scenes done" value={d.scenesDone} mono onChange={v => patch(d.id, { scenesDone: parseInt(v) || 0 })} />
                <div>
                  <div className="flex items-center gap-1 text-[9.5px] uppercase tracking-[0.1em] text-zinc-600">Planned
                    {d.scenesPlanManual == null && <span title="Auto from the stripboard" className="rounded bg-electric/15 px-1 text-[8px] font-700 not-italic text-electric-soft">AUTO</span>}
                  </div>
                  <div className="flex items-center gap-1 font-mono text-[13px] font-600 text-zinc-200">
                    <Edit value={String(plan)} onChange={v => patch(d.id, { scenesPlanManual: parseInt(v) || 0 })} placeholder="—" className="font-mono text-[13px]" />
                    {d.scenesPlanManual != null && !readOnly && <button title="Back to auto" onClick={() => patch(d.id, { scenesPlanManual: null })} className="text-zinc-600 hover:text-electric-soft"><Icon name="X" size={10} /></button>}
                  </div>
                </div>
                <DPRField label="Pages" value={d.pages} mono onChange={v => patch(d.id, { pages: v })} />
                <DPRField label="Setups" value={d.setups} mono onChange={v => patch(d.id, { setups: parseInt(v) || 0 })} />
              </div>
              <div className="border-t border-line px-3.5 py-2.5">
                <div className="text-[9.5px] uppercase tracking-[0.1em] text-zinc-600">Notes & incidents</div>
                <div className="text-[12px] text-zinc-300"><Edit value={d.note} onChange={v => patch(d.id, { note: v })} placeholder="End-of-day notes…" multiline className="text-[12px]" /></div>
              </div>
            </Panel>
          );
        })}
      </div>
      )}
    </div>
  );
}

window.DPRModule = DPRModule;
