/* Reusable building blocks */
const { useState } = React;

/* GridBackdrop — wrapper that paints a 40px linear-gradient grid behind its children */
const GridBackdrop = ({ children, color = BRAND.surface.grid, size = 40, opacity = 1, style = {}, className = "" }) => {
  const bg = {
    backgroundImage: `linear-gradient(to right, ${color} 1px, transparent 1px), linear-gradient(to bottom, ${color} 1px, transparent 1px)`,
    backgroundSize: `${size}px ${size}px`,
    opacity,
  };
  return (
    <div className={`relative ${className}`} style={style}>
      <div className="absolute inset-0 pointer-events-none" style={bg} />
      <div className="relative">{children}</div>
    </div>
  );
};

/* SectionEyebrow — "01 · LABEL" with primary-blue underline */
const SectionEyebrow = ({ number, label, style = {} }) => (
  <div className="mb-6" style={style}>
    <div
      className="inline-flex items-baseline gap-2 pb-1.5"
      style={{
        borderBottom: `2px solid ${BRAND.primary[500]}`,
        color: BRAND.ink.body,
      }}
    >
      <span
        className="font-mono"
        style={{
          fontSize: 12,
          fontWeight: 700,
          letterSpacing: "0.18em",
          color: BRAND.primary[500],
        }}
      >
        {number}
      </span>
      <span
        style={{
          fontSize: 12,
          fontWeight: 700,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: BRAND.ink.body,
        }}
      >
        · {label}
      </span>
    </div>
  </div>
);

/* TabButton — pill segment with icon + label, active = primary 500 fill */
const TabButton = ({ icon: Icon, label, active, onClick }) => (
  <button
    onClick={onClick}
    className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full transition-all"
    style={{
      background: active ? BRAND.primary[500] : "transparent",
      color: active ? "#FFFFFF" : BRAND.ink.muted,
      fontSize: 13,
      fontWeight: 600,
      letterSpacing: "0.01em",
    }}
  >
    <Icon size={15} strokeWidth={active ? 2 : 1.75} />
    <span>{label}</span>
  </button>
);

/* Swatch — click-to-copy color tile.
   variant: "block" (large color block on top, meta below), "row" (tight horizontal) */
const Swatch = ({ hex, name, role, textColor, variant = "block" }) => {
  const [copied, setCopied] = useState(false);
  const [hover, setHover] = useState(false);
  const onCopy = () => {
    navigator.clipboard?.writeText(hex);
    setCopied(true);
    window.setTimeout(() => setCopied(false), 1100);
  };
  const fg = textColor || (isDark(hex) ? "#FFFFFF" : BRAND.ink.body);

  if (variant === "row") {
    return (
      <button
        onClick={onCopy}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        className="w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-left transition-colors"
        style={{
          background: BRAND.surface.card,
          border: `1px solid ${BRAND.surface.border}`,
        }}
      >
        <div className="rounded" style={{ width: 28, height: 28, background: hex, border: `1px solid ${BRAND.surface.border}` }} />
        <div className="flex-1 min-w-0">
          <div style={{ fontSize: 13, fontWeight: 600, color: BRAND.ink.body }}>{name}</div>
          {role ? <div style={{ fontSize: 11, color: BRAND.ink.subtle }}>{role}</div> : null}
        </div>
        <span className="font-mono" style={{ fontSize: 12, color: BRAND.ink.muted }}>{hex.toUpperCase()}</span>
        <span style={{ color: BRAND.ink.subtle, opacity: hover || copied ? 1 : 0.35, transition: "opacity 150ms" }}>
          {copied ? <Check size={14} /> : <Copy size={14} />}
        </span>
      </button>
    );
  }

  return (
    <button
      onClick={onCopy}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      className="group relative w-full text-left rounded-lg overflow-hidden transition-shadow"
      style={{
        border: `1px solid ${BRAND.surface.border}`,
        background: BRAND.surface.card,
        boxShadow: hover ? "0 4px 16px rgba(15,23,42,0.08)" : "0 1px 0 rgba(15,23,42,0.02)",
      }}
    >
      <div
        className="relative px-3 pt-3 pb-12 flex items-start justify-between"
        style={{ background: hex, color: fg, minHeight: 112 }}
      >
        <span className="font-mono" style={{ fontSize: 13, fontWeight: 500, letterSpacing: "-0.01em" }}>
          {hex.toUpperCase()}
        </span>
        <span
          className="inline-flex items-center justify-center rounded-md"
          style={{
            width: 26,
            height: 26,
            background: copied ? "rgba(255,255,255,0.18)" : "rgba(255,255,255,0.12)",
            color: fg,
            opacity: hover || copied ? 1 : 0,
            transition: "opacity 150ms",
            backdropFilter: "blur(2px)",
          }}
        >
          {copied ? <Check size={13} strokeWidth={2.25} /> : <Copy size={13} strokeWidth={1.75} />}
        </span>
      </div>
      <div className="px-3 py-2.5" style={{ borderTop: `1px solid ${BRAND.surface.border}` }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: BRAND.ink.body, lineHeight: 1.2 }}>{name}</div>
        {role ? (
          <div style={{ fontSize: 11, color: BRAND.ink.subtle, marginTop: 2, lineHeight: 1.3 }}>{role}</div>
        ) : null}
      </div>
    </button>
  );
};

