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

function trackMetaPageView(route = "home") {
  if (typeof window.fbq !== "function") return;
  window.fbq("track", "PageView");
  window.fbq("trackCustom", "RouteView", { route });
}

function trackMetaInitiateCheckout(anchor) {
  if (typeof window.fbq !== "function") return;
  const contentId = anchor?.dataset?.contentId || "razorpay_checkout";
  const contentName = anchor?.dataset?.contentName || "Razorpay Checkout";
  const value = Number(anchor?.dataset?.value || 999);
  const currency = anchor?.dataset?.currency || "INR";
  window.fbq("track", "InitiateCheckout", {
    content_name: contentName,
    content_id: contentId,
    content_ids: [contentId],
    content_type: "product",
    value,
    currency,
  });
}

function trackMetaViewContent(pack) {
  if (typeof window.fbq !== "function" || !pack) return;
  const contentId = pack.slug || pack.id || "pack";
  const value = Number(pack.amount || String(pack.price || "").replace(/[^\d.]/g, "")) || 0;
  window.fbq("track", "ViewContent", {
    content_name: pack.name,
    content_id: contentId,
    content_ids: [contentId],
    content_type: "product",
    value,
    currency: "INR",
  });
}

function trackMetaContact(anchor) {
  if (typeof window.fbq !== "function" || !anchor) return;
  const href = anchor.getAttribute("href") || "";
  const channel = href.startsWith("mailto:")
    ? "email"
    : href.includes("instagram.com")
      ? "instagram"
      : href.includes("cal.com")
        ? "cal"
        : href.includes("#/contact")
          ? "contact_page"
          : "contact";
  window.fbq("trackCustom", "ContactClick", {
    channel,
    href,
    route: window.location.hash || "#/home",
  });
}

function trackMetaLead(source = "contact_form") {
  if (typeof window.fbq !== "function") return;
  window.fbq("track", "Lead", { source });
}

function analyticsSlug(value, fallback = "unknown") {
  return String(value || fallback)
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    || fallback;
}

function getAnalyticsPageTitle(route) {
  const cleanRoute = route || (window.location.hash.replace("#/", "") || "home");
  if (cleanRoute.startsWith("packs/")) {
    const pack = findPackBySlug(cleanRoute.slice("packs/".length));
    return pack?.name || cleanRoute;
  }
  const labels = {
    home: "Home",
    packs: "Packs",
    portfolio: "Portfolio",
    about: "About",
    contact: "Contact",
    dashboard: "Dashboard",
  };
  return labels[cleanRoute] || cleanRoute.replace(/\//g, " / ");
}

function getAnalyticsButtonSource(anchor) {
  if (anchor?.dataset?.buttonSource) return anchor.dataset.buttonSource;
  if (anchor?.closest?.(".checkout-panel")) return "checkout_notice";
  if (anchor?.closest?.(".product-cta-row")) return "product_page";
  if (anchor?.closest?.(".pack")) return "pack_card";
  if (anchor?.closest?.(".hero")) return "hero";
  if (anchor?.closest?.(".stickybar")) return "sticky_bar";
  if (anchor?.closest?.(".mnav-overlay")) return "mobile_nav";
  if (anchor?.closest?.(".nav")) return "navbar";
  if (anchor?.closest?.("footer")) return "footer";
  return "site";
}

function getAnalyticsDestinationType(hrefAttr, isPackCheckout, isGlobalCheckout) {
  if (isPackCheckout) return "razorpay_pack_checkout";
  if (isGlobalCheckout) return "global_checkout_notice";
  if (hrefAttr === "#/packs") return "packs_page";
  if (hrefAttr.startsWith("#/packs/")) return "pack_detail_page";
  if (hrefAttr.startsWith("mailto:")) return "email";
  if (hrefAttr.includes("instagram.com")) return "instagram";
  if (hrefAttr.includes("cal.com")) return "cal";
  return hrefAttr.startsWith("#/") ? "internal_page" : "external_link";
}

function getAnalyticsVisitorId() {
  try {
    const key = "koshur-analytics-visitor-id";
    let value = localStorage.getItem(key);
    if (!value) {
      value = `v${Math.random().toString(36).slice(2, 12)}${Date.now().toString(36).slice(-4)}`;
      localStorage.setItem(key, value);
    }
    return value;
  } catch {
    return `v${Math.random().toString(36).slice(2, 12)}`;
  }
}

function getAnalyticsSessionId() {
  try {
    const key = "koshur-analytics-session-id";
    let value = sessionStorage.getItem(key);
    if (!value) {
      value = `s${Math.random().toString(36).slice(2, 12)}${Date.now().toString(36).slice(-4)}`;
      sessionStorage.setItem(key, value);
    }
    return value;
  } catch {
    return `s${Math.random().toString(36).slice(2, 12)}`;
  }
}

function sendSiteAnalytics(type, payload = {}) {
  if (typeof window === "undefined") return;
  const currentRoute = payload.route || (window.location.hash.replace("#/", "") || "home");
  const currentPath = window.location.hash || "#/home";
  const body = {
    type,
    route: currentRoute,
    pageTitle: payload.pageTitle || getAnalyticsPageTitle(currentRoute),
    visitorId: getAnalyticsVisitorId(),
    sessionId: getAnalyticsSessionId(),
    referrer: document.referrer || "",
    viewportWidth: window.innerWidth,
    viewportHeight: window.innerHeight,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "",
    language: navigator.language || "",
    path: currentPath,
    ...payload,
  };

  const json = JSON.stringify(body);

  try {
    if (navigator.sendBeacon) {
      navigator.sendBeacon("/api/analytics-track", new Blob([json], { type: "application/json" }));
      return;
    }
  } catch {}

  fetch("/api/analytics-track", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: json,
    keepalive: true,
  }).catch(() => {});
}

function findPackBySlug(slug) {
  return (window.SITE?.packs || []).find((pack) => pack.slug === slug || pack.id === slug) || null;
}

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

function getPackDeliveryCopy(pack) {
  if (pack.comingSoon) return "This pack is not live yet. Use the contact links to ask for launch timing or early access.";
  if (pack.contactOnly) return `For this pack, contact ${window.SITE.links.email} to confirm delivery, pricing, and access.`;
  return "After Razorpay payment, the matching pack redirects automatically to Google Drive within a few seconds.";
}

function getPackLicenceCopy(pack) {
  if (pack.contactOnly) return "This is handled as a direct inquiry bundle. Usage, delivery scope, and commercial access are confirmed over email before handoff.";
  return "Commercial licence for brand, client, social, tourism, and campaign use. Raw file redistribution or resale as a competing pack is not allowed.";
}

