// Shared UI primitives for the RDB Backstage UI kit.
// Exports onto window so other Babel script files can use them.

// ============ Logo ============
function Logo({ size = 80, variant = "stacked", color = "gold", showSubtitle = true, subtitleColor }) {
  // size = monogram height in px
  const R = (id, f) => (window.__resources && window.__resources[id]) || f;
  const src =
    color === "gold"  ? R("monogramGold",  "assets/rdb-monogram-gold.png")  :
    color === "black" ? R("monogramBlack", "assets/rdb-monogram-black.png") :
                        R("monogramIvory", "assets/rdb-monogram-ivory.png");

  const sub = subtitleColor || (color === "black" ? "#0D0D0D" : "var(--rdb-gold)");

  if (variant === "horizontal") {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <img src={src} alt="RDB" style={{ height: size, width: "auto", display: "block" }} />
        <div style={{ width: 1, height: size * 0.7, background: sub }} />
        <div style={{
          fontFamily: "var(--font-body)",
          fontWeight: 700,
          fontSize: size * 0.18,
          letterSpacing: "0.32em",
          color: sub,
          textTransform: "uppercase",
          lineHeight: 1
        }}>Backstage</div>
      </div>
    );
  }

  // stacked
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: size * 0.14 }}>
      <img src={src} alt="RDB" style={{ height: size, width: "auto", display: "block" }} />
      {showSubtitle && (
        <>
          <div style={{ height: 1, width: size * 0.6, background: sub, opacity: 0.85 }} />
          <div style={{
            fontFamily: "var(--font-body)",
            fontWeight: 700,
            fontSize: Math.max(10, size * 0.10),
            letterSpacing: "0.32em",
            color: sub,
            textTransform: "uppercase",
            lineHeight: 1
          }}>Backstage</div>
        </>
      )}
    </div>
  );
}

// ============ Button ============
function Button({ variant = "primary", size = "md", icon, iconRight, disabled, onClick, children, type, fullWidth, style }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);

  const base = {
    fontFamily: "var(--font-body)",
    fontWeight: 600,
    letterSpacing: "0.04em",
    border: "1px solid transparent",
    borderRadius: 2,
    cursor: disabled ? "not-allowed" : "pointer",
    transition: "all 200ms cubic-bezier(.22,1,.36,1)",
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    gap: 8,
    lineHeight: 1,
    width: fullWidth ? "100%" : undefined,
    opacity: disabled ? 0.4 : 1,
    ...style,
  };
  const sizes = {
    sm: { fontSize: 11, padding: "8px 14px" },
    md: { fontSize: 13, padding: "12px 22px" },
    lg: { fontSize: 14, padding: "16px 28px" },
  };
  const variants = {
    primary: {
      background: hover ? "#E8C96A" : "var(--rdb-gold)",
      color: "#0D0D0D",
      boxShadow: press ? "inset 0 0 0 1px rgba(201,168,76,0.4)" : "none",
    },
    secondary: {
      background: "transparent",
      color: hover ? "var(--rdb-gold)" : "var(--fg-1)",
      borderColor: hover ? "var(--rdb-gold)" : "var(--ink-4)",
    },
    ghost: {
      background: "transparent",
      color: hover ? "var(--rdb-gold)" : "var(--fg-2)",
    },
    danger: {
      background: hover ? "rgba(192,57,43,0.14)" : "transparent",
      color: "#C0392B",
      borderColor: "rgba(192,57,43,0.4)",
    },
  };

  return (
    <button
      type={type || "button"}
      disabled={disabled}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{ ...base, ...sizes[size], ...variants[variant] }}
    >
      {icon}
      {children}
      {iconRight}
    </button>
  );
}

