/* =========================================================================
   TAXR — Shared UI primitives  (exports to window)
   ========================================================================= */
const { useState, useEffect, useRef } = React;

/* ----------------------------------------------------------------- Icon */
function Icon({ name, size = 18, stroke = 1.7, style }) {
  const p = { fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    arrow:   <path {...p} d="M5 12h14M13 6l6 6-6 6" />,
    back:    <path {...p} d="M19 12H5M11 6l-6 6 6 6" />,
    check:   <polyline {...p} points="20 6 9 17 4 12" />,
    x:       <path {...p} d="M18 6 6 18M6 6l12 12" />,
    lock:    <g {...p}><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></g>,
    chev:    <polyline {...p} points="9 6 15 12 9 18" />,
    chevd:   <polyline {...p} points="6 9 12 15 18 9" />,
    play:    <path {...p} d="M7 5l11 7-11 7V5z" />,
    cards:   <g {...p}><rect x="4" y="6" width="13" height="13" rx="2" /><path d="M8 3h9a2 2 0 0 1 2 2v9" /></g>,
    book:    <g {...p}><path d="M4 5a2 2 0 0 1 2-2h11v15H6a2 2 0 0 0-2 2z" /><path d="M17 3v15" /></g>,
    flag:    <g {...p}><path d="M5 21V4M5 4h11l-2 4 2 4H5" /></g>,
    star:    <path {...p} d="M12 3l2.6 5.6 6 .8-4.4 4.2 1.1 6L12 17l-5.3 2.6 1.1-6L3.4 9.4l6-.8z" />,
    clock:   <g {...p}><circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" /></g>,
    spark:   <path {...p} d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M18 6l-2.5 2.5M8.5 15.5 6 18" />,
    trophy:  <g {...p}><path d="M7 4h10v5a5 5 0 0 1-10 0V4z" /><path d="M7 6H4v1a3 3 0 0 0 3 3M17 6h3v1a3 3 0 0 1-3 3M9 19h6M10 16v3M14 16v3" /></g>,
    target:  <g {...p}><circle cx="12" cy="12" r="8.5" /><circle cx="12" cy="12" r="4.5" /><circle cx="12" cy="12" r="0.6" /></g>,
    bulb:    <g {...p}><path d="M9 18h6M10 21h4" /><path d="M12 3a6 6 0 0 0-3.5 10.9c.6.5 1 1.2 1 2h5c0-.8.4-1.5 1-2A6 6 0 0 0 12 3z" /></g>,
    user:    <g {...p}><circle cx="12" cy="8" r="4" /><path d="M5 20a7 7 0 0 1 14 0" /></g>,
    menu:    <path {...p} d="M4 7h16M4 12h16M4 17h16" />,
    grid:    <g {...p}><rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/></g>,
    fish:    <g {...p}><path d="M3 12c3-5 9-5 12 0-3 5-9 5-12 0z"/><path d="M15 12c2-2 4-3 6-3-1 2-1 4 0 6-2 0-4-1-6-3z"/><circle cx="7" cy="11" r="0.6" fill="currentColor"/></g>,
    shield:  <g {...p}><path d="M12 3l7 3v6c0 4-3 7-7 9-4-2-7-5-7-9V6z" /><polyline points="9 12 11 14 15 10" /></g>,
  };
  return <svg width={size} height={size} viewBox="0 0 24 24" style={style} aria-hidden="true">{paths[name]}</svg>;
}

/* --------------------------------------------------------------- Eyebrow */
function Eyebrow({ children, green, style }) {
  return <span className={"eyebrow" + (green ? " green" : "")} style={style}><span className="dot" />{children}</span>;
}

/* ----------------------------------------------------------------- Badge */
function Badge({ children, kind = "", dot, style }) {
  return (
    <span className={"badge " + kind} style={style}>
      {dot && <span className="dot" />}{children}
    </span>
  );
}

/* ---------------------------------------------------------------- Button */
function Button({ children, variant = "primary", size, arrow, back, block, onClick, disabled, style, type }) {
  const cls = ["btn", "btn-" + variant];
  if (size) cls.push("btn-" + size);
  if (block) cls.push("btn-block");
  return (
    <button type={type || "button"} className={cls.join(" ")} onClick={onClick} disabled={disabled} style={style}>
      {back && <Icon name="back" size={17} style={{ marginRight: -2 }} />}
      {children}
      {arrow && <Icon name="arrow" size={17} style={{ marginLeft: -2 }} />}
    </button>
  );
}

/* ------------------------------------------------------------ Logo / mark */
function Logo({ size = 22, light }) {
  return (
    <span className="row" style={{ gap: 9, alignItems: "center" }}>
      <span style={{ fontSize: size * 1.15 }}>🐧</span>
      <span style={{ fontFamily: "var(--serif)", fontWeight: 700, fontSize: size, letterSpacing: "-0.02em", color: light ? "var(--on-light)" : "var(--text)" }}>
        Taxr
      </span>
    </span>
  );
}

