// History.jsx — Daily prep log + broadcast acks (read-only).
// Each row = one event: who, when, what.

const History = () => {
  const [tab, setTab] = useState('prep');
  const [date, setDate] = useState(() => { const d = new Date(); d.setDate(d.getDate() - 1); return d; });

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1280 }}>
      <div className="portal-page-header">
        <div>
          <h1 className="portal-page-title">History</h1>
          <div className="portal-page-subtitle">Read-only event log of every prep completion and broadcast acknowledgement.</div>
        </div>
        <PBtn variant="secondary" icon="download" onClick={() => alert('Exported CSV: history-' + isoDate(date) + '.csv')}>Export</PBtn>
      </div>

      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 18 }}>
        <PSegment
          value={tab} onChange={setTab}
          options={[
            { value: 'prep', label: 'Daily prep log' },
            { value: 'acks', label: 'Broadcast acks' },
          ]}
        />
        <div style={{ flex: 1 }} />
        <PDatePicker value={date} onChange={setDate} />
      </div>

      {tab === 'prep' && <PrepLogView date={date} />}
      {tab === 'acks' && <AckLogView date={date} />}
    </div>
  );
};

// ---------------------------------------------------------------------
// Daily prep log — one row per completion event
// ---------------------------------------------------------------------
const PrepLogView = ({ date }) => {
  const items   = window.SAMPLE_PREP_ITEMS.filter(i => i.target > 0);
  const seed    = date.getDate() + date.getMonth() * 31;
  const staffPool = ['mei', 'jorge', 'bo', 'ana', 'luis', 'tina'];

  // Build a synthetic event log: each item gets logged in 1–3 chunks
  // by 1–2 different people, scattered across the prep window.
  const events = [];
  items.forEach((item, idx) => {
    const variance  = ((seed + idx * 7) % 5) - 2;
    const completed = Math.max(0, Math.min(item.target + 1, item.target + variance));
    if (completed === 0) return;

    const numChunks = ((seed + idx) % 3) + 1; // 1..3
    let remaining = completed;
    for (let c = 0; c < numChunks && remaining > 0; c++) {
      const isLast = c === numChunks - 1;
      const qty = isLast ? remaining : Math.max(1, Math.floor(remaining / (numChunks - c)));
      remaining -= qty;
      const staffId = staffPool[(seed + idx + c * 3) % staffPool.length];
      const hour    = 7 + ((seed + idx + c) % 6);
      const minute  = (seed * 13 + idx * 7 + c * 19) % 60;
      events.push({
        time: `${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`,
        staffId,
        item,
        qty,
      });
    }
  });

  events.sort((a, b) => a.time.localeCompare(b.time));

  return (
    <div className="portal-card">
      <table className="portal-table">
        <thead>
          <tr>
            <th style={{ width: 90 }}>Time</th>
            <th style={{ width: 220 }}>Person</th>
            <th>Item</th>
            <th style={{ width: 110, textAlign: 'right' }}>Quantity</th>
          </tr>
        </thead>
        <tbody>
          {events.length === 0 && (
            <tr>
              <td colSpan={4} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
                No prep activity logged on this date.
              </td>
            </tr>
          )}
          {events.map((e, i) => {
            const staff = window.SAMPLE_STAFF.find(s => s.id === e.staffId);
            return (
              <tr key={i}>
                <td style={{ fontSize: 12.5, fontVariantNumeric: 'tabular-nums', color: 'var(--fg-2)' }}>{e.time}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <PAvatar staff={staff} size={22} />
                    <span style={{ fontWeight: 500, fontSize: 13 }}>{staff?.name || e.staffId}</span>
                  </div>
                </td>
                <td style={{ fontSize: 13, fontWeight: 500 }}>{e.item.name}</td>
                <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 500, fontSize: 13 }}>+{e.qty}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

// ---------------------------------------------------------------------
// Broadcast acks — one row per acknowledgement event
// ---------------------------------------------------------------------
const AckLogView = ({ date }) => {
  const broadcasts = [
    { id: 'b1', title: 'Walk-in cooler door — keep firmly shut',   acks: ['mei','jorge','bo','tina','ana'] },
    { id: 'b2', title: 'New cabbage prep technique',                acks: ['mei','jorge','bo'] },
    { id: 'b3', title: 'Reminder: log every batch on the iPad',     acks: ['mei','luis'] },
  ];
  const seed = date.getDate() + date.getMonth() * 31;

  // Flatten broadcasts × acks into individual events
  const events = [];
  broadcasts.forEach((b, bi) => {
    b.acks.forEach((staffId, ai) => {
      const hour   = 8 + ((seed + bi * 3 + ai) % 9);
      const minute = (seed * 17 + bi * 13 + ai * 11) % 60;
      events.push({
        time: `${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`,
        staffId,
        broadcast: b.title,
      });
    });
  });

  events.sort((a, b) => a.time.localeCompare(b.time));

  return (
    <div className="portal-card">
      <table className="portal-table">
        <thead>
          <tr>
            <th style={{ width: 90 }}>Time</th>
            <th style={{ width: 220 }}>Person</th>
            <th>Broadcast</th>
          </tr>
        </thead>
        <tbody>
          {events.length === 0 && (
            <tr>
              <td colSpan={3} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
                No broadcasts acknowledged on this date.
              </td>
            </tr>
          )}
          {events.map((e, i) => {
            const staff = window.SAMPLE_STAFF.find(s => s.id === e.staffId);
            return (
              <tr key={i}>
                <td style={{ fontSize: 12.5, fontVariantNumeric: 'tabular-nums', color: 'var(--fg-2)' }}>{e.time}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <PAvatar staff={staff} size={22} />
                    <span style={{ fontWeight: 500, fontSize: 13 }}>{staff?.name || e.staffId}</span>
                  </div>
                </td>
                <td style={{ fontSize: 13, color: 'var(--fg-1)' }}>{e.broadcast}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

window.History = History;