// ============ Input ============
function Input({ label, type = "text", value, onChange, placeholder, error, autoFocus, hint, trailing, name }) {
  const [focused, setFocused] = React.useState(false);
  const borderColor = error ? "#C0392B" : focused ? "var(--rdb-gold)" : "var(--ink-4)";
  const labelColor  = error ? "#C0392B" : focused ? "var(--rdb-gold)" : "var(--ink-7)";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6, width: "100%" }}>
      {label && (
        <label style={{
          fontFamily: "var(--font-body)",
          fontWeight: 500,
          fontSize: 11,
          letterSpacing: "0.16em",
          textTransform: "uppercase",
          color: labelColor,
          transition: "color 200ms cubic-bezier(.22,1,.36,1)"
        }}>{label}</label>
      )}
      <div style={{ position: "relative", display: "flex", alignItems: "center", borderBottom: `1px solid ${borderColor}`, transition: "border-color 200ms cubic-bezier(.22,1,.36,1)", paddingBottom: 0 }}>
        <input
          type={type}
          name={name}
          value={value}
          onChange={(e) => onChange && onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          autoFocus={autoFocus}
          style={{
            flex: 1,
            background: "transparent",
            border: "none",
            color: "var(--fg-1)",
            fontFamily: "var(--font-body)",
            fontSize: 15,
            padding: "12px 0",
            outline: "none",
          }}
        />
        {trailing}
      </div>
      {error && (
        <span style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "#C0392B" }}>{error}</span>
      )}
      {!error && hint && (
        <span style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "var(--fg-3)" }}>{hint}</span>
      )}
    </div>
  );
}

// ============ Chip ============
function Chip({ tone = "neutral", outlined = false, children, dot = true, style }) {
  const tones = {
    success:  { fg: "#7FA86C", bg: "rgba(127,168,108,0.14)" },
    warning:  { fg: "#E8A33D", bg: "rgba(232,163,61,0.14)" },
    danger:   { fg: "#C0392B", bg: "rgba(192,57,43,0.14)" },
    info:     { fg: "#4A6FA5", bg: "rgba(74,111,165,0.14)" },
    gold:     { fg: "var(--rdb-gold)", bg: "rgba(201,168,76,0.12)" },
    neutral:  { fg: "var(--fg-2)", bg: "transparent" },
  };
  const t = tones[tone];
  return (
    <span style={{
      fontFamily: "var(--font-body)",
      fontWeight: 600,
      fontSize: 10,
      letterSpacing: "0.16em",
      textTransform: "uppercase",
      padding: "5px 10px",
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      lineHeight: 1,
      borderRadius: 2,
      background: outlined ? "transparent" : t.bg,
      color: t.fg,
      border: outlined ? `1px solid ${tone === "neutral" ? "var(--ink-4)" : t.fg}` : "1px solid transparent",
      ...style,
    }}>
      {dot && tone !== "neutral" && <span style={{ width: 6, height: 6, borderRadius: "50%", background: t.fg, display: "inline-block" }} />}
      {children}
    </span>
  );
}

// ============ Avatar ============
function Avatar({ initials, size = 28, tone = "gold" }) {
  const fg = tone === "gold" ? "var(--rdb-gold)" : "var(--fg-1)";
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: "var(--ink-3)",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--font-body)", fontSize: Math.max(10, size * 0.4),
      fontWeight: 600, color: fg, letterSpacing: 0.5
    }}>{initials}</div>
  );
}

// ============ Icon (lucide) ============
function Icon({ name, size = 18, color, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = "";
      const el = document.createElement("i");
      el.setAttribute("data-lucide", name);
      ref.current.appendChild(el);
      window.lucide.createIcons({ icons: window.lucide.icons, attrs: { width: size, height: size, stroke: color || "currentColor", "stroke-width": 1.5 }, nameAttr: "data-lucide" });
    }
  }, [name, size, color]);
  return <span ref={ref} style={{ display: "inline-flex", lineHeight: 0, color: color || "currentColor", ...style }} />;
}

Object.assign(window, { Logo, Button, Input, Chip, Avatar, Icon });
