/* ============================================================
   Shared UI primitives for the Post-Call Analysis app.
   Composes the ai-coustics design-system bundle (Button, Icon)
   and adds dark-tuned Badge / chips, mirroring how the brand's
   own inverse "Developer Platform" kit retunes feedback colors
   for the black app shell.
   ============================================================ */
;(function(){
const DS = window.AiCousticsDesignSystem_19d2ca;
const Icon = DS.Icon;
const Button = DS.Button;

// responsive helper: true on phone-width viewports (drives inline-style branching)
function useIsMobile(bp = 640) {
  const q = `(max-width: ${bp}px)`;
  const [m, setM] = React.useState(() => typeof window !== "undefined" && window.matchMedia(q).matches);
  React.useEffect(() => {
    const mql = window.matchMedia(q);
    const on = (e) => setM(e.matches);
    mql.addEventListener ? mql.addEventListener("change", on) : mql.addListener(on);
    setM(mql.matches);
    return () => { mql.removeEventListener ? mql.removeEventListener("change", on) : mql.removeListener(on); };
  }, [q]);
  return m;
}

// dark-surface badge tones (the bundle's defaults are tuned for light)
const BADGE_TONES = {
  neutral: { fg: "var(--gray-40)", bg: "var(--surface-sunken)", dot: "var(--gray-60)" },
  accent: { fg: "#9db8ff", bg: "rgba(105,147,255,0.16)", dot: "var(--blue-40)" },
  positive: { fg: "#43d6c0", bg: "rgba(0,191,166,0.16)", dot: "var(--teal)" },
  warning: { fg: "#f4cd7a", bg: "rgba(244,185,66,0.18)", dot: "var(--amber)" },
  critical: { fg: "#eaa597", bg: "rgba(226,140,124,0.20)", dot: "var(--clay)" },
};

function Badge({ children, tone = "neutral", dot, size = "md", style }) {
  const t = BADGE_TONES[tone] || BADGE_TONES.neutral;
  const pad = size === "sm" ? "2px 8px" : "3px 10px";
  const fs = size === "sm" ? 11 : 12;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6, padding: pad,
      paddingLeft: dot ? 8 : undefined, fontFamily: "var(--font-sans)", fontSize: fs, fontWeight: 600,
      borderRadius: "var(--radius-pill)", color: t.fg, background: t.bg, whiteSpace: "nowrap", lineHeight: 1.4, ...style,
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: "50%", background: t.dot, flex: "0 0 auto" }} />}
      {children}
    </span>
  );
}

// pill chip for filters / segmented controls (dark)
function Chip({ children, active, onClick, icon, style }) {
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 13px",
      fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500, lineHeight: 1,
      borderRadius: "var(--radius-pill)", cursor: "pointer",
      border: `1px solid ${active ? "var(--blue-40)" : "var(--border-subtle)"}`,
      background: active ? "rgba(105,147,255,0.14)" : "transparent",
      color: active ? "#bcd0ff" : "var(--text-secondary)",
      transition: "all var(--dur-fast) var(--ease-standard)", ...style,
    }}>
      {icon && <Icon name={icon} size={14} color={active ? "var(--blue-40)" : "var(--text-tertiary)"} />}
      {children}
    </button>
  );
}

function Tooltip({ label, children, width = 240 }) {
  const [open, setOpen] = React.useState(false);
  return (
    <span style={{ position: "relative", display: "inline-flex" }}
      onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      {children}
      {open && (
        <span style={{
          position: "absolute", bottom: "calc(100% + 8px)", left: "50%", transform: "translateX(-50%)",
          width, zIndex: 50, background: "var(--off-black)", border: "1px solid var(--border-subtle)",
          borderRadius: "var(--radius-sm)", padding: "9px 11px", boxShadow: "var(--shadow-lg)",
          fontFamily: "var(--font-sans)", fontSize: 12, lineHeight: 1.5, color: "var(--text-secondary)",
          textTransform: "none", letterSpacing: 0, fontWeight: 400, pointerEvents: "none",
        }}>{label}</span>
      )}
    </span>
  );
}

// shared modal scaffold: backdrop + centered panel
const closeBtn = {
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  width: 34, height: 34, borderRadius: "var(--radius-md)", flex: "0 0 auto",
  border: "1px solid var(--border-subtle)", background: "transparent", cursor: "pointer",
};
function Overlay({ children, onClose }) {
  const isMobile = useIsMobile();
  React.useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div onMouseDown={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100, display: "flex",
      alignItems: isMobile ? "flex-start" : "center", justifyContent: "center",
      padding: isMobile ? 10 : 24, background: "rgba(5,5,5,0.62)",
      backdropFilter: "blur(6px)", WebkitBackdropFilter: "blur(6px)",
      animation: "aiFade 160ms var(--ease-out)", overflowY: "auto",
    }}>
      <div onMouseDown={(e) => e.stopPropagation()} style={{
        background: "var(--surface-card)", border: "1px solid var(--border-subtle)",
        borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)",
        padding: isMobile ? 16 : 24, maxWidth: "100%", width: isMobile ? "100%" : undefined,
        maxHeight: isMobile ? "none" : "92vh", overflowY: isMobile ? "visible" : "auto",
        animation: "aiRise 220ms var(--ease-out)",
      }}>{children}</div>
    </div>
  );
}

// horizontal severity meter used inside score cells & breakdown
function SeverityBar({ value, neutral, height = 4, track = "rgba(255,255,255,0.07)", color: colorProp }) {
  const { severityColor } = window.AIData;
  const color = colorProp || (neutral ? "var(--gray-60)" : severityColor(value, 0.92));
  return (
    <div style={{ height, borderRadius: 999, background: track, overflow: "hidden", width: "100%" }}>
      <div style={{ width: `${Math.max(2, value * 100)}%`, height: "100%", borderRadius: 999, background: color }} />
    </div>
  );
}

window.UI = { DS, Icon, Button, Badge, Chip, Tooltip, SeverityBar, Overlay, closeBtn, BADGE_TONES, useIsMobile };
})();
