// Shared helpers for the Zentro website UI kit.
// Lucide icon renderer + small layout atoms. Exports to window.

const Icon = ({ name, size = 20, color = "currentColor", strokeWidth = 2, style = {} }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !window.lucide || !window.lucide[name]) return;
    ref.current.innerHTML = "";
    const el = window.lucide.createElement(window.lucide[name]);
    el.setAttribute("width", size);
    el.setAttribute("height", size);
    el.setAttribute("stroke", color);
    el.setAttribute("stroke-width", strokeWidth);
    ref.current.appendChild(el);
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} style={{ display: "inline-flex", ...style }} />;
};

// Centered max-width container
const Container = ({ children, max = 1200, style = {} }) => (
  <div style={{ width: "100%", maxWidth: max, margin: "0 auto", padding: "0 var(--gutter)", boxSizing: "border-box", ...style }}>
    {children}
  </div>
);

const Eyebrow = ({ children, style = {} }) => (
  <span style={{
    fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700,
    letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-500)",
    display: "inline-flex", alignItems: "center", gap: 10, ...style,
  }}>
    <span style={{ width: 28, height: 2, background: "var(--gold-500)" }} />
    {children}
  </span>
);

// Logo lockup (mark + wordmark) using brand assets
const Logo = ({ height = 26 }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 0 }}>
    <img src="assets/zentro-logo.png" alt="Zentro" style={{ height, width: "auto", display: "block" }} />
  </span>
);

// ─── YouTube Reel Card ───────────────────────────────────────────────────────
// Pass a full YouTube URL or video ID via the `youtubeUrl` prop.
// Falls back to the dark gradient placeholder when no URL is provided.
const ReelThumb = ({ title, tag, duration, tone = "a", ratio = "16/9", youtubeUrl = "" }) => {
  const tones = {
    a: "linear-gradient(135deg, #1A1A1E 0%, #2A2A30 100%)",
    b: "linear-gradient(135deg, #211417 0%, #3a1d1d 100%)",
    c: "linear-gradient(135deg, #14171c 0%, #232a33 100%)",
    d: "linear-gradient(135deg, #1c1820 0%, #2e2533 100%)",
  };
  const [playing, setPlaying] = React.useState(false);
  const [hover, setHover] = React.useState(false);

  // Extract video ID from any YouTube URL format
  const getVideoId = (url) => {
    if (!url) return null;
    // Already a bare ID (11 chars, no slash/dot)
    if (/^[a-zA-Z0-9_-]{11}$/.test(url.trim())) return url.trim();
    try {
      const u = new URL(url);
      // youtu.be/ID
      if (u.hostname === "youtu.be") return u.pathname.slice(1);
      // youtube.com/watch?v=ID  or  youtube.com/shorts/ID  or  youtube.com/embed/ID
      return u.searchParams.get("v") || u.pathname.split("/").pop() || null;
    } catch {
      return null;
    }
  };

  const videoId = getVideoId(youtubeUrl);
  const embedSrc = videoId
    ? `https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0&modestbranding=1`
    : null;
  const thumbSrc = videoId
    ? `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`
    : null;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ cursor: "pointer" }}
    >
      <div style={{
        position: "relative", aspectRatio: ratio, borderRadius: "var(--radius-lg)",
        overflow: "hidden",
        background: thumbSrc ? "#000" : tones[tone],
        border: "1px solid var(--border-subtle)",
        transition: "border-color var(--dur-base) var(--ease-out), box-shadow var(--dur-base) var(--ease-out)",
        borderColor: hover ? "rgba(251,208,40,0.5)" : "var(--border-subtle)",
        boxShadow: hover ? "var(--shadow-lg)" : "none",
      }}>

        {/* ── Thumbnail / placeholder background ── */}
        {thumbSrc && !playing && (
          <img
            src={thumbSrc}
            alt={title}
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" }}
          />
        )}

        {/* ── YouTube iframe (shown after clicking play) ── */}
        {playing && embedSrc && (
          <iframe
            src={embedSrc}
            title={title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: "none" }}
          />
        )}

        {/* ── Gradient overlays (only when not playing) ── */}
        {!playing && (
          <>
            {/* subtle vignette / glow */}
            <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 80% at 50% 120%, rgba(251,208,40,0.14), transparent 60%)" }} />
            {/* dark scrim so play button pops on thumbnails */}
            {thumbSrc && <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.25)" }} />}
          </>
        )}

        {/* ── Play button (hidden while iframe is active) ── */}
        {!playing && (
          <div
            onClick={() => embedSrc && setPlaying(true)}
            style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}
          >
            <span style={{
              width: 56, height: 56, borderRadius: "50%",
              background: hover ? "var(--gold-500)" : "rgba(255,255,255,0.12)",
              backdropFilter: "blur(6px)", display: "flex", alignItems: "center", justifyContent: "center",
              border: "1px solid rgba(255,255,255,0.25)",
              transform: hover ? "scale(1.08)" : "scale(1)",
              transition: "all var(--dur-base) var(--ease-out)",
            }}>
              <Icon name="Play" size={20} color={hover ? "#08080A" : "#fff"} />
            </span>
          </div>
        )}

        {/* ── Duration chip ── */}
        {duration && !playing && (
          <span style={{
            position: "absolute", bottom: 10, right: 10, fontFamily: "var(--font-mono)",
            fontSize: 11, fontWeight: 500, color: "#fff", background: "rgba(0,0,0,0.6)",
            padding: "3px 7px", borderRadius: 4, letterSpacing: "0.02em",
          }}>{duration}</span>
        )}

        {/* ── Category tag ── */}
        {tag && !playing && (
          <span style={{
            position: "absolute", top: 10, left: 10, fontFamily: "var(--font-sans)",
            fontSize: 11, fontWeight: 700, color: "var(--gold-300)", background: "rgba(0,0,0,0.5)",
            padding: "4px 9px", borderRadius: "var(--radius-pill)", letterSpacing: "0.04em", textTransform: "uppercase",
          }}>{tag}</span>
        )}
      </div>

      {/* ── Card title ── */}
      <div style={{ marginTop: 12, fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 600, color: "var(--text-primary)" }}>{title}</div>
    </div>
  );
};

Object.assign(window, { Icon, Container, Eyebrow, Logo, ReelThumb });
