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

// ============ HOOKS ============
function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && e.target.classList.add("in")),
      { threshold: 0.05, rootMargin: "0px 0px -8% 0px" }
    );
    document.querySelectorAll(".reveal:not(.in)").forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

function useScroll() {
  const [y, setY] = useState(0);
  useEffect(() => {
    const on = () => setY(window.scrollY);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  return y;
}

function useRoute() {
  const [route, setRoute] = useState(() => window.location.hash.replace("#/", "") || "home");
  useEffect(() => {
    const on = () => {
      setRoute(window.location.hash.replace("#/", "") || "home");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return [route, (r) => (window.location.hash = "#/" + r)];
}

function getPackRoute(pack) {
  return `#/packs/${pack.slug || pack.id}`;
}

// ============ SMALL COMPONENTS ============
function SplitHeading({ text, className = "", italics = [] }) {
  // italics is array of word indices to italicize
  const words = text.split(" ");
  return (
    <span className={className}>
      {words.map((w, i) => (
        <span key={i} className={italics.includes(i) ? "it" : ""} style={{ display: "inline-block", marginRight: "0.24em" }}>
          {w}
        </span>
      ))}
    </span>
  );
}

function Arrow({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>
  );
}

function ArrowDown({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 5v14M6 13l6 6 6-6" />
    </svg>
  );
}

function IconX({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 6L6 18M6 6l12 12" />
    </svg>
  );
}
function IconMenu({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 7h16M4 12h16M4 17h16" />
    </svg>
  );
}

function CheckoutNotice({ open, onClose }) {
  const checkout = window.SITE.links.checkout || window.SITE.links.whop;
  if (!open) return null;
  return (
    <div className="checkout-notice" role="dialog" aria-modal="true" aria-labelledby="checkout-notice-title" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="checkout-panel">
        <button className="checkout-close" type="button" onClick={onClose} aria-label="Close checkout note">
          <IconX />
        </button>
        <span className="eyebrow">Before Razorpay</span>
        <h3 id="checkout-notice-title">Complete checkout and wait for redirect.</h3>
        <p>After payment, the matching pack redirects to Google Drive automatically within a few seconds.</p>
        <div className="checkout-actions">
          <button type="button" className="btn secondary" onClick={onClose}>Cancel</button>
          <a href={checkout} target="_blank" rel="noreferrer" data-direct-checkout="true" className="btn primary" onClick={onClose}>
            Open Razorpay <Arrow />
          </a>
        </div>
      </div>
    </div>
  );
}

// ============ NAV ============
function ThemeToggle({ theme, onToggle }) {
  const isLight = theme === "light";
  return (
    <button
      type="button"
      className="theme-toggle"
      onClick={onToggle}
      aria-label={`Switch to ${isLight ? "dark" : "light"} theme`}
      aria-pressed={isLight}
    >
      <span className="theme-toggle-dot" />
      <span>{isLight ? "Dark" : "Light"}</span>
    </button>
  );
}

function Nav({ route, go, theme = "dark", onThemeToggle = () => {} }) {
  const y = useScroll();
  const [open, setOpen] = useState(false);
  const items = [
    { k: "packs", l: "Packs" },
    { k: "portfolio", l: "Portfolio" },
    { k: "about", l: "About" },
    { k: "contact", l: "Contact" },
  ];
  return (
    <>
      <header className={`nav ${y > 20 ? "scrolled" : ""}`}>
        <div className="shell row">
          <a href="#/home" className="brand" onClick={() => setOpen(false)}>
            <span>Koshur&nbsp;</span>
            <span className="mark">Fpv</span>
          </a>
          <nav>
            <ul>
              {items.map((it) => (
                <li key={it.k}>
                  <a href={`#/${it.k}`} className={it.k === "packs" ? (route === "packs" || route.startsWith("packs/") ? "active" : "") : route === it.k ? "active" : ""}>
                    {it.l}
                  </a>
                </li>
              ))}
            </ul>
          </nav>
          <div className="cta-wrap">
            <ThemeToggle theme={theme} onToggle={onThemeToggle} />
            <a href="#/packs" className="btn primary cta">
              View Samples <Arrow />
            </a>
          </div>
          <button className="burger" onClick={() => setOpen(true)} aria-label="Menu">
            <IconMenu />
          </button>
        </div>
      </header>
      <div className={`mnav-overlay ${open ? "open" : ""}`}>
        <div className="top">
          <span className="brand" style={{ fontFamily: "var(--ff-display)", fontSize: 24 }}>
            Koshur <span style={{ color: "var(--accent)", fontStyle: "italic" }}>Fpv</span>
          </span>
          <button onClick={() => setOpen(false)} style={{ width: 42, height: 42, border: "1px solid var(--border)", borderRadius: 999 }}>
            <IconX />
          </button>
        </div>
        <nav>
          {[{ k: "home", l: "Home" }, ...items].map((it) => (
            <a key={it.k} href={`#/${it.k}`} onClick={() => setOpen(false)}>
              {it.l}
            </a>
          ))}
        </nav>
        <a href="#/packs" className="btn primary cta" style={{ marginTop: 30 }}>
          View Samples <Arrow />
        </a>
        <ThemeToggle theme={theme} onToggle={onThemeToggle} />
      </div>
    </>
  );
}

// ============ HERO ============
function Hero() {
  const [idx, setIdx] = useState(0);
  const [lifted, setLifted] = useState(false);
  const [mediaMode, setMediaMode] = useState(() => window.innerWidth >= 1024 ? "landscape" : "vertical");
  const videoRefs = useRef([]);
  const y = useScroll();
  const videos = window.SITE.heroVideos.slice(0, 1);

  useEffect(() => {
    setIdx(0);
  }, [mediaMode]);

  useEffect(() => {
    const t = setTimeout(() => setLifted(true), 1000);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    let timeoutId;
    const syncMediaMode = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        setMediaMode(window.innerWidth >= 1024 ? "landscape" : "vertical");
      }, 200);
    };

    syncMediaMode();
    window.addEventListener("resize", syncMediaMode);

    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener("resize", syncMediaMode);
    };
  }, []);

  useEffect(() => {
    const playHeroVideos = () => {
      videoRefs.current.forEach((video) => {
        if (!video) return;
        video.muted = true;
        video.defaultMuted = true;
        video.controls = false;
        video.playsInline = true;
        video.setAttribute("muted", "");
        video.setAttribute("playsinline", "");
        video.setAttribute("webkit-playsinline", "");
        video.setAttribute("x5-playsinline", "");
        video.setAttribute("x5-video-player-type", "h5");
        video.setAttribute("controlslist", "nodownload nofullscreen noremoteplayback");
        video.play?.().catch(() => {});
      });
    };

    playHeroVideos();
    window.addEventListener("touchstart", playHeroVideos, { passive: true, once: true });
    window.addEventListener("pointerdown", playHeroVideos, { passive: true, once: true });

    return () => {
      window.removeEventListener("touchstart", playHeroVideos);
      window.removeEventListener("pointerdown", playHeroVideos);
    };
  }, [videos.length, mediaMode]);

  const baseScale = mediaMode === "landscape" ? 1.16 : 1;
  const scale = baseScale + (mediaMode === "landscape" ? Math.min(y / 2600, 0.06) : 0);
  const fade = Math.max(0, 1 - y / 700);

  const wrapWords = (text, delayStart = 0) =>
    text.split(" ").map((w, i) => (
      <span className="word" key={i}>
        <span style={{ animationDelay: `${delayStart + i * 0.08}s` }}>{w}</span>
      </span>
    ));

  return (
    <section className="hero" id="home">
      <div className="video-wrap" style={{ transform: `scale(${scale})` }}>
        {videos.map((v, i) => {
          const isLandscape = mediaMode === "landscape";
          const src = isLandscape ? v.landscapeSrc || v.src : v.verticalSrc || v.src;
          const poster = isLandscape ? v.landscapePoster || v.poster : v.verticalPoster || v.poster;

          return (
            <video
              ref={(el) => { videoRefs.current[i] = el; }}
              key={`${mediaMode}-${v.label || i}`}
              src={src}
              poster={poster}
              muted
              loop
              playsInline
              webkit-playsinline="true"
              x5-playsinline="true"
              x5-video-player-type="h5"
              x-webkit-airplay="deny"
              autoPlay
              preload="auto"
              controls={false}
              controlsList="nodownload nofullscreen noremoteplayback"
              disablePictureInPicture
              disableRemotePlayback
              tabIndex={-1}
              aria-hidden="true"
              style={{ opacity: i === idx ? 1 : 0, transition: "opacity 1.6s cubic-bezier(0.22,1,0.36,1)" }}
            />
          );
        })}
      </div>
      <div className={`scrim ${lifted ? "lifted" : ""}`} />

      <div className="hero-index">
        {videos.map((_, i) => (
          <div key={i} className={`ib ${i === idx ? "on" : ""}`} />
        ))}
      </div>

      <div className="content shell centered" style={{ opacity: fade }}>
        <div className="eyebrow-row">
          <span className="dot" />
          <span className="eyebrow">DGCA-Certified · Shot Across Kashmir · Works Globally</span>
        </div>
        <h1>
          {wrapWords("Kashmir's", 0.3)}
          <span className="it">{wrapWords("Premium Stock", 0.45)}</span>
          <br />
          <span className="it">{wrapWords("Footages", 0.7)}</span>
        </h1>
        <p className="hero-sub">
          Premium stock footage and pictures from around the globe.
        </p>
        <div className="ctas">
          <a href="#/packs" className="btn primary">
            Check Out Packs <Arrow />
          </a>
          <a href="#/portfolio" className="btn secondary">View Portfolio</a>
        </div>
      </div>
    </section>
  );
}

// ============ PROOF MARQUEE ============
function ProofMarquee() {
  const brands = window.SITE.proofBrands;
  const items = [...brands, ...brands, ...brands, ...brands];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {items.map((b, i) => (
          <span className="marquee-item" key={i}>
            {b}
          </span>
        ))}
      </div>
    </div>
  );
}

