/* ============================================================
   P&L App (Lite) · date picker, dropdowns and the period button (brief 29)
   ------------------------------------------------------------
   One of each for the whole page, so every date and every list looks and works the same:
   - DateField: one click opens the calendar (Notion style). Type the date at the top and press
     Enter, or pick a day. Today has a lime ring; the date already in the field is solid green.
   - Dropdown: the job-picker look (white card, lime-soft line under the mouse, a tick on the
     chosen one). Long lists get a search box.
   - PeriodButton: a small "Year to date v" button. The custom range's from / to dates sit INSIDE
     its menu, so they take no room on the page.
   ui.jsx sends Input type="date", Select, FilterSelect and EditCell (date / select) here, so the
   screens did not have to change. The date and period maths are plain functions (no screen),
   checked by pickers.test.js.
   The same file exists for the UK page (pickers.jsx) and Romania (ro/pickers.jsx); only PICK differs.
   ============================================================ */
const PICK = {
  order: 'MDY', sep: '/', typeHint: 'MM/DD/YYYY', weekStart: 0,          // weeks start on Sunday in the US
  days: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],                      // Sunday first, whatever weekStart is
  months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  w: { today: 'Today', clear: 'Clear', choose: 'Choose…', search: 'Search…', none: 'Nothing matches.', pick: 'Pick a date…',
       from: 'From', to: 'To', apply: 'Apply', badDate: 'Type it as MM/DD/YYYY', badRange: 'The start date is after the end date' },
  periods: { ytd: 'Year to date', month: 'This month', lastmonth: 'Last month', quarter: 'This quarter', lastq: 'Last quarter',
             last12: 'Last 12 months', custom: 'Custom range…', year: y => String(y) },
};
// "Jan 1 to Oct 27, 2026" (same year) or "Nov 1, 2025 to Oct 27, 2026"
function pickRangeText(from, to) {
  const part = (iso, withYear) => PICK.monthsShort[+iso.slice(5, 7) - 1] + ' ' + (+iso.slice(8, 10)) + (withYear ? ', ' + iso.slice(0, 4) : '');
  return from.slice(0, 4) === to.slice(0, 4) ? part(from, false) + ' to ' + part(to, true) : part(from, true) + ' to ' + part(to, true);
}

/* ---------- the maths (no screen) ---------- */
function _pickIso(y, m, d) { return new Date(Date.UTC(y, m - 1, d)).toISOString().slice(0, 10); }
// 2026-10-27 -> 10/27/2026 (the way the date is typed on this page)
function pickFmt(iso) {
  if (!iso) return '';
  const [y, m, d] = iso.split('-'), parts = { Y: y, M: m, D: d };
  return PICK.order.split('').map(k => parts[k]).join(PICK.sep);
}
// what a person typed -> 2026-10-27, or null when it is not a real date. Takes / . - and 1-digit days and months.
function pickParse(text) {
  const s = String(text || '').trim();
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return pickValid(+s.slice(0, 4), +s.slice(5, 7), +s.slice(8, 10));
  const bits = s.split(/[\/.\-\s]+/).filter(Boolean);
  if (bits.length !== 3 || bits.some(b => !/^\d+$/.test(b))) return null;
  const v = {}; PICK.order.split('').forEach((k, i) => { v[k] = +bits[i]; });
  if (v.Y < 100) v.Y += 2000;
  return pickValid(v.Y, v.M, v.D);
}
function pickValid(y, m, d) {
  if (!(m >= 1 && m <= 12 && d >= 1 && d <= 31 && y >= 1900 && y <= 2200)) return null;
  const iso = _pickIso(y, m, d);
  return +iso.slice(5, 7) === m ? iso : null;            // 02/30 rolls into March: not a real date
}
// the 42 days a month's grid shows (6 weeks), starting on the page's first day of the week
function pickGrid(y, m) {
  const first = new Date(Date.UTC(y, m - 1, 1)), back = (first.getUTCDay() - PICK.weekStart + 7) % 7;
  return Array.from({ length: 42 }, (_, i) => _pickIso(y, m, 1 - back + i));
}
function _pickLastDay(y, m) { return _pickIso(y, m + 1, 0); }
/* A period as dates. key: ytd | month | lastmonth | quarter | lastq | last12 | year | custom.
   A period never runs past today: "This month" is the 1st to today, a year still running stops at today. */
