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

const AR = (typeof window !== "undefined" && window.WATHIQ_LANG === "ar");

/* ============================================================
   PRODUCT — page hero + pinned horizontal product showcase.
   As you scroll the pinned track, the current product slides
   left and out while the next slides in from the right, with
   parallax on the text + image and a live progress indicator.
   ============================================================ */

const PRODUCTS = [
  {
    tag: "AI Lab",
    tagAr: "مختبر الذكاء الاصطناعي",
    title: AR
      ? "اسأل، وحلّل مستنداتك، واكتب مسوّداتك أسرع — بذكاءٍ اصطناعي يفهم الأنظمة السعودية."
      : "Ask questions, analyze documents, and draft faster with AI built for Saudi law.",
    body: AR
      ? "من مختبر الذكاء الاصطناعي يبدأ عملك القانوني. اسأل بلغتك الطبيعية — عربيةً أو إنجليزية — لتأتيك إجابةٌ مبنيّة على الأنظمة السعودية ومستندات مكتبك. ارفع ملفاتك، واحصُر سؤالك في قضيةٍ بعينها، واختر شكل المخرجات: إجابةً حواريّة، أو مستندًا قانونيًّا جاهزًا، أو جدول مراجعةٍ منظَّمًا. ولكل إجابةٍ مصدرُها الموثوق."
      : "Wathiq's AI Lab is where your legal work starts. Ask anything in natural language — Arabic or English — and get analysis grounded in Saudi regulations and your firm's documents. Upload files, scope queries to a matter, and choose your output: a conversational answer, a formatted legal document, or a structured review table. Every response cites its sources.",
    slot: "prod-assistant",
    demo: "assistant",
  },
  {
    tag: "Word Add-in",
    tagAr: "إضافة Word",
    title: AR
      ? "قدرات وثّق كاملةً، بين يديك داخل Microsoft Word."
      : "Bring the full power of Wathiq's AI directly into Microsoft Word.",
    body: AR
      ? "راجِع مستنداتك القانونية وحرّرها ونقّحها دون أن تغادر Word. يقترح وثّق الصياغة، وينبّهك إلى المخاطر، ويطبّق أدلة عمل مكتبك — كل ذلك داخل المستند نفسه. أجرِ مراجعة العقود وفق مواقفك المعتمدة وبنودك البديلة، وأنشئ التعديلات على طريقتك. عربيًّا وإنجليزيًّا، بلغةٍ أصيلة."
      : "Review, draft, and refine legal documents without leaving Word. Wathiq suggests language, flags risks, and applies your firm's playbooks — all inline. Run contract review against your standard positions and fallback terms, and generate markup based on your preferences. Arabic and English, natively.",
    slot: "prod-word",
    demo: "contract-review",
  },
  {
    tag: "Knowledge",
    tagAr: "قاعدة المعرفة",
    title: AR
      ? "ابحث في الأنظمة واللوائح السعودية في كل تخصّص."
      : "Research Saudi laws and regulations across every jurisdiction.",
    body: AR
      ? "٤٦٦ نظامًا ولائحةً سارية ومصدرها هيئة الخبراء، وتُحدَّث من جريدة أم القرى الرسمية — تبحث فيها وتُصفّيها وتستشهد بها مباشرةً. قارِن بين المواد القانونية جنبًا إلى جنب والفروق بينها بارزة، وأضِف مستندات مكتبك لتُنشئ طبقة معرفةٍ خاصة بك فوق المصادر العامة."
      : "466 in-force laws and regulations sourced from the Bureau of Experts and updated from the Umm Al-Qura Official Gazette — searchable, filterable, and directly citable. Compare legal articles side by side with differences highlighted, and add your firm's own documents to build a private knowledge layer on top of public sources.",
    slot: "prod-knowledge",
    demo: "knowledge",
  },
  {
    tag: "Vault",
    tagAr: "الخزنة",
    title: AR
      ? "احفظ مستنداتك القانونية ونظّمها وحلّلها بأمان، مهما كثُرت."
      : "Securely store, organize, and analyze your legal documents at scale.",
    body: AR
      ? "ارفع العقود والاتفاقيات وملفات القضايا إلى مساحات عملٍ خاصة بكل مشروع. واسأل الذكاء الاصطناعي عنها مباشرةً — فتأتيك الإجابة من ملفاتك الفعلية لا من معرفةٍ عامة. أجرِ جداول المراجعة على مجموعات المستندات كاملة، واكتب مسوّداتك من قوالبك الخاصة. خاصةً كانت أم مشتركة، فأنت المتحكِّم في الوصول إليها."
      : "Upload contracts, agreements, and case files into project-level workspaces. Ask the AI questions directly about these documents — grounded in your actual files, not general knowledge. Run review tables across entire document sets, and create drafts from your own templates. Private or shared — you control access.",
    slot: "prod-vault",
    demo: "vault",
  },
  {
    tag: "Playbook",
    tagAr: "دليل العمل",
    title: AR
      ? "اجعل معايير مكتبك قواعد يلتزم بها الذكاء الاصطناعي."
      : "Codify your firm's standards into rules the AI enforces.",
    body: AR
      ? "اجمع مواقف مكتبك التعاقدية وبنوده البديلة ومعايير مراجعته في أدلة عملٍ منظَّمة — هي القواعد التي يطبّقها وثّق في كل قضية. سجّل الخطوات والموجِّهات والموافقات التي يسير عليها فريقك أصلًا، لتأتي المخرجات متّسقةً في كل مرّة، والحوكمة جزءٌ منها."
      : "Turn your firm's contract positions, fallback terms, and review standards into structured playbooks — the rules Wathiq applies on every matter. Capture the steps, prompts, and approvals your team already follows so output is consistent, every time, with governance built in.",
    slot: "prod-playbook",
    demo: "playbook",
  },
  {
    tag: "Library",
    tagAr: "المكتبة",
    title: AR
      ? "خبرة مكتبك جاهزةً لإعادة الاستخدام — موجِّهات، وأدلة عمل، ووكلاء سير عمل، وأمثلة."
      : "Your firm's reusable intelligence — prompts, playbooks, workflow agents, and examples.",
    body: AR
      ? "50 موجِّهًا قانونيًّا جاهزًا في كل مجالات الممارسة السعودية — عربيًّا وإنجليزيًّا. وأدلة عملٍ تضبط معايير مراجعة العقود في مكتبك على أساس نظام العمل السعودي. ووكلاء سير عملٍ يتولّون المهام متعددة الخطوات: تحليل المحاضر، وصياغة المذكرات، وتلخيص تبادل المستندات. كلّها تعيد استخدامها وتشاركها متى شئت."
      : "50 pre-built legal prompts across every Saudi practice area — in Arabic and English. Playbooks that codify your firm's contract review standards grounded in Saudi Labor Law. Workflow agents that automate multi-step tasks like transcript analysis, memo drafting, and discovery summarization. All reusable, all shareable.",
    slot: "prod-library",
    demo: "workflow-agents",
  },
  {
    tag: "Workflow",
    tagAr: "سير العمل",
    title: AR
      ? "ابنِ وكلاء سير عملٍ خاصين بك وأدلة مراجعة عقود — دون كتابة سطرٍ برمجي."
      : "Create custom workflow agents and contract review playbooks — no code required.",
    body: AR
      ? "صِف ما تريده بعبارةٍ بسيطة، فيبني لك مُنشئ الوكلاء سير عملٍ ذكيًّا متعدد الخطوات. اسحب وأفلِت، واربط، ونقّح، وانشر. ويمكّنك مُنشئ أدلة العمل من تحويل معايير مكتبك التعاقدية إلى قواعد يلتزم بها الذكاء الاصطناعي. وكلاهما لا يُفعَّل إلا بعد موافقتك."
      : "Describe what you need in plain language and the Agent Builder generates a multi-step AI workflow. Drag, connect, refine, deploy. The Playbook Builder lets you turn your firm's contract standards into rules the AI can enforce. Both go through approval before going live.",
    slot: "prod-workflow",
    demo: "agent-builder",
  },
];