// ============ PACK CARD ============
function PackCard({ pack, feature = false }) {
  const videoRef = useRef(null);
  const useOriginalAudio = Boolean(pack.useOriginalAudio);
  const checkoutUrl = pack.checkoutUrl || window.SITE.links.checkout || window.SITE.links.whop;
  const contactUrl = `mailto:${window.SITE.links.email}?subject=${encodeURIComponent(pack.name + " inquiry")}`;
  const detailUrl = getPackRoute(pack);
  const isComingSoon = Boolean(pack.comingSoon);
  const isContactOnly = Boolean(pack.contactOnly);
  const isPreviewLocked = Boolean(pack.previewLocked);
  const trackingId = pack.slug || pack.id;
  return (
    <article
      className={`pack ${feature ? "feature" : ""}`}
      onMouseEnter={() => videoRef.current?.play()}
      onMouseLeave={() => { if (videoRef.current) videoRef.current.currentTime = 0; }}
    >
      <div className="media">
        <video
          ref={videoRef}
          src={pack.video}
          poster={pack.poster}
          muted={!useOriginalAudio}
          loop
          playsInline
          autoPlay={!useOriginalAudio}
          controls={useOriginalAudio && !isPreviewLocked}
          controlsList={isPreviewLocked ? "nodownload noplaybackrate noremoteplayback" : undefined}
          disablePictureInPicture={isPreviewLocked}
          disableRemotePlayback={isPreviewLocked}
          draggable={isPreviewLocked ? false : undefined}
          onContextMenu={isPreviewLocked ? (event) => event.preventDefault() : undefined}
          preload="metadata"
        />
        <span className="cat">{pack.category}</span>
        <span className="price">{pack.price}</span>
      </div>
      <div className="body">
        <h3><a href={detailUrl}>{pack.name}</a></h3>
        <p>{pack.description}</p>
        <ul className="bullets">
          {pack.bullets.map((b) => <li key={b}>{b}</li>)}
        </ul>
        <div className="buy-row">
          <div className="buy-meta">
            <span className="live-dot">{isComingSoon ? "Coming soon" : isContactOnly ? "Contact via Gmail" : "Checkout via Razorpay"}</span>
            <a href={detailUrl} className="detail-link">View details</a>
          </div>
          {isComingSoon ? (
            <button type="button" className="btn primary" disabled aria-disabled="true">
              Coming Soon
            </button>
          ) : isContactOnly ? (
            <a href={contactUrl} className="btn primary">
              Contact <Arrow />
            </a>
          ) : (
            <a
              href={checkoutUrl}
              target="_blank"
              rel="noreferrer"
              className="btn primary"
              data-content-id={trackingId}
              data-content-name={pack.name}
              data-value={pack.amount || 999}
              data-currency="INR"
            >
              Buy <Arrow />
            </a>
          )}
        </div>
      </div>
    </article>
  );
}

