// DailyReport.jsx — bi-weekly completion overview for bonus calc.
//
// Rows = each of the 14 days in the active pay period (anchor stored on
// restaurants.pay_period_anchor_date, edited in Settings → Pay period).
// Columns: Date · Daily Prep · Daily Checklist · Temperature Log.
//
// v1 completion heuristic — binary ✓/✗ based on "did anything happen
// that day":
//   Prep        ✓ iff at least one prep_completions row for that_date
//   Checklist   ✓ iff at least one checklist_completions row for that_date
//   Temperature ✓ iff at least one temperature_logs row with finalized_at
// Future days are shown as — (not-yet-happened, distinct from missed).
//
// Future v2 (per Ryan's note "in the future even more details like the
// percentage of completion"): replace ✓/✗ with actual completion % per
// module, computed against the day's catalog/template. The existing
// PrepEditor / ChecklistLog / TemperatureLog components already have the
// full predicates — generalize and hoist when v2 lands.

const DailyReport = ({ payAnchor }) => {
  // periodOffset: 0 = current period, -1 = previous, +1 = next, etc.
  const [periodOffset, setPeriodOffset] = useState(0);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  // Anchor not loaded yet — App is still bootstrapping or column was
  // somehow NULL (shouldn't happen post-migration, but be defensive).
  if (!payAnchor || !window.getPayPeriod) {
    return (
      <div className="portal-page-wide" style={{ maxWidth: 1080 }}>
        <div className="portal-page-header">
          <h1 className="portal-page-title">Daily Report</h1>
        </div>
        <div className="portal-card" style={{ padding: 36, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
          Waiting for pay period setting to load…
        </div>
      </div>
    );
  }

  // Pick a date inside the target period — start with today, then shift
  // by 14*offset. getPayPeriod snaps to the period containing the date,
  // so this is robust to month boundaries.
  const today = new Date();
  const refDate = new Date(today);
  refDate.setDate(refDate.getDate() + periodOffset * 14);
  const period = window.getPayPeriod(payAnchor, refDate);
  const startISO = isoDate(period.start);
  const endISO = isoDate(period.end);
  const todayISO = isoDate(today);

  useEffect(() => {
    if (!window.supa) return;
    let cancelled = false;
    setLoading(true);
    Promise.all([
      window.supa.from('prep_completions').select('the_date').gte('the_date', startISO).lte('the_date', endISO).eq('restaurant_id', window.RESTAURANT_ID),
      window.supa.from('checklist_completions').select('the_date').gte('the_date', startISO).lte('the_date', endISO).eq('restaurant_id', window.RESTAURANT_ID),
      window.supa.from('temperature_logs').select('the_date, finalized_at').gte('the_date', startISO).lte('the_date', endISO).eq('restaurant_id', window.RESTAURANT_ID),
    ]).then(([prepR, checkR, tempR]) => {
      if (cancelled) return;
      const prepDays = new Set((prepR.data || []).map(r => r.the_date));
      const checkDays = new Set((checkR.data || []).map(r => r.the_date));
      const tempDays = new Set((tempR.data || []).filter(r => r.finalized_at).map(r => r.the_date));
      setData({ prepDays, checkDays, tempDays });
      setLoading(false);
    }).catch(e => {
      if (cancelled) return;
      console.error('DailyReport load failed', e);
      setLoading(false);
    });
    return () => { cancelled = true; };
  }, [startISO, endISO]);

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1080 }}>
      <div className="portal-page-header">
        <div>
          <h1 className="portal-page-title">Daily Report</h1>
          <div className="portal-page-subtitle">
            Bi-weekly completion overview — Daily Prep, Daily Checklist, and Temperature Log per day. Use this to spot missed days for bonus calculations.
          </div>
        </div>
        <PeriodNav period={period} offset={periodOffset} onOffsetChange={setPeriodOffset} />
      </div>

      <div className="portal-card" style={{ padding: 0, marginTop: 18 }}>
        {loading ? (
          <div style={{ padding: 36, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Loading…</div>
        ) : !data ? (
          <div style={{ padding: 36, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Couldn't load report data.</div>
        ) : (
          <ReportTable period={period} data={data} todayISO={todayISO} />
        )}
      </div>

      <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 14, lineHeight: 1.6, maxWidth: 720 }}>
        <b style={{ color: 'var(--fg-2)' }}>v1 heuristic:</b> A module is marked ✓ when at least one completion entry exists for that day (the crew engaged with the module). Future dates show as — to distinguish "not yet happened" from "missed." Percent-of-target completion is planned for a future release; for now, drill into the relevant page (Daily Prep / Daily Checklist / Temperature Log) to see exact item-level detail for any flagged day.
      </div>
    </div>
  );
};

// Period navigator: ← Previous · current period chip · Next →
const PeriodNav = ({ period, offset, onOffsetChange }) => {
  const label = `${fmtDate(period.start)} – ${fmtDate(period.end)}`;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
      <PBtn variant="secondary" size="sm" icon="chevronL" onClick={() => onOffsetChange(offset - 1)} title="Previous period" />
      <div style={{
        padding: '6px 14px',
        background: 'var(--bg-surface)',
        border: '1px solid var(--border-1)',
        borderRadius: 8,
        fontSize: 12.5, fontWeight: 500,
        minWidth: 220, textAlign: 'center',
        whiteSpace: 'nowrap',
      }}>
        <span style={{ color: 'var(--fg-3)', marginRight: 8 }}>Period #{period.index}</span>
        {label}
      </div>
      <PBtn variant="secondary" size="sm" icon="chevronR" onClick={() => onOffsetChange(offset + 1)} title="Next period" />
      {offset !== 0 && (
        <PBtn variant="ghost" size="sm" onClick={() => onOffsetChange(0)}>Today</PBtn>
      )}
    </div>
  );
};

