// App shell: sidebar + topbar + content area

const NAV = [
  { id: "screener",  label: "Home",     icon: "home",     group: "Analisi" },
  { id: "watchlist", label: "Watchlist", icon: "star",     group: "Analisi" },
  { id: "dashboard", label: "Dashboard", icon: "candles",  group: "Analisi" },
  { id: "calendar",  label: "Calendario",icon: "calendar", group: "Analisi" },
  { id: "news",      label: "News",      icon: "bell",     group: "Analisi" },
  { id: "sectors",    label: "Settori",    icon: "trending",   group: "Analisi" },
  { id: "premarket", label: "Pre-market",icon: "clock",    group: "Analisi" },
  { id: "picks",     label: "Top Picks",  icon: "spark",    group: "Analisi" },
  { id: "chain",     label: "Chain",      icon: "chain",    group: "Analisi" },
  { id: "report",    label: "Report",    icon: "fileText", group: "Strumenti" },
  { id: "accuracy",  label: "Accuratezza", icon: "check",  group: "Strumenti" },
  { id: "simulator", label: "Simulatore", icon: "chart",   group: "Strumenti" },
  { id: "sleeves",   label: "Sleeves",   icon: "chart",    group: "Strumenti" },
  { id: "evaluate",  label: "Evaluate",  icon: "beaker",   group: "Strumenti" },
  { id: "config",    label: "Configurazione", icon: "settings", group: "Sistema" },
  { id: "logs",      label: "Log",       icon: "terminal", group: "Sistema" },
  { id: "costs",     label: "Costi",     icon: "coins",    group: "Sistema", adminOnly: true },
  { id: "admin",     label: "Utenti",    icon: "users",    group: "Sistema", adminOnly: true },
];

const TAB_TITLES = {
  dashboard: { t: "Dashboard",      s: "Watchlist · candele 5m · forecast multi-tool" },
  screener:  { t: "Home",           s: "Panoramica segnali su tutto il watchlist" },
  watchlist: { t: "Watchlist",      s: "Le tue liste personali · prezzo e variazione giornaliera in tempo reale" },
  calendar:  { t: "Calendario",     s: "Earnings, eventi Fed, macro" },
  news:      { t: "News",           s: "Agenda manuale dei catalizzatori · lanci, prodotti, IPO · digest Telegram del lunedì" },
  sectors:   { t: "Settori",        s: "SPDR sector ETFs · momentum · alert Telegram" },
  premarket: { t: "Pre-market",    s: "Gap-and-Crap detector · futures · score 0-100" },
  picks:     { t: "Top Picks",     s: "Stock Discovery · 5 factor quant + catalyst AI · crescita attesa prossimo mese (~30gg)" },
  chain:     { t: "Chain",          s: "Lead-lag · quando A sale, i follower seguono 1-5gg · corr returns + Granger" },
  report:    { t: "Report",        s: "Report di sintesi più recenti" },
  accuracy:  { t: "Accuratezza",    s: "Previsioni verificate vs reale · dir-accuracy, bias, salute dati" },
  simulator: { t: "Simulatore",     s: "Paper-trading settimanale · denaro fittizio · vs buy&hold/SPY" },
  sleeves:   { t: "Sleeves",        s: "Forward-test pre-registrato · 4 strategie meccaniche · 12 settimane vs €90/sett" },
  evaluate:  { t: "Evaluate",       s: "Valuta i CSV esportati dei tre tool" },
  config:    { t: "Configurazione", s: "Tool attivi, visibilità, JSON editor" },
  logs:      { t: "Log",            s: "Output del daemon · refresh ogni 30s" },
  costs:     { t: "Costi",          s: "Costi API a pagamento (Anthropic + Perplexity) · per provider, mese, tool" },
  admin:     { t: "Utenti",         s: "Gestione account e 2FA Telegram" },
};

// ── Risk Banner (Tool0) — striscia di stato rischio sempre visibile ───────────
const _RISK_REG = {
  neutral:  { cls: "neutral",  label: "NEUTRALE" },
  elevated: { cls: "elevated", label: "RISCHIO ELEVATO" },
  risk_off: { cls: "risk-off", label: "RISK-OFF" },
};

