// Shared UI atoms for the admin

function Btn({ children, variant = "primary", size = "md", icon, onClick, disabled, style, type = "button", ...rest }) {
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
    border: 0, cursor: disabled ? "not-allowed" : "pointer",
    fontWeight: 600, letterSpacing: "0.01em",
    transition: "transform .08s ease, background .12s ease, color .12s ease",
    fontFamily: "inherit",
    opacity: disabled ? 0.5 : 1,
  };
  const sizes = {
    sm: { height: 28, padding: "0 12px", fontSize: 12, borderRadius: 6 },
    md: { height: 36, padding: "0 16px", fontSize: 13, borderRadius: 8 },
    lg: { height: 44, padding: "0 22px", fontSize: 14, borderRadius: 10 },
  }[size];
  const variants = {
    primary: { background: "var(--red)", color: "#fff" },
    secondary: { background: "var(--panel-2)", color: "var(--ink)", border: "1px solid var(--line-2)" },
    ghost: { background: "transparent", color: "var(--ink-2)" },
    danger: { background: "transparent", color: "var(--red-2)", border: "1px solid rgba(255,59,50,0.3)" },
  }[variant];
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{ ...base, ...sizes, ...variants, ...style }} {...rest}>
      {icon}
      {children}
    </button>
  );
}

function Pill({ children, tone = "neutral", style }) {
  const tones = {
    neutral:    { background: "rgba(255,255,255,0.06)", color: "var(--ink-2)", border: "1px solid var(--line)" },
    red:        { background: "var(--red-soft)", color: "var(--red-2)", border: "1px solid rgba(255,59,50,0.25)" },
    green:      { background: "rgba(30,215,115,0.1)", color: "var(--green)", border: "1px solid rgba(30,215,115,0.25)" },
    amber:      { background: "rgba(255,176,32,0.1)", color: "var(--amber)", border: "1px solid rgba(255,176,32,0.25)" },
    blue:       { background: "rgba(74,166,255,0.1)", color: "var(--blue)", border: "1px solid rgba(74,166,255,0.25)" },
  };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "3px 8px", borderRadius: 999,
      fontSize: 11, fontWeight: 600, letterSpacing: "0.02em",
      ...tones[tone], ...style,
    }}>{children}</span>
  );
}

function Card({ children, style, label, action, padding = 20 }) {
  return (
    <section style={{
      background: "var(--panel)",
      border: "1px solid var(--line)",
      borderRadius: "var(--radius-lg)",
      ...style,
    }}>
      {(label || action) && (
        <header style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "14px 18px", borderBottom: "1px solid var(--line)",
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-3)" }}>
            {label}
          </div>
          {action}
        </header>
      )}
      <div style={{ padding }}>{children}</div>
    </section>
  );
}

// Live-status sync indicator (Google Sheets)
function SheetsSync({ status = "synced", count, onRefresh }) {
  const cfg = ({
    synced:       { dot: "var(--green)",  text: "Google Sheets — synced" },
    syncing:      { dot: "var(--amber)",  text: "Syncing to Google Sheets…" },
    error:        { dot: "var(--red-2)",  text: "Sync error — retrying" },
    unconfigured: { dot: "var(--ink-4)",  text: "Webhook not configured" },
    idle:         { dot: "var(--ink-4)",  text: "Sheets — idle" },
  }[status]) || { dot: "var(--ink-4)", text: "Sheets — " + status };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12, color: "var(--ink-2)" }}>
      <div style={{
        width: 6, height: 6, borderRadius: 999, background: cfg.dot,
        boxShadow: `0 0 10px ${cfg.dot}`,
        animation: status === "syncing" ? "pulse 1.2s ease-in-out infinite" : "none",
      }} />
      <span>{cfg.text}</span>
      {count != null && <span style={{ color: "var(--ink-4)" }}>· {count.toLocaleString()} rows</span>}
      {onRefresh && (
        <button
          onClick={onRefresh}
          disabled={status === "syncing"}
          title="Refresh from sheet"
          style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            width: 22, height: 22, padding: 0, marginLeft: 2,
            background: "transparent", border: "1px solid var(--line-2)",
            borderRadius: 6, color: "var(--ink-3)",
            cursor: status === "syncing" ? "default" : "pointer",
            opacity: status === "syncing" ? 0.5 : 1,
            fontFamily: "inherit", fontSize: 12,
          }}
          onMouseEnter={(e) => { if (status !== "syncing") { e.currentTarget.style.borderColor = "var(--red)"; e.currentTarget.style.color = "var(--ink)"; } }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-2)"; e.currentTarget.style.color = "var(--ink-3)"; }}
        >
          <span style={{
            display: "inline-block",
            animation: status === "syncing" ? "spin 0.8s linear infinite" : "none",
          }}>↻</span>
        </button>
      )}
    </div>
  );
}

