// components.jsx - Sinatra Labs site components

const { useState, useEffect, useRef } = React;

function isTeamPagePath() {
  return /\/team(\.html)?$/i.test(window.location.pathname);
}

/* ---------- Reveal hook (IntersectionObserver) ---------- */
function useInView(opts = { once: true }) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);

  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;

    const check = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight - 40 && r.bottom > 0) {
        setInView(true);
        return true;
      }
      return false;
    };

    if (check() && opts.once) return;

    const onScroll = () => {
      if (check() && opts.once) {
        window.removeEventListener("scroll", onScroll);
      }
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    const t = setTimeout(onScroll, 60);

    return () => {
      clearTimeout(t);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  return [ref, inView];
}

/* ---------- Reveal wrapper ---------- */
function Reveal({ children, delay = 0, as = "div", className = "", ...props }) {
  const [ref, inView] = useInView();
  const Tag = as;

  return (
    <Tag
      ref={ref}
      className={`reveal ${inView ? "in" : ""} ${className}`}
      style={{ "--d": `${delay}ms` }}
      {...props}
    >
      {children}
    </Tag>
  );
}

/* ---------- Split words (line by line) ---------- */
function SplitLines({ children, delay = 0, stagger = 90 }) {
  const lines = String(children).split("\n");
  const [ref, inView] = useInView();

  return (
    <span ref={ref} className="split-wrap" style={{ display: "block" }}>
      {lines.map((ln, i) => (
        <span
          key={i}
          className={`split-line ${inView ? "in" : ""}`}
          style={{ "--d": `${delay + i * stagger}ms`, display: "block" }}
        >
          <span>{ln}</span>
        </span>
      ))}
    </span>
  );
}

/* ---------- Top nav ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const onTeamPage = isTeamPagePath();

  useEffect(() => {
    const updateScrolled = () => {
      if (onTeamPage) {
        setScrolled(true);
      } else {
        const hero = document.getElementById("top");
        if (!hero) {
          setScrolled(window.scrollY > 18);
        } else {
          setScrolled(hero.getBoundingClientRect().bottom <= 0);
        }
      }
    };

    updateScrolled();
    window.addEventListener("scroll", updateScrolled, { passive: true });
    window.addEventListener("resize", updateScrolled);

    return () => {
      window.removeEventListener("scroll", updateScrolled);
      window.removeEventListener("resize", updateScrolled);
    };
  }, [onTeamPage]);

  const brandHref = onTeamPage ? "index.html#top" : "#top";
  const processHref = onTeamPage ? "index.html#process" : "#process";
  const teamHref = onTeamPage ? "#team" : "team.html#team";
  const contactHref = onTeamPage ? "index.html#contact" : "#contact";

  return (
    <nav className={`sticky-nav${scrolled ? " is-scrolled" : ""}`}>
      <a href={brandHref} className="brand" style={{ justifyContent: "center" }}>
        <span className="brand-script">Sinatra</span>
      </a>
      <div className="links" aria-label="Primary">
        <a href={processHref}>Process</a>
        <a href={teamHref}>Team</a>
        <a href={contactHref}>Contact</a>
        <a
          href="https://calendly.com/nick-sinatralabs/30min"
          target="_blank"
          rel="noopener"
          className="btn-cta"
        >
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 10,
              padding: "8px 16px",
              border: "1px solid currentColor",
              borderRadius: 999,
            }}
          >
            Schedule a Working Session <span aria-hidden>&#8599;</span>
          </span>
        </a>
      </div>
    </nav>
  );
}

/* ---------- Hero with animated neon LABS ---------- */
function Hero() {
  const videoRef = useRef(null);

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

    const setPlaybackRate = () => {
      video.defaultPlaybackRate = 0.6;
      video.playbackRate = 0.6;
    };

    setPlaybackRate();
    video.addEventListener("loadedmetadata", setPlaybackRate);
    video.addEventListener("canplay", setPlaybackRate);

    return () => {
      video.removeEventListener("loadedmetadata", setPlaybackRate);
      video.removeEventListener("canplay", setPlaybackRate);
    };
  }, []);

  const heroRef = useRef(null);
  useEffect(() => {
    const state = {
      targetY: 0,
      currentY: 0,
      targetScale: 1,
      currentScale: 1,
      targetMarkOpacity: 1,
      currentMarkOpacity: 1,
      targetMarkY: 0,
      currentMarkY: 0,
      targetMarkScale: 1,
      currentMarkScale: 1,
      targetMarkBlur: 0,
      currentMarkBlur: 0,
      raf: 0,
    };

    const updateTargets = () => {
      const y = window.scrollY;
      state.targetY = Math.min(y * 0.09, 36);
      state.targetScale = 1 + Math.min(y / 14000, 0.015);
      const dissolve = Math.max(0, Math.min(1, y / 180));
      state.targetMarkOpacity = 1 - dissolve;
      state.targetMarkY = dissolve * -20;
      state.targetMarkScale = 1 - dissolve * 0.04;
      state.targetMarkBlur = dissolve * 10;
    };

    const tick = () => {
      if (!heroRef.current) return;

      state.currentY += (state.targetY - state.currentY) * 0.06;
      state.currentScale += (state.targetScale - state.currentScale) * 0.06;
      state.currentMarkOpacity += (state.targetMarkOpacity - state.currentMarkOpacity) * 0.08;
      state.currentMarkY += (state.targetMarkY - state.currentMarkY) * 0.08;
      state.currentMarkScale += (state.targetMarkScale - state.currentMarkScale) * 0.08;
      state.currentMarkBlur += (state.targetMarkBlur - state.currentMarkBlur) * 0.08;

      heroRef.current.style.setProperty("--hero-img-y", `${state.currentY.toFixed(2)}px`);
      heroRef.current.style.setProperty("--hero-img-scale", state.currentScale.toFixed(4));
      heroRef.current.style.setProperty("--hero-mark-opacity", state.currentMarkOpacity.toFixed(3));
      heroRef.current.style.setProperty("--hero-mark-y", `${state.currentMarkY.toFixed(2)}px`);
      heroRef.current.style.setProperty("--hero-mark-scale", state.currentMarkScale.toFixed(4));
      heroRef.current.style.setProperty("--hero-mark-blur", `${state.currentMarkBlur.toFixed(2)}px`);

      state.raf = window.requestAnimationFrame(tick);
    };

    updateTargets();
    tick();
    window.addEventListener("scroll", updateTargets, { passive: true });
    window.addEventListener("resize", updateTargets);

    return () => {
      window.removeEventListener("scroll", updateTargets);
      window.removeEventListener("resize", updateTargets);
      window.cancelAnimationFrame(state.raf);
    };
  }, []);

  return (
    <section id="top" className="hero hero-fullbleed" ref={heroRef}>
      <div className="hero-bg" aria-hidden>
        <video
          ref={videoRef}
          className="hero-bg-media hero-bg-video"
          autoPlay
          muted
          loop
          playsInline
          preload="auto"
          poster="assets/hero-bg.jpg"
        >
          <source src="video.mp4" type="video/mp4" />
        </video>
        <div className="hero-bg-grain" />
        <div className="hero-bg-tint" />
        <div className="hero-bg-vignette" />
      </div>

      <div className="container hero-grid hero-grid-fb">
        <div className="hero-center">
          <div
            className="wordmark hero-wordmark hero-wordmark-fb"
            aria-label="Sinatra Labs"
            style={{ justifyContent: "center" }}
          >
            <span className="sinatra sinatra-script">Sinatra</span>
            <span className="hero-wordmark-labs">LABS</span>
          </div>
        </div>

        <div className="hero-bottom-fb">
          <div className="hero-bottom-left">
            <h1 className="hero-h1 hero-h1-fb">
              <SplitLines stagger={120}>{"MAKE YOUR NEXT AI MOVE"}</SplitLines>
            </h1>
            <Reveal delay={700} className="hero-sub">
              <p>Strategies and Solutions</p>
            </Reveal>
            <Reveal delay={900} className="hero-cta">
              <a
                href="https://calendly.com/nick-sinatralabs/30min"
                target="_blank"
                rel="noopener"
                className="btn"
              >
                <span>Schedule a Working Session</span>
                <span className="arrow">&#8594;</span>
              </a>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Tools ticker ---------- */
function ToolsBanner() {
  const tools = [
    { key: "claude", label: "Claude", logo: "assets/tool-logos/claude.png" },
    { key: "openai", label: "OpenAI", logo: "assets/tool-logos/openai.png" },
    { key: "gemini", label: "Gemini", logo: "assets/tool-logos/gemini.png" },
    { key: "aws", label: "AWS", logo: "assets/tool-logos/aws.png" },
    { key: "gcp", label: "Google Cloud", logo: "assets/tool-logos/gcp.png" },
    { key: "vercel", label: "Vercel", logo: "assets/tool-logos/vercel.png" },
    { key: "postgresql", label: "PostgreSQL", logo: "assets/tool-logos/postgresql.png" },
    { key: "supabase", label: "Supabase", logo: "assets/tool-logos/supabase.png" },
    { key: "snowflake", label: "Snowflake", logo: "assets/tool-logos/snowflake.png" },
    { key: "hubspot", label: "HubSpot", logo: "assets/tool-logos/hubspot.png" },
    { key: "n8n", label: "n8n", logo: "assets/tool-logos/n8n.png" },
    { key: "docker", label: "Docker", logo: "assets/tool-logos/docker.png" },
  ];

  return (
    <section className="tools-banner paper" aria-label="Tools we use">
      <div className="container tools-banner-head">
        <p className="tools-banner-label">Tools We Use</p>
      </div>
      <div className="marquee tools-marquee">
        {[0, 1].map((track) => (
          <div
            key={track}
            className="marquee-track tools-track"
            aria-hidden={track === 1 ? "true" : undefined}
          >
            {tools.map((tool) => (
              <div key={`${track}-${tool.key}`} className="tools-logo">
                <img
                  src={tool.logo}
                  alt=""
                  aria-hidden="true"
                  className="tools-logo-img"
                  loading="lazy"
                  decoding="async"
                />
                <span className="tools-word">{tool.label}</span>
              </div>
            ))}
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Proof strip ---------- */
function Proof() {
  const offerings = [
    {
      n: "01",
      title: "AI preparation strategy",
      copy: "Choose where AI belongs, where it does not, and the first system worth building.",
    },
    {
      n: "02",
      title: "CRM and database systems",
      copy: "Clean records, connect sources, create owner views, and make follow-up visible.",
    },
    {
      n: "03",
      title: "Institutional-caliber research",
      copy: "Gather sources, preserve judgment, and produce decision briefs leadership can trust.",
    },
    {
      n: "04",
      title: "New-hire onboarding systems",
      copy: "Turn company knowledge into guided paths, checklists, and answers new people can use.",
    },
    {
      n: "05",
      title: "Custom tools and products",
      copy: "Create internal tools, portals, websites, and web apps around real work.",
    },
  ];

  return (
    <section className="proof paper" id="overview">
      <div className="container">
        <div className="proof-overview-frame">
          <Reveal className="proof-overview-head">
            <h2 className="proof-title">
              MAKE YOUR NEXT AI MOVE
            </h2>
            <p className="proof-copy">
              Strategies and Solutions
            </p>
          </Reveal>

          <div className="proof-offerings">
            {offerings.map((item, index) => (
              <Reveal key={item.n} delay={index * 70} className="proof-offering" as="article">
                <span className="proof-offering-n">{item.n}</span>
                <div className="proof-offering-body">
                  <h3>{item.title}</h3>
                  <p>{item.copy}</p>
                </div>
              </Reveal>
            ))}
          </div>

          <Reveal delay={260} className="proof-footer">
            <p className="proof-footer-copy">
              Bring one messy workflow, tool stack, research question, or product idea.
              Leave with the first build worth scoping.
            </p>
            <a href="#contact" className="proof-footer-cta">
              <span>Schedule a working session</span>
              <span className="proof-footer-arrow" aria-hidden="true">&gt;</span>
            </a>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { useInView, Reveal, SplitLines, Nav, Hero, ToolsBanner, Proof, isTeamPagePath });
