/* Shell: Sidebar, Topbar, generic UI primitives. Exports to window. */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Icons (inline, stroke-based) ---------- */
function Icon({ name, size = 16, color = "currentColor" }) {
  const s = size;
  const stroke = { stroke: color, strokeWidth: 1.6, fill: "none", strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "dashboard":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>;
    case "filter":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M4 5h16l-6 8v6l-4-2v-4z"/></svg>;
    case "details":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="4" width="18" height="16" rx="1.5"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="9" x2="9" y2="20"/></svg>;
    case "reports":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M9 3h7l4 4v13a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M15 3v5h5"/><line x1="11" y1="13" x2="17" y2="13"/><line x1="11" y1="17" x2="17" y2="17"/></svg>;
    case "alerts":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M18 16v-5a6 6 0 1 0-12 0v5l-2 2h16z"/><path d="M10 20a2 2 0 0 0 4 0"/></svg>;
    case "users":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.2"/><path d="M3 19c0-2.8 2.7-5 6-5s6 2.2 6 5"/><path d="M15 19c0-1.8 1.6-3.5 4-3.5s3 1.5 3 3"/></svg>;
    case "settings":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.7l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-1.7-.3 1.6 1.6 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.6 1.6 0 0 0-1-1.5 1.6 1.6 0 0 0-1.7.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0 .3-1.7 1.6 1.6 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.6 1.6 0 0 0 1.5-1 1.6 1.6 0 0 0-.3-1.7l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.6 1.6 0 0 0 1.7.3H9a1.6 1.6 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.7-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.7V9a1.6 1.6 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z"/></svg>;
    case "search":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="11" cy="11" r="7"/><line x1="20" y1="20" x2="16.6" y2="16.6"/></svg>;
    case "calendar":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="5" width="18" height="16" rx="1.5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="3" x2="8" y2="7"/><line x1="16" y1="3" x2="16" y2="7"/></svg>;
    case "download":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 4v12"/><path d="M7 11l5 5 5-5"/><path d="M5 20h14"/></svg>;
    case "chevron-right":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M9 6l6 6-6 6"/></svg>;
    case "chevron-down":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M6 9l6 6 6-6"/></svg>;
    case "chevron-up":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M6 15l6-6 6 6"/></svg>;
    case "arrow-up":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 19V5"/><path d="M5 12l7-7 7 7"/></svg>;
    case "arrow-down":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 5v14"/><path d="M19 12l-7 7-7-7"/></svg>;
    case "close":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>;
    case "plus":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>;
    case "check":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M5 12l5 5L20 7"/></svg>;
    case "info":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="9"/><line x1="12" y1="11" x2="12" y2="16"/><circle cx="12" cy="8" r=".5" fill={color}/></svg>;
    case "users-2":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>;
    case "bed":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M3 18V8"/><path d="M3 14h18v4"/><path d="M21 18v-4a3 3 0 0 0-3-3H10v3"/><circle cx="7" cy="11" r="2"/></svg>;
    case "clock":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case "repeat":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>;
    case "drill":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M3 7h18"/><path d="M6 12h12"/><path d="M9 17h6"/><path d="M11 21l1 1 1-1"/></svg>;
    case "external":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M14 4h6v6"/><path d="M10 14L20 4"/><path d="M19 13v6a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h6"/></svg>;
    case "save":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M5 4h11l4 4v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><path d="M8 4v5h7V4"/><rect x="7" y="13" width="10" height="7"/></svg>;
    case "refresh":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M3 12a9 9 0 0 1 15.5-6.3L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15.5 6.3L3 16"/><path d="M3 21v-5h5"/></svg>;
    case "share":
      return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="18" cy="5" r="2.5"/><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="19" r="2.5"/><path d="M8.2 11l7.6-4.5"/><path d="M8.2 13l7.6 4.5"/></svg>;
    default:
      return null;
  }
}

/* ---------- Sidebar ---------- */
function Sidebar({ active, onNavigate }) {
  const items = [
    { id: "riepilogo", label: "M1 · Riepilogo", icon: "dashboard" },
    { id: "filtri", label: "M2 · Filtri", icon: "filter" },
    { id: "dettagli", label: "M3 · Dettagli & drill", icon: "details" },
    { id: "ia", label: "M4 · Intelligenza Artificiale", icon: "reports" },
    { id: "consumi", label: "M5 · Consumi DM", icon: "drill" }
  ];
  const items2 = [
    { id: "reports", label: "Reportistica", icon: "reports", badge: "12" },
    { id: "alerts", label: "Alert clinici", icon: "alerts", badge: "3" },
    { id: "anagrafica", label: "Anagrafiche", icon: "users-2" }
  ];

  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <img src="assets/ausl_bologna.png" alt="AUSL Bologna — Servizio Sanitario Regionale Emilia-Romagna" className="sidebar__brand-logo" />
      </div>
      <div style={{ padding: "10px 16px 12px", borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
        <div style={{ fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(255,255,255,0.5)", fontWeight: 600 }}>Clinical BI</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 2, flexWrap: "wrap" }}>
          <div style={{ fontSize: 16, color: "#fff", fontWeight: 700, letterSpacing: "0.02em" }}>MAIA</div>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", fontWeight: 500 }}>by CrowdM AI</div>
        </div>
      </div>

      <div className="sidebar__section">
        <div className="sidebar__section-label">Demo Gara</div>
        <nav className="sidebar__nav">
          {items.map(it => (
            <button
              key={it.id}
              className={"sidebar__item " + (active === it.id ? "is-active" : "")}
              onClick={() => onNavigate(it.id)}
            >
              <Icon name={it.icon} size={15} />
              <span>{it.label}</span>
            </button>
          ))}
        </nav>
      </div>

      <div className="sidebar__section">
        <div className="sidebar__section-label">Strumenti</div>
        <nav className="sidebar__nav">
          {items2.map(it => (
            <button key={it.id} className="sidebar__item" onClick={() => {}}>
              <Icon name={it.icon} size={15} />
              <span>{it.label}</span>
              {it.badge && <span className="badge">{it.badge}</span>}
            </button>
          ))}
        </nav>
      </div>

      <div className="sidebar__footer">
        <div className="sidebar__avatar">MR</div>
        <div>
          <div className="sidebar__user-name">Dr. M. Ricci</div>
          <div className="sidebar__user-role">Direzione Sanitaria</div>
        </div>
      </div>
    </aside>
  );
}

/* ---------- Topbar ---------- */
function Topbar({ crumbs = [], onExport, onSave }) {
  return (
    <header className="topbar">
      <div className="topbar__crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="topbar__sep"><Icon name="chevron-right" size={12} /></span>}
            {i === crumbs.length - 1 ? <strong>{c}</strong> : <span>{c}</span>}
          </React.Fragment>
        ))}
      </div>
      <span className="topbar__env">Ambiente Demo</span>
      <div className="topbar__spacer" />
      <button className="topbar__action" onClick={onSave}>
        <Icon name="save" size={13} />
        <span>Salva vista</span>
      </button>
      <button className="topbar__action" onClick={onExport}>
        <Icon name="download" size={13} />
        <span>Esporta</span>
      </button>
      <button className="topbar__action topbar__action--primary">
        <Icon name="share" size={13} color="white"/>
        <span>Condividi</span>
      </button>
    </header>
  );
}

