/* How loaded each editor is, week by week.

   The rule: two short videos a day or one long one, Monday to Saturday. So a
   short video costs half a day, a long one a full day, and the cap is six days
   a week. A task lands in the week of its deadline — work with no deadline
   cannot be placed and is called out separately, because unplanned work is
   exactly what blows a week up. */

function WeekCell({ week, capacity, onOpen, directory }) {
  const used = week.days;
  const pct = capacity ? Math.min(100, (used / capacity) * 100) : 0;
  const over = used > capacity;
  const tight = !over && used >= capacity * 0.85;
  const tone = over ? 'var(--red)' : tight ? 'var(--amber)' : 'var(--green)';
  return (
    <div className={'load-cell' + (over ? ' over' : '')}>
      <div className="row" style={{ gap: 5, marginBottom: 5 }}>
        <strong style={{ color: used ? tone : 'var(--text-dim)', fontSize: 15 }}>
          {used % 1 === 0 ? used : used.toFixed(1)}
        </strong>
        <span className="small muted">/ {capacity} days</span>
        {over && <span className="chip red">+{(used - capacity).toFixed(1)}</span>}
      </div>
      <div className="load-bar">
        <div style={{ width: `${pct}%`, background: tone }} />
      </div>
      <div className="load-tasks">
        {week.tasks.map((t) => {
          const client = directory.byId[t.client_id];
          return (
            <div key={t.id} className="load-task" onClick={() => onOpen(t.id)}
                 title={`${t.title} · ${t.days} ${t.days === 1 ? 'day' : 'days'} · due ${t.due_date}`}>
              <span className="dot" style={{ background: STATUS_COLORS[t.status] }} />
              <span className="load-task-text">
                {client ? client.name : '—'} · {t.quantity > 1 ? `${t.quantity}× ` : ''}{t.video_length === 'long' ? 'long' : 'short'}
              </span>
              <span className="small muted">{t.days}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function WorkloadScreen({ go, directory }) {
  const [data, setData] = React.useState(null);
  const [start, setStart] = React.useState(null);

  const load = React.useCallback(() => {
    const qs = start ? `?start=${start}&weeks=4` : '?weeks=4';
    api.get('/api/workload' + qs).then(setData).catch((e) => toast(e.message, 'error'));
  }, [start]);
  React.useEffect(load, [load]);

  if (!data) return <div className="empty">Loading…</div>;

  if (!data.people.length) {
    return (
      <EmptyState
        title="Nobody is capacity-tracked yet"
        hint="Set the weekly capacity in days on the people who cut video, from Team. Six days means Monday to Saturday."
        action={<button className="btn primary" onClick={() => go('team')}>Open Team</button>}
      />
    );
  }

  const shift = (n) => {
    const d = new Date((start || data.start) + 'T00:00:00');
    d.setDate(d.getDate() + n * 7);
    setStart(iso(d));
  };
  const weekLabel = (k) => {
    const d = new Date(k + 'T00:00:00');
    const end = new Date(d); end.setDate(end.getDate() + 5); // Monday to Saturday
    const fmt = (x) => x.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
    return `${fmt(d)} – ${fmt(end)}`;
  };
  const thisWeekKey = data.weeks.find((k) => {
    const d = new Date(k + 'T00:00:00');
    const t = new Date(data.today + 'T00:00:00');
    return t >= d && t < new Date(d.getTime() + 7 * 86400000);
  });

  return (
    <>
      <div className="filters">
        <button className="btn sm" onClick={() => shift(-1)}>←</button>
        <button className="btn sm" onClick={() => setStart(null)}>This week</button>
        <button className="btn sm" onClick={() => shift(1)}>→</button>
        <span className="small muted">
          Two short videos a day or one long one, Monday to Saturday. A task counts in the week of its deadline.
        </span>
      </div>

      <div className="card" style={{ overflowX: 'auto' }}>
        <table className="list load-table">
          <thead>
            <tr>
              <th style={{ minWidth: 150 }}>Editor</th>
              {data.weeks.map((k) => (
                <th key={k} style={{ minWidth: 190 }}>
                  {weekLabel(k)}{k === thisWeekKey ? ' · this week' : ''}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.people.map((p) => (
              <tr key={p.id} style={{ cursor: 'default' }}>
                <td style={{ verticalAlign: 'top' }}>
                  <div className="row">
                    <Avatar user={{ name: p.name }} />
                    <div>
                      <div style={{ fontWeight: 600 }}>{p.name}</div>
                      <div className="small muted">{p.job_title || 'Editor'} · cap {p.capacity}/week</div>
                    </div>
                  </div>
                  {p.unscheduled.length > 0 && (
                    <div className="chip amber" style={{ marginTop: 8 }}
                         title={p.unscheduled.map((t) => t.title).join('\n')}>
                      {p.unscheduled.reduce((a, t) => a + t.days, 0)} days with no deadline
                    </div>
                  )}
                </td>
                {data.weeks.map((k) => (
                  <td key={k} style={{ verticalAlign: 'top' }}>
                    <WeekCell week={p.weeks[k]} capacity={p.capacity} directory={directory}
                              onOpen={(id) => go('task', id)} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p className="small muted" style={{ marginTop: 12 }}>
        Only video counts against the cap, and published ads drop out. A batch task
        multiplies: three short videos in one task is a day and a half.
      </p>
    </>
  );
}
