/* ============================================================
   JIT BATCH — Shared UI components & helpers
   Exposes window.UI = { Badge, KPI, Card, LevelBar, Toaster,
     toast, fmt, statusMaps, Drawer, Modal, Tag }
   ============================================================ */
const { useState: useSU, useEffect: useEU, useRef: useRU } = React;
const Icon = window.Icon;

/* ---- formatting ---- */
const fmt = {
  n: (v, d = 0) => Number(v).toLocaleString("it-IT", { minimumFractionDigits: d, maximumFractionDigits: d }),
  pct: (v) => `${Math.round(v)}%`,
};

/* ---- status dictionaries ---- */
const statusMaps = {
  impianto: {
    in_funzione: { cls: "run", label: "In funzione", pulse: false },
    pausa: { cls: "warn", label: "In pausa" },
    allarme: { cls: "alarm", label: "Allarme", pulse: true },
    fermo: { cls: "idle", label: "Fermo" },
  },
  ordine: {
    programmato: { cls: "info", label: "Programmato" },
    in_produzione: { cls: "run", label: "In produzione", pulse: true },
    completato: { cls: "idle", label: "Completato" },
    sospeso: { cls: "warn", label: "Sospeso" },
  },
  mezzo: {
    disponibile: { cls: "run", label: "Disponibile" },
    in_carico: { cls: "info", label: "In carico", pulse: true },
    in_consegna: { cls: "warn", label: "In consegna" },
    manutenzione: { cls: "idle", label: "Manutenzione" },
  },
  scorta: {
    ok: { cls: "run", label: "OK" },
    basso: { cls: "warn", label: "Basso" },
    critico: { cls: "alarm", label: "Critico", pulse: true },
  },
  gravita: {
    info: { cls: "info", label: "Info" },
    warning: { cls: "warn", label: "Warning" },
    critico: { cls: "alarm", label: "Critico", pulse: true },
  },
  allarmeStato: {
    aperto: { cls: "alarm", label: "Aperto" },
    riconosciuto: { cls: "warn", label: "Riconosciuto" },
    risolto: { cls: "idle", label: "Risolto" },
  },
};

function Badge({ cls = "idle", label, pulse = false, dot = true, style }) {
  return (
    <span className={`badge ${cls} ${pulse ? "pulse" : ""}`} style={style}>
      {dot && <span className="bd" />}{label}
    </span>
  );
}
function StatusBadge({ map, value, style }) {
  const m = (statusMaps[map] || {})[value] || { cls: "idle", label: value };
  return <Badge cls={m.cls} label={m.label} pulse={m.pulse} style={style} />;
}

function Tag({ children, color = "var(--fg-3)", bg = "var(--bg-sunken)" }) {
  return <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color, background: bg, padding: "2px 7px", borderRadius: 5, whiteSpace: "nowrap" }}>{children}</span>;
}

function Card({ title, icon, sub, action, children, bodyStyle, style, noBody = false }) {
  return (
    <div className="card" style={style}>
      {(title || action) && (
        <div className="card-head">
          {icon && <Icon name={icon} size={17} className="card-title-ico" />}
          {title && <h3>{title}</h3>}
          {sub && <span className="ch-sub">{sub}</span>}
          <span className="spacer" />
          {action}
        </div>
      )}
      {noBody ? children : <div className="card-body" style={bodyStyle}>{children}</div>}
    </div>
  );
}

function KPI({ icon, label, value, unit, foot, footIcon, trend, accent = "var(--navy-600)", accentBg = "var(--navy-50)" }) {
  return (
    <div className="kpi">
      <div className="kpi-top">
        <span className="kpi-ico" style={{ background: accentBg, color: accent }}><Icon name={icon} size={17} /></span>
        <span className="kpi-label">{label}</span>
      </div>
      <div className="kpi-val">{value}{unit && <small>{unit}</small>}</div>
      {foot && (
        <div className={`kpi-foot ${trend === "up" ? "trend-up" : trend === "down" ? "trend-dn" : "muted"}`}>
          {footIcon && <Icon name={footIcon} size={13} />}{foot}
        </div>
      )}
    </div>
  );
}

function LevelBar({ pct, status }) {
  const cls = status === "critico" || pct <= 15 ? "lv-crit" : status === "basso" || pct <= 30 ? "lv-warn" : "lv-ok";
  return <div className={`levelbar ${cls}`}><span style={{ width: `${Math.max(0, Math.min(100, pct))}%` }} /></div>;
}

/* ---- Toasts (decoupled via window event) ---- */
function toast(opts) {
  window.dispatchEvent(new CustomEvent("jit-toast", { detail: { id: Date.now() + Math.random(), type: "info", ...opts } }));
}
function Toaster() {
  const [items, setItems] = useSU([]);
  useEU(() => {
    const h = (e) => {
      const t = e.detail;
      setItems((cur) => [...cur, t]);
      setTimeout(() => setItems((cur) => cur.filter((x) => x.id !== t.id)), t.duration || 4200);
    };
    window.addEventListener("jit-toast", h);
    return () => window.removeEventListener("jit-toast", h);
  }, []);
  const ico = { run: "checkCircle", info: "info", warn: "triangle", alarm: "alertCircle" };
  const icoBg = { run: "var(--status-run-bg)", info: "var(--status-info-bg)", warn: "var(--status-warn-bg)", alarm: "var(--status-alarm-bg)" };
  const icoCol = { run: "var(--status-run)", info: "var(--status-info)", warn: "var(--status-warn)", alarm: "var(--status-alarm)" };
  return (
    <div className="toast-wrap">
      {items.map((t) => (
        <div key={t.id} className={`toast ${t.type}`}>
          <span className="t-ico" style={{ background: icoBg[t.type], color: icoCol[t.type] }}><Icon name={ico[t.type]} size={17} /></span>
          <div className="t-body">
            <div className="t-title">{t.title}</div>
            {t.msg && <div className="t-msg">{t.msg}</div>}
          </div>
          <button className="t-close" onClick={() => setItems((cur) => cur.filter((x) => x.id !== t.id))}><Icon name="x" size={15} /></button>
        </div>
      ))}
    </div>
  );
}

/* ---- Drawer ---- */
function Drawer({ title, sub, onClose, children, footer }) {
  useEU(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <React.Fragment>
      <div className="overlay" onClick={onClose} />
      <div className="drawer" role="dialog">
        <div className="drawer-head">
          <div className="dh-titles">
            {sub && <div className="dh-sub">{sub}</div>}
            <h2>{title}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </div>
    </React.Fragment>
  );
}

/* ---- Modal ---- */
function Modal({ title, sub, onClose, children, footer, width }) {
  useEU(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <React.Fragment>
      <div className="overlay" onClick={onClose} />
      <div className="modal" role="dialog" style={width ? { width } : undefined}>
        <div className="drawer-head">
          <div className="dh-titles">
            {sub && <div className="dh-sub">{sub}</div>}
            <h2>{title}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </div>
    </React.Fragment>
  );
}

window.UI = { Badge, StatusBadge, Tag, Card, KPI, LevelBar, Toaster, toast, fmt, statusMaps, Drawer, Modal };
