/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

/* ---------------- Nav ---------------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [activeLink, setActiveLink] = useState(null); // no link active until user clicks one
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", on, { passive: true });
    on();
    return () => window.removeEventListener("scroll", on);
  }, []);

  const links = [
    { href: "#work",         label: "Work" },
    { href: "#services",     label: "Services" },
    { href: "#process",      label: "Process" },
    { href: "#capabilities", label: "Capabilities" },
    { href: "#contact",      label: "Contact" },
  ];

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="nav-inner">
        <a href="#top" className="nav-logo" aria-label="Grabsoft Digital home" onClick={() => setActiveLink(null)}>
          <img className="logo-light" src="assets/grabsoft-logo-light.png" alt="Grabsoft Digital"/>
        </a>
        <div className="nav-links">
          {links.map((link) => (
            <a
              key={link.href}
              href={link.href}
              className={`nav-link ${activeLink === link.href ? "active" : ""}`}
              onClick={() => setActiveLink(link.href)}
            >
              {link.label}
            </a>
          ))}
        </div>
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <div className="nav-social">
            <a href="https://www.facebook.com/grabsoft" target="_blank" rel="noopener" className="nav-social-btn" aria-label="Facebook">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>
              </svg>
            </a>
            <a href="https://www.youtube.com/watch?v=ZZ_KMrN12g0"
               target="_blank"
               rel="noopener"
               className="nav-social-btn"
               aria-label="YouTube">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" width="16" height="16" fill="currentColor">
                <path d="M549.7 124.1C543.5 100.4 524.9 81.8 501.4 75.5 458.9 64 288.1 64 288.1 64S117.3 64 74.7 75.5C51.2 81.8 32.7 100.4 26.4 124.1 15 167 15 256.4 15 256.4s0 89.4 11.4 132.3c6.3 23.6 24.8 41.5 48.3 47.8 42.6 11.5 213.4 11.5 213.4 11.5s170.8 0 213.4-11.5c23.5-6.3 42-24.2 48.3-47.8 11.4-42.9 11.4-132.3 11.4-132.3s0-89.4-11.4-132.3zM232.2 337.6l0-162.4 142.7 81.2-142.7 81.2z"/>
              </svg>
            </a>
          </div>
          <a href="#contact" className="btn btn-green" onClick={() => setActiveLink("#contact")}>
            Start a project
            <ArrowSm/>
          </a>
        </div>
      </div>
    </nav>
  );
}

function ArrowSm() {
  return (
    <svg className="arrow-rotate" width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M3 11L11 3M11 3H4.5M11 3V9.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}
function ArrowLg({color = "white"}) {
  return (
    <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
      <path d="M6 22L22 6M22 6H9M22 6V19" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---------------- Hero Lamp ---------------- */
// Two <img> tags — one for each theme — always in DOM.
// CSS shows/hides them via [data-theme] selector.
// No JS state, no re-renders, no animation glitches.
function HeroLamp() {
  return (
    <div className="hero-lamp" aria-hidden="true">
      <img src="assets/light-mode.png" alt="" className="hero-lamp-img hero-lamp-img--light" />
      <img src="assets/dark-mode.png"  alt="" className="hero-lamp-img hero-lamp-img--dark" />
    </div>
  );
}

/* ---------------- Hero ---------------- */
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-mark"></div>
      <HeroLamp />
      <div className="wrap hero-grid">
        <div className="hero-meta">
          <span className="eyebrow">Digital agency · Est. 2020 · Dhaka, BD</span>
          <div className="hero-meta-item mono"><span className="dot"></span>Live Digital Services</div>
        </div>

        <h1 className="hero-title">
          <div className="row">
            <span>We design</span>
            <span className="pill">
              <SwatchDot/>brands
            </span>
          </div>
          <div className="row indent">
            <span>that <em>actually</em></span>
          </div>
          <div className="row">
            <span>move&nbsp;markets.</span>
          </div>
        </h1>

        <div className="hero-footer">
          <div className="hero-foot-block">
            <div className="label">A note from the studio</div>
            <p>Grabsoft is a 40-strong team of researchers, strategists, designers and engineers building digital products, brands and growth engines for ambitious teams across 35+ countries.</p>
          </div>
          <div className="hero-foot-block">
            <div className="label">Combined client valuation</div>
            <div className="big"><AnimatedNum to={500}/><sup>M+</sup></div>
          </div>
          <div className="hero-foot-block">
            <div className="label">Products launched</div>
            <div className="big"><AnimatedNum to={250}/><sup>+</sup></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function SwatchDot() {
  return (
    <svg viewBox="0 0 64 64" fill="none">
      <circle cx="32" cy="32" r="28" stroke="white" strokeWidth="3"/>
      <circle cx="32" cy="32" r="14" fill="white"/>
    </svg>
  );
}

function AnimatedNum({ to, duration = 1400 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{val}</span>;
}

/* ---------------- Marquee ---------------- */
function Marquee() {
  const items = ["UI/UX Design", "Branding", "Web Development", "App Engineering", "Software Systems", "SEO & Growth", "Media Buying", "2D / 3D Motion"];
  const row = (
    <span>
      {items.map((s, i) => (
        <React.Fragment key={i}>
          <span>{s}</span>
          <span className="star">✦</span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {row}{row}
      </div>
    </div>
  );
}

window.Nav = Nav;
window.Hero = Hero;
window.HeroLamp = HeroLamp;
window.Marquee = Marquee;
window.AnimatedNum = AnimatedNum;
window.ArrowSm = ArrowSm;
window.ArrowLg = ArrowLg;

/* ---------------- Video Reel ---------------- */
function VideoReel() {
  const [playing, setPlaying] = useState(true);
  const [unmuted, setUnmuted] = useState(false);
  const VIDEO_ID = "Nxb2KYTWLrM";
  const params = new URLSearchParams({
    autoplay: "1",
    mute: unmuted ? "0" : "1",
    loop: "1",
    playlist: VIDEO_ID,
    controls: "0",
    modestbranding: "1",
    rel: "0",
    playsinline: "1",
    iv_load_policy: "3",
    enablejsapi: "1",
  });
  const src = `https://www.youtube-nocookie.com/embed/${VIDEO_ID}?${params.toString()}`;
  return (
    <section className="reel" id="reel">
      <div className="wrap">
        <div className="reel-head">
          <span className="eyebrow">The studio reel · 2025</span>
          <h2 className="reel-title">Six years of <em>shipping</em>, in ninety seconds.</h2>
        </div>
        <div className="reel-frame">
          <div className="reel-aspect">
            {playing ? (
              <iframe
                src={src}
                title="Grabsoft Digital — Studio Reel"
                frameBorder="0"
                allow="autoplay; encrypted-media; picture-in-picture; web-share"
                allowFullScreen
              ></iframe>
            ) : (
              <button className="reel-cover" onClick={() => setPlaying(true)} aria-label="Play studio reel">
                <span className="reel-play">
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="white"><path d="M8 5v14l11-7z"/></svg>
                </span>
              </button>
            )}
          </div>
          <div className="reel-bar">
            <div className="reel-bar-left">
              <span className="dot pulse"></span>
              <span className="mono">LIVE · grabsoft studio reel</span>
            </div>
            <div className="reel-bar-right">
              <button className="reel-pill" onClick={() => setUnmuted((u) => !u)}>
                {unmuted ? "Mute" : "Unmute"} sound
              </button>
              <a className="reel-pill" href={`https://www.youtube.com/watch?v=${VIDEO_ID}`} target="_blank" rel="noopener">
                Watch on YouTube ↗
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.VideoReel = VideoReel;