/* ----------------------------------------------------------- Fish token */
function Fish({ count, onClick, compact }) {
  return (
    <button className="row" onClick={onClick} title="Hint balance — click to buy more"
      style={{ gap: 7, padding: compact ? "6px 11px" : "8px 13px", borderRadius: 999,
        border: "1px solid rgba(231,179,92,0.35)", background: "var(--amber-soft)", color: "var(--amber)",
        fontFamily: "var(--mono)", fontSize: 13, letterSpacing: ".02em", cursor: "pointer" }}>
      <Icon name="fish" size={15} /><span className="tnum" style={{ fontWeight: 600 }}>{count}</span>
    </button>
  );
}

/* ------------------------------------------------------------ Window mock */
function WindowMock({ url, children, style }) {
  return (
    <div className="win" style={style}>
      <div className="win-bar">
        <span className="win-dot" style={{ background: "#ec6a5e" }} />
        <span className="win-dot" style={{ background: "#f4bf4f" }} />
        <span className="win-dot" style={{ background: "#61c554" }} />
        {url && <span className="win-url">{url}</span>}
      </div>
      <div>{children}</div>
    </div>
  );
}

/* -------------------------------------------------------------- Progress */
function Progress({ value, green, thin }) {
  return (
    <div className={"track" + (green ? " green" : "") + (thin ? " thin" : "")}>
      <div className="fill" style={{ width: Math.max(0, Math.min(100, value)) + "%" }} />
    </div>
  );
}

function Ring({ value, size = 54, stroke = 5 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} className="ring">
      <circle className="bg" cx={size / 2} cy={size / 2} r={r} fill="none" strokeWidth={stroke} />
      <circle className="fg" cx={size / 2} cy={size / 2} r={r} fill="none" strokeWidth={stroke}
        strokeDasharray={c} strokeDashoffset={c * (1 - value / 100)} />
    </svg>
  );
}

/* ------------------------------------------------------------------- Pip */
/* The friendly penguin guide. tone: 'tip' | 'cheer' | 'warn' */
function Pip({ children, tone = "tip", title, compact, style }) {
  const tones = {
    tip:   { c: "var(--peri)",  bd: "rgba(147,166,255,0.3)",  bg: "rgba(147,166,255,0.08)" },
    cheer: { c: "var(--green)", bd: "rgba(70,214,164,0.32)", bg: "var(--green-soft)" },
    warn:  { c: "var(--amber)", bd: "rgba(231,179,92,0.35)", bg: "var(--amber-soft)" },
  }[tone];
  return (
    <div className="row" style={{ gap: 14, alignItems: "flex-start", padding: compact ? "14px 16px" : "18px 20px",
      borderRadius: 16, border: "1px solid " + tones.bd, background: tones.bg, ...style }}>
      <span style={{ fontSize: 26, lineHeight: 1, flex: "none", marginTop: -1 }}>🐧</span>
      <div className="col" style={{ gap: 4 }}>
        {title && <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: tones.c }}>{title}</span>}
        <div className="fs-15 lh-rel" style={{ color: "var(--text)" }}>{children}</div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------ Modal shell */
function Modal({ children, onClose, max = 520 }) {
  useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <div onClick={onClose} className="center" style={{ position: "fixed", inset: 0, zIndex: 90,
      background: "rgba(5,8,13,0.72)", backdropFilter: "blur(6px)", padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} className="card pop"
        style={{ width: "100%", maxWidth: max, background: "var(--surface)", boxShadow: "var(--shadow-lg)", maxHeight: "90vh", overflow: "auto" }}>
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { Icon, Eyebrow, Badge, Button, Logo, Fish, WindowMock, Progress, Ring, Pip, Modal, ThemeSwitcher, applyTheme });

/* ----------------------------------------------------------- Theme switch */
function applyTheme(t) {
  if (!t || t === "dark") document.documentElement.removeAttribute("data-theme");
  else document.documentElement.setAttribute("data-theme", t);
  try { localStorage.setItem("taxr_theme", t || "dark"); } catch (e) {}
}
function ThemeSwitcher() {
  const [t, setT] = useState(() => { try { return localStorage.getItem("taxr_theme") || "dark"; } catch (e) { return "dark"; } });
  useEffect(() => { applyTheme(t); }, [t]);
  const opts = [["dark", "#0a0e17"], ["cream", "#f4eee1"], ["forest", "#e7efdc"]];
  return (
    <div className="row gap-8" title="Theme" style={{ alignItems: "center" }}>
      {opts.map(([id, c]) => (
        <button key={id} className={"swatch" + (t === id ? " on" : "")} onClick={() => setT(id)} aria-label={id}
          style={{ background: c, boxShadow: id === "dark" ? "inset 0 0 0 1px rgba(255,255,255,0.18)" : "inset 0 0 0 1px rgba(0,0,0,0.14)" }} />
      ))}
    </div>
  );
}
