/* Dump — datepicker.jsx: unified inline scheduling panel.
   ONE action: pick a day, optionally add a time, optionally sync to Google.
   No Appointment/This day/Reminder taxonomy. Feels like part of the card —
   an inline expansion, not a modal. Used by the card's ··· → Date and by
   tapping an existing due-date chip. Exposed as window.DatePickerPanel. */

const DP_DOW = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
const DP_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'];
const DP_FULL_DOW = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const DP_LETTER = { 0: 'S', 1: 'M', 2: 'T', 3: 'W', 4: 'T', 5: 'F', 6: 'S' };
const DP_WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday-first day pills

function dpIso(d) {
  return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function dpParse(s) { return new Date(s + 'T12:00:00'); }
function dpGridStart(y, m) {
  const first = new Date(y, m, 1, 12);
  const offset = (first.getDay() + 6) % 7; // Monday-first
  const start = new Date(first);
  start.setDate(first.getDate() - offset);
  return start;
}

function DatePickerPanel({ task, onPatch, onClose }) {
  const { google, anchors } = useDumpStore();
  const todayIso = DumpUtil.todayISO();
  const init = task.dueDate ? dpParse(task.dueDate) : new Date();
  const [view, setView] = useState({ y: init.getFullYear(), m: init.getMonth() });
  const [showTime, setShowTime] = useState(!!task.time);
  /* local copies so anchor check reacts immediately without relying on prop updates */
  const [localTime, setLocalTime] = useState(task.time || '');
  const [localDate, setLocalDate] = useState(task.dueDate || null);

  /* anchor conflict — fully local, no prop or window dependency */
  let anchorConflict = null;
  if (localTime && localDate) {
    const tp = localTime.split(':');
    const timeMin = (parseInt(tp[0], 10) || 0) * 60 + (parseInt(tp[1], 10) || 0);
    const dow = dpParse(localDate).getDay();
    for (const a of (anchors || [])) {
      if (!Array.isArray(a.days) || !a.days.includes(dow) || !a.time) continue;
      const ap = a.time.split(':');
      const aStart = (parseInt(ap[0], 10) || 0) * 60 + (parseInt(ap[1], 10) || 0);
      if (timeMin >= aStart && timeMin < aStart + (a.duration || 30)) { anchorConflict = a; break; }
    }
  }

  const selected = task.dueDate || null;
  const syncOn = task.syncGoogle !== false; // on by default

  // Escape closes the panel. Edits save live via onPatch, so dismissing is
  // equivalent to Done. (Deliberately NO click-outside listener: an inline
  // panel lives inside a scroll container, so a mousedown on the scrollbar
  // would count as "outside" and close it mid-scroll. The header ✕ + Escape
  // are the close affordances instead.)
  const panelRef = useRef(null);
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const gridStart = dpGridStart(view.y, view.m);
  const cells = Array.from({ length: 42 }, (_, i) => {
    const d = new Date(gridStart);
    d.setDate(gridStart.getDate() + i);
    return d;
  });

  const stepMonth = (dir) => setView((v) => {
    const d = new Date(v.y, v.m + dir, 1);
    return { y: d.getFullYear(), m: d.getMonth() };
  });
  const pick = (d) => {
    const iso = dpIso(d);
    setLocalDate(iso);
    const patch = { dueDate: iso };
    if (task.recurrence && task.recurrence.frequency === 'weekly') {
      patch.recurrence = { frequency: 'weekly', days: [d.getDay()], endDate: null };
    }
    onPatch(patch);
  };
  const clearDate = () => { setLocalDate(null); setLocalTime(''); onPatch({ dueDate: null, time: null, recurrence: null, trackDaily: false }); setShowTime(false); };

  // ----- Repeats -----
  const rec = task.recurrence || null;
  const mode = !rec ? 'never' : rec.frequency;
  const selDow = selected ? dpParse(selected).getDay() : null;
  const setMode = (m) => {
    if (m === 'never') return onPatch({ recurrence: null, trackDaily: false });
    if (m === 'daily') return onPatch({ recurrence: { frequency: 'daily', days: [0, 1, 2, 3, 4, 5, 6], endDate: null } });
    if (m === 'weekly') return onPatch({ recurrence: { frequency: 'weekly', days: [selDow], endDate: null } });
    // custom: keep existing chosen days, else sensible weekday default
    const days = (rec && rec.days && rec.days.length) ? rec.days.slice() : [1, 2, 3, 4, 5];
    return onPatch({ recurrence: { frequency: 'custom', days: days, endDate: null } });
  };
  const toggleDay = (d) => {
    const days = (rec && rec.days) ? rec.days.slice() : [];
    const i = days.indexOf(d);
    if (i === -1) days.push(d); else days.splice(i, 1);
    days.sort((a, b) => a - b);
    onPatch({ recurrence: { frequency: 'custom', days: days, endDate: null } });
  };

  return (
    <div className="edit-panel dp" ref={panelRef} onClick={(e) => e.stopPropagation()}>
      <div className="dp-cal-head">
        <span className="dp-month">{DP_MONTHS[view.m]} {view.y}</span>
        <span className="dp-nav">
          <button className="dp-nav-btn" onClick={() => stepMonth(-1)} aria-label="Previous month">{Icons.chevL(15)}</button>
          <button className="dp-nav-btn" onClick={() => stepMonth(1)} aria-label="Next month">{Icons.chevR(15)}</button>
          <button className="dp-close-btn" onClick={onClose} aria-label="Close">{Icons.x(15)}</button>
        </span>
      </div>

      <div className="dp-grid">
        {DP_DOW.map((d) => <span key={d} className="dp-dow">{d}</span>)}
        {cells.map((d, i) => {
          const iso = dpIso(d);
          const cls = 'dp-day'
            + (d.getMonth() === view.m ? '' : ' other')
            + (iso === todayIso ? ' today' : '')
            + (iso === selected ? ' selected' : '');
          return <button key={i} className={cls} onClick={() => pick(d)}>{d.getDate()}</button>;
        })}
      </div>

      {selected ? (
        showTime ? (
          <div>
            <div className="dp-time-row">
              <label>Time</label>
              <input type="time" value={localTime}
                onChange={(e) => { const v = e.target.value || ''; setLocalTime(v); onPatch({ time: v || null }); }} />
              {localTime ? <button className="linklike" onClick={() => { setLocalTime(''); onPatch({ time: null }); }}>remove</button> : null}
            </div>
            {localTime ? <p className="dp-commit-note">This will appear on your calendar as a commitment.</p> : null}
            {anchorConflict ? <p className="dp-anchor-warn">↔ This overlaps with your {anchorConflict.name} anchor.</p> : null}
          </div>
        ) : (
          <button className="linklike dp-add-time" onClick={() => setShowTime(true)}>+ Add a time?</button>
        )
      ) : null}

      {selected ? (
        <div className="dp-repeat">
          <div className="dp-repeat-head">
            <span className="dp-repeat-label">{Icons.repeat(13)} Repeats</span>
            <span className="dp-repeat-seg">
              {[['never', 'Never'], ['daily', 'Daily'], ['weekly', 'Weekly'], ['custom', 'Custom']].map(([v, l]) => (
                <button key={v} className={mode === v ? 'active' : ''} onClick={() => setMode(v)}>{l}</button>
              ))}
            </span>
          </div>
          {mode === 'weekly' ? (
            <p className="dp-repeat-note">Every {DP_FULL_DOW[(rec && rec.days && rec.days.length) ? rec.days[0] : selDow]}</p>
          ) : null}
          {mode === 'custom' ? (
            <div className="dp-day-pills">
              {DP_WEEK_ORDER.map((d) => (
                <button key={d}
                  className={'dp-day-pill' + (rec && rec.days && rec.days.indexOf(d) !== -1 ? ' on' : '')}
                  onClick={() => toggleDay(d)}>{DP_LETTER[d]}</button>
              ))}
            </div>
          ) : null}
          {rec ? (
            <div className="dp-track">
              <label className="dp-track-row" onClick={() => onPatch({ trackDaily: !task.trackDaily })}>
                <span className={'switch' + (task.trackDaily ? ' on' : '')}></span>
                <span className="dp-track-main">Track each day</span>
              </label>
              <p className="dp-track-note">{task.trackDaily
                ? 'Lives on Today as a daily check — tick it each day, see your streak and any missed days. A memory aid, not an alarm.'
                : 'Turn on for things like meds or vitamins — checks each day, so a missed day shows instead of hiding.'}</p>
            </div>
          ) : null}
        </div>
      ) : null}

      {selected && google.connected ? (
        <label className="dp-sync" onClick={() => onPatch({ syncGoogle: !syncOn })}>
          <span className={'switch' + (syncOn ? ' on' : '')}></span>
          <span>Sync to Google Calendar</span>
        </label>
      ) : null}

      <div className="dp-foot">
        <button className="btn btn-primary btn-sm" onClick={onClose}>Done</button>
        {selected ? <button className="linklike" onClick={clearDate}>Clear date</button> : null}
      </div>
    </div>
  );
}

window.DatePickerPanel = DatePickerPanel;
