// ChecklistLog.jsx — per-day view of which checklist items got
// completed (by whom, when). Reads checklist_completions for the
// selected date and groups them by the template's checklist_groups.
//
// Templates change over time; this view shows the template *as it is
// now* and overlays the day's completion rows. Completed items show a
// green check + avatar + timestamp; uncompleted items show as empty.
//
// Mirrors the look of PrepCompletionsLog (per-item accordion) but
// since each checklist item has at most one completion per day, the
// expanded view here is simpler — no timeline of contributions, just
// the single (or absent) completion fact.

const ChecklistLog = ({ density = 'comfortable' }) => {
  const [date, setDate] = useState(() => new Date());
  const dateKey = isoDate(date);
  const past = isPast(date);
  const future = isFuture(date);

  // Template (groups + items) read from window — synced via the realtime
  // subscription inside the Template editor when the admin edits it.
  const groups = (window.SAMPLE_CHECKLIST_GROUPS || [])
    .filter(g => !g.archived)
    .slice()
    .sort((a, b) => a.sortOrder - b.sortOrder || a.triggerTime.localeCompare(b.triggerTime));
  const items = (window.SAMPLE_CHECKLIST_ITEMS || []).filter(i => !i.archived);

  // Filter groups to only those scheduled for the selected weekday.
  const dow = date.getDay(); // 0 = Sun
  const visibleGroups = groups.filter(g => (g.weekdays || []).includes(dow));

  // Completions for the day, keyed by item id.
  const [completions, setCompletions] = useState({});
  useEffect(() => {
    if (!window.supa) return;
    let cancelled = false;
    window.supa.from('checklist_completions').select('*')
      .eq('restaurant_id', window.RESTAURANT_ID)
      .eq('the_date', dateKey)
      .then(({ data }) => {
        if (cancelled || !data) return;
        const m = {};
        data.forEach(c => {
          m[c.item_id] = {
            id: c.id, staffId: c.staff_id, completedAt: c.completed_at,
          };
        });
        setCompletions(m);
      });

    const ch = window.supa
      .channel('portal-checklist-completions:' + window.RESTAURANT_ID + ':' + dateKey)
      .on('postgres_changes', {
        event: '*', schema: 'public', table: 'checklist_completions',
        filter: 'restaurant_id=eq.' + window.RESTAURANT_ID,
      }, (payload) => {
        const row = payload.new || payload.old;
        if (!row || row.the_date !== dateKey) return;
        setCompletions(prev => {
          const next = { ...prev };
          if (payload.eventType === 'DELETE') {
            delete next[row.item_id];
          } else {
            next[row.item_id] = {
              id: row.id, staffId: row.staff_id, completedAt: row.completed_at,
            };
          }
          return next;
        });
      })
      .subscribe();
    return () => { cancelled = true; window.supa.removeChannel(ch); };
  }, [dateKey]);

  const staffById = useMemo(() => {
    const m = {};
    (window.SAMPLE_STAFF || []).forEach(s => { m[s.id] = s; });
    return m;
  }, []);

  // Totals across visible groups for the date.
  const allItemsToday = visibleGroups
    .flatMap(g => items.filter(i => i.groupId === g.id));
  const doneCount = allItemsToday.filter(i => completions[i.id]).length;
  const totalCount = allItemsToday.length;

  const [expanded, setExpanded] = useState(() => new Set());
  const toggle = (groupId) => setExpanded(prev => {
    const next = new Set(prev);
    if (next.has(groupId)) next.delete(groupId);
    else next.add(groupId);
    return next;
  });

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1080 }}>
      <PPageHeader
        title="Daily Checklist"
        subtitle={past
          ? 'Historical record — what got done on this date.'
          : future
            ? 'Future date — the iPad will start tracking on the day itself.'
            : "Today's checklist as it stands. Updates live as the iPad logs items."}
        right={<>
          {past && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '3px 9px', borderRadius: 999,
              background: 'var(--bg-sunken)', color: 'var(--fg-2)',
              fontSize: 11, fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase',
            }}>
              <PIcon name="lock" size={11} /> Read-only
            </span>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1, alignItems: 'flex-end' }}>
            <span style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>Done</span>
            <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', fontFamily: 'var(--font-num)' }}>
              {doneCount}/{totalCount}
            </span>
          </div>
          <PDatePicker value={date} onChange={setDate} />
        </>}
        crewLead
        crewLeadDate={dateKey}
      />

      {visibleGroups.length === 0 ? (
        <div className="portal-card" style={{ padding: 48, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
          {groups.length === 0
            ? <>No template yet — go to <a href="#" onClick={e => { e.preventDefault(); window.location.hash = 'checklist-template'; }} style={{ color: 'var(--fg-1)', fontWeight: 500 }}>Template</a> to set one up.</>
            : 'No groups scheduled for this weekday.'}
        </div>
      ) : visibleGroups.map(group => {
        const groupItems = items.filter(i => i.groupId === group.id)
          .sort((a, b) => a.sortOrder - b.sortOrder);
        const gDone = groupItems.filter(i => completions[i.id]).length;
        const gTotal = groupItems.length;
        const open = expanded.has(group.id);
        const pct = gTotal > 0 ? gDone / gTotal : 0;

        return (
          <div key={group.id} className="portal-card" style={{ padding: 0, marginBottom: 12 }}>
            <button
              onClick={() => toggle(group.id)}
              style={{
                width: '100%', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 16px',
                background: 'transparent', border: 'none',
                cursor: 'pointer',
              }}
            >
              <ChecklistProgressRing done={gDone} total={gTotal} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>
                  {group.name}
                  <span style={{
                    marginLeft: 10, fontSize: 12, color: 'var(--fg-3)', fontWeight: 400,
                    fontFamily: 'var(--font-num)',
                  }}>
                    {window.formatChecklistTime12(group.triggerTime)}
                  </span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>
                  {gDone}/{gTotal} done
                  {pct === 1 && gTotal > 0 && <span style={{ marginLeft: 8, color: '#2D6A2A', fontWeight: 600 }}>· complete</span>}
                </div>
              </div>
              <PIcon name={open ? 'chevronD' : 'chevronR'} size={13} color="var(--fg-3)" />
            </button>

            {open && (
              <div style={{ padding: '0 16px 12px 60px' }}>
                {groupItems.length === 0 ? (
                  <div style={{ padding: '6px 0 10px', fontSize: 12.5, color: 'var(--fg-3)' }}>
                    No items in this group yet.
                  </div>
                ) : groupItems.map(item => {
                  const c = completions[item.id];
                  const staff = c && staffById[c.staffId];
                  return (
                    <div key={item.id} style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '8px 4px',
                      borderBottom: '1px solid var(--border-2)',
                      fontSize: 12.5,
                    }}>
                      <div style={{
                        width: 18, height: 18, borderRadius: 5,
                        background: c ? '#2D6A2A' : 'transparent',
                        border: c ? 'none' : '1.5px solid var(--border-1)',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        flexShrink: 0,
                      }}>
                        {c && <PIcon name="check" size={11} color="#fff" strokeWidth={3} />}
                      </div>
                      <div style={{ flex: 1, color: c ? 'var(--fg-2)' : 'var(--fg-1)', textDecoration: c ? 'line-through' : 'none' }}>
                        {item.name}
                      </div>
                      {c ? (
                        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                          {staff ? <PAvatar staff={staff} size={20} /> : null}
                          <span style={{ fontSize: 11.5, color: 'var(--fg-3)', fontFamily: 'var(--font-num)' }}>
                            {staff?.name || c.staffId} · {formatLogTime(c.completedAt)}
                          </span>
                        </div>
                      ) : (
                        <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>
                          {past ? 'Not done' : 'Pending'}
                        </span>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
};

// Mini ring — same idea as PrepEditor's ProgressRing but inlined here to
// keep this file standalone-readable.
const ChecklistProgressRing = ({ done, total, size = 36, stroke = 4 }) => {
  const pct = total > 0 ? Math.min(1, done / total) : 0;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - pct);
  const complete = pct >= 1;
  const color = complete ? '#2D6A2A' : (pct > 0 ? '#1D4ED8' : 'var(--border-1)');
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flexShrink: 0 }}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--border-1)" strokeWidth={stroke} />
      {pct > 0 && (
        <circle
          cx={size / 2} cy={size / 2} r={r}
          fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={c} strokeDashoffset={off}
          strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
      )}
      {complete && (
        <path d={`M ${size * 0.30} ${size * 0.52} L ${size * 0.45} ${size * 0.66} L ${size * 0.72} ${size * 0.38}`}
          fill="none" stroke={color} strokeWidth={stroke * 0.6} strokeLinecap="round" strokeLinejoin="round" />
      )}
    </svg>
  );
};

function formatLogTime(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
}

window.ChecklistLog = ChecklistLog;
