/* ============================================================
   common.jsx — shared UI primitives + icons
   ============================================================ */
const { useState, useEffect, useRef, useContext, useMemo } = React;

/* ---------- minimalist geometric icons (rects / circles / lines only) ---------- */
function Icon({ name, size = 20, stroke = 1.7 }) {
  const c = "currentColor";
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: c, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    pos:   <><rect x="3" y="4" width="18" height="13" rx="1.5" /><line x1="3" y1="20" x2="21" y2="20" /></>,
    grid:  <><rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" /><rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" /></>,
    report:<><rect x="4" y="3" width="16" height="18" rx="1.5" /><line x1="8" y1="8" x2="16" y2="8" /><line x1="8" y1="12" x2="16" y2="12" /><line x1="8" y1="16" x2="13" y2="16" /></>,
    box:   <><rect x="4" y="4" width="16" height="16" rx="1.5" /><line x1="4" y1="9.5" x2="20" y2="9.5" /></>,
    store: <><rect x="4" y="9" width="16" height="11" rx="1" /><path d="M4 9l1.2-4h13.6L20 9" /></>,
    list:  <><line x1="8" y1="6" x2="20" y2="6" /><line x1="8" y1="12" x2="20" y2="12" /><line x1="8" y1="18" x2="20" y2="18" /><circle cx="4" cy="6" r="1" /><circle cx="4" cy="12" r="1" /><circle cx="4" cy="18" r="1" /></>,
    chart: <><line x1="4" y1="20" x2="20" y2="20" /><rect x="6" y="11" width="3" height="7" /><rect x="11" y="7" width="3" height="11" /><rect x="16" y="14" width="3" height="4" /></>,
    plus:  <><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></>,
    minus: <><line x1="5" y1="12" x2="19" y2="12" /></>,
    close: <><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></>,
    check: <><polyline points="4 12 10 18 20 6" /></>,
    bell:  <><path d="M6 9a6 6 0 0112 0c0 5 2 6 2 6H4s2-1 2-6" /><path d="M10 20a2 2 0 004 0" /></>,
    user:  <><circle cx="12" cy="8" r="3.2" /><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6" /></>,
    cup:   <><path d="M6 8h11v6a4 4 0 01-4 4H10a4 4 0 01-4-4z" /><path d="M17 9h2a2 2 0 010 4h-2" /></>,
    cash:  <><rect x="3" y="6" width="18" height="12" rx="1.5" /><circle cx="12" cy="12" r="2.5" /></>,
    arrow: <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="13 6 19 12 13 18" /></>,
    search:<><circle cx="11" cy="11" r="6" /><line x1="20" y1="20" x2="16" y2="16" /></>,
  };
  return <svg {...common}>{paths[name] || null}</svg>;
}

/* ---------- KPI / stat card ---------- */
function Stat({ label, value, sub, accent, tone }) {
  return (
    <div className={"stat" + (accent ? " stat-accent" : "")}>
      <div className="stat-l">{label}</div>
      <div className="stat-v" style={tone ? { color: tone } : null}>{value}</div>
      {sub != null && <div className="stat-s">{sub}</div>}
    </div>
  );
}

/* ---------- pill / badge ---------- */
function Pill({ tone = "neutral", children }) {
  return <span className={"pill pill-" + tone}>{children}</span>;
}

/* ---------- modal ---------- */
function Modal({ open, onClose, children, width = 460, title, subtitle }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-scrim" onMouseDown={onClose}>
      <div className="modal" style={{ width }} onMouseDown={(e) => e.stopPropagation()}>
        {title && (
          <div className="modal-head">
            <div>
              <div className="modal-title">{title}</div>
              {subtitle && <div className="modal-sub">{subtitle}</div>}
            </div>
            <button className="icon-btn" onClick={onClose}><Icon name="close" size={18} /></button>
          </div>
        )}
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

/* ---------- toast host (imperative via window event) ---------- */
function ToastHost() {
  const [toasts, setToasts] = useState([]);
  useEffect(() => {
    const h = (e) => {
      const id = Math.random().toString(36).slice(2);
      setToasts((t) => [...t, { id, ...e.detail }]);
      setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), e.detail.duration || 3200);
    };
    window.addEventListener("pos-toast", h);
    return () => window.removeEventListener("pos-toast", h);
  }, []);
  return (
    <div className="toast-host">
      {toasts.map((t) => (
        <div key={t.id} className={"toast toast-" + (t.tone || "ok")}>
          <span className="toast-ic"><Icon name={t.tone === "warn" ? "bell" : "check"} size={16} /></span>
          <div>
            <div className="toast-t">{t.title}</div>
            {t.msg && <div className="toast-m">{t.msg}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}
function toast(detail) { window.dispatchEvent(new CustomEvent("pos-toast", { detail })); }

/* ---------- simple CSS bar chart ---------- */
function BarChart({ data, labels, height = 150, accent }) {
  const max = Math.max(...data, 1);
  return (
    <div className="bars" style={{ height }}>
      {data.map((v, i) => (
        <div className="bar-col" key={i}>
          <div className="bar-track">
            <div className="bar-fill" style={{ height: (v / max * 100) + "%", background: accent }} />
          </div>
          <div className="bar-lab">{labels[i]}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------- horizontal compare bar ---------- */
function CompareBar({ value, max, accent, label, right }) {
  return (
    <div className="cmp-row">
      <div className="cmp-label">{label}</div>
      <div className="cmp-track"><div className="cmp-fill" style={{ width: (value / max * 100) + "%", background: accent }} /></div>
      <div className="cmp-val">{right}</div>
    </div>
  );
}

Object.assign(window, { Icon, Stat, Pill, Modal, ToastHost, toast, BarChart, CompareBar });
