// doing-days.jsx — after a task is taken out of doing (back to to do or backlog), ask which of
// the days it sat there were really spent on it. The days left unticked come off standup's
// doing lists (api/doing-days on the server; it offers the days, see doingRun there).

// ask: { taskId, title, days: ['YYYY-MM-DD', …] (oldest first), onSave(remove) }: onSave gets the
// unticked days, and takes them off (straight away, or when the task panel is saved)
function DoingDaysModal({ ask, onClose }) {
  const [picked, setPicked] = React.useState(() => new Set(ask.days)); // all ticked: closing changes nothing
  // Esc closes this, not the task panel underneath it as well
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); onClose(); } };
    window.addEventListener('keydown', onKey, true);
    return () => window.removeEventListener('keydown', onKey, true);
  }, [onClose]);
  const offered = new Set(ask.days);
  const parse = (s) => { const [y, m, d] = s.split('-').map(Number); return new Date(y, m - 1, d); };
  const key = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;

  // whole weeks, Monday first, from the first day offered to the last
  const first = parse(ask.days[0]), last = parse(ask.days[ask.days.length - 1]);
  const start = new Date(first); start.setDate(start.getDate() - (start.getDay() + 6) % 7);
  const weeks = [];
  for (const d = new Date(start); d <= last; ) {
    const week = [];
    for (let i = 0; i < 7; i++, d.setDate(d.getDate() + 1)) week.push(new Date(d));
    weeks.push(week);
  }

  const toggle = (k) => setPicked(p => { const n = new Set(p); n.has(k) ? n.delete(k) : n.add(k); return n; });
  const save = () => {
    const remove = ask.days.filter(d => !picked.has(d));
    if (remove.length) ask.onSave(remove);
    onClose();
  };

  return (
    <div className="nb-help-overlay" style={{ zIndex: 350 }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="nb-help-modal" style={{ maxWidth: 440 }} role="dialog" aria-labelledby="dd-title">
        <div className="nb-help-header">
          <div id="dd-title" style={{ fontFamily: 'var(--hand)', fontSize: 26, color: 'var(--ink)' }}>Dates worked on...</div>
          <button className="nb-help-close" onClick={onClose} title="close (Esc)">✕</button>
        </div>
        <p className="dd-sub"><b>{ask.title}</b> was in doing on the selected days. Please deselect the dates
          you did not work on this task.</p>
        <div className="dd-month">
          {[...new Set([first, last].map(d => d.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' })))].join(' – ')}
        </div>
        <div className="dd-cal">
          {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((x, i) => <div key={i} className="dd-dow">{x}</div>)}
          {weeks.flat().map(d => {
            const k = key(d);
            if (!offered.has(k)) return <div key={k} className="dd-day is-off">{d.getDate()}</div>;
            return (
              <button key={k} className={`dd-day ${picked.has(k) ? 'is-on' : ''}`} onClick={() => toggle(k)}
                aria-pressed={picked.has(k)} title={d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })}>
                {d.getDate()}
              </button>
            );
          })}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 }}>
          <button className="nb-btn" onClick={onClose}>keep all</button>
          <button className="nb-btn accent" onClick={save} autoFocus>save</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DoingDaysModal });