const ReportTable = ({ period, data, todayISO }) => {
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{
        width: '100%', borderCollapse: 'collapse',
        fontSize: 13,
      }}>
        <thead>
          <tr style={{ background: 'var(--bg-sunken)', borderBottom: '1px solid var(--border-1)' }}>
            <th style={drThStyle({ width: 130, textAlign: 'left' })}>Date</th>
            <th style={drThStyle({ width: 130 })}>Daily Prep</th>
            <th style={drThStyle({ width: 140 })}>Daily Checklist</th>
            <th style={drThStyle({ width: 150 })}>Temperature Log</th>
          </tr>
        </thead>
        <tbody>
          {period.days.map(d => {
            const iso = isoDate(d);
            const isFuture = iso > todayISO;
            const isToday = iso === todayISO;
            return (
              <tr key={iso} style={{
                borderBottom: '1px solid var(--border-2)',
                background: isToday ? 'rgba(255, 200, 0, 0.04)' : 'transparent',
              }}>
                <td style={tdStyle()}>
                  <div style={{ fontWeight: 500, color: isFuture ? 'var(--fg-3)' : 'var(--fg-1)' }}>
                    {fmtDate(d)}
                  </div>
                  {isToday && (
                    <div style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 2 }}>
                      Today
                    </div>
                  )}
                </td>
                <td style={tdStyle({ textAlign: 'center' })}>
                  <StatusCell done={data.prepDays.has(iso)} future={isFuture} />
                </td>
                <td style={tdStyle({ textAlign: 'center' })}>
                  <StatusCell done={data.checkDays.has(iso)} future={isFuture} />
                </td>
                <td style={tdStyle({ textAlign: 'center' })}>
                  <StatusCell done={data.tempDays.has(iso)} future={isFuture} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

const StatusCell = ({ done, future }) => {
  if (future) {
    return <span style={{ color: 'var(--fg-3)', fontSize: 16, fontFamily: 'var(--font-num)' }}>—</span>;
  }
  if (done) {
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 26, height: 26, borderRadius: 999,
        background: '#DCFCE7', color: '#166534',
      }}>
        <PIcon name="check" size={15} strokeWidth={2.5} />
      </span>
    );
  }
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 26, height: 26, borderRadius: 999,
      background: '#FEE2E2', color: '#991B1B',
    }}>
      <PIcon name="x" size={15} strokeWidth={2.5} />
    </span>
  );
};

const drThStyle = (extra) => ({
  padding: '12px 16px',
  fontSize: 11,
  fontWeight: 600,
  letterSpacing: '0.06em',
  textTransform: 'uppercase',
  color: 'var(--fg-3)',
  textAlign: 'center',
  ...extra,
});

const tdStyle = (extra) => ({
  padding: '12px 16px',
  verticalAlign: 'middle',
  ...extra,
});

window.DailyReport = DailyReport;