function RiskBanner({ dataLoaded }) {
  const [risk, setRisk] = useState(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (!dataLoaded) return;
    const load = () => fetch("/api/tool0-risk").then(r => r.json()).then(setRisk).catch(() => {});
    load();
    const t = setInterval(load, 5 * 60 * 1000);
    return () => clearInterval(t);
  }, [dataLoaded]);

  if (!risk || !risk.regime) return null;
  const r = _RISK_REG[risk.regime] || _RISK_REG.neutral;
  const triggers = risk.triggers || [];

  return (
    <div className={`risk-banner ${r.cls}`}>
      <button className="risk-banner-bar" onClick={() => setOpen(o => !o)} title="Dettaglio segnali di rischio">
        <span className="risk-dot"/>
        <span className="risk-label">Rischio mercato: <strong>{r.label}</strong></span>
        <span className="risk-sev">{risk.severity}<small>/100</small></span>
        {triggers.length > 0 && <span className="risk-count">{triggers.length} segnali attivi</span>}
        <span className="risk-caret">{open ? "▾" : "▸"}</span>
      </button>
      {open && (
        <div className="risk-banner-detail">
          {triggers.length === 0
            ? <span className="risk-empty">Nessun segnale di rischio attivo.</span>
            : triggers.map((t, i) => (
                <div key={i} className="risk-trigger">
                  <strong>{t.label}</strong>
                  {t.value != null && <code>{String(t.value)}</code>}
                  {t.note && <span className="risk-note">{t.note}</span>}
                </div>
              ))}
          {risk.portfolio && (
            <div className="risk-trigger" style={{ marginTop: 6, borderTop: "1px solid var(--border-soft)", paddingTop: 8 }}>
              <strong>Portafoglio</strong>
              <code>{risk.portfolio.top_sector_pct}% {risk.portfolio.top_sector}</code>
              {risk.portfolio.mean_corr_1d != null && <code>corr {risk.portfolio.mean_corr_1d}</code>}
              <span className="risk-note">{(risk.portfolio.notes || []).join(" · ")}</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function AppShell({ user, tab, setTab, onLogout, sidebarCollapsed, setSidebarCollapsed, dataVersions }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [activeSym, setActiveSym] = useState(null);
  const dataLoaded = (dataVersions?.dashboard || 0) > 0;
  const filteredNav = NAV.filter(n => !n.adminOnly || user.is_admin);
  const grouped = filteredNav.reduce((acc, n) => {
    (acc[n.group] = acc[n.group] || []).push(n);
    return acc;
  }, {});
  const title = TAB_TITLES[tab] || { t: "BVF", s: "" };

  return (
    <div className={`app-shell ${sidebarCollapsed ? "collapsed" : ""} ${mobileOpen ? "mobile-open" : ""}`}>
      {/* Mobile backdrop */}
      {mobileOpen && (
        <div className="mobile-backdrop" onClick={() => setMobileOpen(false)}/>
      )}

      {/* SIDEBAR */}
      <aside className="sidebar">
        <div className="sb-header">
          <div className="sb-mark"><Icon name="trending" size={15} strokeWidth={2.2}/></div>
          <div className="sb-brand">
            <strong>BVF Analyzer</strong>
            <small>v2.4 · trading desk</small>
          </div>
          <button className="icon-btn" style={{marginLeft:"auto"}} onClick={()=>setSidebarCollapsed(c=>!c)} title="Comprimi menu">
            <Icon name="menu" size={15}/>
          </button>
          <button className="icon-btn mobile-close-btn" onClick={() => setMobileOpen(false)} title="Chiudi">
            <Icon name="x" size={15}/>
          </button>
        </div>

        <nav className="sb-nav">
          {Object.entries(grouped).map(([g, items]) => (
            <React.Fragment key={g}>
              <div className="sb-section-title">{g}</div>
              {items.map(it => (
                <button key={it.id} className={`sb-item ${tab===it.id ? "active":""}`} onClick={()=>{ setTab(it.id); setMobileOpen(false); }}>
                  <span className="sb-item-icon"><Icon name={it.icon} size={16}/></span>
                  <span className="sb-item-label">{it.label}</span>
                </button>
              ))}
            </React.Fragment>
          ))}
        </nav>

        <div className="sb-footer">
          <DaemonStatus collapsed={sidebarCollapsed}/>
          <div className="sb-user">
            <div className="sb-avatar">{user.username.slice(0,1).toUpperCase()}</div>
            <div className="sb-user-info">
              <strong>{user.username}</strong>
              <small>{user.is_admin ? "Admin" : "Utente"}</small>
            </div>
            <button className="icon-btn sb-logout" title="Esci" onClick={onLogout}>
              <Icon name="logout" size={15}/>
            </button>
          </div>
        </div>
      </aside>

      {/* MAIN */}
      <main className="main">
        <header className="topbar">
          <button className="icon-btn mobile-menu-btn" onClick={() => setMobileOpen(true)} title="Menu">
            <Icon name="menu" size={17}/>
          </button>
          <div>
            <h2>{title.t}</h2>
            <div className="sub">{title.s}</div>
          </div>
          <div className="spacer"></div>
          <TabFreshness tab={tab}/>
          <MarketPill/>
          <AlertBell dataLoaded={dataLoaded}/>
        </header>

        <RiskBanner dataLoaded={dataLoaded}/>

        <div className="content">
          {tab === "dashboard" && <Dashboard refreshTick={dataVersions?.dashboard || 0} initSym={activeSym}/>}
          {tab === "screener"  && <ScreenerView key={dataVersions?.dashboard || 0} onNavigate={sym => { setActiveSym(sym); setTab("dashboard"); }}/>}
          {tab === "watchlist" && <WatchlistView/>}
          {tab === "calendar"  && <CalendarView/>}
          {tab === "sectors"   && <SectorsView/>}
          {tab === "premarket" && <PremarketView/>}
          {tab === "picks"     && <TopPicksView/>}
          {tab === "chain"     && <ChainView/>}
          {tab === "report"    && <ReportView key={`rp-${dataVersions?.report  || 0}`}/>}
          {tab === "accuracy"  && <AccuracyView/>}
          {tab === "simulator" && <SimulatorView/>}
          {tab === "sleeves"   && <SleevesView/>}
          {tab === "news"      && <NewsView/>}
          {tab === "evaluate"  && <EvaluateView/>}
          {tab === "config"    && <ConfigView user={user}/>}
          {tab === "logs"      && <LogsView/>}
          {tab === "costs"     && user.is_admin && <CostsView/>}
          {tab === "admin"     && <AdminView user={user}/>}
        </div>

        {/* Mobile bottom nav */}
        <nav className="mobile-bottom-nav">
          {filteredNav.slice(0, 5).map(it => (
            <button key={it.id} className={`mobile-nav-item ${tab===it.id?"active":""}`} onClick={()=>setTab(it.id)}>
              <Icon name={it.icon} size={20}/>
              <span>{it.label}</span>
            </button>
          ))}
        </nav>
      </main>
    </div>
  );
}

// ── Alert Bell ────────────────────────────────────────────────────────────────

const _SIG_COLOR = {
  BUY:         { color: "var(--green)", bg: "var(--green-soft)" },
  STRONG_BUY:  { color: "var(--green)", bg: "var(--green-soft)" },
  SELL:        { color: "var(--red)",   bg: "var(--red-soft)" },
  STRONG_SELL: { color: "var(--red)",   bg: "var(--red-soft)" },
  HOLD:        { color: "var(--amber)", bg: "var(--amber-soft)" },
};
const _TOOL_LABEL = { tool2: "AI", tool3: "TA", tool4: "News" };

function AlertBell({ dataLoaded }) {
  const [alerts, setAlerts]   = useState([]);
  const [unread, setUnread]   = useState(0);
  const [open, setOpen]       = useState(false);
  const ref = useRef(null);

  const fetchAlerts = () => {
    if (!dataLoaded) return;
    fetch("/api/alerts")
      .then(r => r.json())
      .then(d => { setAlerts(d.alerts || []); setUnread(d.unread || 0); })
      .catch(() => {});
  };

  useEffect(() => {
    fetchAlerts();
    const t = setInterval(fetchAlerts, 5 * 60 * 1000);
    return () => clearInterval(t);
  }, [dataLoaded]);

  useEffect(() => {
    const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const handleToggle = () => {
    const next = !open;
    setOpen(next);
    if (next && unread > 0) {
      fetch("/api/alerts/mark-read", { method: "POST" })
        .then(() => setUnread(0))
        .catch(() => {});
    }
  };

  return (
    <div ref={ref} className="alert-bell-wrap">
      <button className="icon-btn alert-bell-btn" title="Alert segnali" onClick={handleToggle}>
        <Icon name="bell" size={16}/>
        {unread > 0 && <span className="alert-badge"/>}
      </button>

      {open && (
        <div className="alert-dropdown">
          <div className="alert-dropdown-head">
            <strong>Segnali ultime 24h</strong>
            {unread > 0 && <span className="alert-unread-badge">{unread} nuovi</span>}
            <button className="icon-btn" style={{marginLeft:"auto"}} onClick={() => setOpen(false)}>
              <Icon name="x" size={13}/>
            </button>
          </div>
          <div className="alert-list">
            {alerts.length === 0
              ? <div className="alert-empty">Nessun segnale recente (esclusi HOLD).</div>
              : alerts.map((a, i) => {
                  const sc = _SIG_COLOR[a.signal] || { color:"var(--text-muted)", bg:"var(--surface)" };
                  return (
                    <div key={i} className="alert-row">
                      <span className="alert-sym">{a.symbol}</span>
                      <span className="alert-sig" style={{color: sc.color, background: sc.bg}}>
                        {(a.signal || "").replace(/_/g, " ")}
                      </span>
                      <div className="alert-meta">
                        <span className="alert-tool">{_TOOL_LABEL[a.tool] || a.tool}</span>
                        <span className="alert-time">{(a.timestamp || "").slice(11, 16)}</span>
                      </div>
                    </div>
                  );
                })
            }
          </div>
        </div>
      )}
    </div>
  );
}

// ── Daemon Status ─────────────────────────────────────────────────────────────

function DaemonStatus({ collapsed }) {
  const [running, setRunning] = useState(null);   // null = caricamento
  const [onLinux, setOnLinux] = useState(false);
  const [busy, setBusy]       = useState(false);

  const fetchStatus = () => {
    fetch("/api/status")
      .then(r => r.json())
      .then(d => { setRunning(d.running); setOnLinux(d.on_linux); })
      .catch(() => {});
  };

  useEffect(() => {
    fetchStatus();
    const t = setInterval(fetchStatus, 30000);
    return () => clearInterval(t);
  }, []);

  const doAction = async (action) => {
    if (busy) return;
    setBusy(true);
    try {
      await fetch(`/api/${action}`, { method: "POST" });
      await new Promise(r => setTimeout(r, 1500));
      fetchStatus();
    } finally {
      setBusy(false);
    }
  };

  if (running === null) return null;

  return (
    <div className="sb-daemon" title={running ? "Daemon in esecuzione" : "Daemon fermo"}>
      <span className={`daemon-dot ${running ? "running":"stopped"}`}></span>
      <span className="daemon-label">{running ? "In esecuzione" : "Fermo"}</span>
      {onLinux && (
        <div className="daemon-actions">
          {running ? (
            <button className="icon-btn red" onClick={()=>doAction("stop")} title="Ferma" disabled={busy}>
              <Icon name="stop" size={12} strokeWidth={2.4}/>
            </button>
          ) : (
            <button className="icon-btn green" onClick={()=>doAction("start")} title="Avvia" disabled={busy}>
              <Icon name="play" size={12} strokeWidth={2.4}/>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function MarketPill() {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const t = setInterval(()=>setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  // ET market hours (very rough)
  const etHour = (now.getUTCHours() - 4 + 24) % 24;
  const open = etHour >= 9 && etHour < 16 && now.getDay() >= 1 && now.getDay() <= 5;
  return (
    <div className="market-pill">
      <span className={`dot ${open ? "" : "closed"}`}></span>
      <span className="label">{open ? "Mercato aperto" : "Chiuso"}</span>
      <span className="clock mono">{now.toLocaleTimeString("it-IT")}</span>
    </div>
  );
}

// Badge freschezza dati per la tab attiva (legge window.HEALTH da /api/health).
// "Mostra sempre con badge età" — non nasconde mai i dati, segnala solo l'età.
const _TAB_TOOL = {
  dashboard: "tool1", screener: "tool1", sectors: "tool7",
  premarket: "tool8", picks: "tool9", chain: "tool10", calendar: "tool5",
};
function TabFreshness({ tab }) {
  const key = _TAB_TOOL[tab];
  const h = key && (window.HEALTH || {})[key];
  if (!h) return null;
  const age = h.age_min;
  const label = age == null ? "n/d" : age < 90 ? `${age}min fa` : `${(age / 60).toFixed(1)}h fa`;
  const hasAnom = h.anomalies && h.anomalies.length > 0;
  const color = h.ok ? "var(--green)" : (h.fresh ? "var(--amber)" : "var(--red)");
  const title = hasAnom ? h.anomalies.join("; ") : `Ultimo aggiornamento dati: ${label}`;
  return (
    <div title={title} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12,
         color: "var(--text-muted)", padding: "3px 9px", border: "1px solid var(--border-soft)",
         borderRadius: 20, whiteSpace: "nowrap" }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: color, flexShrink: 0 }}></span>
      dati {label}
    </div>
  );
}

window.AppShell = AppShell;
window.TAB_TITLES = TAB_TITLES;

// ────────── Shared filter components (available to all views) ──────────

// Custom dropdown — options as { value, label } array
function FilterSelect({ value, onChange, options, placeholder = "Tutti", width }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const selected = options.find(o => o.value === value);
  const label = selected ? selected.label : placeholder;
  const isAll = !selected || selected.label === placeholder || value === "all";

  return (
    <div ref={ref} className="fsel-wrap" style={width ? {width} : {}}>
      <button className={`fsel-btn ${open ? "open" : ""}`} onClick={() => setOpen(o => !o)}>
        <span className={`fsel-val ${!isAll ? "active" : ""}`}>{label}</span>
        <svg className="fsel-arrow" viewBox="0 0 10 6" width="10" height="6" fill="none" stroke="currentColor" strokeWidth="1.6">
          <path d="M1 1l4 4 4-4"/>
        </svg>
      </button>
      {open && (
        <div className="fsel-dropdown">
          {options.map(o => (
            <button
              key={o.value}
              className={`fsel-option ${o.value === value ? "active" : ""}`}
              onClick={() => { onChange(o.value); setOpen(false); }}
            >
              {o.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// Mini-calendar date picker — mostra un calendario mensile stilizzato
// availableDates: array di "YYYY-MM-DD" selezionabili (null = tutte le date disponibili)
// showClear: mostra il pulsante "Tutte le date" per resettare
function FilterCalendar({ value, onChange, availableDates, showClear = false, placeholder = "Tutte le date" }) {
  const isAll = !value || value === "all";

  const initMonth = () => {
    const d = !isAll ? new Date(value + "T12:00:00") : (availableDates?.length ? new Date(availableDates[0] + "T12:00:00") : new Date());
    return { y: d.getFullYear(), m: d.getMonth() };
  };
  const [open, setOpen]     = useState(false);
  const [view, setView]     = useState(initMonth);
  const ref                 = useRef(null);
  const availSet            = new Set(availableDates || []);

  // Aggiorna il mese visualizzato quando cambia il valore selezionato
  useEffect(() => {
    if (!isAll) {
      const d = new Date(value + "T12:00:00");
      setView({ y: d.getFullYear(), m: d.getMonth() });
    }
  }, [value]);

  useEffect(() => {
    const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const fmtBtn = d => {
    if (!d || d === "all") return placeholder;
    return new Date(d + "T12:00:00").toLocaleDateString("it-IT", { weekday:"short", day:"2-digit", month:"short" });
  };

  const firstDay = new Date(view.y, view.m, 1);
  const lastDay  = new Date(view.y, view.m + 1, 0);
  const startWd  = (firstDay.getDay() + 6) % 7; // Lun=0
  const monthLabel = firstDay.toLocaleDateString("it-IT", { month: "long", year: "numeric" });

  const cells = [];
  for (let i = 0; i < startWd; i++) cells.push(null);
  for (let d = 1; d <= lastDay.getDate(); d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const makeKey = d => `${view.y}-${String(view.m+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`;
  const today = new Date();
  const todayKey = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,"0")}-${String(today.getDate()).padStart(2,"0")}`;

  const prevMonth = () => { const d = new Date(view.y, view.m - 1, 1); setView({ y: d.getFullYear(), m: d.getMonth() }); };
  const nextMonth = () => { const d = new Date(view.y, view.m + 1, 1); setView({ y: d.getFullYear(), m: d.getMonth() }); };

  const pickDay = (d) => {
    const key = makeKey(d);
    if (availableDates && !availSet.has(key)) return;
    onChange(key);
    setOpen(false);
  };

  return (
    <div ref={ref} className="fsel-wrap">
      <button className={`fsel-btn ${open ? "open" : ""}`} onClick={() => setOpen(o => !o)}>
        <svg viewBox="0 0 14 14" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" style={{flexShrink:0, opacity:0.6}}>
          <rect x="1" y="2" width="12" height="11" rx="2"/><path d="M1 6h12M4.5 1v2M9.5 1v2"/>
        </svg>
        <span className={`fsel-val ${!isAll ? "active" : ""}`}>{fmtBtn(value)}</span>
        {!isAll && showClear && (
          <span className="fsel-clear" onClick={e => { e.stopPropagation(); onChange("all"); setOpen(false); }}>×</span>
        )}
        <svg className="fsel-arrow" viewBox="0 0 10 6" width="10" height="6" fill="none" stroke="currentColor" strokeWidth="1.6">
          <path d="M1 1l4 4 4-4"/>
        </svg>
      </button>

      {open && (
        <div className="fsel-cal-panel">
          {/* Intestazione mese */}
          <div className="fsel-cal-head">
            <button className="fsel-cal-nav" onClick={prevMonth}>‹</button>
            <span className="fsel-cal-month">{monthLabel}</span>
            <button className="fsel-cal-nav" onClick={nextMonth}>›</button>
          </div>

          {/* Pulsante "Tutte le date" */}
          {showClear && (
            <button
              className={`fsel-cal-all ${isAll ? "active" : ""}`}
              onClick={() => { onChange("all"); setOpen(false); }}
            >{placeholder}</button>
          )}

          {/* Griglia */}
          <div className="fsel-cal-grid">
            {["L","M","M","G","V","S","D"].map((d, i) => (
              <span key={i} className="fsel-cal-dow">{d}</span>
            ))}
            {cells.map((d, i) => {
              if (!d) return <span key={i} />;
              const key      = makeKey(d);
              const avail    = !availableDates || availSet.has(key);
              const selected = key === value;
              const isToday  = key === todayKey;
              return (
                <button
                  key={i}
                  className={`fsel-cal-day${selected ? " sel" : ""}${isToday && !selected ? " today" : ""}${!avail ? " dim" : ""}`}
                  onClick={() => pickDay(d)}
                  disabled={!avail}
                >{d}</button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// Alias per retrocompatibilità (non più usato ma evita errori se rimane riferimento)
const FilterDateChips = FilterCalendar;

// Styled date input — opens native date picker from a custom button
function FilterDateInput({ value, onChange }) {
  const ref = useRef(null);
  return (
    <div className="fsel-wrap">
      <button className={`fsel-btn ${value ? "open-date" : ""}`} onClick={() => { try { ref.current?.showPicker(); } catch(_) { ref.current?.click(); } }}>
        <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.5" style={{flexShrink:0, color:"var(--text-muted)"}}>
          <rect x="1" y="3" width="14" height="12" rx="2"/><path d="M1 7h14M5 1v4M11 1v4"/>
        </svg>
        <span className={`fsel-val ${value ? "active" : ""}`}>
          {value ? new Date(value + "T12:00:00").toLocaleDateString("it-IT", { weekday:"short", day:"2-digit", month:"short", year:"numeric" }) : "Seleziona data"}
        </span>
        <input
          ref={ref}
          type="date"
          value={value}
          onChange={e => onChange(e.target.value)}
          style={{position:"absolute", opacity:0, width:1, height:1, pointerEvents:"none"}}
          tabIndex={-1}
        />
      </button>
    </div>
  );
}