/* A product demo frame: the still mock is the persistent base; the
   animated (video) demo fades in on top only while this product is the
   active panel, so exactly one demo animates at a time and there is no
   white flash while it boots. */
function DemoFrame({ demo, active, label }) {
  const [vReady, setVReady] = useState(false);
  useEffect(() => { if (!active) setVReady(false); }, [active]);
  // One file per demo serves BOTH languages (?lang) and the static poster
  // (?still=1, climax frame). The page's language drives which the iframe loads.
  const lang = AR ? "ar" : "en";
  const base = `/demos/${demo}-video.html`;
  return (
    <div className="pshow-media-frame is-demo">
      <iframe
        className="demo-iframe demo-still"
        src={`${base}?still=1&lang=${lang}`}
        title={`${label} preview`}
        loading="lazy"
        tabIndex={-1}
        scrolling="no"
      ></iframe>
      {active ? (
        <iframe
          className={`demo-iframe demo-video ${vReady ? "is-ready" : ""}`}
          src={`${base}?lang=${lang}`}
          title={`${label} animated demo`}
          onLoad={() => setVReady(true)}
          tabIndex={-1}
          scrolling="no"
        ></iframe>
      ) : null}
    </div>
  );
}

function ProductHero() {
  return (
    <section className="page-hero product-hero">
      <div className="container">
        <div className="eyebrow page-hero-eyebrow">{AR ? "المنصة" : "The platform"}</div>
        <h1 className="h-display reveal">
          {AR ? "مساحة عمل واحدة." : "One workspace."}<br/>
          <span className="ph-accent">{AR ? "لعملك القانوني بكل تفاصيله." : "Every part of legal work."}</span>
        </h1>
        <p className="body-lg reveal" style={{ marginTop: 22 }}>
          {AR
            ? "سبعة منتجات في منظومةٍ واحدة موحّدة — صُمِّمت على ما تعمل به المكاتب السعودية فعلًا."
            : "Seven products, one governed system — built for the way Saudi firms actually practice."}
        </p>
        <div className="product-hero-meta reveal" aria-hidden="true">
          <span><strong>7</strong> {AR ? "منتجات" : "products"}</span>
          <span className="phm-sep" />
          <span><strong>1</strong> {AR ? "منظومة موحّدة" : "governed system"}</span>
          <span className="phm-sep" />
          <span>{AR ? <>عربي + إنجليزي <strong>أصيلان</strong></> : <>Native <strong>Arabic + English</strong></>}</span>
        </div>
        <div className="product-hero-scroll reveal" aria-hidden="true">
          <span className="phs-label">{AR ? "مرّر للاستكشاف" : "Scroll to explore"}</span>
          <span className="phs-rail"><span className="phs-dot" /></span>
        </div>
      </div>
    </section>
  );
}

