/* ============================================================================
 * Reformed IT · shared UI primitives
 *
 * Globally registered (window.{Button, Badge, Eyebrow, Container, Icon, ...})
 * because each <script type="text/babel"> file lives in its own scope.
 * Style objects use distinct names per component to avoid collisions.
 * ============================================================================ */

const { useEffect, useRef, useState } = React;

/* ---------- Container ---------- */
function Container({ children, wide = false, style, ...rest }) {
  return (
    <div
      style={{
        maxWidth: wide ? 1440 : 1200,
        marginLeft: "auto",
        marginRight: "auto",
        padding: "0 32px",
        ...style,
      }}
      {...rest}
    >
      {children}
    </div>
  );
}

/* ---------- Eyebrow ---------- */
function Eyebrow({ number, children, color = "var(--ri-pink)", style }) {
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 12,
        fontSize: 12,
        fontWeight: 600,
        letterSpacing: "0.22em",
        textTransform: "uppercase",
        color,
        marginBottom: 18,
        ...style,
      }}
    >
      <span
        style={{ width: 36, height: 1, background: color, display: "inline-block" }}
        aria-hidden
      />
      {number && <span style={{ opacity: 0.9 }}>{number} ·</span>}
      <span>{children}</span>
    </div>
  );
}

/* ---------- Icon (Lucide wrapper) ---------- */
function Icon({ name, size = 22, stroke = 2, style, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const i = document.createElement("i");
      i.setAttribute("data-lucide", name);
      i.setAttribute("stroke-width", String(stroke));
      ref.current.appendChild(i);
      window.lucide.createIcons({
        attrs: { width: size, height: size },
      });
    }
  }, [name, size, stroke]);
  return (
    <span
      ref={ref}
      style={{ display: "inline-flex", lineHeight: 0, color: "currentColor", ...style }}
      {...rest}
    />
  );
}

/* ---------- Button ---------- */
const buttonBase = {
  fontFamily: "var(--font-sans)",
  fontWeight: 600,
  fontSize: 14,
  lineHeight: 1,
  border: 0,
  cursor: "pointer",
  borderRadius: 999,
  display: "inline-flex",
  alignItems: "center",
  gap: 8,
  textDecoration: "none",
  transition:
    "transform 120ms var(--ease-out), opacity 120ms var(--ease-out), box-shadow 240ms var(--ease-out), background 200ms var(--ease-out)",
  whiteSpace: "nowrap",
};

/* Anchor-rendered buttons must NEVER show the global link border/underline. */
if (typeof document !== "undefined" && !document.getElementById("__ri-btn-styles")) {
  const s = document.createElement("style");
  s.id = "__ri-btn-styles";
  s.textContent = `
    a.ri-btn, a.ri-btn:hover, a.ri-btn:visited {
      text-decoration: none !important;
      border-bottom: 0 !important;
    }
  `;
  document.head.appendChild(s);
}

const buttonSizes = {
  sm: { padding: "8px 16px", fontSize: 12 },
  md: { padding: "12px 22px", fontSize: 14 },
  lg: { padding: "16px 28px", fontSize: 15 },
};

const buttonVariants = {
  primary: {
    color: "#fff",
    background: "var(--grad-brand)",
    boxShadow: "var(--shadow-pink)",
  },
  pink: {
    color: "#fff",
    background: "var(--ri-pink)",
    boxShadow: "var(--shadow-pink)",
  },
  outline: {
    color: "var(--ri-ink)",
    background: "#fff",
    border: "1.5px solid var(--ri-ink)",
  },
  ink: { color: "#fff", background: "var(--ri-ink)" },
  ghost: { color: "var(--ri-ink)", background: "transparent" },
  onInkOutline: {
    /* Secondary button for use on ink/dark backgrounds.
     * Paper-filled (not transparent) so it pops cleanly against the dark hero. */
    color: "var(--ri-ink)",
    background: "var(--ri-paper)",
  },
};

