// Shared primitives for Skillhub Builders
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// --- Mono label ---
function Label({ children, style, ...rest }) {
  return (
    <span className="mono" style={{ display: "inline-block", ...style }} {...rest}>
      {children}
    </span>
  );
}

// --- Tiny status dot ---
function Dot({ color = "var(--accent)", size = 7, pulse = false }) {
  return (
    <span style={{
      display: "inline-block", width: size, height: size, borderRadius: 99,
      background: color, boxShadow: pulse ? `0 0 0 0 ${color}` : "none",
      animation: pulse ? "pulse 1.8s ease-out infinite" : undefined,
      verticalAlign: "middle"
    }} />
  );
}

// --- Terminal window chrome ---
function Terminal({ title = "skillhub@local:~/hub", children, style, ...rest }) {
  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--line-strong)",
      borderRadius: 8,
      overflow: "hidden",
      fontFamily: "var(--mono)",
      fontSize: 13,
      lineHeight: 1.6,
      boxShadow: "0 1px 0 var(--line), 0 20px 40px -24px rgba(0,0,0,0.18)",
      ...style
    }} {...rest}>
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        padding: "10px 14px", borderBottom: "1px solid var(--line)",
        background: "var(--surface-2)"
      }}>
        <span style={{ display: "flex", gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: 99, background: "var(--line-strong)" }} />
          <span style={{ width: 10, height: 10, borderRadius: 99, background: "var(--line-strong)" }} />
          <span style={{ width: 10, height: 10, borderRadius: 99, background: "var(--line-strong)" }} />
        </span>
        <span className="mono" style={{ marginLeft: 8, color: "var(--fg-3)" }}>{title}</span>
      </div>
      <div style={{ padding: "18px 18px 20px" }}>{children}</div>
    </div>
  );
}

// --- Typed line (for terminal hero) ---
function TypedLine({ prompt = "$", text, delay = 0, speed = 22, onDone }) {
  const [shown, setShown] = useState(0);
  const [started, setStarted] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setStarted(true), delay);
    return () => clearTimeout(t);
  }, [delay]);
  useEffect(() => {
    if (!started) return;
    if (shown >= text.length) { onDone && onDone(); return; }
    const t = setTimeout(() => setShown(s => s + 1), speed);
    return () => clearTimeout(t);
  }, [started, shown, text, speed, onDone]);
  return (
    <div style={{ whiteSpace: "pre-wrap" }}>
      <span style={{ color: "var(--fg-3)" }}>{prompt}&nbsp;</span>
      <span>{text.slice(0, shown)}</span>
      {started && shown < text.length && <span className="cursor" />}
    </div>
  );
}

// --- Button ---
function Btn({ children, variant = "primary", size = "md", as = "button", href, onClick, style, ...rest }) {
  const base = {
    display: "inline-flex", alignItems: "center", gap: 8,
    fontFamily: "var(--mono)", fontSize: size === "sm" ? 11 : 12,
    letterSpacing: "0.04em", textTransform: "uppercase",
    padding: size === "sm" ? "8px 12px" : "12px 18px",
    borderRadius: 6, border: "1px solid transparent", cursor: "pointer",
    transition: "transform 120ms ease, background 160ms ease, color 160ms ease, border-color 160ms ease",
    whiteSpace: "nowrap"
  };
  const variants = {
    primary: { background: "var(--accent)", color: "var(--accent-fg)", borderColor: "var(--accent)" },
    ghost: { background: "transparent", color: "var(--fg)", borderColor: "var(--line-strong)" },
    soft: { background: "var(--accent-soft)", color: "var(--accent)", borderColor: "transparent" }
  };
  const Cmp = as;
  const props = {
    onClick, href, style: { ...base, ...variants[variant], ...style },
    onMouseEnter: (e) => { e.currentTarget.style.transform = "translateY(-1px)"; },
    onMouseLeave: (e) => { e.currentTarget.style.transform = "translateY(0)"; },
    ...rest
  };
  return <Cmp {...props}>{children}</Cmp>;
}

// --- Arrow icon ---
function Arrow({ size = 14, dir = "right" }) {
  const rot = { right: 0, up: -45, down: 135, upRight: -45 }[dir] ?? 0;
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none" style={{ transform: `rotate(${rot}deg)`, transition: "transform 160ms" }}>
      <path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square" strokeLinejoin="miter" />
    </svg>
  );
}