/* ---------- KPI ---------- */
function KpiCard({ label, value, unit, delta, deltaLabel, icon, tone = "primary" }) {
  const deltaCls = delta == null ? "neutral" : delta > 0 ? "up" : delta < 0 ? "down" : "neutral";
  const deltaSign = delta == null ? "" : delta > 0 ? "+" : "";
  return (
    <div className="kpi">
      <div className="kpi__label">{label}</div>
      <div className="kpi__value">
        {value}
        {unit && <span className="kpi__unit">{unit}</span>}
      </div>
      {(delta != null || deltaLabel) && (
        <div className={"kpi__delta kpi__delta--" + deltaCls}>
          {delta != null && (
            <>
              <Icon name={delta > 0 ? "arrow-up" : delta < 0 ? "arrow-down" : "check"} size={12} />
              <span>{deltaSign}{delta}% {deltaLabel || "vs periodo precedente"}</span>
            </>
          )}
          {delta == null && deltaLabel && <span>{deltaLabel}</span>}
        </div>
      )}
      {icon && (
        <div className="kpi__icon" style={tone === "accent" ? { background: "var(--c-accent-50)", color: "var(--c-accent)" } : undefined}>
          <Icon name={icon} size={15} />
        </div>
      )}
    </div>
  );
}

/* ---------- Card ---------- */
function Card({ title, sub, action, children, flush, tight }) {
  const bodyCls = "card__body" + (flush ? " card__body--flush" : tight ? " card__body--tight" : "");
  return (
    <div className="card">
      {(title || action) && (
        <div className="card__head">
          <div>
            {title && <div className="card__title">{title}</div>}
            {sub && <div className="card__sub">{sub}</div>}
          </div>
          <div className="card__head-spacer" />
          {action}
        </div>
      )}
      <div className={bodyCls}>{children}</div>
    </div>
  );
}

/* ---------- Pill ---------- */
function Pill({ tone, children }) {
  const cls = "pill" + (tone ? " pill--" + tone : "");
  return <span className={cls}>{children}</span>;
}

/* ---------- Segmented ---------- */
function Segmented({ value, options, onChange }) {
  return (
    <div className="segmented">
      {options.map(o => (
        <button
          key={o.value}
          className={"segmented__btn " + (value === o.value ? "is-active" : "")}
          onClick={() => onChange(o.value)}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

/* ---------- Filter bar (read-only summary) ---------- */
function FilterBar({ filters, onEdit }) {
  const D = window.DATA;
  const chips = [];
  if (filters.periodoFrom && filters.periodoTo) {
    chips.push({ k: "periodo", label: D.fmtDate(filters.periodoFrom) + " — " + D.fmtDate(filters.periodoTo) });
  }
  filters.dipartimenti.forEach(d => chips.push({ k: "dip-" + d, label: D.dipNome(d) }));
  filters.regimi.forEach(r => chips.push({ k: "reg-" + r, label: "Regime: " + D.regimeNome(r) }));
  filters.tipoIntervento.forEach(t => chips.push({ k: "tipo-" + t, label: t === "EL" ? "Elettivo" : "PS/Urgenza" }));
  filters.generi.forEach(g => chips.push({ k: "gen-" + g, label: g === "F" ? "Femmine" : "Maschi" }));
  filters.fasceEta.forEach(f => chips.push({ k: "eta-" + f, label: "Età " + f }));
  filters.drg.forEach(d => chips.push({ k: "drg-" + d, label: "DRG " + d }));
  filters.provenienze.forEach(p => chips.push({ k: "prov-" + p, label: p }));

  return (
    <div className="filter-bar">
      <span className="filter-bar__label">Filtri attivi</span>
      {chips.map(c => (
        <span key={c.k} className="chip is-active">
          {c.label}
        </span>
      ))}
      <div className="spacer" />
      <button className="btn btn--sm" onClick={onEdit}>
        <Icon name="filter" size={12} />
        Modifica filtri
      </button>
    </div>
  );
}

Object.assign(window, { Icon, Sidebar, Topbar, KpiCard, Card, Pill, Segmented, FilterBar });