function ProductShowcase() {
  const trackRef = useRef(null);
  const railRef = useRef(null);
  const panelRefs = useRef([]);
  const [active, setActive] = useState(0);
  const N = PRODUCTS.length;

  useEffect(() => {
    let raf = 0;
    const ease = (t) => t; // linear feels right for direct scroll mapping
    // In RTL the panels lay right-to-left, so the rail must pan the other way
    // (and the parallax mirrors). Without this, only the first panel is
    // reachable — you can't scroll through the products.
    const RTL = document.documentElement.dir === "rtl";
    const sx = RTL ? 1 : -1;
    const par = RTL ? -1 : 1;

    const frame = () => {
      raf = requestAnimationFrame(frame);
      const track = trackRef.current;
      const rail = railRef.current;
      if (!track || !rail) return;

      const total = track.offsetHeight - window.innerHeight;
      const scrolled = Math.min(Math.max(-track.getBoundingClientRect().top, 0), total);
      const progress = total > 0 ? scrolled / total : 0; // 0..1
      const pos = progress * (N - 1); // 0..N-1 — which panel is centered

      // Move the rail so panel `pos` is centered.
      rail.style.transform = `translate3d(${sx * pos * 100}vw, 0, 0)`;

      // Per-panel parallax + fade based on distance from center.
      panelRefs.current.forEach((p, i) => {
        if (!p) return;
        const d = i - pos;                  // signed distance in panels
        const ad = Math.min(Math.abs(d), 1);
        const media = p.querySelector(".pshow-media");
        const text = p.querySelector(".pshow-text");
        const op = 1 - ad * 0.75;
        if (media) {
          media.style.transform = `translate3d(${par * d * 14}%, 0, 0) scale(${1 - ad * 0.06})`;
          media.style.opacity = op;
        }
        if (text) {
          text.style.transform = `translate3d(${par * d * 32}%, 0, 0)`;
          text.style.opacity = op;
        }
      });

      const idx = Math.round(pos);
      setActive((prev) => (prev === idx ? prev : idx));
    };
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, [N]);

  const goTo = (i) => {
    const track = trackRef.current;
    if (!track) return;
    const total = track.offsetHeight - window.innerHeight;
    const top = track.offsetTop + (i / (N - 1)) * total;
    const lenis = window.__motion && window.__motion.lenis;
    if (lenis) lenis.scrollTo(top, { duration: 1.1 });
    else window.scrollTo({ top, behavior: "smooth" });
  };

  // Deep-link: Product.html#vault (etc.) GLIDES to that product — a smooth
  // animated scroll, not an instant jump. Each product is a scroll position in
  // the pinned showcase. Handles BOTH first load (#hash in the URL) AND clicking
  // a product in the menu while already on this page (same-page hashchange).
  useEffect(() => {
    const idxForHash = () => {
      const hash = window.location.hash.replace("#", "");
      if (!hash) return -1;
      return PRODUCTS.findIndex((p) => p.slot === "prod-" + hash);
    };
    const targetTop = (idx) => {
      const track = trackRef.current;
      if (!track) return null;
      if (window.innerWidth <= 860 && panelRefs.current[idx]) {
        return panelRefs.current[idx].getBoundingClientRect().top + window.scrollY - 80;
      }
      const total = Math.max(track.offsetHeight - window.innerHeight, 0);
      return track.offsetTop + (idx / (N - 1)) * total;
    };
    // Gentle ease-in-out so the scroll starts soft and lands soft (no "poof").
    const easeInOutCubic = (t) =>
      t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    const glide = (idx) => {
      const top = targetTop(idx);
      if (top == null) return;
      const lenis = window.__motion && window.__motion.lenis;
      if (lenis) lenis.scrollTo(top, { duration: 1.3, easing: easeInOutCubic, force: true });
      else window.scrollTo({ top, behavior: "smooth" });
    };
    // Clicking a product in the menu while already on the page just changes the
    // hash (no reload) — glide to it.
    const onHash = () => { const idx = idxForHash(); if (idx >= 0) glide(idx); };
    window.addEventListener("hashchange", onHash);
    // First load with a #hash (e.g. arriving from the home page): hold at the
    // very TOP while the page settles (Babel + Lenis + layout stop shifting),
    // then do ONE long eased scroll from the top all the way down to the
    // product — as if the user scrolled there themselves. No "park one-before
    // then step", no settling-override landing on the wrong product.
    const ready = () =>
      !!(trackRef.current && trackRef.current.offsetHeight > window.innerHeight * (N - 0.5)
         && window.__motion && window.__motion.lenis);
    const initIdx = idxForHash();
    const mobile = window.innerWidth <= 860;
    if (initIdx >= 0 && "scrollRestoration" in history) {
      try { history.scrollRestoration = "manual"; } catch (e) {}
    }
    let timer, tries = 0, phase = 1, lastH = -1, stable = 0;
    if (initIdx >= 0) {
      const step = () => {
        tries++;
        const track = trackRef.current;
        const lenis = window.__motion && window.__motion.lenis;
        if (phase === 1) {
          // pin at the top and wait until the showcase height stops changing
          if (lenis) lenis.scrollTo(0, { immediate: true, force: true });
          else window.scrollTo(0, 0);
          const h = track ? track.offsetHeight : 0;
          if (ready() && h === lastH) stable++; else stable = 0;
          lastH = h;
          if (stable >= 3 || tries > 60) { phase = 2; timer = setTimeout(step, 40); return; }
          timer = setTimeout(step, 70);
          return;
        }
        // phase 2: one long eased glide from the top down to the product
        if (track && lenis) {
          const total = Math.max(track.offsetHeight - window.innerHeight, 0);
          const top = mobile && panelRefs.current[initIdx]
            ? panelRefs.current[initIdx].getBoundingClientRect().top + window.scrollY - 80
            : track.offsetTop + (initIdx / (N - 1)) * total;
          const dur = 1.3 + (initIdx / Math.max(N - 1, 1)) * 1.3; // farther product = longer, smoother glide
          lenis.scrollTo(top, { duration: dur, easing: easeInOutCubic, force: true });
        } else if (tries < 70) {
          timer = setTimeout(step, 80);
        }
      };
      timer = setTimeout(step, 120);
    }
    return () => { window.removeEventListener("hashchange", onHash); clearTimeout(timer); };
  }, [N]);

  return (
    <section className="pshow" ref={trackRef} style={{ height: `${N * 100}vh` }}>
      <div className="pshow-stage">
        {/* progress chrome */}
        <div className="container pshow-chrome">
          <div className="pshow-count">
            <span className="pshow-count-now">{String(active + 1).padStart(2, "0")}</span>
            <span className="pshow-count-sep">/</span>
            <span className="pshow-count-tot">{String(N).padStart(2, "0")}</span>
          </div>
          <nav className="pshow-tabs" aria-label={AR ? "المنتجات" : "Products"}>
            {PRODUCTS.map((p, i) => (
              <button
                key={p.slot}
                className={`pshow-tab ${active === i ? "is-active" : ""}`}
                onClick={() => goTo(i)}
              >
                <span className="pshow-tab-dot" aria-hidden="true" />
                <span className="pshow-tab-label">{AR ? p.tagAr : p.tag}</span>
              </button>
            ))}
          </nav>
        </div>

        <div className="pshow-rail" ref={railRef}>
          {PRODUCTS.map((p, i) => (
            <article
              className="pshow-panel"
              key={p.slot}
              ref={(el) => (panelRefs.current[i] = el)}
            >
              <div className="container pshow-panel-inner">
                <div className="pshow-media">
                  <DemoFrame
                    demo={p.demo}
                    active={active === i}
                    label={AR ? p.tagAr : p.tag}
                  />
                </div>
                <div className="pshow-text">
                  <div className="eyebrow">{AR ? p.tagAr : p.tag}</div>
                  <h2 className="pshow-title">{p.title}</h2>
                  <p className="pshow-body">{p.body}</p>
                  <a href="Contact.html" className="pshow-cta">
                    {AR ? "سجّل للوصول المبكر" : "Apply for Early Access"} <span className="arrow">{AR ? "←" : "→"}</span>
                  </a>
                </div>
              </div>
            </article>
          ))}
        </div>

        <div className="pshow-progress" aria-hidden="true">
          <div className="pshow-progress-bar" style={{ width: `${(active / (N - 1)) * 100}%` }} />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ProductHero, ProductShowcase });