// --- Section heading ---
function SectionHead({ kicker, title, sub, align = "left", style }) {
  return (
    <div style={{ textAlign: align, maxWidth: 760, margin: align === "center" ? "0 auto" : 0, ...style }}>
      {kicker && <Label style={{ color: "var(--accent)", marginBottom: 14 }}>{kicker}</Label>}
      <h2 style={{
        fontFamily: "var(--sans)", fontWeight: 600, letterSpacing: "-0.02em",
        fontSize: "clamp(28px, 3.4vw, 44px)", lineHeight: 1.08, margin: "0 0 14px",
        textWrap: "pretty"
      }}>{title}</h2>
      {sub && <p style={{ color: "var(--fg-2)", fontSize: 17, lineHeight: 1.55, margin: 0, textWrap: "pretty" }}>{sub}</p>}
    </div>
  );
}

// --- Container ---
function Container({ children, style, wide = false, ...rest }) {
  return (
    <div style={{
      maxWidth: wide ? 1360 : 1200, margin: "0 auto",
      padding: "0 clamp(20px, 4vw, 48px)", ...style
    }} {...rest}>{children}</div>
  );
}

// --- Divider w/ mono caption ---
function HRule({ label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "48px 0" }}>
      <div style={{ flex: 1, borderTop: "1px solid var(--line)" }} />
      {label && <Label style={{ color: "var(--fg-3)" }}>{label}</Label>}
      <div style={{ flex: 1, borderTop: "1px solid var(--line)" }} />
    </div>
  );
}

// --- Accordion item ---
function Accordion({ items }) {
  const [open, setOpen] = useState(0);
  return (
    <div style={{ borderTop: "1px solid var(--line-strong)" }}>
      {items.map((it, i) => {
        const isOpen = open === i;
        return (
          <div key={i} style={{ borderBottom: "1px solid var(--line-strong)" }}>
            <button
              onClick={() => setOpen(isOpen ? -1 : i)}
              style={{
                width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "22px 4px", textAlign: "left", gap: 24
              }}
            >
              <span style={{ display: "flex", alignItems: "baseline", gap: 18 }}>
                <Label style={{ color: "var(--fg-3)", minWidth: 28 }}>{String(i + 1).padStart(2, "0")}</Label>
                <span style={{ fontSize: 18, fontWeight: 500, letterSpacing: "-0.01em" }}>{it.q}</span>
              </span>
              <span style={{
                width: 22, height: 22, display: "grid", placeItems: "center",
                border: "1px solid var(--line-strong)", borderRadius: 99, flexShrink: 0,
                transform: isOpen ? "rotate(45deg)" : "rotate(0)", transition: "transform 200ms"
              }}>
                <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 1v8M1 5h8" stroke="currentColor" strokeWidth="1.2" /></svg>
              </span>
            </button>
            <div style={{
              display: "grid",
              gridTemplateRows: isOpen ? "1fr" : "0fr",
              transition: "grid-template-rows 240ms ease"
            }}>
              <div style={{ overflow: "hidden" }}>
                <div className="acc-answer" style={{ padding: "0 4px 22px 66px", color: "var(--fg-2)", fontSize: 15.5, lineHeight: 1.6, maxWidth: 680 }}>
                  {it.a}
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// --- Ticker ---
function Ticker({ items }) {
  const content = (
    <>
      {items.map((it, i) => (
        <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 12, color: "var(--fg-2)" }}>
          <Dot />
          <span className="mono">{it}</span>
        </span>
      ))}
    </>
  );
  return (
    <div style={{
      overflow: "hidden", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)",
      padding: "14px 0", background: "var(--surface)"
    }}>
      <div className="ticker-track">
        {content}{content}
      </div>
    </div>
  );
}

// --- Placeholder media tile (striped) ---
function PlaceholderMedia({ label, ratio = "4 / 3", tone = "a" }) {
  const stripes = tone === "a"
    ? `repeating-linear-gradient(135deg, var(--surface-2) 0 10px, transparent 10px 20px)`
    : `repeating-linear-gradient(45deg, var(--accent-soft) 0 10px, transparent 10px 20px)`;
  return (
    <div style={{
      aspectRatio: ratio, width: "100%", border: "1px solid var(--line-strong)",
      borderRadius: 8, background: `${stripes}, var(--surface)`, position: "relative", overflow: "hidden"
    }}>
      <span className="mono" style={{
        position: "absolute", left: 12, top: 12, padding: "4px 8px",
        background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 4
      }}>{label}</span>
    </div>
  );
}

Object.assign(window, { Label, Dot, Terminal, TypedLine, Btn, Arrow, SectionHead, Container, HRule, Accordion, Ticker, PlaceholderMedia });