function periodRange(p, today) {
  const y = +today.slice(0, 4), m = +today.slice(5, 7), q0 = Math.floor((m - 1) / 3) * 3 + 1;
  let from, to = today;
  switch (p && p.key) {
    case 'month': from = _pickIso(y, m, 1); break;
    case 'lastmonth': from = _pickIso(y, m - 1, 1); to = _pickLastDay(y, m - 1); break;
    case 'quarter': from = _pickIso(y, q0, 1); break;
    case 'lastq': from = _pickIso(y, q0 - 3, 1); to = _pickLastDay(y, q0 - 1); break;
    case 'last12': from = _pickIso(y, m - 11, 1); break;
    case 'year': from = p.year + '-01-01'; to = p.year + '-12-31' < today ? p.year + '-12-31' : today; break;
    case 'custom': from = p.from; to = p.to; break;
    default: from = _pickIso(y, 1, 1);
  }
  return { from, to, label: pickRangeText(from, to) };
}
// the months a period touches, as '2026-07' keys (what the month charts draw)
function periodMonths(from, to) {
  const out = []; let y = +from.slice(0, 4), m = +from.slice(5, 7);
  const end = to.slice(0, 7);
  while (out.length < 240) { const k = y + '-' + String(m).padStart(2, '0'); out.push(k); if (k >= end) break; if (++m > 12) { m = 1; y++; } }
  return out;
}
// the name on the period button
function periodName(p, today) {
  if (!p || !p.key || p.key === 'ytd') return PICK.periods.ytd;
  if (p.key === 'year') return PICK.periods.year(p.year);
  if (p.key === 'custom') return periodRange(p, today).label;
  return PICK.periods[p.key];
}

/* ---------- a panel that floats under an element, drawn at the page root ---------- */
// Flips above when there is no room below, stays inside the window. Click outside or Esc closes it.
function PickFloat({ anchorRef, open, onClose, width = 280, align = 'left', children }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState(null);
  React.useEffect(() => {
    if (!open || !anchorRef.current) { setPos(null); return; }
    const place = () => {
      if (!anchorRef.current) return;
      const r = anchorRef.current.getBoundingClientRect(), w = Math.max(width, align === 'stretch' ? r.width : 0);
      const left = Math.max(8, Math.min(align === 'right' ? r.right - w : r.left, window.innerWidth - w - 8));
      const below = window.innerHeight - r.bottom;
      setPos({ left, width: w, ...(below < 360 && r.top > below ? { bottom: window.innerHeight - r.top + 6 } : { top: r.bottom + 6 }) });
    };
    place();
    // follow the button when the page or a table scrolls, or the window changes size
    window.addEventListener('scroll', place, true); window.addEventListener('resize', place);
    return () => { window.removeEventListener('scroll', place, true); window.removeEventListener('resize', place); };
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    // a click inside ANY floating panel does not close this one: the period menu holds date fields whose calendars float too
    const away = e => { if (e.target.closest && e.target.closest('[data-pick-float]')) return; if (anchorRef.current && anchorRef.current.contains(e.target)) return; onClose(); };
    const esc = e => { if (e.key === 'Escape') { e.stopPropagation(); onClose(); } };
    const t = setTimeout(() => document.addEventListener('mousedown', away, true), 0);
    document.addEventListener('keydown', esc, true);
    return () => { clearTimeout(t); document.removeEventListener('mousedown', away, true); document.removeEventListener('keydown', esc, true); };
  }, [open]);
  if (!open || !pos) return null;
  return ReactDOM.createPortal(
    <div ref={ref} data-pick-float className="rounded-2xl border border-line bg-surface p-2.5 pop-in"
         style={{ position: 'fixed', zIndex: 90, boxShadow: '0 16px 40px rgba(16,32,24,.14)', ...pos }}
         onClick={e => e.stopPropagation()}>{children}</div>,
    document.body);
}

