/* global React, DotPattern, CityBackdrop, BorderBeam */
const { useEffect, useRef, useState } = React;

/* ============================================================================
   Hero — type as protagonist, parallax photographic + 3D atmosphere behind.

   z-0   Tebex banner image (subtle parallax + smoked chrome/red light wash)
   z-1   dot pattern
   z-2   global blob (rendered separately by Atmosphere)
   z-20  type block: eyebrow, mega H1 (char split), subhead, CTAs
   z-30  HUD chrome: detail card, scroll cue, side ticker
   ============================================================================ */

const H1_LINES = [
  { text: "THERE'S A",    tone: "ink",     delay: 0.18 },
  { text: "VERSION OF",   tone: "ink",     delay: 0.30 },
  { text: "YOUR SERVER",  tone: "outline", delay: 0.44 },
  { text: "YOU HAVEN'T",  tone: "ink",     delay: 0.62 },
  { text: "SEEN YET.",    tone: "warm",    delay: 0.82 },
];

function Hero() {
  const ref = useRef(null);
  const [parallax, setParallax] = useState({ y: 0, mx: 0, my: 0 });

  useEffect(() => {
    const el = ref.current;
    const onScroll = () => {
      if (!el) return;
      const r = el.getBoundingClientRect();
      const p = Math.max(0, Math.min(1, -r.top / r.height));
      setParallax((s) => ({ ...s, y: p }));
    };
    const onMove = (e) => {
      const w = window.innerWidth, h = window.innerHeight;
      setParallax((s) => ({ ...s, mx: (e.clientX / w - 0.5) * 2, my: (e.clientY / h - 0.5) * 2 }));
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("mousemove", onMove, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("mousemove", onMove);
    };
  }, []);

  return (
    <section
      id="hero"
      ref={ref}
      data-screen-label="01 Hero"
      style={{
        position: "relative",
        minHeight: "100vh",
        width: "100%",
        overflow: "hidden",
        background: "var(--color-base)",
      }}
    >
      {/* Tebex-aligned cinematic banner backdrop */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 1,
        transform: `translate3d(${parallax.mx * -16}px, ${parallax.y * -70 + parallax.my * -8}px, 0) scale(${1.05 + parallax.y * 0.05})`,
        transition: "transform 0.15s linear",
      }}>
        <div style={{
          position: "absolute",
          inset: 0,
          backgroundImage: `
            linear-gradient(90deg, rgba(5,5,5,0.94) 0%, rgba(5,5,5,0.62) 42%, rgba(5,5,5,0.84) 100%),
            linear-gradient(180deg, rgba(5,5,5,0.28) 0%, rgba(5,5,5,0.95) 100%),
            url("assets/tebex-banner.webp")
          `,
          backgroundSize: "cover",
          backgroundPosition: "center",
          filter: "contrast(1.08) saturate(0.72)",
        }}></div>
      </div>

      <div style={{
        position: "absolute",
        inset: 0,
        zIndex: 2,
        background: `
          radial-gradient(60% 45% at 68% 44%, rgba(200,204,210,0.18), transparent 65%),
          radial-gradient(42% 36% at 82% 72%, rgba(200,48,47,0.14), transparent 70%),
          linear-gradient(180deg, transparent 0%, rgba(5,5,5,0.72) 100%)
        `,
        pointerEvents: "none",
      }}></div>

      <DotPattern style={{ zIndex: 4, opacity: 0.22 }} />

      {/* Big outline 927 watermark, subtle, lower-right */}
      <div aria-hidden="true" style={{
        position: "absolute",
        right: "-6vw", bottom: "-4vh",
        zIndex: 5,
        opacity: 0.08,
        transform: `translateY(${parallax.y * -120}px)`,
        pointerEvents: "none",
      }}>
        <img src="assets/927-logo-white.png" alt="" style={{
          width: "min(60vw, 620px)", height: "auto",
          mixBlendMode: "screen",
        }} />
      </div>

      {/* TYPE BLOCK ---------------------------------------------------------- */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 20,
        display: "flex", flexDirection: "column", justifyContent: "center",
        padding: "10rem clamp(2rem, 6vw, 6rem) 8rem",
        maxWidth: "92vw",
        pointerEvents: "none",
      }}>
        <BlurLine delay={0.05}>
          <div style={{
            display: "flex", alignItems: "center", gap: 14,
            marginBottom: "2rem",
          }}>
            <span style={{
              display: "inline-block", width: 36, height: 1,
              background: "var(--color-accent)",
              boxShadow: "0 0 12px var(--color-accent)",
            }}></span>
            <p style={{
              fontFamily: "var(--font-body)", fontWeight: 400, fontSize: 11,
              textTransform: "uppercase", letterSpacing: "0.4em",
              color: "var(--color-accent)", margin: 0,
            }}>
              927 DEVELOPMENT // FIVEM DEV STUDIO
            </p>
          </div>
        </BlurLine>

        <SplitH1 />

        <BlurLine delay={1.3}>
          <div style={{
            display: "flex", gap: 14, marginTop: "2.5rem", flexWrap: "wrap",
            pointerEvents: "auto",
          }}>
            <MagneticButton href="#retainers" variant="primary" label="See retainers">
              See the tiers
            </MagneticButton>
            <MagneticButton href="https://discord.gg/hRZeHwWyHG" variant="ghost" external label="Discord">
              Open Discord
            </MagneticButton>
          </div>
        </BlurLine>
      </div>

      {/* HUD CHROME ---------------------------------------------------------- */}
      {/* Top-right session ticker */}
      <div aria-hidden="true" style={{
        position: "absolute", top: "max(6rem, 10vh)", right: "clamp(1.5rem, 4vw, 4rem)",
        zIndex: 30,
        fontFamily: "var(--font-body)", fontSize: 10,
        letterSpacing: "0.35em", textTransform: "uppercase",
        color: "var(--color-ink-muted)",
        textAlign: "right",
        lineHeight: 2,
      }}>
        <div style={{ color: "var(--color-accent-warm)" }}>NIGHT SHIFT // RUNNING</div>
      </div>

      {/* Detail card bottom-right */}
      <div style={{
        position: "absolute", bottom: "clamp(2rem, 5vh, 4rem)", right: "clamp(1.5rem, 4vw, 4rem)",
        zIndex: 30,
      }}>
        <DetailHUD />
      </div>

      {/* Scroll cue bottom-center */}
      <div style={{
        position: "absolute", bottom: "2.4rem", left: "50%", transform: "translateX(-50%)",
        zIndex: 30,
        display: "flex", flexDirection: "column", alignItems: "center", gap: 14,
        pointerEvents: "none",
      }}>
        <div style={{
          fontFamily: "var(--font-body)", fontSize: 10,
          letterSpacing: "0.5em", textTransform: "uppercase",
          color: "var(--color-ink-muted)",
        }}>SCROLL</div>
        <div style={{
          width: 1, height: 60,
          background: "var(--color-accent-warm)",
          animation: "scroll-cue 1.7s ease-in-out infinite",
          boxShadow: "0 0 8px var(--color-accent-warm)",
        }}></div>
      </div>
    </section>
  );
}

