/* Shared UI primitives + design tokens. */
const { useState, useEffect, useRef, useMemo } = React;

const TOKENS = {
  bg: "#0b0d11",
  bgElev: "#10131a",
  panel: "#141821",
  panel2: "#1a1f2a",
  panel3: "#222836",
  border: "#262d3b",
  borderSoft: "#1d2330",
  text: "#e8ecf4",
  textDim: "#aab2c2",
  muted: "#6f7889",
  mutedDeep: "#525a6b",
  amber: "#e9b949",
  amberDim: "#b08826",
  blue: "#5fb1ff",
  green: "#6bd49b",
  warn: "#ffc857",
  danger: "#ff7676",
  mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace',
  sans: '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
  serif: '"Newsreader", "Source Serif Pro", Georgia, serif',
};

/* ---------- Pill / Tag ---------- */
function Tag({ kind, children }) {
  const palette = {
    sourced:    { bg: "rgba(107,212,155,.12)", fg: TOKENS.green },
    "recruiter-supplied": { bg: "rgba(95,177,255,.13)", fg: TOKENS.blue },
    inference:  { bg: "rgba(255,200,87,.14)", fg: TOKENS.warn },
    unknown:    { bg: "rgba(138,147,164,.14)", fg: TOKENS.muted },
  };
  const k = (kind || "unknown").toLowerCase();
  const p = palette[k] || palette.unknown;
  return (
    <span style={{
      display: "inline-block", padding: "2px 7px", borderRadius: 3,
      fontFamily: TOKENS.mono, fontSize: 10.5, fontWeight: 500, letterSpacing: ".02em",
      textTransform: "uppercase", background: p.bg, color: p.fg, lineHeight: 1.5,
    }}>{children}</span>
  );
}

function Tier({ value }) {
  const map = {
    "Tier 1": { bg: "rgba(233,185,73,.16)", fg: TOKENS.amber },
    "Tier 2": { bg: "rgba(95,177,255,.13)", fg: TOKENS.blue },
    "Tier 3": { bg: "rgba(138,147,164,.15)", fg: TOKENS.textDim },
    "Avoid":  { bg: "rgba(255,118,118,.13)", fg: TOKENS.danger },
  };
  const p = map[value] || map["Tier 3"];
  return (
    <span style={{
      display: "inline-block", padding: "2px 8px", borderRadius: 3,
      fontFamily: TOKENS.mono, fontSize: 10.5, fontWeight: 700,
      background: p.bg, color: p.fg, letterSpacing: ".02em", lineHeight: 1.5,
    }}>{value}</span>
  );
}

function Severity({ level }) {
  const map = {
    High:   { fg: TOKENS.danger, dot: TOKENS.danger },
    Medium: { fg: TOKENS.warn,   dot: TOKENS.warn },
    Low:    { fg: TOKENS.green,  dot: TOKENS.green },
  };
  const p = map[level] || map.Low;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: TOKENS.mono, fontSize: 11, color: p.fg, fontWeight: 600 }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: p.dot, display: "inline-block" }} />
      {level.toUpperCase()}
    </span>
  );
}

/* ---------- Editable text ---------- */
function Editable({ value, onChange, multiline, placeholder, style, mono }) {
  const [v, setV] = useState(value);
  useEffect(() => setV(value), [value]);
  const baseStyle = {
    background: "transparent", border: "1px solid transparent", color: "inherit",
    font: "inherit", fontFamily: mono ? TOKENS.mono : "inherit",
    width: "100%", padding: "4px 6px", margin: "-4px -6px", borderRadius: 4,
    resize: multiline ? "vertical" : "none", lineHeight: "inherit",
    transition: "border-color .12s, background .12s",
    ...style,
  };
  const props = {
    value: v ?? "",
    placeholder,
    style: baseStyle,
    onChange: (e) => setV(e.target.value),
    onFocus: (e) => { e.target.style.borderColor = TOKENS.border; e.target.style.background = TOKENS.bg; },
    onBlur: (e) => {
      e.target.style.borderColor = "transparent";
      e.target.style.background = "transparent";
      if (v !== value) onChange?.(v);
    },
  };
  return multiline ? <textarea {...props} rows={3} /> : <input type="text" {...props} />;
}

