// rwic-timecard.jsx — Daily timecard with multi-block activity entries.
// 24-hour times, RFL-style activity codes grouped by Field/Training/Office/etc.
// Live totals broken out by group and a 24-hour timeline visualization.

function ScreenTimecard({ goTo }) {
  const { user, shift, updateShift, clockState, liveHrs, timecardSubmitted, submitTimecard } = useApp();

  // Local form state — derive initial blocks from clockState if present
  const [blocks, setBlocks] = useState(() => {
    // Use closed segments + current open one
    const closed = clockState.activityLog.map((seg, i) => ({
      id: `seg-${i}`,
      code: seg.code,
      start: isoToHM(seg.start),
      end: isoToHM(seg.end),
      notes: '',
    }));
    const open = clockState.startedAt ? [{
      id: 'live',
      code: clockState.currentCode,
      start: isoToHM(clockState.startedAt),
      end: clockState.status === 'off' ? isoToHM(new Date().toISOString()) : '',
      notes: '',
    }] : [];
    return closed.length || open.length ? [...closed, ...open] : [{
      id: 'b1',
      code: 'F10', start: '06:14', end: '13:30', notes: '',
    }, {
      id: 'b2',
      code: 'V10', start: '13:30', end: '14:15', notes: 'Skykomish → MP 142.8',
      travelFrom: 'Skykomish staging', travelTo: 'MP 142.8',
    }, {
      id: 'b3',
      code: 'F10', start: '14:15', end: '', notes: '',
    }];
  });

  const [dayNotes, setDayNotes] = useState('');

  const upd = (id, k, v) => setBlocks(bs => bs.map(b => b.id === id ? { ...b, [k]: v } : b));
  const remove = (id) => setBlocks(bs => bs.filter(b => b.id !== id));
  const add = (code = 'F10') => setBlocks(bs => [...bs, {
    id: `b${Date.now()}`, code, start: nowHM(), end: '', notes: '',
  }]);

  const totalMins = blocks.reduce((s, b) => s + (calcMins(b.start, b.end) || 0), 0);
  const totalHrs = minsToDecimal(totalMins);

  const groupTotals = blocks.reduce((acc, b) => {
    const ac = codeByValue(b.code);
    const g = ac?.group || 'Other';
    const m = calcMins(b.start, b.end) || 0;
    acc[g] = (acc[g] || 0) + m;
    return acc;
  }, {});

  const canSubmit = blocks.some(b => b.start && b.end) && shift.projectNumber;

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 340px', overflow: 'hidden' }}>
      <div style={{ overflowY: 'auto', padding: '20px 28px 32px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="eyebrow">DAILY TIMECARD · MULTI-ACTIVITY</div>
            <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>{fmtDateLong(shift.date)}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
              <span className="mono">{shift.projectNumber}</span> · {shift.projectName}
            </div>
          </div>
          {timecardSubmitted
            ? <Badge tone="good" icon={<IconCheck size={11} />}>Submitted</Badge>
            : <Badge tone="warn">Editable</Badge>}
        </div>

        {/* Day summary hero */}
        <Card padding={18} style={{ marginBottom: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 24, alignItems: 'center' }}>
            <div>
              <div className="eyebrow">TOTAL DAY</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span className="mono tnum" style={{ fontSize: 48, fontWeight: 700, letterSpacing: -1.5, lineHeight: 1 }}>
                  {(totalHrs || 0).toFixed(2)}
                </span>
                <span style={{ fontSize: 14, color: 'var(--muted)' }}>hrs</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>
                {totalHrs > 8 && <span style={{ color: 'var(--warn)', fontWeight: 600 }}>+{(totalHrs - 8).toFixed(2)} OT</span>}
                {totalHrs > 8 && ' · '}
                {blocks.length} {blocks.length === 1 ? 'block' : 'blocks'}
              </div>
            </div>

            {/* Group totals */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
              {Object.entries(groupTotals).filter(([, m]) => m > 0).map(([g, m]) => (
                <div key={g} style={{
                  padding: '8px 14px',
                  background: 'var(--panel-2)',
                  border: `1px solid ${GROUP_COLORS[g] || 'var(--line)'}33`,
                  borderRadius: 10,
                  minWidth: 90,
                }}>
                  <div className="eyebrow" style={{ color: GROUP_COLORS[g], fontSize: 10 }}>{g}</div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 2 }}>
                    {minsToDecimal(m).toFixed(2)}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Timeline bar */}
          <div style={{ marginTop: 16 }}>
            <div style={{
              position: 'relative', height: 24, borderRadius: 6, overflow: 'hidden',
              background: '#EDEAE3', border: '1px solid var(--line)',
            }}>
              {blocks.filter(b => b.start && b.end).map(b => {
                const ac = codeByValue(b.code);
                const col = GROUP_COLORS[ac?.group || 'Field'] || 'var(--accent)';
                const sm = calcMins('00:00', b.start) || 0;
                const dur = calcMins(b.start, b.end) || 0;
                return (
                  <div key={b.id} title={`${ac?.code} ${b.start}–${b.end}`}
                    style={{
                      position: 'absolute', left: `${(sm / 1440) * 100}%`,
                      width: `${(dur / 1440) * 100}%`, height: '100%',
                      background: col, opacity: 0.85,
                    }} />
                );
              })}
              {/* Hour ticks */}
              {Array.from({ length: 25 }).map((_, i) => (
                <div key={i} style={{
                  position: 'absolute', left: `${(i / 24) * 100}%`, top: 0, bottom: 0,
                  width: 1, background: 'rgba(0,0,0,0.07)',
                }} />
              ))}
            </div>
            <div style={{
              display: 'flex', justifyContent: 'space-between', marginTop: 4,
              fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--muted-2)',
            }}>
              <span>00</span><span>04</span><span>08</span><span>12</span><span>16</span><span>20</span><span>24</span>
            </div>
          </div>
        </Card>

        {/* Activity blocks */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: -0.2 }}>Activity entries ({blocks.length})</div>
          <span className="eyebrow">24-HOUR · GPS ON SUBMIT</span>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {blocks.map((b, i) => (
            <ActivityBlock key={b.id} block={b} idx={i + 1}
              onUpdate={(k, v) => upd(b.id, k, v)}
              onRemove={() => remove(b.id)}
              isOnly={blocks.length === 1}
            />
          ))}
        </div>

        {/* Add buttons */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <button onClick={() => add('F10')} style={{
            background: 'rgba(229,91,19,0.08)',
            border: '2px dashed var(--accent)',
            borderRadius: 12, padding: '12px 16px',
            color: 'var(--accent-deep)', fontWeight: 700, fontSize: 14,
            cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <IconPlus size={14} /> Add activity
          </button>
          <button onClick={() => add('V10')} style={{
            background: 'rgba(180,83,9,0.08)',
            border: '2px dashed var(--warn)',
            borderRadius: 12, padding: '12px 16px',
            color: 'var(--warn)', fontWeight: 700, fontSize: 14,
            cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <IconCar size={14} /> Add travel time
          </button>
        </div>

        {/* Notes */}
        <div style={{ marginTop: 18 }}>
          <Field label="Day notes" hint="Overtime reason, standby, delays — applies to full day">
            <Textarea rows={3} value={dayNotes} onChange={e => setDayNotes(e.target.value)} placeholder="e.g. Train delays at MP 142.9 added 2hr OT. Standby authorized by D. Reyes." />
          </Field>
        </div>

        {/* Submit */}
        <div style={{
          marginTop: 18, padding: 18,
          background: canSubmit ? 'var(--good-soft)' : 'var(--panel-2)',
          border: `1px solid ${canSubmit ? 'var(--good)' : 'var(--line)'}`,
          borderRadius: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>
              {timecardSubmitted ? 'Timecard submitted' :
                canSubmit ? `${(totalHrs || 0).toFixed(2)} hours ready` :
                  'Add at least one complete activity'}
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
              GPS captured at submit · clocks all blocks to {shift.projectNumber}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="secondary" onClick={() => goTo('today')}>Back to today</Button>
            <Button variant="primary" size="lg" icon={<IconCheck size={16} />}
              disabled={!canSubmit || timecardSubmitted}
              onClick={() => {
                submitTimecard({
                  employeeBadge: user.badge,
                  projectNumber: shift.projectNumber,
                  date: shift.date,
                  blocks: blocks
                    .filter(b => b.start && b.end)
                    .map(b => ({ code: b.code, hrs: minsToDecimal(calcMins(b.start, b.end)) || 0, state: shift.workState })),
                });
                goTo('today');
              }}>
              {timecardSubmitted ? 'Submitted' : 'Submit timecard'}
            </Button>
          </div>
        </div>
      </div>

      {/* RIGHT — code reference & history */}
      <TimecardContextRail blocks={blocks} totalHrs={totalHrs} groupTotals={groupTotals} />
    </div>
  );
}

// ─── Activity block — one row ──────────────────────────────────
function ActivityBlock({ block, idx, onUpdate, onRemove, isOnly }) {
  const ac = codeByValue(block.code) || ACTIVITY_CODES[0];
  const mins = calcMins(block.start, block.end);
  const hrs = minsToDecimal(mins);
  const isTravel = ac.group === 'Travel';
  const groupCol = GROUP_COLORS[ac.group] || 'var(--accent)';
  const [pickOpen, setPickOpen] = useState(false);

  return (
    <div style={{
      background: 'var(--panel)',
      border: `1px solid ${groupCol}33`,
      borderLeft: `4px solid ${groupCol}`,
      borderRadius: 12,
      padding: '14px 18px',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr 280px auto', gap: 16, alignItems: 'center' }}>
        {/* Index */}
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: `${groupCol}1c`, color: groupCol,
          display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13,
          fontFamily: 'var(--font-mono)',
        }}>{String(idx).padStart(2, '0')}</div>

        {/* Activity code button */}
        <button onClick={() => setPickOpen(true)} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '8px 12px',
          background: 'var(--panel-2)', border: '1px solid var(--line)',
          borderRadius: 10, cursor: 'pointer', textAlign: 'left',
          width: '100%',
        }}>
          <span className="mono" style={{
            fontSize: 12, fontWeight: 700,
            padding: '3px 7px', borderRadius: 4,
            background: groupCol, color: '#fff', flexShrink: 0,
          }}>{ac.code}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.2 }}>{ac.label}</div>
            <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>{ac.group}</div>
          </div>
          <IconChevronDown size={14} style={{ color: 'var(--muted)' }} />
        </button>

        {/* Times */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 8, alignItems: 'center' }}>
          <TimeField label="Start" value={block.start} onChange={v => onUpdate('start', v)} groupCol={groupCol} />
          <span style={{ color: 'var(--muted-2)', fontSize: 12, marginTop: 16 }}>→</span>
          <TimeField label="End" value={block.end} onChange={v => onUpdate('end', v)} groupCol={groupCol} />
        </div>

        {/* Hours pill */}
        <div style={{ textAlign: 'center', minWidth: 72 }}>
          {hrs != null ? (
            <div style={{
              padding: '6px 12px', background: `${groupCol}15`, border: `1px solid ${groupCol}44`,
              borderRadius: 8,
            }}>
              <div className="mono tnum" style={{ fontSize: 18, fontWeight: 700, color: groupCol, lineHeight: 1 }}>{hrs.toFixed(2)}</div>
              <div className="eyebrow" style={{ fontSize: 9, marginTop: 2 }}>hrs</div>
            </div>
          ) : (
            <div style={{ padding: '6px 12px', background: 'var(--panel-2)', borderRadius: 8, color: 'var(--muted-2)', fontSize: 12 }}>—</div>
          )}
        </div>
      </div>

      {/* Travel sub-fields */}
      {isTravel && (
        <div style={{
          marginTop: 12, padding: '10px 14px',
          background: 'rgba(180,83,9,0.05)', borderRadius: 10,
          display: 'grid', gridTemplateColumns: '1fr 1fr 100px', gap: 10,
        }}>
          <Field label="From" style={{ marginBottom: 0 }}>
            <Input value={block.travelFrom || ''} onChange={e => onUpdate('travelFrom', e.target.value)} placeholder="Origin" />
          </Field>
          <Field label="To" style={{ marginBottom: 0 }}>
            <Input value={block.travelTo || ''} onChange={e => onUpdate('travelTo', e.target.value)} placeholder="Destination" />
          </Field>
          <Field label="Miles" style={{ marginBottom: 0 }}>
            <Input type="number" value={block.travelMiles || ''} onChange={e => onUpdate('travelMiles', e.target.value)} />
          </Field>
        </div>
      )}

      {/* Notes + remove */}
      <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
        <input
          value={block.notes || ''} onChange={e => onUpdate('notes', e.target.value)}
          placeholder="Optional notes — OT reason, location, details"
          style={{
            flex: 1, padding: '7px 12px',
            border: '1px solid var(--line)', borderRadius: 8,
            background: 'var(--panel-2)', fontSize: 13, fontFamily: 'inherit', outline: 'none',
          }}
        />
        {!isOnly && (
          <button onClick={onRemove} style={{
            background: 'transparent', border: '1px solid var(--line)', borderRadius: 8,
            padding: '7px 10px', cursor: 'pointer', color: 'var(--bad)',
            display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 500,
          }}>
            <IconClose size={12} /> Remove
          </button>
        )}
      </div>

      <CodePickerSheet
        open={pickOpen}
        currentCode={block.code}
        onClose={() => setPickOpen(false)}
        onPick={(c) => { onUpdate('code', c); setPickOpen(false); }}
      />
    </div>
  );
}

// ─── Time field with "Now" stamp button ────────────────────────
function TimeField({ label, value, onChange, groupCol }) {
  return (
    <div>
      <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 3 }}>{label}</div>
      <div style={{ display: 'flex', gap: 4 }}>
        <input type="time" value={value} onChange={e => onChange(e.target.value)} style={{
          flex: 1, padding: '6px 8px', fontFamily: 'var(--font-mono)', fontSize: 13,
          fontWeight: 600, letterSpacing: 0.5,
          border: `1px solid var(--line)`, borderRadius: 6, outline: 'none',
          background: 'var(--panel-2)', textAlign: 'center',
        }} />
        <button onClick={() => onChange(nowHM())} title="Stamp current time" style={{
          background: groupCol, color: '#fff', border: 'none',
          borderRadius: 6, padding: '0 8px', cursor: 'pointer',
          fontSize: 10, fontWeight: 700, letterSpacing: 0.5,
        }}>NOW</button>
      </div>
    </div>
  );
}