// ============ STICKY BUY BAR ============
function StickyBar() {
  const y = useScroll();
  const show = y > 700;
  return (
    <div className={`stickybar ${show ? "show" : ""}`}>
      <div className="left">
        <span className="sb-dot" />
        <div className="sb-text">
          <small>Kashmir premium stock packs</small>
          <span><em>Razorpay checkout</em> — automatic Google Drive redirect</span>
        </div>
      </div>
      <a href="#/packs" className="btn primary">
        View Samples <Arrow />
      </a>
    </div>
  );
}

// ============ SECTION HEAD ============
function SectionHead({ eyebrow, title, copy, action }) {
  return (
    <div className="section-head reveal">
      <div>
        <span className="eyebrow">{eyebrow}</span>
        <h2>{title}</h2>
      </div>
      <div>
        {copy && <p>{copy}</p>}
        {action && <div style={{ marginTop: 20 }}>{action}</div>}
      </div>
    </div>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer className="footer">
      <div className="shell">
        <div className="reveal">
          <div className="eyebrow" style={{ marginBottom: 24 }}>Licence · Book · Shoot</div>
          <h2 className="big">
            Kashmir, <em>flown</em>.<br />On your deadline.
          </h2>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 60 }}>
            <a href="#/packs" className="btn primary">Check Out Packs <Arrow /></a>
            <a href="#/contact" className="btn secondary">Book a Shoot</a>
          </div>
        </div>
        <div className="cols">
          <div>
            <div className="brand" style={{ fontFamily: "var(--ff-display)", fontSize: 28, marginBottom: 14 }}>
              Koshur <span style={{ color: "var(--accent)", fontStyle: "italic" }}>Fpv</span>
            </div>
            <p style={{ color: "var(--muted)", fontSize: 13, lineHeight: 1.7, maxWidth: 42 + "ch", margin: 0 }}>
              DGCA-certified Fpv pilot based in Srinagar. Cinematic Kashmir footage for brands, tourism, creators, and commercial campaigns.
            </p>
          </div>
          <div>
            <h5>Store</h5>
            <a href="#/packs">All Packs</a>
            <a href="#/packs">Sample Library</a>
            <a href="#/packs">Licensing</a>
          </div>
          <div>
            <h5>Studio</h5>
            <a href="#/portfolio">Portfolio</a>
            <a href="#/about">About Shoaib</a>
            <a href="#/contact">Book a shoot</a>
          </div>
          <div>
            <h5>Contact</h5>
            <a href={window.SITE.links.instagram} target="_blank" rel="noreferrer">Instagram</a>
            <a href={`mailto:${window.SITE.links.email}`}>Email</a>
            <a href={window.SITE.links.cal} target="_blank" rel="noreferrer">Cal.com</a>
          </div>
        </div>
        <div className="fine">
          <span>© 2026 Koshur Fpv · Srinagar, Kashmir</span>
          <span>Built for brands, creators and campaign teams.</span>
        </div>
      </div>
    </footer>
  );
}