/* CodeBlock — copyable implementation snippet for developer guidance */
const CodeBlock = ({ label, code }) => {
  const [copied, setCopied] = useState(false);
  const onCopy = () => {
    navigator.clipboard?.writeText(code);
    setCopied(true);
    window.setTimeout(() => setCopied(false), 1100);
  };

  return (
    <div
      className="overflow-hidden"
      style={{
        background: BRAND.dark.navy,
        border: `1px solid ${BRAND.dark.navyAccent}`,
        borderRadius: 12,
      }}
    >
      <div
        className="flex items-center justify-between gap-3 px-4 py-3"
        style={{ borderBottom: `1px solid ${BRAND.dark.navyAccent}` }}
      >
        <span
          className="font-mono"
          style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.16em", color: BRAND.primary[300] }}
        >
          {label}
        </span>
        <button
          onClick={onCopy}
          className="inline-flex items-center gap-2 rounded-md px-2.5 py-1.5"
          style={{
            background: copied ? BRAND.primary[500] : "rgba(255,255,255,0.06)",
            color: "#FFFFFF",
            fontSize: 12,
            fontWeight: 600,
            border: `1px solid ${copied ? BRAND.primary[500] : BRAND.dark.navyAccent}`,
          }}
        >
          {copied ? <Check size={13} strokeWidth={2.25} /> : <Copy size={13} strokeWidth={1.75} />}
          {copied ? "Copied" : "Copy"}
        </button>
      </div>
      <pre
        className="font-mono"
        style={{
          margin: 0,
          padding: 16,
          overflowX: "auto",
          color: "#FFFFFF",
          fontSize: 12,
          lineHeight: 1.65,
          background: BRAND.dark.navyDeep,
        }}
      >
        <code>{code}</code>
      </pre>
    </div>
  );
};

/* dark-color detector for swatch contrast */
function isDark(hex) {
  const h = hex.replace("#", "");
  const r = parseInt(h.substring(0, 2), 16);
  const g = parseInt(h.substring(2, 4), 16);
  const b = parseInt(h.substring(4, 6), 16);
  // perceived brightness
  return (r * 299 + g * 587 + b * 114) / 1000 < 150;
}

/* Card — opinionated white card */
const Card = ({ children, className = "", style = {}, padding = 24 }) => (
  <div
    className={className}
    style={{
      background: BRAND.surface.card,
      border: `1px solid ${BRAND.surface.border}`,
      borderRadius: 12,
      padding,
      ...style,
    }}
  >
    {children}
  </div>
);

Object.assign(window, { GridBackdrop, SectionEyebrow, TabButton, Swatch, CodeBlock, Card, isDark });
