/* KitRate — shared UI components */

const { useState, useEffect, useMemo, useRef, useCallback } = React;

/* ---------- tiny icon set (stroke, 16px grid) ---------- */
function KrIcon({ d, size = 16, sw = 1.6, style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" style={style} aria-hidden="true">
      <path d={d} stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"></path>
    </svg>
  );
}
const ICONS = {
  arrowRight: "M2.5 8h11M9.5 4l4 4-4 4",
  arrowLeft: "M13.5 8h-11M6.5 4l-4 4 4 4",
  check: "M2.5 8.5l3.5 3.5L13.5 4.5",
  copy: "M5.5 5.5h8v8h-8zM3 10.5h-.5v-8h8V3",
  download: "M8 2.5v8M4.5 7l3.5 3.5L11.5 7M3 13.5h10",
  link: "M6.5 9.5l3-3M5 11l-1.2 1.2a2.4 2.4 0 01-3.4-3.4L2.6 7M11 5l1.2-1.2a2.4 2.4 0 013.4 3.4L13.4 9",
  mail: "M1.5 3.5h13v9h-13zM1.5 4l6.5 5 6.5-5",
  edit: "M11.5 2.5l2 2-8.5 8.5-3 1 1-3zM10 4l2 2",
  sliders: "M2 4.5h7M12 4.5h2M2 11.5h2M7 11.5h7M9 2.5v4M4 9.5v4",
  shield: "M8 1.5l5.5 2v4c0 3.5-2.5 6-5.5 7-3-1-5.5-3.5-5.5-7v-4z",
  info: "M8 7.5v4M8 4.8v.1M8 14.5a6.5 6.5 0 100-13 6.5 6.5 0 000 13z",
  refresh: "M13.5 8a5.5 5.5 0 11-1.6-3.9M13.5 2.5v2.5h-2.5",
  plus: "M8 3v10M3 8h10",
  x: "M4 4l8 8M12 4l-8 8",
  eye: "M1.5 8s2.5-4.5 6.5-4.5S14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8zM8 9.8a1.8 1.8 0 100-3.6 1.8 1.8 0 000 3.6z",
  doc: "M4 1.5h5.5l3 3V14.5H4zM9.5 1.5v3h3M6 8h4.5M6 10.5h4.5",
  spark: "M8 1.5l1.6 4.9 4.9 1.6-4.9 1.6L8 14.5 6.4 9.6 1.5 8l4.9-1.6z",
  clock: "M8 4.5V8l2.5 1.5M8 14.5a6.5 6.5 0 100-13 6.5 6.5 0 000 13z",
  warn: "M8 2l6.5 11.5h-13zM8 6.5V10M8 11.8v.1"
};

/* ---------- form field ---------- */
function Field({ label, hint, error, children, style }) {
  return (
    <div style={{ marginBottom: 18, ...style }}>
      {label && <label className="kr-label">{label}</label>}
      {children}
      {error ? <div className="kr-error-text">{error}</div> : hint ? <div className="kr-hint">{hint}</div> : null}
    </div>
  );
}

/* ---------- confidence chip ---------- */
function ConfidenceChip({ level, label }) {
  const cls = level === "high" ? "kr-chip-good" : level === "medium" ? "kr-chip-warn" : "kr-chip-bad";
  return <span className={"kr-chip " + cls}>{label || level + " confidence"}</span>;
}

function StatusChip({ status }) {
  const map = { active: "kr-chip-good", outdated: "kr-chip-bad", experimental: "kr-chip-warn" };
  return <span className={"kr-chip " + (map[status] || "")} style={{ fontSize: 10 }}>{status}</span>;
}

/* ---------- toast ---------- */
function useToast() {
  const [msg, setMsg] = useState(null);
  const timer = useRef(null);
  const toast = useCallback((m) => {
    setMsg(m);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setMsg(null), 2400);
  }, []);
  const node = msg ? <div className="kr-toast">{msg}</div> : null;
  return [toast, node];
}

/* ---------- copy-to-clipboard button ---------- */
function CopyBtn({ text, label = "Copy", toast, small, disabled = false }) {
  return (
    <button disabled={disabled} className={"kr-btn kr-btn-secondary" + (small ? " kr-btn-sm" : "")} onClick={() => {
      const ta = document.createElement("textarea");
      ta.value = text; document.body.appendChild(ta); ta.select();
      try { document.execCommand("copy"); } catch (e) {}
      document.body.removeChild(ta);
      toast && toast("Copied to clipboard");
    }}>
      <KrIcon d={ICONS.copy} size={14} />{label}
    </button>
  );
}