/* ---------- the calendar ---------- */
function CalendarPanel({ value, onPick, onClear, allowClear = true, min, max }) {
  const today = todayISO();
  const start = value || today;
  const [ym, setYm] = React.useState([+start.slice(0, 4), +start.slice(5, 7)]);
  const [typed, setTyped] = React.useState(pickFmt(value));
  const [bad, setBad] = React.useState(false);
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (inputRef.current) { inputRef.current.focus(); inputRef.current.select(); } }, []);
  const move = d => setYm(([y, m]) => { let mm = m + d, yy = y; if (mm < 1) { mm = 12; yy--; } if (mm > 12) { mm = 1; yy++; } return [yy, mm]; });
  const onKey = e => {
    if (e.key !== 'Enter') return;
    e.preventDefault();
    if (!typed.trim()) { if (allowClear) onClear(); return; }
    const iso = pickParse(typed);
    if (!iso || (min && iso < min) || (max && iso > max)) { setBad(true); return; }
    onPick(iso);
  };
  const days = pickGrid(ym[0], ym[1]);
  const heads = Array.from({ length: 7 }, (_, i) => PICK.days[(i + PICK.weekStart) % 7]);
  return (
    <div className="w-[262px]">
      <input ref={inputRef} value={typed} placeholder={PICK.typeHint}
             onChange={e => { setTyped(e.target.value); setBad(false); }} onKeyDown={onKey}
             className="w-full h-9 px-2.5 rounded-xl border-[1.5px] bg-white text-[14px] font-600 text-ink outline-none"
             style={{ borderColor: bad ? 'var(--neg)' : 'var(--sidebar)' }} />
      {bad && <div className="text-[11.5px] mt-1 px-0.5" style={{ color: 'var(--neg)' }}>{PICK.w.badDate}</div>}
      <div className="flex items-center gap-1 mt-2.5 mb-1.5 px-0.5">
        <b className="text-[14px] font-800 text-ink mr-auto">{PICK.months[ym[1] - 1]} {ym[0]}</b>
        <button type="button" onClick={() => onPick(today)} className="px-2 h-7 rounded-lg text-[12.5px] font-700 text-muted hover:bg-[#F6F8F3] hover:text-ink">{PICK.w.today}</button>
        <button type="button" onClick={() => move(-1)} className="w-7 h-7 rounded-lg inline-flex items-center justify-center text-muted hover:bg-[#F6F8F3] hover:text-ink"><Icon name="chevronLeft" size={15} /></button>
        <button type="button" onClick={() => move(1)} className="w-7 h-7 rounded-lg inline-flex items-center justify-center text-muted hover:bg-[#F6F8F3] hover:text-ink"><Icon name="chevronRight" size={15} /></button>
      </div>
      <div className="grid grid-cols-7 gap-0.5 text-center">
        {heads.map(h => <div key={h} className="text-[11.5px] font-700 text-muted py-1">{h}</div>)}
        {days.map(iso => {
          const out = +iso.slice(5, 7) !== ym[1], sel = iso === value, isToday = iso === today;
          const off = (min && iso < min) || (max && iso > max);   // outside the allowed dates: shown, not pickable
          return (
            <button key={iso} type="button" disabled={off} onClick={() => onPick(iso)}
              className={'h-[33px] rounded-[10px] text-[13.5px] num transition-colors ' + (sel ? 'font-700' : off ? 'text-[#D3D8D0] line-through cursor-default' : out ? 'text-[#B8BFB5]' : 'font-600 text-ink hover:bg-[var(--lime-soft)]')}
              style={{ ...(sel ? { background: 'var(--sidebar)', color: '#fff' } : {}), ...(isToday && !sel ? { boxShadow: 'inset 0 0 0 2px var(--lime-2)' } : {}) }}>
              {+iso.slice(8, 10)}
            </button>
          );
        })}
      </div>
      {allowClear && (
        <div className="flex justify-between border-t border-line mt-2 pt-1.5">
          <button type="button" onClick={onClear} className="px-2 h-7 rounded-lg text-[12.5px] font-700 text-muted hover:bg-[#F6F8F3] hover:text-ink">{PICK.w.clear}</button>
        </div>
      )}
    </div>
  );
}