// ─── Code picker sheet — grouped activity codes ────────────────
function CodePickerSheet({ open, currentCode, onClose, onPick }) {
  const [q, setQ] = useState('');
  const [picked, setPicked] = useState(currentCode);
  useEffect(() => { if (open) { setQ(''); setPicked(currentCode); } }, [open, currentCode]);
  if (!open) return null;

  const matches = ACTIVITY_CODES.filter(t => {
    if (!q) return true;
    const s = q.toLowerCase();
    return t.code.toLowerCase().includes(s) || t.label.toLowerCase().includes(s);
  });
  const grouped = GROUP_ORDER.map(g => [g, matches.filter(m => m.group === g)]).filter(([, items]) => items.length);

  return (
    <Sheet open={open} onClose={onClose} title="Select activity code" height="80%">
      <div style={{ position: 'relative', marginBottom: 14 }}>
        <IconSearch size={16} style={{ position: 'absolute', top: 12, left: 12, color: 'var(--muted)' }} />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search code or activity…"
          style={{
            width: '100%', padding: '10px 12px 10px 38px',
            border: '1px solid var(--line-strong)', borderRadius: 10,
            fontSize: 14, fontFamily: 'inherit', background: 'var(--panel)', outline: 'none',
          }}
        />
      </div>
      <div style={{ maxHeight: 380, overflowY: 'auto', margin: '0 -4px', padding: '0 4px' }}>
        {grouped.map(([g, items]) => (
          <div key={g} style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 4px' }}>
              <span className="eyebrow" style={{ color: GROUP_COLORS[g] }}>{g}</span>
              <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{items.length}</span>
            </div>
            {items.map(t => {
              const on = picked === t.code;
              return (
                <button key={t.code} onClick={() => setPicked(t.code)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, width: '100%',
                  padding: '10px 12px',
                  background: on ? 'var(--accent-soft)' : 'transparent',
                  border: `1px solid ${on ? 'var(--accent)' : 'transparent'}`,
                  borderRadius: 10, cursor: 'pointer', textAlign: 'left',
                }}>
                  <span className="mono" style={{
                    fontSize: 12, fontWeight: 700,
                    padding: '4px 8px', borderRadius: 5,
                    background: on ? 'var(--accent)' : 'var(--panel-2)',
                    color: on ? '#fff' : 'var(--text-2)',
                    minWidth: 48, textAlign: 'center', flexShrink: 0,
                  }}>{t.code}</span>
                  <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{t.label}</div>
                  {on && <IconCheckCircle size={18} style={{ color: 'var(--accent)' }} />}
                </button>
              );
            })}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        <Button variant="secondary" style={{ flex: 1 }} onClick={onClose}>Cancel</Button>
        <Button variant="primary" style={{ flex: 2 }} icon={<IconCheck size={16} />}
          onClick={() => onPick(picked)}>Use {picked}</Button>
      </div>
    </Sheet>
  );
}

// ─── Context rail (timecard) ───────────────────────────────────
function TimecardContextRail({ blocks, totalHrs, groupTotals }) {
  const { history } = useApp();
  return (
    <div style={{
      borderLeft: '1px solid var(--line)', background: 'var(--panel-2)',
      overflowY: 'auto', padding: '20px 18px 24px',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>BREAKDOWN BY GROUP</div>
        {Object.keys(groupTotals).length === 0 && (
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>No hours logged yet.</div>
        )}
        {Object.entries(groupTotals).filter(([, m]) => m > 0).map(([g, m]) => {
          const hrs = minsToDecimal(m);
          const pct = totalHrs ? (hrs / totalHrs) * 100 : 0;
          return (
            <div key={g} style={{ marginBottom: 8 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                <span style={{ color: GROUP_COLORS[g], fontWeight: 600 }}>{g}</span>
                <span className="mono" style={{ fontWeight: 600 }}>{hrs.toFixed(2)}h</span>
              </div>
              <div style={{ height: 6, borderRadius: 3, background: 'var(--line)', overflow: 'hidden' }}>
                <div style={{ width: `${pct}%`, height: '100%', background: GROUP_COLORS[g], transition: 'width 200ms' }} />
              </div>
            </div>
          );
        })}
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>WEEK SO FAR</div>
        {history.slice(0, 5).map(h => (
          <div key={h.date} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', fontSize: 12.5 }}>
            <div>
              <span className="mono" style={{ color: 'var(--muted)' }}>{h.date.slice(5)}</span>
              <span style={{ marginLeft: 8, color: 'var(--text-2)' }}>{codeByValue(h.code)?.short || h.code}</span>
            </div>
            <span className="mono" style={{ fontWeight: 600 }}>{h.hours.toFixed(1)}h</span>
          </div>
        ))}
        <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
          <span style={{ fontWeight: 700 }}>5-day total</span>
          <span className="mono" style={{ fontWeight: 700 }}>{history.slice(0, 5).reduce((s, h) => s + h.hours, 0).toFixed(1)}h</span>
        </div>
      </Card>

      <Card padding={14}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>RULES</div>
        <div style={{ fontSize: 12, color: 'var(--muted-2)', lineHeight: 1.6 }}>
          <div>• Times use 24-hour format</div>
          <div>• Blocks cannot overlap</div>
          <div>• Travel ({'<'}-{'>'}) is its own code</div>
          <div>• OT begins after 8 hrs/day</div>
          <div>• GPS attaches at submit</div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { ScreenTimecard });

// ─── Local helpers ─────────────────────────────────────────────
function isoToHM(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toTimeString().slice(0, 5);
}