/* ---------- Copy button ---------- */
function CopyBtn({ text, label = "Copy" }) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      onClick={() => {
        navigator.clipboard.writeText(typeof text === "function" ? text() : text);
        setCopied(true);
        setTimeout(() => setCopied(false), 1200);
      }}
      style={{
        background: "transparent", border: `1px solid ${copied ? TOKENS.green : TOKENS.border}`,
        color: copied ? TOKENS.green : TOKENS.textDim, padding: "4px 10px",
        borderRadius: 4, fontFamily: TOKENS.mono, fontSize: 10.5, fontWeight: 600,
        cursor: "pointer", letterSpacing: ".04em", textTransform: "uppercase",
        transition: "all .15s",
      }}
    >{copied ? "✓ Copied" : label}</button>
  );
}

/* ---------- Section heading + anchors ---------- */
function SectionHead({ id, eyebrow, title, right }) {
  return (
    <div id={id} style={{
      display: "flex", justifyContent: "space-between", alignItems: "flex-end",
      paddingBottom: 10, marginBottom: 14, borderBottom: `1px solid ${TOKENS.border}`,
      scrollMarginTop: 80,
    }}>
      <div>
        {eyebrow && (
          <div style={{
            fontFamily: TOKENS.mono, fontSize: 10.5, color: TOKENS.amberDim,
            letterSpacing: ".12em", textTransform: "uppercase", marginBottom: 4, fontWeight: 600,
          }}>{eyebrow}</div>
        )}
        <h2 style={{ font: "600 22px/1.2 " + TOKENS.serif, margin: 0, letterSpacing: "-0.01em", color: TOKENS.text }}>{title}</h2>
      </div>
      {right}
    </div>
  );
}

/* ---------- Panel ---------- */
function Panel({ children, style, dense }) {
  return (
    <div style={{
      background: TOKENS.panel,
      border: `1px solid ${TOKENS.borderSoft}`,
      borderRadius: 8,
      padding: dense ? "14px 16px" : "20px 22px",
      marginBottom: 14,
      ...style,
    }}>{children}</div>
  );
}

/* ---------- KV row ---------- */
function KV({ k, v, mono }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: 14, padding: "8px 0", borderBottom: `1px solid ${TOKENS.borderSoft}`, alignItems: "baseline" }}>
      <div style={{ fontFamily: TOKENS.mono, fontSize: 10.5, color: TOKENS.muted, textTransform: "uppercase", letterSpacing: ".08em" }}>{k}</div>
      <div style={{ fontFamily: mono ? TOKENS.mono : "inherit", fontSize: 13, color: TOKENS.text }}>{v}</div>
    </div>
  );
}

/* ---------- Internal-only ribbon ---------- */
function InternalOnly({ visible, children, label = "Internal only" }) {
  if (!visible) return null;
  return (
    <div style={{
      position: "relative",
      border: `1px dashed ${TOKENS.amberDim}`,
      borderRadius: 8,
      padding: "16px 18px 18px",
      margin: "12px 0",
      background: "rgba(233,185,73,.025)",
    }}>
      <div style={{
        position: "absolute", top: -9, left: 12, padding: "1px 8px",
        background: TOKENS.bg, fontFamily: TOKENS.mono, fontSize: 10, color: TOKENS.amber,
        letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 700,
      }}>★ {label}</div>
      {children}
    </div>
  );
}

/* ---------- Viewport hook ---------- */
function useViewport() {
  const [w, setW] = useState(typeof window !== "undefined" ? window.innerWidth : 1200);
  useEffect(() => {
    const onR = () => setW(window.innerWidth);
    window.addEventListener("resize", onR);
    window.addEventListener("orientationchange", onR);
    return () => {
      window.removeEventListener("resize", onR);
      window.removeEventListener("orientationchange", onR);
    };
  }, []);
  return { width: w, isMobile: w < 768, isTablet: w >= 768 && w < 1024, isDesktop: w >= 1024 };
}

window.IE_UI = {
  TOKENS, Tag, Tier, Severity, Editable, CopyBtn, SectionHead, Panel, KV, InternalOnly, useViewport,
};