/* ---------- integration note (where real APIs would connect) ---------- */
function IntegrationNote({ children }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="kr-no-print" style={{ border: "1px dashed var(--line-strong)", borderRadius: 8, background: "var(--surface-2)", margin: "10px 0" }}>
      <button onClick={() => setOpen(!open)} style={{
        display: "flex", alignItems: "center", gap: 8, width: "100%", textAlign: "left",
        background: "none", border: "none", padding: "8px 12px",
        fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)"
      }}>
        <KrIcon d={ICONS.info} size={13} /> Integration note {open ? "▾" : "▸"}
      </button>
      {open && <div style={{ padding: "0 12px 10px 33px", fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{children}</div>}
    </div>
  );
}

/* ---------- big metric stat ---------- */
function Stat({ value, label, accent }) {
  return (
    <div>
      <div className="kr-serif" style={{ fontSize: 30, fontWeight: 500, letterSpacing: "-0.01em", color: accent ? "var(--accent)" : "var(--ink)", lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>{label}</div>
    </div>
  );
}

/* ---------- horizontal range bar (rate visual) ---------- */
function RangeBar({ low, high, max }) {
  const l = Math.max(0, (low / max) * 100);
  const w = Math.max(2, ((high - low) / max) * 100);
  return (
    <div style={{ position: "relative", height: 6, background: "var(--surface-2)", borderRadius: 99, overflow: "hidden" }}>
      <div style={{ position: "absolute", left: l + "%", width: w + "%", top: 0, bottom: 0, background: "var(--accent)", borderRadius: 99, opacity: 0.85 }}></div>
    </div>
  );
}

/* ---------- empty state ---------- */
function EmptyState({ icon = "doc", title, desc, action }) {
  return (
    <div style={{ textAlign: "center", padding: "56px 24px", color: "var(--muted)" }}>
      <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--surface-2)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 14, color: "var(--ink-2)" }}>
        <KrIcon d={ICONS[icon]} size={22} />
      </div>
      <div className="kr-serif" style={{ fontSize: 19, color: "var(--ink)", marginBottom: 6 }}>{title}</div>
      <p style={{ fontSize: 13.5, maxWidth: 360, margin: "0 auto 18px" }}>{desc}</p>
      {action}
    </div>
  );
}

/* ---------- modal ---------- */
function Modal({ title, onClose, children, width = 560 }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(29,26,21,0.45)", zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div className="kr-card kr-fade-in" onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: width, maxHeight: "85vh", display: "flex", flexDirection: "column", boxShadow: "var(--shadow-2)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 22px", borderBottom: "1px solid var(--line)" }}>
          <div className="kr-serif" style={{ fontSize: 19, fontWeight: 500 }}>{title}</div>
          <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={onClose} aria-label="Close"><KrIcon d={ICONS.x} size={14} /></button>
        </div>
        <div className="kr-scroll" style={{ overflowY: "auto", padding: 22 }}>{children}</div>
      </div>
    </div>
  );
}

/* ---------- section heading ---------- */
function SectionHead({ eyebrow, title, desc, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 22, flexWrap: "wrap" }}>
      <div style={{ maxWidth: 620 }}>
        {eyebrow && <div className="kr-eyebrow" style={{ marginBottom: 8 }}>{eyebrow}</div>}
        <h2 className="kr-serif" style={{ fontSize: 30, fontWeight: 500, letterSpacing: "-0.015em", lineHeight: 1.15 }}>{title}</h2>
        {desc && <p style={{ color: "var(--ink-2)", marginTop: 8, fontSize: 14.5 }}>{desc}</p>}
      </div>
      {right && <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>{right}</div>}
    </div>
  );
}

/* ---------- platform glyphs (abstract, not trademarked logos) ---------- */
function PlatformMark({ name, size = 26 }) {
  const letter = { instagram: "IG", tiktok: "TT", youtube: "YT" }[name] || "•";
  return (
    <span style={{
      width: size, height: size, borderRadius: 7, background: "var(--ink)", color: "var(--paper)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--mono)", fontSize: size * 0.38, fontWeight: 500, letterSpacing: "0.02em", flexShrink: 0
    }}>{letter}</span>
  );
}

Object.assign(window, {
  KrIcon, ICONS, Field, ConfidenceChip, StatusChip, useToast, CopyBtn,
  IntegrationNote, Stat, RangeBar, EmptyState, Modal, SectionHead, PlatformMark
});