/* A date field: a box (in forms) or plain text (plain, in tables). One click opens the calendar. */
function DateField({ value, onChange, compact, plain, placeholder, className = '', required, children, min, max }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  // one calendar open at a time: opening this one closes any other (e.g. From, then To, in the custom range)
  const me = React.useRef({});
  React.useEffect(() => {
    const other = e => { if (e.detail !== me.current) setOpen(false); };
    window.addEventListener('pick-date-open', other);
    return () => window.removeEventListener('pick-date-open', other);
  }, []);
  React.useEffect(() => { if (open) window.dispatchEvent(new CustomEvent('pick-date-open', { detail: me.current })); }, [open]);
  const pick = iso => { setOpen(false); onChange(iso); };
  const shown = value ? (typeof fmtDate === 'function' ? fmtDate(value) : pickFmt(value)) : null;
  const box = plain
    ? 'inline-flex items-center rounded-md px-1.5 py-1 -mx-1.5 min-h-[28px] cursor-pointer hover:bg-[var(--lime-soft)] ' + (open ? 'bg-[var(--lime-soft)]' : '')
    : (compact ? 'h-8 px-2.5 rounded-lg text-[13px]' : 'h-10 px-3 rounded-xl text-sm') + ' field-focus w-full inline-flex items-center gap-2 border bg-surface text-left text-ink transition-all ' + (open ? 'border-[var(--sidebar)]' : 'border-line');
  return (
    <>
      <button type="button" ref={ref} onClick={e => { e.preventDefault(); e.stopPropagation(); setOpen(o => !o); }} className={box + ' ' + className}>
        {!plain && <Icon name="calendar" size={15} className="text-muted shrink-0" />}
        {children != null ? children : shown ? <span className="num truncate">{shown}</span> : <span className="text-[#9AA298] truncate">{placeholder || PICK.w.pick}</span>}
      </button>
      <PickFloat anchorRef={ref} open={open} onClose={() => setOpen(false)} width={282}>
        <CalendarPanel value={value || ''} onPick={pick} onClear={() => pick(null)} allowClear={!required} min={min} max={max} />
      </PickFloat>
    </>
  );
}