// ============ PAGE: HOME ============
function HomePage() {
  const S = window.SITE;
  const packs = S.packs;
  return (
    <main>
      <Hero />
      <ProofMarquee />

      {/* PACKS PREVIEW */}
      <section className="section" id="packs-preview">
        <div className="shell">
          <SectionHead
            eyebrow="Samples"
            title={<>Kashmir Premium <em style={{ fontStyle: "italic", color: "var(--accent)" }}>Stock Samples</em></>}
            copy="Preview the motion style, pacing, and locations before you buy. Every live pack includes a commercial licence and opens its matching Google Drive bundle right after Razorpay payment."
            action={
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <a href="#/packs" className="btn ghost">View all samples <Arrow /></a>
                <a href="#/portfolio" className="btn ghost">View portfolio <Arrow /></a>
              </div>
            }
          />
          <div className="home-pack-grid">
            {packs.slice(0, 5).map((p, i) => (
              <div
                className={`home-pack-item ${i === 0 ? "home-pack-item-feature" : ""} reveal reveal-delay-${(i % 4) + 1}`}
                key={p.id}
              >
                <PackCard pack={p} feature={i === 0} />
              </div>
            ))}
          </div>
          <style>{`
            #packs-preview .home-pack-grid {
              display: grid;
              grid-template-columns: repeat(2, minmax(0, 1fr));
              gap: 20px;
              align-items: stretch;
            }

            #packs-preview .home-pack-item {
              display: flex;
              min-width: 0;
            }

            #packs-preview .home-pack-item > .pack {
              width: 100%;
            }

            #packs-preview .home-pack-item-feature {
              grid-column: 1 / -1;
            }

            @media (max-width: 900px) {
              #packs-preview .home-pack-grid {
                grid-template-columns: 1fr;
              }

              #packs-preview .home-pack-item-feature {
                grid-column: auto;
              }
            }
          `}</style>
        </div>
      </section>

      {/* PROCESS */}
      <section className="section ink">
        <div className="shell">
          <SectionHead
            eyebrow="Process"
            title={<>Three steps. <em style={{ fontStyle: "italic", color: "var(--accent)" }}>No back-and-forth.</em></>}
            copy="Footage packs are built for editors who don't have time to brief a shoot. Preview, purchase, and access the bundle immediately."
          />
          <div className="process-row reveal">
            {S.process.map((p) => (
              <div className="process-cell" key={p.n}>
                <div className="n">{p.n}</div>
                <h4>{p.t}</h4>
                <p>{p.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* STATS + TESTIMONIALS */}
      <section className="section">
        <div className="shell">
          <SectionHead
            eyebrow="Proof"
            title={<>Built for <em style={{ fontStyle: "italic", color: "var(--accent)" }}>campaign work</em>.</>}
            copy="Four years flying Kashmir. Delivered for national brands, tourism teams, and production units."
          />
          <div className="numstrip reveal" style={{ marginBottom: 48 }}>
            {S.stats.map((s) => (
              <div className="cell" key={s.label}>
                <div className="v">{s.value}</div>
                <div className="l">{s.label}</div>
              </div>
            ))}
          </div>
          <div className="grid g-3">
            {S.testimonials.map((t, i) => (
              <figure className={`tcard reveal reveal-delay-${i + 1}`} key={i}>
                <div className="quote-mark">"</div>
                <blockquote>{t.quote}</blockquote>
                <figcaption>
                  <b>{t.role}</b>
                  {t.company}
                </figcaption>
              </figure>
            ))}
          </div>
          <InstagramReelEmbeds />
        </div>
      </section>

      {/* ABOUT TEASER */}
      <section className="section ink" id="about">
        <div className="shell">
          <div className="grid" style={{ gridTemplateColumns: "0.9fr 1.1fr", gap: 80, alignItems: "center" }}>
            <div className="reveal" style={{ position: "relative" }}>
              <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--surface)" }}>
                <img src="assets/images/shoaib-fpv-large.jpg" alt="Shoaib Saleem" style={{ aspectRatio: "4/5", width: "100%", objectFit: "cover" }} />
              </div>
              <div style={{ position: "absolute", left: 20, bottom: 20, background: "rgba(10,10,10,0.85)", backdropFilter: "blur(12px)", border: "1px solid var(--border)", borderRadius: 10, padding: "14px 18px" }}>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 30, lineHeight: 1 }}>DGCA</div>
                <div style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>Certified pilot</div>
              </div>
            </div>
            <div className="reveal reveal-delay-1">
              <span className="eyebrow">About Shoaib</span>
              <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(44px, 6vw, 88px)", lineHeight: 0.94, letterSpacing: "-0.025em", margin: "14px 0 0" }}>
                Kashmir Fpv, flown by someone <em style={{ fontStyle: "italic", color: "var(--accent)" }}>who knows the terrain</em>.
              </h2>
              <div style={{ marginTop: 32, display: "grid", gap: 18, color: "var(--muted)", fontSize: 16, lineHeight: 1.75 }}>
                <p>Shoaib Saleem is a Srinagar-based Fpv drone pilot, editor, and creator behind Koshur Fpv. Four years flying Kashmir's valleys, mountain roads, lakes, gardens, and commercial locations for brands and content teams.</p>
                <p>The store turns that field experience into digital footage packs editors can license quickly. Custom shoots remain available for campaigns that need planned routes, location-specific coverage, and on-ground production support.</p>
              </div>
              <div style={{ display: "flex", gap: 12, marginTop: 32 }}>
                <a href="#/about" className="btn secondary">Read the full story <Arrow /></a>
                <a href="#/contact" className="btn ghost">Book a shoot</a>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* LOCATIONS */}
      <section className="section">
        <div className="shell">
          <SectionHead
            eyebrow="Locations"
            title={<>Where we <em style={{ fontStyle: "italic", color: "var(--accent)" }}>fly</em>.</>}
            copy="Every pack is built from locations we've filmed personally. Scouted, permitted, and routed."
          />
          <div className="loc-list reveal">
            {S.locations.map((l, i) => (
              <div className="loc-row" key={l.n}>
                <span className="idx">{String(i + 1).padStart(2, "0")}</span>
                <h4>{l.n}</h4>
                <span className="sub">{l.sub}</span>
                <span className="arr"><Arrow size={20} /></span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section ink" id="faq">
        <div className="shell" style={{ maxWidth: 1000 }}>
          <SectionHead
            eyebrow="FAQ"
            title={<>Everything <em style={{ fontStyle: "italic", color: "var(--accent)" }}>before you buy</em>.</>}
            copy="Licensing, delivery, file use, custom shoot bookings, and digital product policy in plain language."
          />
          <div className="faq reveal">
            {S.faqs.map((f, i) => (
              <details className="faq-item" key={i}>
                <summary>
                  <span>{f.q}</span>
                  <span className="plus" />
                </summary>
                <div className="a">{f.a}</div>
              </details>
            ))}
          </div>
        </div>
      </section>

      {/* CONTACT TEASE */}
      <section className="section" id="contact-teaser">
        <div className="shell">
          <div className="grid" style={{ gridTemplateColumns: "0.9fr 1.1fr", gap: 60, alignItems: "end" }}>
            <div className="reveal">
              <span className="eyebrow">Reach out</span>
              <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(44px, 6vw, 80px)", lineHeight: 0.95, letterSpacing: "-0.025em", margin: "14px 0 0" }}>
                Buy the pack today. Book the shoot <em style={{ fontStyle: "italic", color: "var(--accent)" }}>when the campaign needs its own flight path</em>.
              </h2>
            </div>
            <div className="reveal reveal-delay-1">
              <p style={{ color: "var(--muted)", fontSize: 16, lineHeight: 1.75, marginBottom: 28 }}>
                DM for custom Fpv shoots, tourism campaigns, hotel and resort visuals, brand collaborations, or a footage pack question before purchase.
              </p>
              <ContactBlock />
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function InstagramReelEmbeds() {
  const reels = ["DWWRIajiekV", "DXMjt7YEVo1"];

  return (
    <div className="reveal" style={{ marginTop: 48 }}>
      <span className="eyebrow">Social proof</span>
      <div className="grid g-2" style={{ marginTop: 20, alignItems: "start" }}>
        {reels.map((id) => (
          <div
            key={id}
            style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", overflow: "hidden", height: 620 }}
          >
            <iframe
              title={`Instagram reel ${id}`}
              src={`https://www.instagram.com/reel/${id}/embed`}
              allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
              loading="lazy"
              style={{ border: 0, width: "100%", height: 700, display: "block", background: "var(--bg)", transform: "translateY(-58px)" }}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ PAGE: PACKS ============
function PacksPage() {
  const S = window.SITE;
  const cats = ["All", ...Array.from(new Set(S.packs.map((p) => p.category)))];
  const [f, setF] = useState("All");
  const list = useMemo(() => f === "All" ? S.packs : S.packs.filter((p) => p.category === f), [f]);
  return (
    <main style={{ paddingTop: 120 }}>
      <section className="section tight">
        <div className="shell">
          <div className="reveal" style={{ marginBottom: 48 }}>
            <span className="eyebrow">The Library</span>
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(56px, 8vw, 140px)", lineHeight: 0.92, letterSpacing: "-0.035em", margin: "16px 0 0" }}>
              Kashmir Fpv <em style={{ fontStyle: "italic", color: "var(--accent)" }}>Sample Library</em>
            </h1>
            <p style={{ color: "var(--muted)", fontSize: 17, lineHeight: 1.7, marginTop: 28, maxWidth: "56ch" }}>
              A clean preview library for motion style, locations, pacing, and campaign fit. Open any product page for the full sample, pricing, delivery, and licensing details.
            </p>
          </div>
          <div className="chips reveal">
            {cats.map((c) => (
              <button key={c} className={`chip ${f === c ? "on" : ""}`} onClick={() => setF(c)}>{c}</button>
            ))}
          </div>
          <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
            {list.map((p, i) => (
              <div className={`reveal reveal-delay-${(i % 4) + 1}`} key={p.id}>
                <PackCard pack={p} />
              </div>
            ))}
          </div>
        </div>
        <style>{`
          @media (max-width: 1100px) { main .grid { grid-template-columns: repeat(2, 1fr) !important; } }
          @media (max-width: 720px) { main .grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>
    </main>
  );
}

function BundleSamples({ pack }) {
  const samples = pack.sampleVideos || [];
  if (!samples.length) return null;

  return (
    <div className="bundle-samples reveal">
      <div className="bundle-samples-head">
        <div>
          <span className="eyebrow muted">Protected samples</span>
          <h3>Preview the bundle clips</h3>
        </div>
        <p>Short watermarked previews only. The full four-pack bundle unlocks through Google Drive after Razorpay checkout.</p>
      </div>
      <div className="bundle-sample-grid">
        {samples.slice(0, 3).map((sample) => (
          <article key={sample.id} className="bundle-sample-card">
            <div className="bundle-sample-frame">
              <video
                src={sample.src}
                poster={sample.poster}
                muted
                loop
                playsInline
                autoPlay
                preload="metadata"
                controls={false}
                controlsList="nodownload noplaybackrate noremoteplayback"
                disablePictureInPicture
                disableRemotePlayback
                draggable={false}
                onContextMenu={(event) => event.preventDefault()}
              />
              <span className="sample-watermark">Koshur Fpv Preview</span>
            </div>
            <strong>{sample.title}</strong>
          </article>
        ))}
      </div>
      {pack.includedPacks?.length ? (
        <div className="bundle-included">
          {pack.includedPacks.map((item) => <span key={item}>{item}</span>)}
        </div>
      ) : null}
    </div>
  );
}

function PackDetailPage({ slug }) {
  const S = window.SITE;
  const pack = findPackBySlug(slug);

  useEffect(() => {
    if (pack) {
      trackMetaViewContent(pack);
      sendSiteAnalytics("pack_view", {
        packId: pack.slug || pack.id,
        packName: pack.name,
      });
    }
  }, [pack?.id]);

  if (!pack) {
    return (
      <main style={{ paddingTop: 120 }}>
        <section className="section tight">
          <div className="shell">
            <div className="product-empty reveal in">
              <span className="eyebrow">Pack not found</span>
              <h1>That product page is not available.</h1>
              <p>The pack may have moved, or the link may be outdated. Head back to the library to browse the live catalogue.</p>
              <a href="#/packs" className="btn primary">
                Back to Packs <Arrow />
              </a>
            </div>
          </div>
        </section>
      </main>
    );
  }

  const useOriginalAudio = Boolean(pack.useOriginalAudio);
  const isComingSoon = Boolean(pack.comingSoon);
  const isContactOnly = Boolean(pack.contactOnly);
  const isPreviewLocked = Boolean(pack.previewLocked);
  const trackingId = pack.slug || pack.id;
  const detailFacts = [
    { label: "Price", value: pack.price, note: isComingSoon ? "Launch timing to be announced" : isContactOnly ? "Custom access handled by email" : "One-time pack access" },
    { label: "Format", value: pack.format || "MP4 footage", note: "Built for edits, reels, and campaign cuts" },
    { label: "Delivery", value: pack.delivery || (isComingSoon ? "Coming soon" : isContactOnly ? "Contact us" : "Auto Google Drive redirect"), note: isComingSoon ? "Ask for early access by email" : isContactOnly ? "Confirmed directly with Koshur Fpv" : "Opens the matching Drive pack after payment" },
    { label: "Usage", value: isContactOnly ? "Direct inquiry" : "Commercial licence", note: "Use in your own brand, client, and social projects" },
  ];
  const bestFor = pack.bestFor?.length ? pack.bestFor : pack.bullets.slice(0, 3);
  const related = S.packs.filter((item) => item.id !== pack.id).slice(0, 3);
  const contactUrl = `mailto:${S.links.email}?subject=${encodeURIComponent(pack.name + " inquiry")}`;

  return (
    <main style={{ paddingTop: 120 }}>
      <section className="section tight product-page">
        <div className="shell">
          <a href="#/packs" className="product-back reveal">All packs</a>
          <div className="product-hero">
            <div className="product-media reveal">
              <div className={`product-video-frame ${isPreviewLocked ? "bundle-product-video-frame" : ""}`}>
                <video
                  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="product-chip">{pack.category}</span>
                <span className="product-price">{pack.price}</span>
                {pack.saleLabel ? <span className="product-sale-pill">{pack.saleLabel}</span> : null}
                {isPreviewLocked ? <span className="sample-watermark product-watermark">Preview only</span> : null}
              </div>
              <div className="product-facts">
                {detailFacts.map((fact) => (
                  <div key={fact.label} className="product-fact">
                    <span>{fact.label}</span>
                    <strong>{fact.value}</strong>
                    <small>{fact.note}</small>
                  </div>
                ))}
              </div>
            </div>

            <div className="product-copy reveal reveal-delay-1">
              <span className="eyebrow">Individual product page</span>
              <h1>{pack.name}</h1>
              <p className="product-lead">{pack.description}</p>
              <div className="product-cta-row">
                {isComingSoon ? (
                  <button type="button" className="btn primary" disabled aria-disabled="true">
                    Coming Soon
                  </button>
                ) : isContactOnly ? (
                  <a href={contactUrl} className="btn primary">
                    Contact Us <Arrow />
                  </a>
                ) : (
                  <a
                    href={pack.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 Now <Arrow />
                  </a>
                )}
                <a href="#/portfolio" className="btn secondary">Past Works</a>
              </div>
              <p className="product-note">{getPackDeliveryCopy(pack)}</p>
              <div className="product-side-card">
                <span className="eyebrow muted">Pack fit</span>
                <div className="product-side-pills">
                  {bestFor.slice(0, 3).map((item) => <span key={item}>{item}</span>)}
                </div>
                <p>
                  Preview the sample, check the usage notes, then use the footage in polished social edits, campaign films, travel reels, and client work.
                </p>
              </div>
            </div>
          </div>

          <div className="product-grid">
            <div className="product-panel reveal">
              <span className="eyebrow muted">What’s inside</span>
              <h3>Core pack highlights</h3>
              <ul className="product-list">
                {pack.bullets.map((item) => <li key={item}>{item}</li>)}
              </ul>
            </div>
            <div className="product-panel reveal reveal-delay-1">
              <span className="eyebrow muted">Best fit</span>
              <h3>Where this pack works</h3>
              <ul className="product-list">
                {bestFor.map((item) => <li key={item}>{item}</li>)}
              </ul>
            </div>
            <div className="product-panel reveal reveal-delay-2">
              <span className="eyebrow muted">Delivery</span>
              <h3>What happens after payment</h3>
              <p>{getPackDeliveryCopy(pack)}</p>
            </div>
            <div className="product-panel reveal reveal-delay-3">
              <span className="eyebrow muted">Licence</span>
              <h3>Usage and access</h3>
              <p>{getPackLicenceCopy(pack)}</p>
            </div>
          </div>

          <BundleSamples pack={pack} />
        </div>
      </section>

      <div className="mobile-product-buy" aria-label="Mobile quick purchase">
        <div>
          <span>{pack.price}</span>
          <strong>{isComingSoon ? "Coming soon" : isContactOnly ? "Contact for access" : "Ready to checkout"}</strong>
        </div>
        {isComingSoon ? (
          <button type="button" className="btn primary" disabled aria-disabled="true">
            Coming Soon
          </button>
        ) : isContactOnly ? (
          <a href={contactUrl} className="btn primary" data-button-source="mobile_product_bar">
            Contact <Arrow />
          </a>
        ) : (
          <a
            href={pack.checkoutUrl}
            target="_blank"
            rel="noreferrer"
            className="btn primary"
            data-button-source="mobile_product_bar"
            data-content-id={trackingId}
            data-content-name={pack.name}
            data-value={pack.amount || 999}
            data-currency="INR"
          >
            Buy Now <Arrow />
          </a>
        )}
      </div>

      <section className="section ink">
        <div className="shell">
          <SectionHead
            eyebrow="More from the library"
            title={<>Browse more <em style={{ fontStyle: "italic", color: "var(--accent)" }}>sample packs</em>.</>}
            copy="The live catalogue stays focused on the current products. Packs outside the active list remain marked as coming soon or contact-only."
            action={<a href="#/packs" className="btn ghost">View all packs <Arrow /></a>}
          />
          <div className="grid g-3">
            {related.map((item, index) => (
              <div key={item.id} className={`reveal reveal-delay-${(index % 3) + 1}`}>
                <PackCard pack={item} />
              </div>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

// ============ PAGE: PORTFOLIO ============
function PortfolioPage() {
  const S = window.SITE;
  const allItems = useMemo(() => [...(S.portfolioItems || []), ...(S.drivePortfolioItems || [])], [S]);
  const cats = useMemo(() => ["All", ...Array.from(new Set(allItems.map((item) => item.category)))], [allItems]);
  const [f, setF] = useState("All");
  const [sel, setSel] = useState(null);
  const list = useMemo(() => f === "All" ? allItems : allItems.filter((i) => i.category === f), [f, allItems]);
  return (
    <main style={{ paddingTop: 120 }}>
      <section className="section tight">
        <div className="shell">
          <div className="reveal" style={{ marginBottom: 48 }}>
            <span className="eyebrow">Portfolio</span>
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(56px, 8vw, 140px)", lineHeight: 0.92, letterSpacing: "-0.035em", margin: "16px 0 0" }}>
              Past works and <em style={{ fontStyle: "italic", color: "var(--accent)" }}>sample flights</em>
            </h1>
            <p style={{ color: "var(--muted)", fontSize: 17, lineHeight: 1.7, marginTop: 28, maxWidth: "56ch" }}>
              A cinematic media grid structured for tourism, commercial, roads, landscapes, hotels, and campaign work.
            </p>
          </div>
          <div className="grid reveal reveal-delay-1" style={{ gridTemplateColumns: "0.9fr 1.1fr", gap: 18, alignItems: "stretch", marginBottom: 34 }}>
            <div className="crow">
              <span className="k">Portfolio contact</span>
              <span className="v">Shoaib Saleem</span>
              <p style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.7, margin: 0 }}>
                Srinagar-based Fpv pilot, editor, and creator behind Koshur Fpv. For custom shoots, campaign work, or portfolio references, reach out directly.
              </p>
            </div>
            <div className="cblock">
              <a className="crow" href={S.links.instagram} target="_blank" rel="noreferrer">
                <span className="k">Instagram</span>
                <span className="v">@koshurfpv</span>
              </a>
              <a className="crow" href={`mailto:${S.links.email}`}>
                <span className="k">Email</span>
                <span className="v">{S.links.email}</span>
              </a>
            </div>
          </div>
          <div className="chips reveal">
            {cats.map((c) => (
              <button key={c} className={`chip ${f === c ? "on" : ""}`} onClick={() => setF(c)}>{c}</button>
            ))}
          </div>
          <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
            {list.map((it, i) => (
              <div className={`mtile reveal reveal-delay-${(i % 4) + 1}`} key={it.id} onClick={() => setSel(it)}>
                <video src={it.video} poster={it.poster} muted loop playsInline autoPlay preload="metadata" />
                <div className="tint" />
                <div className="info">
                  <span className="cat">{it.category} · {it.year}</span>
                  <h4>{it.title}</h4>
                  <div className="meta">
                    <span>{it.location}</span>
                    <span>·</span>
                    <span>{it.format}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <style>{`
          @media (max-width: 1100px) { main .grid { grid-template-columns: repeat(2, 1fr) !important; } }
          @media (max-width: 720px) { main .grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>

      <div className={`lightbox ${sel ? "open" : ""}`} onClick={() => setSel(null)}>
        <button className="close" onClick={() => setSel(null)}><IconX /></button>
        {sel && (
          <div className="box" onClick={(e) => e.stopPropagation()}>
            <video src={sel.video} poster={sel.poster} controls autoPlay playsInline />
          </div>
        )}
      </div>
    </main>
  );
}

// ============ PAGE: ABOUT ============
function AboutPage() {
  const S = window.SITE;
  return (
    <main style={{ paddingTop: 120 }}>
      <section className="section tight">
        <div className="shell">
          <div className="grid reveal" style={{ gridTemplateColumns: "0.95fr 1.05fr", gap: 72, alignItems: "center" }}>
            <div>
              <img src="assets/images/shoaib-fpv-large.jpg" alt="Shoaib Saleem" style={{ aspectRatio: "4/5", width: "100%", objectFit: "cover", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)" }} />
            </div>
            <div>
              <span className="eyebrow">Shoaib Saleem</span>
              <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(52px, 7vw, 112px)", lineHeight: 0.92, letterSpacing: "-0.035em", margin: "14px 0 0" }}>
                The pilot <em style={{ fontStyle: "italic", color: "var(--accent)" }}>behind</em> Koshur Fpv.
              </h1>
              <div style={{ marginTop: 32, display: "grid", gap: 18, color: "var(--muted)", fontSize: 16, lineHeight: 1.75 }}>
                <p>Koshur Fpv is run by Shoaib Saleem, a DGCA-certified Fpv pilot based in Srinagar. The brand sits at the meeting point of local access, cinematic movement, and fast commercial delivery.</p>
                <p>The work spans digital footage packs for editors and custom Fpv shoots for brands, hotels, tourism teams, creators, and production houses working across Kashmir.</p>
              </div>
              <div className="numstrip" style={{ marginTop: 40 }}>
                {S.stats.map((s) => (
                  <div className="cell" key={s.label}>
                    <div className="v">{s.value}</div>
                    <div className="l">{s.label}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="section ink">
        <div className="shell">
          <SectionHead
            eyebrow="Collaborations"
            title={<>Brand-ready <em style={{ fontStyle: "italic", color: "var(--accent)" }}>from day one</em>.</>}
            copy="The site is built around proof, product clarity, and direct conversion for buyers who need footage quickly."
          />
          <div className="grid g-4 reveal">
            {S.proofBrands.map((b) => (
              <div key={b} style={{ border: "1px solid var(--border)", background: "var(--bg)", padding: 32, textAlign: "center", borderRadius: "var(--radius-lg)", fontFamily: "var(--ff-display)", fontSize: 30, letterSpacing: "-0.02em", color: "var(--fg-dim)" }}>
                {b}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="shell">
          <SectionHead
            eyebrow="Team"
            title={<>Lean <em style={{ fontStyle: "italic", color: "var(--accent)" }}>production crew</em>.</>}
            copy="A compact support team around Fpv, cinematography, client handling, and content."
          />
          <div className="grid g-3">
            {S.team.map((m, i) => (
              <div key={m.name} className={`tmem reveal reveal-delay-${(i % 3) + 1}`}>
                <div className="av">{m.initials}</div>
                <h4>{m.name}</h4>
                <div className="role">{m.role}</div>
                <div className="exp">{m.experience}</div>
              </div>
            ))}
          </div>
          <div className="reveal" style={{ marginTop: 56 }}>
            <ContactBlock />
          </div>
        </div>
      </section>
    </main>
  );
}

// ============ CONTACT BLOCK ============
function ContactBlock() {
  return (
    <div className="cblock">
      <a className="crow" href={window.SITE.links.instagram} target="_blank" rel="noreferrer">
        <span className="k">Instagram</span>
        <span className="v">@koshurfpv</span>
      </a>
      <a className="crow" href={`mailto:${window.SITE.links.email}`}>
        <span className="k">Email</span>
        <span className="v">{window.SITE.links.email}</span>
      </a>
      <a className="crow" href={window.SITE.links.cal} target="_blank" rel="noreferrer">
        <span className="k">Cal.com</span>
        <span className="v">Book a call</span>
      </a>
      <a className="crow" href="#/packs">
        <span className="k">Store</span>
        <span className="v">All packs</span>
      </a>
    </div>
  );
}

// ============ PAGE: CONTACT ============
function ContactPage() {
  const [form, setForm] = useState({ name: "", email: "", brief: "" });
  const submit = (e) => {
    e.preventDefault();
    trackMetaLead("contact_form");
    sendSiteAnalytics("lead", { source: "contact_form" });
    const subject = encodeURIComponent(`Koshur Fpv inquiry from ${form.name || "website"}`);
    const body = encodeURIComponent(`Name: ${form.name}\nEmail: ${form.email}\n\nProject brief:\n${form.brief}`);
    window.location.href = `mailto:${window.SITE.links.email}?subject=${subject}&body=${body}`;
  };
  return (
    <main style={{ paddingTop: 120 }}>
      <section className="section tight">
        <div className="shell">
          <div className="grid" style={{ gridTemplateColumns: "0.9fr 1.1fr", gap: 72 }}>
            <div className="reveal">
              <span className="eyebrow">Contact</span>
              <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(52px, 7vw, 112px)", lineHeight: 0.92, letterSpacing: "-0.035em", margin: "14px 0 0" }}>
                For packs, <em style={{ fontStyle: "italic", color: "var(--accent)" }}>custom shoots</em>, and campaign briefs.
              </h1>
              <p style={{ color: "var(--muted)", fontSize: 17, lineHeight: 1.75, marginTop: 28, maxWidth: "52ch" }}>
                Fastest path: pick a live pack, complete Razorpay checkout, and access the matching Google Drive delivery automatically. For location-specific flights, hotel campaigns, tourism films, creator campaigns, or brand work, send a brief through DM, email, Cal.com, or the form.
              </p>
              <div style={{ marginTop: 36 }}>
                <ContactBlock />
              </div>
            </div>
            <form className="form reveal reveal-delay-1" onSubmit={submit}>
              <label>Name
                <input placeholder="Your name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </label>
              <label>Email
                <input type="email" placeholder="you@example.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </label>
              <label>Brief
                <textarea placeholder="Tell us what you need: footage pack question, shoot date, location, deliverables, budget range." value={form.brief} onChange={(e) => setForm({ ...form, brief: e.target.value })} />
              </label>
              <button type="submit" className="btn primary" style={{ justifySelf: "start" }}>
                Send Inquiry <Arrow />
              </button>
            </form>
          </div>
        </div>
      </section>
    </main>
  );
}

function formatDashboardNumber(value) {
  if (typeof value === "string") return value;
  return new Intl.NumberFormat("en-IN").format(Number(value || 0));
}

function DashboardMiniList({ items, empty, suffix = "" }) {
  const list = items?.length ? items : [{ label: empty, value: 0 }];
  return (
    <div className="dashboard-list">
      {list.map((item) => (
        <div className="dashboard-row" key={item.label}>
          <span>{item.label}</span>
          <strong>{formatDashboardNumber(item.value)}{suffix}</strong>
        </div>
      ))}
    </div>
  );
}

function DashboardPageDetailList({ items }) {
  const list = items?.length ? items : [];
  if (!list.length) return <div className="dashboard-empty compact">No page detail yet</div>;
  return (
    <div className="dashboard-list">
      {list.map((item) => (
        <div className="dashboard-row detail" key={item.key || item.label}>
          <span>
            {item.label}
            <small>
              {formatDashboardNumber(item.uniqueVisitors)} visitors · {formatDashboardNumber(item.buyClicks)} buy clicks · {formatDashboardNumber(item.checkoutClicks)} checkout clicks
            </small>
          </span>
          <strong>{formatDashboardNumber(item.pageviews)}</strong>
        </div>
      ))}
    </div>
  );
}

function DashboardLockScreen({ passcode, setPasscode, error, loading, onSubmit }) {
  return (
    <main className="dashboard-main">
      <section className="section tight">
        <div className="shell">
          <div className="dashboard-lock">
            <span className="eyebrow">Private dashboard</span>
            <h1>Analytics access is locked.</h1>
            <p>Enter the dashboard passcode to view traffic, checkout intent, and lead activity.</p>
            <form className="dashboard-login-form" onSubmit={onSubmit}>
              <input
                type="password"
                value={passcode}
                onChange={(event) => setPasscode(event.target.value)}
                placeholder="Dashboard passcode"
                autoComplete="current-password"
              />
              <button type="submit" className="btn primary" disabled={loading}>
                {loading ? "Checking" : "Unlock"} <Arrow />
              </button>
            </form>
            {error ? <div className="dashboard-login-error">{error}</div> : null}
          </div>
        </div>
      </section>
    </main>
  );
}

function AnalyticsDashboardPage() {
  const [summary, setSummary] = useState(null);
  const [authed, setAuthed] = useState(false);
  const [sessionChecked, setSessionChecked] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [passcode, setPasscode] = useState("");
  const [loginError, setLoginError] = useState("");

  const loadSummary = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const response = await fetch("/api/analytics-summary", { cache: "no-store", credentials: "same-origin" });
      if (response.status === 401) {
        setAuthed(false);
        setSummary(null);
        return;
      }
      if (!response.ok) throw new Error(`Dashboard request failed (${response.status})`);
      const data = await response.json();
      setSummary(data);
      setAuthed(true);
    } catch (err) {
      setError(err.message || "Could not load analytics.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/dashboard-session", { cache: "no-store", credentials: "same-origin" })
      .then((response) => response.json())
      .then((data) => {
        if (cancelled) return;
        setAuthed(Boolean(data.authed));
        setSessionChecked(true);
        if (data.authed) loadSummary();
        else setLoading(false);
      })
      .catch(() => {
        if (cancelled) return;
        setAuthed(false);
        setSessionChecked(true);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [loadSummary]);

  useEffect(() => {
    if (!authed) return undefined;
    const id = setInterval(loadSummary, 60000);
    return () => clearInterval(id);
  }, [authed, loadSummary]);

  const login = async (event) => {
    event.preventDefault();
    setLoading(true);
    setLoginError("");
    try {
      const response = await fetch("/api/dashboard-login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ passcode }),
      });
      if (!response.ok) throw new Error("That passcode did not unlock the dashboard.");
      setAuthed(true);
      setPasscode("");
      await loadSummary();
    } catch (err) {
      setLoginError(err.message || "Could not unlock dashboard.");
      setAuthed(false);
      setLoading(false);
    }
  };

  const logout = async () => {
    await fetch("/api/dashboard-logout", { method: "POST", credentials: "same-origin" }).catch(() => {});
    setAuthed(false);
    setSummary(null);
    setPasscode("");
    setLoading(false);
    setSessionChecked(true);
  };

  if (!sessionChecked) {
    return (
      <main className="dashboard-main">
        <section className="section tight">
          <div className="shell">
            <div className="dashboard-empty">Checking private access...</div>
          </div>
        </section>
      </main>
    );
  }

  if (!authed) {
    return (
      <DashboardLockScreen
        passcode={passcode}
        setPasscode={setPasscode}
        error={loginError}
        loading={loading}
        onSubmit={login}
      />
    );
  }

  const checkoutRate = summary?.overview?.checkoutRate || 0;
  const contactRate = summary?.overview?.contactRate || 0;
  const pageviews = summary?.overview?.pageviews || 0;
  const maxFunnel = Math.max(pageviews, summary?.overview?.buyButtonClicks || 0, summary?.overview?.packViews || 0, summary?.overview?.checkoutClicks || 0, summary?.overview?.leads || 0, 1);
  const funnel = summary ? [
    { label: "Page views", value: summary.overview.pageviews },
    { label: "Buy buttons", value: summary.overview.buyButtonClicks || 0 },
    { label: "Pack views", value: summary.overview.packViews },
    { label: "Checkout clicks", value: summary.overview.checkoutClicks },
    { label: "Leads", value: summary.overview.leads },
  ] : [];

  const metricCards = summary ? [
    { label: "Unique visitors", value: summary.overview.uniqueVisitors, helper: "All-time tracked visitors" },
    { label: "Today", value: summary.today.uniqueVisitors, helper: `${formatDashboardNumber(summary.today.pageviews)} page views` },
    { label: "Last 7 days", value: summary.last7Days.uniqueVisitors, helper: `${formatDashboardNumber(summary.last7Days.pageviews)} page views` },
    { label: "Checkout rate", value: `${checkoutRate}%`, helper: "Checkout clicks per page view" },
    { label: "Buy buttons", value: summary.overview.buyButtonClicks || 0, helper: "All Buy CTAs clicked" },
    { label: "Checkout clicks", value: summary.overview.checkoutClicks, helper: "Razorpay intent clicks" },
    { label: "Pack views", value: summary.overview.packViews, helper: "Individual product views" },
    { label: "Contact intent", value: `${contactRate}%`, helper: `${formatDashboardNumber(summary.overview.contactClicks)} contact clicks` },
    { label: "Leads sent", value: summary.overview.leads, helper: "Contact form submissions" },
  ] : [];

  const recentDays = summary?.recentDays || [];
  const maxRecent = Math.max(...recentDays.map((day) => day.pageviews || 0), 1);

  return (
    <main className="dashboard-main">
      <section className="section tight">
        <div className="shell">
          <div className="dashboard-head reveal in">
            <div>
              <span className="eyebrow">Private dashboard</span>
              <h1 className="dashboard-title">Koshur Fpv traffic room.</h1>
              <p className="dashboard-copy">
                Live website signals for traffic, product interest, checkout intent, and contact demand.
              </p>
            </div>
            <div className="dashboard-actions">
              <button type="button" className="btn secondary" onClick={loadSummary}>
                Refresh <Arrow />
              </button>
              <button type="button" className="btn secondary" onClick={logout}>
                Lock
              </button>
              <a href="#/home" className="btn ghost">Back to site <Arrow /></a>
            </div>
          </div>

          {loading && !summary ? <div className="dashboard-empty">Loading analytics…</div> : null}
          {error ? <div className="dashboard-empty">{error}</div> : null}

          {summary ? (
            <>
              <div className="dashboard-grid reveal in">
                {metricCards.map((metric) => (
                  <div className="dashboard-card" key={metric.label}>
                    <span className="dashboard-label">{metric.label}</span>
                    <strong className="dashboard-value">{formatDashboardNumber(metric.value)}</strong>
                    <small>{metric.helper}</small>
                  </div>
                ))}
              </div>

              <div className="dashboard-layout dashboard-layout-primary reveal in">
                <section className="dashboard-panel dashboard-panel-wide">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Recent trend</span>
                    <span className="dashboard-meta">Updated {summary.generatedAtLabel}</span>
                  </div>
                  <h2>Last 14 days</h2>
                  <div className="dashboard-bars">
                    {recentDays.map((day) => (
                      <div className="dashboard-bar-col" key={day.date}>
                        <div
                          className="dashboard-bar"
                          style={{ height: `${Math.max(14, Math.round((day.pageviews / maxRecent) * 180))}px` }}
                          title={`${day.label}: ${day.pageviews} pageviews, ${day.uniqueVisitors} visitors`}
                        />
                        <span>{day.shortLabel}</span>
                      </div>
                    ))}
                  </div>
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Funnel</span>
                    <span className="dashboard-meta">Visitor intent</span>
                  </div>
                  <h2>From view to action</h2>
                  <div className="dashboard-funnel">
                    {funnel.map((item) => (
                      <div className="dashboard-funnel-row" key={item.label}>
                        <div>
                          <span>{item.label}</span>
                          <strong>{formatDashboardNumber(item.value)}</strong>
                        </div>
                        <i style={{ width: `${Math.max(8, Math.round((item.value / maxFunnel) * 100))}%` }} />
                      </div>
                    ))}
                  </div>
                </section>
              </div>

              <div className="dashboard-layout reveal in">
                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Demand</span>
                    <span className="dashboard-meta">Views + checkout intent</span>
                  </div>
                  <h2>Top packs</h2>
                  <DashboardMiniList items={summary.topPacks} empty="No pack signals yet" />
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Pages</span>
                    <span className="dashboard-meta">Traffic paths</span>
                  </div>
                  <h2>Top pages</h2>
                  <DashboardMiniList items={summary.topPages} empty="No page data yet" />
                </section>
              </div>

              <div className="dashboard-layout reveal in">
                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Buy buttons</span>
                    <span className="dashboard-meta">Every CTA source</span>
                  </div>
                  <h2>Button clicks</h2>
                  <DashboardMiniList items={summary.buyButtons} empty="No buy button clicks yet" />
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Checkout</span>
                    <span className="dashboard-meta">Razorpay clicks by page</span>
                  </div>
                  <h2>Checkout pages</h2>
                  <DashboardMiniList items={summary.checkoutPages} empty="No checkout clicks yet" />
                </section>
              </div>

              <div className="dashboard-layout dashboard-layout-primary reveal in">
                <section className="dashboard-panel dashboard-panel-wide">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Page detail</span>
                    <span className="dashboard-meta">Views, visitors, buy clicks</span>
                  </div>
                  <h2>Page performance</h2>
                  <DashboardPageDetailList items={summary.pageDetails} />
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Checkout buttons</span>
                    <span className="dashboard-meta">Pack + source</span>
                  </div>
                  <h2>Buy intent</h2>
                  <DashboardMiniList items={summary.checkoutButtons} empty="No checkout button detail yet" />
                </section>
              </div>

              <div className="dashboard-layout dashboard-layout-three reveal in">
                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Contact</span>
                    <span className="dashboard-meta">DM, email, booking</span>
                  </div>
                  <h2>Channels</h2>
                  <DashboardMiniList items={summary.contactChannels} empty="No contact clicks yet" />
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Device</span>
                    <span className="dashboard-meta">Page views</span>
                  </div>
                  <h2>Device split</h2>
                  <DashboardMiniList items={summary.devices} empty="No device data yet" />
                </section>

                <section className="dashboard-panel">
                  <div className="dashboard-panel-head">
                    <span className="eyebrow muted">Region</span>
                    <span className="dashboard-meta">Country code</span>
                  </div>
                  <h2>Countries</h2>
                  <DashboardMiniList items={summary.countries} empty="No country data yet" />
                </section>
              </div>

              <div className="dashboard-note reveal in">
                Private route: <code>#/dashboard</code>. A shared link opens the locked screen unless the viewer has the passcode.
              </div>
            </>
          ) : null}
        </div>
      </section>
    </main>
  );
}

// ============ APP ============
function App() {
  const [route] = useRoute();
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [theme, setTheme] = useState(() => {
    try { return localStorage.getItem("koshur-theme") || "dark"; }
    catch { return "dark"; }
  });
  const [state, setState] = useState(() => {
    try { return JSON.parse(localStorage.getItem("koshur-tweaks") || "") || { dir: "editorial", density: "airy", accent: "ice" }; }
    catch { return { dir: "editorial", density: "airy", accent: "ice" }; }
  });

  useEffect(() => { try { localStorage.setItem("koshur-theme", theme); } catch {} }, [theme]);
  useEffect(() => { localStorage.setItem("koshur-tweaks", JSON.stringify(state)); }, [state]);

  useEffect(() => {
    const b = document.body;
    const doc = document.documentElement;
    b.classList.remove("dir-editorial", "dir-kinetic");
    b.classList.add(`dir-${state.dir}`);
    b.classList.remove("theme-dark", "theme-light");
    b.classList.add(`theme-${theme}`);
    doc.classList.remove("theme-dark", "theme-light");
    doc.classList.add(`theme-${theme}`);
    // accent
    const r = document.documentElement;
    if (state.accent === "warm") { r.style.setProperty("--accent", "#E6B887"); r.style.setProperty("--accent-hover", "#d9a770"); r.style.setProperty("--accent-dim", "rgba(230,184,135,0.5)"); }
    else if (state.accent === "mono") { r.style.setProperty("--accent", "#FAFAFA"); r.style.setProperty("--accent-hover", "#d4d4d4"); r.style.setProperty("--accent-dim", "rgba(250,250,250,0.5)"); }
    else { r.style.removeProperty("--accent"); r.style.removeProperty("--accent-hover"); r.style.removeProperty("--accent-dim"); }
    // density
    if (state.density === "tight") { r.style.setProperty("--container", "1240px"); }
    else { r.style.setProperty("--container", "1400px"); }
  }, [state, theme]);

  useReveal();

  const [route2, go] = useRoute();
  const initialPageView = useRef(true);

  useEffect(() => {
    if (route2 !== "dashboard") {
      sendSiteAnalytics("pageview", { route: route2 });
    }
    if (initialPageView.current) {
      initialPageView.current = false;
      return;
    }
    if (route2 !== "dashboard") {
      trackMetaPageView(route2);
    }
  }, [route2]);

  useEffect(() => {
    const onCheckoutClick = (event) => {
      const anchor = event.target.closest?.("a");
      if (!anchor) return;
      const hrefAttr = anchor.getAttribute("href") || "";
      const checkout = window.SITE?.links?.checkout || window.SITE?.links?.whop;
      const href = new URL(anchor.href, window.location.href).href.replace(/\/$/, "");
      const checkoutHref = checkout ? new URL(checkout, window.location.href).href.replace(/\/$/, "") : "";
      const isPackCheckout = Boolean(anchor.dataset.contentId);
      const isGlobalCheckout = Boolean(checkoutHref && href === checkoutHref);
      const buttonText = (anchor.textContent || "").replace(/\s+/g, " ").trim();
      const buttonSource = getAnalyticsButtonSource(anchor);
      const destinationType = getAnalyticsDestinationType(hrefAttr, isPackCheckout, isGlobalCheckout);
      const isBuyButton = isPackCheckout || anchor.dataset.directCheckout === "true";
      const isContactLink = hrefAttr.startsWith("mailto:") || hrefAttr.includes("instagram.com") || hrefAttr.includes("cal.com") || hrefAttr === "#/contact";
      if (isBuyButton) {
        sendSiteAnalytics("buy_button_click", {
          buttonSource,
          buttonText,
          destinationType,
          href: hrefAttr || href,
          contentId: anchor.dataset.contentId || destinationType,
          contentName: anchor.dataset.contentName || buttonText || "Buy button",
          value: Number(anchor.dataset.value || 0),
          currency: anchor.dataset.currency || "INR",
        });
      }
      if (isContactLink) {
        trackMetaContact(anchor);
        sendSiteAnalytics("contact_click", {
          channel: hrefAttr.startsWith("mailto:")
            ? "email"
            : hrefAttr.includes("instagram.com")
              ? "instagram"
              : hrefAttr.includes("cal.com")
                ? "cal"
                : "contact_page",
          href: hrefAttr || href,
          buttonSource,
        });
      }
      if (isPackCheckout) {
        trackMetaInitiateCheckout(anchor);
        sendSiteAnalytics("checkout_click", {
          contentId: anchor.dataset.contentId || "checkout",
          contentName: anchor.dataset.contentName || "Pack checkout",
          value: Number(anchor.dataset.value || 0),
          currency: anchor.dataset.currency || "INR",
          buttonSource,
          buttonText,
          destinationType,
          href: hrefAttr || href,
        });
      }
      if (!isGlobalCheckout || anchor.dataset.directCheckout === "true") return;
      if (!isPackCheckout) trackMetaInitiateCheckout(anchor);
      event.preventDefault();
      setCheckoutOpen(true);
    };
    document.addEventListener("click", onCheckoutClick);
    return () => document.removeEventListener("click", onCheckoutClick);
  }, []);

  // edit mode bridge
  useEffect(() => {
    const on = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", on);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", on);
  }, []);

  let page;
  if (route2.startsWith("packs/")) {
    page = <PackDetailPage slug={route2.slice("packs/".length)} />;
  } else {
    switch (route2) {
      case "dashboard": page = <AnalyticsDashboardPage />; break;
      case "packs": page = <PacksPage />; break;
      case "portfolio": page = <PortfolioPage />; break;
      case "about": page = <AboutPage />; break;
      case "contact": page = <ContactPage />; break;
      default: page = <HomePage />;
    }
  }
  const isDashboard = route2 === "dashboard";

  return (
    <>
      <Nav route={route2} go={go} theme={theme} onThemeToggle={() => setTheme((value) => value === "dark" ? "light" : "dark")} />
      {page}
      {!isDashboard && <Footer />}
      {!isDashboard && <StickyBar />}
      {!isDashboard && <CheckoutNotice open={checkoutOpen} onClose={() => setCheckoutOpen(false)} />}
      {!isDashboard && <TweaksPanel open={tweaksOpen} state={state} setState={setState} />}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
