/* Shared UI primitives — exported to window */
const { useState, useEffect, useRef, useCallback } = React;
const _Icon = () => window.Icon;

/* ── Pill (status) ───────────────────────────────────────── */
function StatusPill({ status }) {
  const s = window.CardOps.STATUS[status] || { label: status, tone: "grey" };
  return React.createElement("span", { className: "co-pill " + s.tone },
    React.createElement("span", { className: "dot" }), s.label);
}

function Tag({ product }) {
  const cls = product === "MINE" ? "mine" : "thor";
  return React.createElement("span", { className: "co-tag " + cls }, product);
}

function Fee({ state, amount }) {
  const label = state === "na" ? "N/A" : (state === "paid" ? "Paid" : "Unpaid");
  return React.createElement("span", { className: "co-fee " + state },
    React.createElement("span", { className: "d" }),
    amount && state !== "na" ? `${label} · ${amount}` : label);
}

/* ── Tooltip ─────────────────────────────────────────────── */
function Tip({ label, children, disabled }) {
  if (!label) return children;
  return React.createElement("span", { className: "co-tip" }, children,
    React.createElement("span", { className: "co-tip-bubble" }, label));
}

/* ── Button + role-gated button ──────────────────────────── */
function Button({ variant, size, icon, children, onClick, disabled, block, type, style }) {
  const cls = ["co-btn", "co-btn-" + (variant || "secondary"), size === "sm" ? "co-btn-sm" : "", block ? "co-btn-block" : ""].join(" ");
  return React.createElement("button", { className: cls, onClick, disabled, type: type || "button", style },
    icon && React.createElement(window.Icon, { name: icon }), children);
}

// Gated button: shows disabled + tooltip when role lacks permission
function GatedButton({ perm, role, variant, size, icon, children, onClick, block }) {
  const allowed = window.CardOps.can(role, perm);
  const btn = React.createElement(Button, {
    variant, size, icon, block, disabled: !allowed,
    onClick: allowed ? onClick : undefined, children,
  });
  if (allowed) return btn;
  return React.createElement(Tip, { label: window.CardOps.permReason(perm) }, btn);
}

/* ── Switch ──────────────────────────────────────────────── */
function Switch({ on, onChange, id }) {
  return React.createElement("button", {
    id, role: "switch", "aria-checked": on, className: "co-switch" + (on ? " on" : ""),
    onClick: () => onChange(!on), style: { cursor: "pointer" },
  });
}

/* ── Skeleton ────────────────────────────────────────────── */
function Skel({ w, h, r, style }) {
  return React.createElement("div", { className: "co-skel", style: { width: w || "100%", height: h || 14, borderRadius: r, ...style } });
}
function SkeletonRows({ rows, cols }) {
  return React.createElement("div", { style: { padding: 8 } },
    Array.from({ length: rows || 6 }).map((_, i) =>
      React.createElement("div", { key: i, style: { display: "flex", gap: 16, padding: "13px 8px", alignItems: "center" } },
        Array.from({ length: cols || 6 }).map((__, j) =>
          React.createElement(Skel, { key: j, w: j === 0 ? 90 : (j === (cols || 6) - 1 ? 60 : 120), h: 12 })))));
}

/* ── Empty state ─────────────────────────────────────────── */
function EmptyState({ icon, title, sub, action }) {
  return React.createElement("div", { className: "co-empty" },
    React.createElement("div", { className: "co-empty-icon" }, React.createElement(window.Icon, { name: icon || "inbox", size: 26 })),
    React.createElement("div", { className: "co-empty-title" }, title),
    sub && React.createElement("div", { className: "co-empty-sub" }, sub),
    action);
}

/* ── Overlay primitives ──────────────────────────────────── */
function useEsc(onClose) {
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
}

function Drawer({ children, onClose }) {
  useEsc(onClose);
  return React.createElement(React.Fragment, null,
    React.createElement("div", { className: "co-overlay", onClick: onClose }),
    React.createElement("aside", { className: "co-drawer", role: "dialog" }, children));
}

function Modal({ children, onClose, width, fsTablet }) {
  useEsc(onClose);
  return React.createElement("div", { className: "co-modal" },
    React.createElement("div", { className: "co-overlay", onClick: onClose }),
    React.createElement("div", { className: "co-modal-card" + (fsTablet ? " fs" : ""), style: width ? { width } : null }, children));
}

/* ── Popover (anchored menu) ─────────────────────────────── */
function Popover({ open, onClose, children, style }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    const k = (e) => { if (e.key === "Escape") onClose(); };
    setTimeout(() => document.addEventListener("mousedown", h), 0);
    document.addEventListener("keydown", k);
    return () => { document.removeEventListener("mousedown", h); document.removeEventListener("keydown", k); };
  }, [open, onClose]);
  if (!open) return null;
  return React.createElement("div", { className: "co-pop", ref, style }, children);
}

/* ── Avatar ──────────────────────────────────────────────── */
function Avatar({ name, initials, role, size }) {
  const r = window.CardOps.ROLES[role];
  const bg = r ? r.color : "#6E8BFF";
  return React.createElement("div", {
    className: "co-avatar",
    style: { background: `linear-gradient(135deg, ${bg}, ${bg}99)`, width: size, height: size,
      color: role === "fulfillment" || role === "finance" ? "#0c1525" : "#fff", fontSize: size ? size * 0.38 : null },
  }, initials);
}

function RoleBadge({ role }) {
  const r = window.CardOps.ROLES[role];
  if (!r) return null;
  return React.createElement("span", {
    className: "co-pill", style: { color: r.color, background: r.color + "22" },
  }, r.short);
}

/* ── Definition list ─────────────────────────────────────── */
function DL({ items }) {
  return React.createElement("dl", { className: "co-dl" },
    items.filter(Boolean).map((it, i) =>
      React.createElement("div", { className: "co-dl-row", key: i },
        React.createElement("dt", null, it[0]),
        React.createElement("dd", null, it[1]))));
}

Object.assign(window, {
  StatusPill, Tag, Fee, Tip, Button, GatedButton, Switch, Skel, SkeletonRows,
  EmptyState, Drawer, Modal, Popover, Avatar, RoleBadge, DL, useEsc,
});