/* ---------- the dropdown ---------- */
// options: strings, or { value, label, muted } ; '' is a valid value (e.g. "All")
function _pickOpts(options) { return (options || []).map(o => (o && typeof o === 'object') ? o : { value: o, label: String(o) }); }
function DropdownList({ options, value, onPick, searchable }) {
  const opts = _pickOpts(options);
  const [q, setQ] = React.useState('');
  const shown = q.trim() ? opts.filter(o => String(o.label).toLowerCase().includes(q.trim().toLowerCase())) : opts;
  const [active, setActive] = React.useState(Math.max(0, shown.findIndex(o => o.value === value)));
  const listRef = React.useRef(null);
  const onKey = e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(i => Math.min(i + 1, shown.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(i => Math.max(i - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); if (shown[active]) onPick(shown[active].value); }
  };
  React.useEffect(() => { if (!searchable && listRef.current) listRef.current.focus(); }, []);
  return (
    <div className="flex flex-col gap-1.5" ref={listRef} tabIndex={-1} onKeyDown={onKey} style={{ outline: 'none' }}>
      {searchable && <input autoFocus value={q} onChange={e => { setQ(e.target.value); setActive(0); }} placeholder={PICK.w.search}
                            className="w-full h-9 px-2.5 rounded-xl border-[1.5px] bg-white text-[13px] text-ink outline-none" style={{ borderColor: 'var(--sidebar)' }} />}
      <div className="flex flex-col max-h-[260px] overflow-auto scroll-area">
        {shown.map((o, i) => (
          <button key={String(o.value) + i} type="button" onMouseEnter={() => setActive(i)} onClick={() => onPick(o.value)}
            className={'text-left px-2.5 py-[7px] rounded-[10px] text-[13px] flex items-center gap-2 ' + (o.muted ? 'text-muted ' : 'text-ink ') + (i === active ? 'bg-[var(--lime-soft)]' : '')}>
            <span className="w-3.5 shrink-0 inline-flex">{o.value === value && <Icon name="check" size={13} className="text-primary" />}</span>
            <span className="truncate flex-1">{o.label}</span>
          </button>
        ))}
        {!shown.length && <span className="text-[12px] text-muted px-2.5 py-1.5">{PICK.w.none}</span>}
      </div>
    </div>
  );
}
function Dropdown({ value, onChange, options, placeholder, compact, searchable, className = '', prefix, width, menuWidth }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const opts = _pickOpts(options);
  const cur = opts.find(o => o.value === value);
  const search = searchable != null ? searchable : opts.length > 8;
  return (
    <div className={'relative ' + className} style={width ? { width } : undefined}>
      <button type="button" ref={ref} onClick={e => { e.preventDefault(); setOpen(o => !o); }}
        className={(compact ? 'h-8 pl-2.5 pr-8 rounded-lg text-[13px]' : 'h-10 pl-3 pr-9 rounded-xl text-sm') + ' field-focus w-full border bg-surface text-left text-ink transition-all cursor-pointer truncate ' + (open ? 'border-[var(--sidebar)]' : 'border-line')}>
        {prefix && <span className="text-muted">{prefix}: </span>}
        {cur ? cur.label : value !== '' && value != null ? String(value) : <span className="text-[#9AA298]">{placeholder || PICK.w.choose}</span>}
      </button>
      <Icon name="chevronDown" size={15} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted pointer-events-none" />
      <PickFloat anchorRef={ref} open={open} onClose={() => setOpen(false)} width={menuWidth || 220} align="stretch">
        <DropdownList options={opts} value={value} searchable={search} onPick={v => { setOpen(false); onChange(v); }} />
      </PickFloat>
    </div>
  );
}

/* ---------- the period button ---------- */
// value: { key, year?, from?, to? }. years: past years that have data (newest first), offered as whole years.
function PeriodButton({ value, onChange, years = [], align = 'right' }) {
  const today = todayISO();
  const [open, setOpen] = React.useState(false);
  const [custom, setCustom] = React.useState(false);
  const r0 = periodRange(value, today);
  const [from, setFrom] = React.useState(r0.from), [to, setTo] = React.useState(r0.to);
  const ref = React.useRef(null);
  const toggle = () => { if (!open) { const r = periodRange(value, today); setFrom(r.from); setTo(r.to); setCustom(value && value.key === 'custom'); } setOpen(o => !o); };
  const pick = p => { setOpen(false); onChange(p); };
  const isOn = p => !custom && value && value.key === p.key && (p.key !== 'year' || value.year === p.year) || (!custom && (!value || !value.key) && p.key === 'ytd');
  const presets = ['ytd', 'month', 'lastmonth', 'quarter', 'lastq', 'last12'].map(key => ({ key }));
  const row = (p, label) => (
    <button key={p.key + (p.year || '')} type="button" onClick={() => pick(p)}
      className={'text-left px-2.5 py-[7px] rounded-[10px] text-[13px] text-ink flex items-center gap-2 hover:bg-[var(--lime-soft)] ' + (isOn(p) ? 'bg-[var(--lime-soft)]' : '')}>
      <span className="w-3.5 shrink-0 inline-flex">{isOn(p) && <Icon name="check" size={13} className="text-primary" />}</span>{label}
    </button>
  );
  return (
    <>
      <button type="button" ref={ref} onClick={toggle}
        className="inline-flex items-center gap-1.5 h-[30px] pl-3 pr-2 rounded-[10px] border border-line bg-white text-[12.5px] font-700 text-ink whitespace-nowrap hover:bg-[#F6F8F3]">
        {periodName(value, today)}<Icon name="chevronDown" size={14} className="text-muted" />
      </button>
      <PickFloat anchorRef={ref} open={open} onClose={() => setOpen(false)} width={244} align={align}>
        <div className="flex flex-col">
          {presets.map(p => row(p, PICK.periods[p.key]))}
          {years.length > 0 && <div className="h-px bg-line my-1.5 mx-1" />}
          {years.map(y => row({ key: 'year', year: y }, PICK.periods.year(y)))}
          <div className="h-px bg-line my-1.5 mx-1" />
          <button type="button" onClick={() => setCustom(true)}
            className={'text-left px-2.5 py-[7px] rounded-[10px] text-[13px] text-ink flex items-center gap-2 hover:bg-[var(--lime-soft)] ' + (custom ? 'bg-[var(--lime-soft)]' : '')}>
            <span className="w-3.5 shrink-0 inline-flex">{custom && <Icon name="check" size={13} className="text-primary" />}</span>{PICK.periods.custom}
          </button>
          {custom && (
            <div className="grid grid-cols-[44px_1fr] gap-2 items-center px-1.5 pt-2 pb-1 text-[12.5px] font-700 text-muted">
              <span>{PICK.w.from}</span><DateField compact required value={from} onChange={v => v && setFrom(v)} />
              <span>{PICK.w.to}</span><DateField compact required value={to} onChange={v => v && setTo(v)} />
              {from > to && <span className="col-span-2 text-[11.5px] font-600" style={{ color: 'var(--neg)' }}>{PICK.w.badRange}</span>}
              <button type="button" disabled={from > to} onClick={() => pick({ key: 'custom', from, to })}
                className="col-span-2 h-8 rounded-xl text-[13px] font-700 text-white disabled:opacity-40" style={{ background: 'var(--sidebar)' }}>{PICK.w.apply}</button>
            </div>
          )}
        </div>
      </PickFloat>
    </>
  );
}

Object.assign(window, {
  PICK, pickFmt, pickParse, pickValid, pickGrid, periodRange, periodMonths, periodName, pickRangeText,
  PickFloat, CalendarPanel, DateField, Dropdown, DropdownList, PeriodButton,
});