function Button({
  variant = "primary",
  size = "md",
  as = "button",
  children,
  iconLeft,
  iconRight,
  style,
  className,
  ...rest
}) {
  const [hover, setHover] = useState(false);
  const [press, setPress] = useState(false);
  const v = buttonVariants[variant] || buttonVariants.primary;
  const s = buttonSizes[size] || buttonSizes.md;
  // outline buttons compensate padding for the border
  const isOutline = variant === "outline";
  const padding = isOutline
    ? s.padding
        .split(" ")
        .map((p) => `${parseInt(p, 10) - 1.5}px`)
        .join(" ")
    : s.padding;
  const Component = as;
  return (
    <Component
      className={"ri-btn" + (className ? " " + className : "")}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        ...buttonBase,
        ...v,
        ...s,
        padding,
        opacity: hover && variant !== "outline" ? 0.92 : 1,
        background:
          hover && variant === "outline"
            ? "var(--bg-subtle)"
            : hover && variant === "onInkOutline"
            ? "#FFFFFF"
            : v.background,
        transform: press ? "scale(0.98)" : "scale(1)",
        ...style,
      }}
      {...rest}
    >
      {iconLeft && <Icon name={iconLeft} size={s.fontSize + 4} />}
      {children}
      {iconRight && <Icon name={iconRight} size={s.fontSize + 4} />}
    </Component>
  );
}

/* ---------- Badge ---------- */
const badgePalette = {
  new:          { bg: "#FCE3EB", fg: "#C0244C" },
  enterprise:   { bg: "var(--ri-ink)", fg: "#fff" },
  beta:         { bg: "transparent", fg: "var(--fg)", border: "1px solid var(--border-strong)" },
  operational:  { bg: "#E2F4EC", fg: "#1F8F5E" },
  investigating:{ bg: "#FBEFD8", fg: "#B8761F" },
  incident:     { bg: "#FCE3EB", fg: "#C0244C" },
  resolved:     { bg: "#E1E1FA", fg: "#2B29D1" },
};

function Badge({ tone = "new", dot = false, children, style }) {
  const p = badgePalette[tone] || badgePalette.new;
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "4px 10px",
        background: p.bg,
        color: p.fg,
        border: p.border || "none",
        borderRadius: 999,
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: tone === "enterprise" ? "0.08em" : "0.02em",
        lineHeight: 1.4,
        ...style,
      }}
    >
      {dot && (
        <span
          style={{
            width: 6, height: 6, borderRadius: "50%", background: "currentColor",
          }}
        />
      )}
      {children}
    </span>
  );
}

/* ---------- BrandBar ---------- */
function BrandBar({ height = 22, style }) {
  return (
    <div
      style={{
        height,
        background:
          "linear-gradient(95deg, #F22B69 0%, #B500A1 50%, #2B29D1 100%)",
        ...style,
      }}
    />
  );
}

/* ---------- Toast (lightweight, for form feedback) ---------- */
function useToast() {
  const [t, setT] = useState(null);
  useEffect(() => {
    if (!t) return;
    const id = setTimeout(() => setT(null), 3000);
    return () => clearTimeout(id);
  }, [t]);
  return [t, setT];
}

function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div
      style={{
        position: "fixed", bottom: 28, left: "50%", transform: "translateX(-50%)",
        background: "var(--ri-ink)", color: "#fff",
        padding: "12px 18px", borderRadius: 14, fontSize: 13, fontWeight: 500,
        boxShadow: "0 16px 32px rgba(8,5,38,0.30)",
        display: "inline-flex", alignItems: "center", gap: 10, zIndex: 100,
        animation: "ri-toast-in 240ms cubic-bezier(.22,.61,.36,1)",
      }}
    >
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#4ee49a" }} />
      {msg}
    </div>
  );
}

Object.assign(window, {
  Container, Eyebrow, Icon, Button, Badge, BrandBar, Toast, useToast,
});
