// Shared UI primitives and icons
const { useState, useEffect, useRef, useMemo } = React;

// SAR / number formatter
const fmt = (n, opts = {}) => {
  if (n == null) return "—";
  if (opts.compact && Math.abs(n) >= 1e9) return (n / 1e9).toFixed(1) + "B";
  if (opts.compact && Math.abs(n) >= 1e6) return (n / 1e6).toFixed(1) + "M";
  if (opts.compact && Math.abs(n) >= 1e3) return (n / 1e3).toFixed(1) + "K";
  return n.toLocaleString("en-US", { maximumFractionDigits: opts.dp ?? 0 });
};
const sar = (n, opts = {}) => `SAR ${fmt(n, opts)}`;

// Icon system (lucide-like inline SVG)
const Icon = ({ name, size = 16, stroke = 1.5, className = "" }) => {
  const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round", className };
  const paths = {
    home: <><path d="M3 12 12 4l9 8"/><path d="M5 10v10h14V10"/></>,
    match: <><path d="M9 7H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-4"/><path d="M14 3h7v7"/><path d="m21 3-9 9"/></>,
    sku: <><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></>,
    ship: <><path d="M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1 .6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"/><path d="M19 8.5 12 5l-7 3.5"/><path d="M5 8.5v8M19 8.5v8"/><path d="M12 5v8"/></>,
    box: <><path d="M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></>,
    container: <><rect x="3" y="6" width="18" height="12" rx="1"/><path d="M7 6v12M11 6v12M15 6v12M19 6v12"/></>,
    rfq: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h5"/></>,
    arrow: <><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></>,
    arrowLeft: <><path d="M19 12H5"/><path d="m12 19-7-7 7-7"/></>,
    arrowUp: <><path d="m18 15-6-6-6 6"/></>,
    arrowDown: <><path d="m6 9 6 6 6-6"/></>,
    chevronDown: <><path d="m6 9 6 6 6-6"/></>,
    plus: <><path d="M5 12h14M12 5v14"/></>,
    check: <><path d="m5 12 5 5L20 7"/></>,
    x: <><path d="M18 6 6 18M6 6l12 12"/></>,
    upload: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8 12 3 7 8"/><path d="M12 3v12"/></>,
    download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></>,
    refresh: <><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></>,
    bell: <><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></>,
    sparkle: <><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></>,
    filter: <><path d="M3 6h18M6 12h12M10 18h4"/></>,
    eye: <><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></>,
    file: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></>,
    trash: <><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></>,
    trendUp: <><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></>,
    trendDown: <><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></>,
    play: <><polygon points="6 3 20 12 6 21 6 3"/></>,
    pause: <><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></>,
    spark: <><path d="m12 3 2 7 7 2-7 2-2 7-2-7-7-2 7-2z"/></>,
    flag: <><path d="M4 22V4"/><path d="M4 15V4h14l-4 5 4 6H4"/></>,
    clock: <><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></>,
    users: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.9"/><path d="M16 3.1a4 4 0 0 1 0 7.7"/></>,
    truck: <><path d="M10 17h4V5H2v12h2"/><path d="M22 17h-5v-7h4l1 2z"/><circle cx="7" cy="17" r="2"/><circle cx="17" cy="17" r="2"/></>,
    dollar: <><line x1="12" y1="2" x2="12" y2="22"/><path d="M17 5H9a3 3 0 0 0 0 6h6a3 3 0 0 1 0 6H7"/></>,
    zap: <><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></>,
    factory: <><path d="M2 20h20"/><path d="M4 20V8l5 3V8l5 3V8l5 3v9"/><path d="M9 14h.01M14 14h.01M9 18h.01M14 18h.01"/></>,
    build: <><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></>,
    pill: <><path d="m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z"/><path d="m8.5 8.5 7 7"/></>,
    cart: <><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6"/></>,
  };
  return <svg {...props}>{paths[name] || null}</svg>;
};

// Spark sparkline
function Spark({ data, w = 80, h = 24, color = "var(--ink-2)" }) {
  if (!data?.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const pts = data.map((d, i) => `${i * step},${h - ((d - min) / range) * (h - 2) - 1}`).join(" ");
  return <svg width={w} height={h}><polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" /></svg>;
}

// Topbar
function Topbar({ route, setRoute, industry, setIndustry }) {
  const [open, setOpen] = useState(false);
  const inds = window.INDUSTRIES || {};
  const current = inds[industry] || {};
  useEffect(() => {
    const close = () => setOpen(false);
    if (open) {
      setTimeout(() => window.addEventListener("click", close, { once: true }), 0);
    }
  }, [open]);
  return (
    <header className="topbar">
      <div className="brand" onClick={() => setRoute({ name: "dashboard" })}>
        <div className="brand-mark">P</div>
        <div>
          <div className="brand-name">Procura</div>
          <div className="brand-sub">AI Operations · v2.1</div>
        </div>
      </div>
      <nav className="nav">
        <button className={route.name === "dashboard" ? "active" : ""} onClick={() => setRoute({ name: "dashboard" })}>Overview</button>
        <button className={route.name === "agents" || route.name === "agent" ? "active" : ""} onClick={() => setRoute({ name: "agents" })}>Agents</button>
        <button className={route.name === "spend" ? "active" : ""} onClick={() => setRoute({ name: "spend" })}>Spend</button>
        <button className={route.name === "vendors" ? "active" : ""} onClick={() => setRoute({ name: "vendors" })}>Vendors</button>
        <button className={route.name === "settings" ? "active" : ""} onClick={() => setRoute({ name: "settings" })}>Settings</button>
      </nav>
      <div className="topbar-spacer"></div>

      <div className="industry-picker" onClick={(e) => e.stopPropagation()}>
        <button className="industry-btn" onClick={() => setOpen(!open)}>
          <span className="industry-icon"><Icon name={current.icon || "factory"} size={14} /></span>
          <span className="industry-meta">
            <span className="industry-eyebrow">Demo Industry</span>
            <span className="industry-name">{current.label || "—"}</span>
          </span>
          <Icon name="chevronDown" size={13} />
        </button>
        {open && (
          <div className="industry-menu">
            <div className="industry-menu-head">Switch industry for demo</div>
            {Object.entries(inds).map(([k, v]) => (
              <button key={k} className={`industry-item ${k === industry ? "active" : ""}`} onClick={() => { setIndustry(k); setOpen(false); }}>
                <span className="industry-item-icon" style={{background: v.accent + "1a", color: v.accent}}><Icon name={v.icon} size={14}/></span>
                <span className="industry-item-name">{v.label}</span>
                {k === industry && <Icon name="check" size={13} />}
              </button>
            ))}
            <div className="industry-menu-foot">All data is fictional · for demonstration only</div>
          </div>
        )}
      </div>

      <div className="topbar-search">
        <Icon name="search" size={14} />
        <input placeholder="Search vendors, POs, SKUs…" />
        <span className="kbd">⌘K</span>
      </div>
      <div className="topbar-action"><Icon name="bell" size={16} /></div>
      <div className="avatar">RH</div>
    </header>
  );
}

// Drawer wrapper
function Drawer({ open, onClose, children, width = 720 }) {
  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && open && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  return (
    <>
      <div className={`drawer-overlay ${open ? "open" : ""}`} onClick={onClose} />
      <aside className={`drawer ${open ? "open" : ""}`} style={{ width }}>{children}</aside>
    </>
  );
}

Object.assign(window, { fmt, sar, Icon, Spark, Topbar, Drawer });