// ============ TWEAKS PANEL ============
function TweaksPanel({ open, state, setState }) {
  return (
    <div className={`tweaks ${open ? "open" : ""}`}>
      <h5>Tweaks</h5>
      <div className="group">
        <span className="glabel">Direction</span>
        <div className="seg">
          <button className={state.dir === "editorial" ? "on" : ""} onClick={() => setState({ ...state, dir: "editorial" })}>Editorial</button>
          <button className={state.dir === "kinetic" ? "on" : ""} onClick={() => setState({ ...state, dir: "kinetic" })}>Kinetic</button>
        </div>
      </div>
      <div className="group">
        <span className="glabel">Density</span>
        <div className="seg">
          <button className={state.density === "airy" ? "on" : ""} onClick={() => setState({ ...state, density: "airy" })}>Airy</button>
          <button className={state.density === "tight" ? "on" : ""} onClick={() => setState({ ...state, density: "tight" })}>Tight</button>
        </div>
      </div>
      <div className="group">
        <span className="glabel">Accent</span>
        <div className="seg">
          <button className={state.accent === "ice" ? "on" : ""} onClick={() => setState({ ...state, accent: "ice" })}>Ice</button>
          <button className={state.accent === "warm" ? "on" : ""} onClick={() => setState({ ...state, accent: "warm" })}>Warm</button>
          <button className={state.accent === "mono" ? "on" : ""} onClick={() => setState({ ...state, accent: "mono" })}>Mono</button>
        </div>
      </div>
    </div>
  );
}

// ============ EXPORT ============
Object.assign(window, {
  useReveal, useScroll, useRoute, SplitHeading, Arrow, ArrowDown, IconX, IconMenu,
  Nav, Hero, ProofMarquee, PackCard, StickyBar, SectionHead, Footer, TweaksPanel
});
