const Hero = ({ navigateTo }) => {
  const videoRef = React.useRef(null);
  const autoplayTimeoutRef = React.useRef(null);
  const phaseRef = React.useRef("loading");
  const [phase, setPhase] = React.useState("loading"); // loading | playing | ended

  React.useEffect(() => {
    phaseRef.current = phase;
  }, [phase]);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    let cancelled = false;
    let attempts = 0;

    // Strengthen inline autoplay behavior on mobile Safari/Chrome variants.
    video.setAttribute("playsinline", "");
    video.setAttribute("webkit-playsinline", "true");
    video.setAttribute("x5-playsinline", "true");
    video.disablePictureInPicture = true;
    video.disableRemotePlayback = true;

    const clearAutoplayTimeout = () => {
      if (autoplayTimeoutRef.current) {
        clearTimeout(autoplayTimeoutRef.current);
        autoplayTimeoutRef.current = null;
      }
    };

    const markPlaying = () => {
      if (cancelled) return;
      clearAutoplayTimeout();
      setPhase("playing");
    };

    const scheduleRetry = () => {
      if (cancelled || attempts >= 6) {
        if (!cancelled) setPhase("ended");
        return;
      }

      clearAutoplayTimeout();
      autoplayTimeoutRef.current = setTimeout(() => {
        attemptAutoplay();
      }, 350);
    };

    const attemptAutoplay = () => {
      if (cancelled || phaseRef.current === "ended") return;
      attempts += 1;

      video.muted = true;
      video.defaultMuted = true;
      video.loop = false;
      video.playbackRate = 0.85;

      const playPromise = video.play();
      if (playPromise && typeof playPromise.then === "function") {
        playPromise.then(markPlaying).catch(scheduleRetry);
      } else {
        markPlaying();
      }
    };

    const handleFirstInteraction = () => {
      if (phaseRef.current === "loading" && video.currentTime < 0.1) {
        attemptAutoplay();
      }
    };

    const handleReady = () => {
      if (video.paused && phaseRef.current !== "ended") attemptAutoplay();
    };

    const handleVisibility = () => {
      if (!document.hidden && video.paused && phaseRef.current !== "ended") attemptAutoplay();
    };

    if (video.readyState >= 2 && phaseRef.current !== "ended") attemptAutoplay();
    else {
      video.load();
      video.addEventListener("loadedmetadata", handleReady);
      video.addEventListener("canplay", handleReady);
      video.addEventListener("canplaythrough", handleReady);
    }

    video.addEventListener("playing", markPlaying);
    window.addEventListener("pageshow", handleReady);
    document.addEventListener("visibilitychange", handleVisibility);
    window.addEventListener("touchstart", handleFirstInteraction, { passive: true });
    window.addEventListener("pointerdown", handleFirstInteraction, { passive: true });

    return () => {
      cancelled = true;
      clearAutoplayTimeout();
      video.removeEventListener("loadedmetadata", handleReady);
      video.removeEventListener("canplay", handleReady);
      video.removeEventListener("canplaythrough", handleReady);
      video.removeEventListener("playing", markPlaying);
      window.removeEventListener("pageshow", handleReady);
      document.removeEventListener("visibilitychange", handleVisibility);
      window.removeEventListener("touchstart", handleFirstInteraction);
      window.removeEventListener("pointerdown", handleFirstInteraction);
    };
  }, []);

  return (
    <section data-screen-label="01 Hero" style={{
      position: "relative", width: "100%", height: "100vh",
      background: "#040b0c", overflow: "hidden", flexShrink: 0,
    }}>
      <video
        ref={videoRef}
        src="uploads/hero background.mp4"
        muted
        defaultMuted
        autoPlay
        playsInline
        poster="assets/cyborg.png"
        preload="auto"
        onEnded={() => setPhase("ended")}
        style={{
          position: "absolute", inset: 0,
          width: "100%", height: "100%",
          objectFit: "cover",
          transition: "opacity 1.25s ease-in-out, transform 1.25s ease-in-out, filter 1.25s ease-in-out",
          transform: phase === "ended" ? "scale(1.02)" : "scale(1)",
          filter: phase === "ended" ? "brightness(0.9)" : "brightness(1)",
          opacity: phase === "loading" ? 0 : phase === "ended" ? 0 : 1,
        }}
      />

      <img
        src="assets/cyborg.png"
        alt="Francis AI Assistant"
        style={{
          position: "absolute", inset: 0,
          width: "100%", height: "100%",
          objectFit: "cover", objectPosition: "center 24%",
          transform: phase === "ended" ? "scale(1)" : "scale(1.03)",
          filter: phase === "ended" ? "brightness(1)" : "brightness(0.92)",
          opacity: phase === "ended" ? 1 : 0,
          transition: "opacity 1.25s ease-in-out, transform 1.25s ease-in-out, filter 1.25s ease-in-out",
        }}
      />

      <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.6) 100%)",
        opacity: 0.45,
        transition: "opacity 1.2s ease-in-out",
      }} />

      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0, height: 2,
        background: "linear-gradient(90deg, transparent, var(--teal), transparent)",
        opacity: 0.6,
      }} />

      {phase === "ended" && (
        <button onClick={() => {
          const video = videoRef.current;
          if (!video) return;
          setPhase("loading");
          video.currentTime = 0;
          video.play().catch(() => {});
        }} style={{
          position: "absolute", bottom: 36, right: 48,
          background: "rgba(5,12,13,0.86)", border: "1px solid rgba(20,184,166,0.16)",
          color: "var(--fg)", cursor: "pointer", borderRadius: 999,
          padding: "8px 18px",
          fontFamily: "Roboto Mono, monospace", fontSize: 11, fontWeight: 500,
          letterSpacing: "0.15em", textTransform: "uppercase",
          display: "flex", alignItems: "center", gap: 8,
          boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
          transition: "all 0.2s",
          animation: "fadeIn 0.5s ease",
          zIndex: 6,
        }} onMouseEnter={e=>{ e.currentTarget.style.background="rgba(7,16,17,0.92)"; e.currentTarget.style.borderColor="rgba(20,184,166,0.3)"; e.currentTarget.style.color="var(--teal)"; }} onMouseLeave={e=>{ e.currentTarget.style.background="rgba(5,12,13,0.86)"; e.currentTarget.style.borderColor="rgba(20,184,166,0.16)"; e.currentTarget.style.color="var(--fg)"; }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="var(--teal)">
            <path d="M8 5v14l11-7z"/>
          </svg>
          Replay
        </button>
      )}

      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column",
        alignItems: "flex-start", justifyContent: "flex-end",
        padding: "0 60px 80px",
        pointerEvents: phase === "ended" ? "auto" : "none",
      }}>
        <p style={{
          fontFamily: "Roboto Mono, monospace", fontSize: 15, fontWeight: 500,
          letterSpacing: "0.22em", textTransform: "uppercase",
          color: "var(--fg)", marginBottom: 16,
          opacity: phase === "ended" ? 1 : 0,
          transform: phase === "ended" ? "translateY(0)" : "translateY(20px)",
          transition: "opacity 1.6s ease 0.9s, transform 1.6s ease 0.9s",
        }}>
          AI & Automation <span style={{ color: "var(--teal)" }}>Specialist</span>
        </p>

        <h1 style={{
          fontFamily: "Montserrat, sans-serif", fontWeight: 900,
          fontSize: "clamp(3rem, 7vw, 6rem)",
          lineHeight: 1.0, letterSpacing: "-0.02em",
          color: "var(--fg)", marginBottom: 20,
          textWrap: "balance",
          opacity: phase === "ended" ? 1 : 0,
          transform: phase === "ended" ? "translateY(0)" : "translateY(24px)",
          transition: "opacity 1.9s ease 0s, transform 1.9s ease 0s",
        }}>
          Francis Joseph<br />
          <span style={{ color: "var(--teal)", textShadow: "0 0 14px oklch(0.65 0.16 185 / 0.9), 0 0 32px oklch(0.65 0.16 185 / 0.5)", animation: "tealGlow 2.5s ease-in-out infinite" }}>Danao.</span>
        </h1>

        <p style={{
          fontFamily: "Montserrat, sans-serif", fontSize: 16, fontWeight: 400,
          color: "rgba(255,255,255,0.55)", maxWidth: 480, lineHeight: 1.6,
          marginBottom: 36,
          opacity: phase === "ended" ? 1 : 0,
          transform: phase === "ended" ? "translateY(0)" : "translateY(20px)",
          transition: "opacity 1.7s ease 2s, transform 1.7s ease 2s",
        }}>
          I build intelligent automations, websites, landing pages, and dashboards using tools like Claude Code, Codex,
          and other no-code or low-code platforms
          to speed up delivery, eliminate manual work, and help businesses scale faster with smarter systems.
        </p>

        <div style={{
          display: "flex", gap: 12, flexWrap: "wrap",
          opacity: phase === "ended" ? 1 : 0,
          transform: phase === "ended" ? "translateY(0)" : "translateY(18px)",
          transition: "opacity 1.5s ease 3.1s, transform 1.5s ease 3.1s",
        }}>
          <button onClick={() => navigateTo("projects")} style={{
            background: "var(--teal)", color: "#030d0e",
            border: "none", cursor: "pointer", borderRadius: 999,
            padding: "13px 28px",
            fontFamily: "Montserrat, sans-serif", fontSize: 13, fontWeight: 700,
            letterSpacing: "0.04em",
            boxShadow: "0 0 18px oklch(0.65 0.16 185 / 0.6), 0 0 40px oklch(0.65 0.16 185 / 0.3)",
            animation: "buttonGlow 2.5s ease-in-out infinite",
            transition: "opacity 0.15s",
          }} onMouseEnter={e=>e.target.style.opacity=0.85} onMouseLeave={e=>e.target.style.opacity=1}>
            View My Work
          </button>
          <button onClick={() => navigateTo("contact")} style={{
            background: "rgba(5,12,13,0.86)", color: "var(--fg)",
            border: "1px solid rgba(20,184,166,0.16)", cursor: "pointer", borderRadius: 999,
            padding: "13px 28px",
            fontFamily: "Montserrat, sans-serif", fontSize: 13, fontWeight: 600,
            letterSpacing: "0.04em",
            boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
            transition: "all 0.2s",
          }} onMouseEnter={e=>{ e.currentTarget.style.borderColor="rgba(20,184,166,0.32)"; e.currentTarget.style.background="rgba(7,16,17,0.92)"; e.currentTarget.style.color="var(--teal)"; }} onMouseLeave={e=>{ e.currentTarget.style.borderColor="rgba(20,184,166,0.16)"; e.currentTarget.style.background="rgba(5,12,13,0.86)"; e.currentTarget.style.color="var(--fg)"; }}>
            Get in Touch
          </button>
        </div>
      </div>

      {phase === "ended" && (
        <button onClick={() => navigateTo("projects")} style={{
          position: "absolute", bottom: 32, left: "50%", transform: "translateX(-50%)",
          background: "none", border: "none", cursor: "pointer",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
          animation: "bounce 2s ease-in-out infinite",
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="1.5">
            <path d="M12 5v14M5 12l7 7 7-7"/>
          </svg>
        </button>
      )}
    </section>
  );
};

Object.assign(window, { Hero });
