/* ---------- Date range picker (calendar popover with presets) ---------- */
function DateRangePicker({ from, to, onChange }) {
  const { useState, useEffect, useRef } = React;
  const TODAY = new Date(2026, 6, 27);
  const [open, setOpen] = useState(false);
  const [view, setView] = useState(new Date(2026, 6, 1)); // first visible month
  const [anchor, setAnchor] = useState(null); // pending range start (Date)
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    window.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDoc); window.removeEventListener("keydown", onKey); };
  }, [open]);

  const iso = (d) => d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
  const parse = (s) => (s ? new Date(s + "T00:00:00") : null);
  const fmt = (s) => { const d = parse(s); return d ? d.toLocaleDateString(uiLocale(), { month: "short", day: "numeric", year: "numeric" }) : null; };
  const fromD = parse(from), toD = parse(to);

  const commit = (a, b) => { onChange(iso(a <= b ? a : b), iso(a <= b ? b : a)); setAnchor(null); };
  const pick = (d) => {
    if (!anchor) { setAnchor(d); onChange(iso(d), ""); }
    else commit(anchor, d);
  };
  const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
  const monWeekStart = (d) => addDays(d, -((d.getDay() + 6) % 7));
  const presets = [
    { id: "today", label: T("date.today"), get: () => [TODAY, TODAY] },
    { id: "yesterday", label: T("date.yesterday"), get: () => [addDays(TODAY, -1), addDays(TODAY, -1)] },
    { id: "last7", label: T("date.last7Days"), get: () => [addDays(TODAY, -6), TODAY] },
    { id: "lastWeek", label: T("date.lastWeek"), get: () => { const s = addDays(monWeekStart(TODAY), -7); return [s, addDays(s, 6)]; } },
    { id: "last2Weeks", label: T("date.last2Weeks"), get: () => { const s = addDays(monWeekStart(TODAY), -14); return [s, addDays(s, 13)]; } },
    { id: "thisMonth", label: T("date.thisMonth"), get: () => [new Date(TODAY.getFullYear(), TODAY.getMonth(), 1), TODAY] },
    { id: "lastMonth", label: T("date.lastMonth"), get: () => [new Date(TODAY.getFullYear(), TODAY.getMonth() - 1, 1), new Date(TODAY.getFullYear(), TODAY.getMonth(), 0)] }
  ];
  const activePreset = presets.find((p) => { const [a, b] = p.get(); return from === iso(a) && to === iso(b); });

  const inRange = (d) => {
    const a = anchor || fromD, b = anchor ? null : toD;
    if (a && b) return d >= a && d <= b;
    if (a) return +d === +a;
    return false;
  };
  const isEdge = (d) => (fromD && +d === +fromD) || (toD && +d === +toD) || (anchor && +d === +anchor);

  const Month = ({ base }) => {
    const y = base.getFullYear(), m = base.getMonth();
    const first = new Date(y, m, 1);
    const start = monWeekStart(first);
    const cells = Array.from({ length: 42 }, (_, i) => addDays(start, i));
    return (
      <div className="drp-month">
        <div className="drp-mlabel"><b>{base.toLocaleDateString(uiLocale(), { month: "long" })}</b> {y}</div>
        <div className="drp-grid">
          {Array.from({ length: 7 }, (_, i) => addDays(monWeekStart(first), i)).map((d, i) => (
            <span key={i} className="drp-dow">{d.toLocaleDateString(uiLocale(), { weekday: "short" })}</span>
          ))}
          {cells.map((d, i) => {
            const out = d.getMonth() !== m;
            return (
              <button key={i} type="button"
                className={"drp-day" + (out ? " out" : "") + (inRange(d) ? " in" : "") + (isEdge(d) ? " edge" : "") + (+d === +TODAY ? " today" : "")}
                onClick={() => pick(d)}>{d.getDate()}</button>
            );
          })}
        </div>
      </div>
    );
  };

  const label = from && to ? fmt(from) + " – " + fmt(to) : from ? fmt(from) + " – …" : T("date.allDates");
  const shift = (n) => setView((v) => new Date(v.getFullYear(), v.getMonth() + n, 1));

  return (
    <div className="drp" ref={ref}>
      <button type="button" className={"drp-btn" + (open ? " on" : "")} onClick={() => setOpen((o) => !o)}>
        <Icon name="calendar" size={15} />
        <span className={from ? "" : "dim"}>{label}</span>
      </button>
      {open ? (
        <div className="drp-pop">
          <div className="drp-presets">
            {presets.map((p) => (
              <button key={p.id} type="button" className={"drp-preset" + (activePreset && activePreset.id === p.id ? " on" : "")}
                onClick={() => { const [a, b] = p.get(); commit(a, b); }}>{p.label}</button>
            ))}
            <button type="button" className="drp-preset drp-clear" onClick={() => { onChange("", ""); setAnchor(null); setOpen(false); }}>{T("common.clear")}</button>
          </div>
          <div className="drp-cals">
            <button type="button" className="drp-nav prev" onClick={() => shift(-1)}><Icon name="chevR" size={14} style={{ transform: "rotate(180deg)" }} /></button>
            <Month base={view} />
            <Month base={new Date(view.getFullYear(), view.getMonth() + 1, 1)} />
            <button type="button" className="drp-nav next" onClick={() => shift(1)}><Icon name="chevR" size={14} /></button>
          </div>
        </div>
      ) : null}
    </div>
  );
}
window.DateRangePicker = DateRangePicker;
