
const AboutSection = () => {
  const FORWARD_VIDEO_SRC = "uploads/1777092074855-xfmauam8qu.mp4";
  const REVERSE_VIDEO_SRC = "uploads/about-transform-reverse.mp4";
  const sectionRef = React.useRef(null);
  const videoRef = React.useRef(null);
  const phaseRef = React.useRef("idle");
  const isMobileRef = React.useRef(false);
  const fallbackPhaseRef = React.useRef("idle");
  const playbackAttemptRef = React.useRef(0);
  const [phase, _setPhase] = React.useState("idle"); // idle | transforming | reversing | cyborg
  const [showCyborg, setShowCyborg] = React.useState(false);
  const [videoSrc, setVideoSrc] = React.useState(FORWARD_VIDEO_SRC);
  const [playNonce, setPlayNonce] = React.useState(0);
  const [isVideoPlaying, setIsVideoPlaying] = React.useState(false);
  const shouldShowCyborg = showCyborg && phase !== "reversing";
  const shouldShowLabel = phase === "idle" || phase === "cyborg";

  const setPhase = (nextPhase) => {
    phaseRef.current = nextPhase;
    _setPhase(nextPhase);
  };

  const playCurrentVideo = () => {
    const video = videoRef.current;
    if (!video) return;
    playbackAttemptRef.current += 1;
    const attemptId = playbackAttemptRef.current;

    video.muted = true;
    video.defaultMuted = true;
    video.currentTime = 0;
    video.playbackRate = 0.75;
    const playPromise = video.play();

    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(() => {
        if (attemptId !== playbackAttemptRef.current) return;
        setIsVideoPlaying(false);
        setPhase(fallbackPhaseRef.current);
        setShowCyborg(fallbackPhaseRef.current === "cyborg");
        setVideoSrc(FORWARD_VIDEO_SRC);
      });
    }
  };

  React.useEffect(() => {
    if (phase !== "transforming" && phase !== "reversing") return;

    setIsVideoPlaying(false);

    const frame = requestAnimationFrame(() => {
      playCurrentVideo();
    });

    return () => cancelAnimationFrame(frame);
  }, [phase, videoSrc, playNonce]);

  const startForward = () => {
    fallbackPhaseRef.current = "idle";
    setPhase("transforming");
    setShowCyborg(false);
    setVideoSrc(FORWARD_VIDEO_SRC);
    setPlayNonce((value) => value + 1);
  };

  const startReverse = () => {
    fallbackPhaseRef.current = "cyborg";
    setPhase("reversing");
    setShowCyborg(true);
    setVideoSrc(REVERSE_VIDEO_SRC);
    setPlayNonce((value) => value + 1);
  };

  React.useEffect(() => {
    const mediaQuery = window.matchMedia("(max-width: 768px)");

    const syncMobileState = () => {
      isMobileRef.current = mediaQuery.matches;
    };

    syncMobileState();
    mediaQuery.addEventListener("change", syncMobileState);

    return () => mediaQuery.removeEventListener("change", syncMobileState);
  }, []);

  React.useEffect(() => {
    const section = sectionRef.current;
    const scrollContainer = document.getElementById("scroll-container");
    if (!section || !scrollContainer) return;

    const syncFromScrollPosition = () => {
      if (!isMobileRef.current) return;

      const containerRect = scrollContainer.getBoundingClientRect();
      const sectionRect = section.getBoundingClientRect();
      const visibleTop = Math.max(sectionRect.top, containerRect.top);
      const visibleBottom = Math.min(sectionRect.bottom, containerRect.bottom);
      const visibleHeight = Math.max(0, visibleBottom - visibleTop);
      const ratio = visibleHeight / Math.max(1, Math.min(sectionRect.height, containerRect.height));

      if (ratio >= 0.45 && phaseRef.current === "idle") {
        startForward();
        return;
      }

      if (ratio <= 0.12 && phaseRef.current === "cyborg") {
        startReverse();
      }
    };

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (!isMobileRef.current) return;

        if (entry.intersectionRatio >= 0.55 && phaseRef.current === "idle") {
          startForward();
          return;
        }

        if (entry.intersectionRatio <= 0.2 && phaseRef.current === "cyborg") {
          startReverse();
        }
      },
      {
        root: scrollContainer,
        threshold: [0.2, 0.55],
      }
    );

    observer.observe(section);
    scrollContainer.addEventListener("scroll", syncFromScrollPosition, { passive: true });
    window.addEventListener("resize", syncFromScrollPosition);
    requestAnimationFrame(syncFromScrollPosition);

    return () => {
      observer.disconnect();
      scrollContainer.removeEventListener("scroll", syncFromScrollPosition);
      window.removeEventListener("resize", syncFromScrollPosition);
    };
  }, []);

  const handleActivate = () => {
    if (phaseRef.current === "idle") {
      startForward();
      return;
    }

    if (phaseRef.current === "cyborg") {
      startReverse();
    }
  };

  const handleMouseLeave = () => {};

  const highlights = [
    { label: "Claude Code / Codex", desc: "Landing pages, dashboards, and tailored web experiences connected to smart automation." },
    { label: "AI Automation", desc: "AI agents, RAG pipelines, chatbots, and intelligent routing systems." },
    { label: "n8n / Make / Zapier", desc: "Multi-step automations, API integrations, and cross-platform logic." },
    { label: "GoHighLevel", desc: "CRM pipelines, workflow builder, automated follow-up sequences." },
  ];

  const glassPanel = {
    background: "rgba(5,12,13,0.86)",
    border: "1px solid rgba(20,184,166,0.16)",
    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
  };

  return (
    <section ref={sectionRef} data-screen-label="03 About" style={{
      minHeight: "100vh",
      background: "var(--bg)",
      borderTop: "1px solid var(--border)",
      display: "flex",
      position: "relative",
    }}>
      {/* Atmospheric background */}
      <video autoPlay muted loop playsInline src="uploads/background_teal_moving.mp4"
        onCanPlay={e => e.target.playbackRate = 0.4}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 0, pointerEvents: "none" }} />
      <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.75)", zIndex: 0, pointerEvents: "none" }} />
      <div
        onMouseEnter={handleActivate}
        onClick={handleActivate}
        onMouseLeave={handleMouseLeave}
        style={{ width: "42%", flexShrink: 0, position: "relative", overflow: "hidden", cursor: "crosshair", touchAction: "manipulation", zIndex: 1 }}
      >
        <img
          src="assets/profile-new.png"
          alt="Francis Joseph Danao"
          style={{
            position: "absolute", inset: 0, zIndex: 0,
            width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 18%",
            opacity: phase === "idle" ? 1 : 0,
            transition: "opacity 0.6s ease",
          }}
        />

        <img
          src="assets/cyborg.png"
          alt="Francis Cyborg"
          style={{
            position: "absolute", inset: 0, zIndex: 1,
            width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 24%",
            display: shouldShowCyborg ? "block" : "none",
            opacity: shouldShowCyborg ? 1 : 0,
            visibility: shouldShowCyborg ? "visible" : "hidden",
            transition: shouldShowCyborg ? "opacity 0.4s ease" : "none",
          }}
        />

        <video
          ref={videoRef}
          key={`${videoSrc}-${playNonce}`}
          src={videoSrc}
          muted
          defaultMuted
          playsInline
          autoPlay
          preload="auto"
          onPlaying={() => setIsVideoPlaying(true)}
          onEnded={() => {
            setIsVideoPlaying(false);
            if (phaseRef.current === "transforming") {
              setPhase("cyborg");
              setShowCyborg(true);
              setVideoSrc(FORWARD_VIDEO_SRC);
            } else if (phaseRef.current === "reversing") {
              setPhase("idle");
              setShowCyborg(false);
              setVideoSrc(FORWARD_VIDEO_SRC);
            }
          }}
          style={{
            position: "absolute", inset: 0, zIndex: 2,
            width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 18%",
            opacity: (phase === "transforming" || phase === "reversing") && isVideoPlaying ? 1 : 0,
            transition: phase === "reversing" ? "none" : "opacity 0.15s ease",
            pointerEvents: "none",
          }}
        />

        <div style={{ position: "absolute", inset: 0, zIndex: 3, background: "linear-gradient(to right, transparent 60%, var(--bg) 100%)", pointerEvents: "none" }} />
        <div style={{ position: "absolute", inset: 0, zIndex: 3, background: "linear-gradient(to top, rgba(7,14,16,0.75) 0%, transparent 50%)", pointerEvents: "none" }} />
        <div style={{
          position: "absolute", bottom: 0, left: 0, right: 0, zIndex: 4,
          padding: "28px 32px", display: "flex", alignItems: "center", gap: 16,
          pointerEvents: "none",
          opacity: shouldShowLabel ? 1 : 0,
          transition: "opacity 0.2s ease",
          maxWidth: "100%",
        }}>
          <div style={{ width: 3, height: 44, background: "var(--teal)", opacity: 0.9, flexShrink: 0, boxShadow: "0 0 10px rgba(20,184,166,0.8)" }} />
          <div>
            <p style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: 25, lineHeight: 1, marginBottom: 8, textWrap: "balance" }}>
              {phase === "cyborg" ? (
                <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" }}>
                  Francis&apos;s AI Assistant
                </span>
              ) : (
                <>
                  <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" }}>Francis</span>
                  <span style={{ color: "var(--fg)" }}> Joseph Danao</span>
                </>
              )}
            </p>
            <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 13, color: "var(--teal)", letterSpacing: "0.14em", textTransform: "uppercase", textShadow: "0 0 10px rgba(20,184,166,0.5)" }}>
              AI & Automation Specialist
            </p>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, padding: "100px 72px 80px 64px", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative", zIndex: 1 }}>

        {/* Editorial label */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
          <div style={{ width: 32, height: 2, borderRadius: 2, background: "var(--teal)", boxShadow: "0 0 8px rgba(20,184,166,0.6)", flexShrink: 0 }} />
          <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 11, fontWeight: 500, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--teal)" }}>Background</p>
        </div>

        <h2 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: "clamp(2rem,4vw,3.2rem)", color: "var(--fg)", letterSpacing: "-0.025em", lineHeight: 1.08, marginBottom: 28, textWrap: "balance" }}>
          I help businesses work<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" }}>smarter</span> — not harder.
        </h2>

        <div style={{ display: "flex", flexDirection: "column", gap: 16, marginBottom: 36 }}>
          <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 16, color: "var(--muted)", lineHeight: 1.8 }}>
            I combine <span style={{ color: "var(--fg)", fontWeight: 600 }}>AI with modern no-code and low-code platforms</span> to design and build end-to-end automation systems that eliminate repetitive tasks and unlock growth — without adding headcount.
          </p>
          <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 16, color: "var(--muted)", lineHeight: 1.8 }}>
            Whether it&apos;s orchestrating multi-step logic across platforms or building AI-powered chatbots, I turn chaotic manual processes into <span style={{ color: "var(--fg)", fontWeight: 600 }}>reliable, scalable machines that run 24/7.</span>
          </p>
          <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 16, color: "var(--muted)", lineHeight: 1.8 }}>
            I also use <span style={{ color: "var(--fg)", fontWeight: 600 }}>Claude Code and Codex</span> to design landing pages, dashboards, and tailored web experiences, and I can work with editing tools like <span style={{ color: "var(--fg)", fontWeight: 600 }}>HyperFrames</span> to move faster from concept to polished output.
          </p>
        </div>

        {/* Numbered highlights */}
        <div style={{
          ...glassPanel,
          display: "flex",
          flexDirection: "column",
          gap: 0,
          borderRadius: 24,
          overflow: "hidden",
          position: "relative",
        }}>
          <div style={{
            position: "absolute",
            top: 0,
            left: "8%",
            right: "8%",
            height: 1,
            background: "linear-gradient(90deg, transparent, rgba(255,255,255,0.35), transparent)",
            pointerEvents: "none",
            opacity: 0.35,
          }} />
          {highlights.map((highlight, index) => (
            <div key={highlight.label} style={{
              display: "flex", gap: 20, alignItems: "flex-start",
              padding: "22px 26px",
              borderBottom: index < highlights.length - 1 ? "1px solid rgba(255,255,255,0.08)" : "none",
              background: "transparent",
            }}>
              <span style={{
                fontFamily: "Roboto Mono, monospace",
                fontSize: 9,
                color: "rgba(255,255,255,0.72)",
                letterSpacing: "0.08em",
                paddingTop: 0,
                flexShrink: 0,
                minWidth: 34,
                height: 34,
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                borderRadius: 999,
                background: "rgba(255,255,255,0.05)",
                border: "1px solid rgba(255,255,255,0.1)",
                boxShadow: "inset 0 1px 0 rgba(255,255,255,0.08)",
              }}>
                {String(index + 1).padStart(2, "0")}
              </span>
              <div>
                <p style={{
                  fontFamily: "Montserrat, sans-serif",
                  fontSize: 16,
                  fontWeight: 700,
                  color: "rgba(126,230,219,0.9)",
                  letterSpacing: "0.01em",
                  textTransform: "none",
                  marginBottom: 6,
                }}>{highlight.label}</p>
                <p style={{
                  fontFamily: "Montserrat, sans-serif",
                  fontSize: 15,
                  fontWeight: 500,
                  color: "rgba(237,239,242,0.68)",
                  lineHeight: 1.75,
                  letterSpacing: "-0.01em",
                }}>{highlight.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { AboutSection });