/* ----- SplitH1: per-character entry, mixed tone treatment ----------------- */
function SplitH1() {
  return (
    <h1
      data-cursor=""
      aria-label="There's a version of your server you haven't seen yet."
      style={{
        fontFamily: "var(--font-display)", fontWeight: 700,
        fontSize: "clamp(2.4rem, 7.2vw, 7rem)",
        lineHeight: 0.92, letterSpacing: "-0.04em",
        textTransform: "uppercase",
        margin: 0,
        color: "var(--color-ink)",
        textShadow: "0 0 80px rgba(0,0,0,0.55)",
        maxWidth: "100%",
        whiteSpace: "nowrap",
      }}
    >
      {H1_LINES.map((line, li) => {
        const cls = line.tone === "outline"
          ? "outline-text"
          : line.tone === "warm"
          ? ""
          : "";
        const color = line.tone === "warm" ? "var(--color-accent-warm)" : undefined;
        return (
          <span key={li} className={cls} style={{ display: "block", color }}>
            {line.text.split("").map((ch, ci) => (
              <SplitChar key={ci} ch={ch} delay={line.delay + ci * 0.018} />
            ))}
          </span>
        );
      })}
    </h1>
  );
}

function SplitChar({ ch, delay }) {
  if (ch === " ") return <span style={{ display: "inline-block", width: "0.25em" }}>&nbsp;</span>;
  return (
    <span
      className="splitchar"
      style={{
        opacity: 0,
        animation: `char-rise 0.85s var(--ease-out) ${delay}s forwards`,
      }}
    >{ch}</span>
  );
}

