// calendar.jsx — custom date-range picker + the unified date filter.
const { useState: useStateCal, useRef: useRefCal, useEffect: useEffectCal } = React;

// ---- one month grid --------------------------------------------------------
function MonthGrid({ year, month, from, to, hover, onPick, onHover }) {
  const first = new Date(year, month, 1);
  const startDow = (first.getDay() + 6) % 7; // Mon-first
  const days = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);

  const iso = (d) => window.toISO(new Date(year, month, d));
  const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
  const rangeEnd = to || hover;

  const dayState = (d) => {
    const s = iso(d);
    if (from && s === from) return 'start';
    if (to && s === to) return 'end';
    if (from && rangeEnd) {
      const lo = from < rangeEnd ? from : rangeEnd;
      const hi = from < rangeEnd ? rangeEnd : from;
      if (s > lo && s < hi) return 'mid';
      if (s === lo || s === hi) return 'edge';
    }
    return '';
  };

  const todayISO = window.toISO(new Date(2026, 4, 28));

  return (
    <div className="cal-month">
      <div className="cal-month-label">{window.MONTHS[month]} {year}</div>
      <div className="cal-dow">{['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <span key={i}>{d}</span>)}</div>
      <div className="cal-grid">
        {cells.map((d, i) => {
          if (d === null) return <span key={i} className="cal-empty" />;
          const st = dayState(d);
          const s = iso(d);
          return (
            <button
              key={i}
              className={'cal-day' + (st ? ' is-' + st : '') + (s === todayISO ? ' is-today' : '')}
              onClick={() => onPick(s)}
              onMouseEnter={() => onHover(s)}
            >
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---- range calendar (two months + presets) ---------------------------------
function RangeCalendar({ value, onApply, onClose }) {
  const init = value && value.from ? window.parseISO(value.from) : new Date(2026, 4, 1);
  const [view, setView] = useStateCal({ y: init.getFullYear(), m: init.getMonth() });
  const [from, setFrom] = useStateCal(value ? value.from : null);
  const [to, setTo] = useStateCal(value ? value.to : null);
  const [hover, setHover] = useStateCal(null);

  const pick = (s) => {
    if (!from || (from && to)) { setFrom(s); setTo(null); return; }
    if (s < from) { setTo(from); setFrom(s); }
    else setTo(s);
  };

  const shift = (n) => setView((v) => {
    const d = new Date(v.y, v.m + n, 1);
    return { y: d.getFullYear(), m: d.getMonth() };
  });

  const next = new Date(view.y, view.m + 1, 1);

  const presets = [
    { label: 'Last 7 days', days: 7 },
    { label: 'Last 30 days', days: 30 },
    { label: 'Last 90 days', days: 90 },
    { label: 'Year to date', ytd: true },
  ];
  const applyPreset = (p) => {
    const end = new Date(2026, 4, 28);
    let start;
    if (p.ytd) start = new Date(2026, 0, 1);
    else { start = new Date(end); start.setDate(end.getDate() - (p.days - 1)); }
    onApply({ from: window.toISO(start), to: window.toISO(end) });
  };

  const ready = from && to;

  return (
    <div className="cal-pop" onMouseDown={(e) => e.stopPropagation()}>
      <div className="cal-presets">
        {presets.map((p) => (
          <button key={p.label} className="cal-preset" onClick={() => applyPreset(p)}>{p.label}</button>
        ))}
      </div>
      <div className="cal-main">
        <div className="cal-nav">
          <button className="cal-arrow" onClick={() => shift(-1)} aria-label="Previous month">‹</button>
          <button className="cal-arrow" onClick={() => shift(1)} aria-label="Next month">›</button>
        </div>
        <div className="cal-months" onMouseLeave={() => setHover(null)}>
          <MonthGrid year={view.y} month={view.m} from={from} to={to} hover={hover} onPick={pick} onHover={setHover} />
          <MonthGrid year={next.getFullYear()} month={next.getMonth()} from={from} to={to} hover={hover} onPick={pick} onHover={setHover} />
        </div>
        <div className="cal-foot">
          <span className="cal-foot-range">
            {from ? window.fmtRange(from, to || from) : 'Select a start date'}
          </span>
          <div className="cal-foot-btns">
            <button className="cal-btn cal-btn-ghost" onClick={onClose}>Cancel</button>
            <button className="cal-btn cal-btn-primary" disabled={!ready} onClick={() => onApply({ from, to })}>Apply</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- unified date filter (segmented presets + custom) ----------------------
function DateFilter({ period, onPeriod, custom, onCustom }) {
  const [open, setOpen] = useStateCal(false);
  const wrapRef = useRefCal(null);

  useEffectCal(() => {
    if (!open) return;
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  const customActive = period === 'custom';
  const customLabel = customActive && custom ? window.fmtRange(custom.from, custom.to) : 'Custom';

  return (
    <div className="filter-wrap" ref={wrapRef}>
      <div className="seg" role="tablist" aria-label="Date range">
        {window.PERIOD_KEYS.map((k) => (
          <button key={k} role="tab" aria-selected={period === k}
            className={'seg-btn' + (period === k ? ' is-active' : '')}
            onClick={() => { onPeriod(k); setOpen(false); }}>
            {window.PERIODS[k].label}
          </button>
        ))}
        <button
          className={'seg-btn seg-custom' + (customActive ? ' is-active' : '')}
          aria-selected={customActive}
          onClick={() => setOpen((o) => !o)}
        >
          <svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true" className="seg-cal-ic">
            <rect x="2" y="3" width="12" height="11" rx="2" fill="none" stroke="currentColor" strokeWidth="1.3" />
            <line x1="2" y1="6.5" x2="14" y2="6.5" stroke="currentColor" strokeWidth="1.3" />
            <line x1="5.5" y1="1.5" x2="5.5" y2="4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
            <line x1="10.5" y1="1.5" x2="10.5" y2="4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
          </svg>
          {customLabel}
        </button>
      </div>
      {open && (
        <RangeCalendar
          value={custom}
          onClose={() => setOpen(false)}
          onApply={(r) => { onCustom(r); onPeriod('custom'); setOpen(false); }}
        />
      )}
    </div>
  );
}

Object.assign(window, { DateFilter, RangeCalendar });