// Rolling number animation for serial issuance
function RollingSerial({ value, rolling }) {
  const alphabet = window.ADRO_ALPHABET;
  const chars = (value || "").padEnd(10, "?").split("").slice(0, 10);
  return (
    <div className="mono" style={{
      display: "inline-flex", gap: 2,
      fontSize: 28, fontWeight: 700, letterSpacing: "0.05em",
    }}>
      {chars.map((c, i) => (
        <RollingChar key={i} target={c} rolling={rolling} delay={i * 60} />
      ))}
    </div>
  );
}

function RollingChar({ target, rolling, delay }) {
  const [display, setDisplay] = React.useState(target);
  React.useEffect(() => {
    if (!rolling) { setDisplay(target); return; }
    let active = true;
    const start = performance.now() + delay;
    const dur = 700 + delay * 0.6;
    const tick = () => {
      if (!active) return;
      const now = performance.now();
      if (now < start) {
        requestAnimationFrame(tick);
        return;
      }
      const elapsed = now - start;
      if (elapsed >= dur) { setDisplay(target); return; }
      const idx = Math.floor(Math.random() * window.ADRO_ALPHABET.length);
      setDisplay(window.ADRO_ALPHABET[idx]);
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
    return () => { active = false; };
  }, [target, rolling, delay]);
  return (
    <span style={{
      display: "inline-block",
      minWidth: "0.7em",
      padding: "4px 6px",
      background: rolling ? "rgba(224,32,28,0.1)" : "rgba(255,255,255,0.04)",
      borderRadius: 6,
      border: "1px solid var(--line)",
      color: rolling ? "var(--red-2)" : "var(--ink)",
      transition: "background .2s, color .2s",
      textAlign: "center",
    }}>{display}</span>
  );
}

// Search field
function SearchField({ value, onChange, placeholder = "Search…" }) {
  return (
    <div style={{
      position: "relative", display: "flex", alignItems: "center",
      background: "var(--bg-3)", border: "1px solid var(--line)",
      borderRadius: 8, height: 36, padding: "0 12px", gap: 10, minWidth: 240,
    }}>
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
        <circle cx="7" cy="7" r="5" stroke="var(--ink-3)" strokeWidth="1.5" />
        <path d="M11 11l3 3" stroke="var(--ink-3)" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          flex: 1, background: "transparent", border: 0, outline: "none",
          color: "var(--ink)", fontSize: 13, fontFamily: "inherit",
        }}
      />
      <kbd style={{
        fontSize: 10, color: "var(--ink-4)", padding: "2px 5px",
        border: "1px solid var(--line)", borderRadius: 4,
        fontFamily: "var(--mono)",
      }}>⌘K</kbd>
    </div>
  );
}

// CSS animation keyframes injected once
function GlobalStyles() {
  return (
    <style>{`
      @keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.4 } }
      @keyframes spin  { to { transform: rotate(360deg); } }
      @keyframes glow {
        0%,100% { box-shadow: 0 0 0 0 var(--red-glow), 0 0 20px var(--red-glow); }
        50%     { box-shadow: 0 0 0 6px transparent, 0 0 30px var(--red-glow); }
      }
      @keyframes slideUp {
        from { opacity: 0; transform: translateY(8px); }
        to   { opacity: 1; transform: translateY(0); }
      }
      @keyframes slideDown {
        from { opacity: 0; transform: translateY(-8px); }
        to   { opacity: 1; transform: translateY(0); }
      }
      @keyframes scale-in {
        from { opacity: 0; transform: scale(0.96); }
        to   { opacity: 1; transform: scale(1); }
      }
      @keyframes confetti-fall {
        0%   { transform: translateY(-10vh) rotate(0deg); opacity: 1; }
        100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
      }
      @keyframes shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
      }
      .ah-row { transition: background .12s ease; }
      .ah-row:hover { background: rgba(255,255,255,0.03); }
      .ah-tab { position: relative; cursor: pointer; user-select: none; }
      .ah-tab:hover { color: var(--ink); }
      .ah-tab[data-active="true"]::after {
        content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; background: var(--red);
      }
      input.field, textarea.field, select.field {
        background: var(--bg-3); color: var(--ink); border: 1px solid var(--line);
        border-radius: 8px; padding: 10px 12px; font: inherit; font-size: 13px;
        width: 100%; outline: none; transition: border .12s ease, background .12s ease;
        font-family: inherit;
      }
      input.field:hover, textarea.field:hover, select.field:hover { border-color: var(--line-2); }
      input.field:focus, textarea.field:focus, select.field:focus { border-color: var(--red); background: var(--bg-2); }
      input.field::placeholder, textarea.field::placeholder { color: var(--ink-4); }
      label.lbl {
        display: block; font-size: 11px; font-weight: 700; letter-spacing: 0.08em;
        text-transform: uppercase; color: var(--ink-3); margin-bottom: 6px;
      }
    `}</style>
  );
}

Object.assign(window, { Btn, Pill, Card, SheetsSync, RollingSerial, RollingChar, SearchField, GlobalStyles });