/* ----- BlurLine ----------------------------------------------------------- */
function BlurLine({ delay = 0, children }) {
  return (
    <div style={{ opacity: 0, animation: `line-blur 0.9s var(--ease-out) ${delay}s forwards` }}>
      {children}
    </div>
  );
}

/* ----- Magnetic CTA ------------------------------------------------------- */
function MagneticButton({ children, href, variant = "primary", external, label }) {
  const ref = useRef(null);
  const [t, setT] = useState({ x: 0, y: 0 });
  const onMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const cx = r.left + r.width / 2;
    const cy = r.top + r.height / 2;
    setT({ x: (e.clientX - cx) * 0.3, y: (e.clientY - cy) * 0.3 });
  };
  const onLeave = () => setT({ x: 0, y: 0 });
  const base = {
    fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.3em",
    textTransform: "uppercase", textDecoration: "none",
    padding: "14px 22px",
    display: "inline-flex", alignItems: "center", gap: 10,
    transform: `translate(${t.x}px, ${t.y}px)`,
    transition: "transform 0.32s var(--ease-out), background 0.2s, border-color 0.2s, color 0.2s",
    borderRadius: 8,
    willChange: "transform",
    position: "relative",
  };
  const styles = {
    primary: { ...base, color: "var(--color-base)", background: "var(--color-accent-warm)", border: "1px solid var(--color-accent-warm)" },
    ghost:   { ...base, color: "var(--color-ink)", background: "transparent", border: "1px solid rgba(255,255,255,0.15)" },
  };
  return (
    <a
      ref={ref}
      href={href}
      target={external ? "_blank" : undefined}
      rel={external ? "noreferrer" : undefined}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
      data-cursor={label || ""}
      style={styles[variant]}
    >
      {children} <span style={{ opacity: 0.8 }}>→</span>
    </a>
  );
}

/* ----- HUD Detail card with rotating glow border + BorderBeam ------------ */
function DetailHUD() {
  return (
    <div style={{
      position: "relative",
      width: 300,
      background: "rgba(5,5,5,0.72)",
      border: "1px solid rgba(200,204,210,0.26)",
      padding: "16px 18px",
      borderRadius: 0,
      animation: "line-blur 0.9s var(--ease-out) 1.3s backwards",
    }}>
      <BorderBeam duration={6} colorFrom="var(--color-accent)" colorTo="var(--color-accent-warm)" />
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 9, letterSpacing: "0.4em",
        textTransform: "uppercase", color: "var(--color-ink-muted)", lineHeight: 2,
      }}>
        <div>[STATUS: <span style={{ color: "var(--color-accent)" }}>OPERATIONAL</span>]</div>
        <div style={{ color: "var(--color-accent-warm)" }}>LEAD SLOTS // 2 OF 3 OPEN</div>
      </div>
    </div>
  );
}

Object.assign(window, { Hero });
