/* sections.jsx — home page sections. Uses window shared primitives. */
const { useState: sS, useEffect: sE, useRef: sR } = React;

/* ---------------------------------- HERO ---------------------------------- */
function Hero({ lang, onNavigate }) {
  const T = (v) => window.t(v, lang);
  const H = window.OLV.hero, B = window.OLV.brand;
  const photoRef = sR(null);
  sE(() => {
    const el = photoRef.current; if (!el) return;
    const onScroll = () => { const y = window.scrollY; if (y < window.innerHeight) el.style.transform = `translateY(${y * 0.06}px) scale(1.04)`; };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className="hero" id="home">
      <div className="hero-bg" />
      <div className="hero-grid">
        <div>
          <Reveal><Overline>{T(H.overline)}</Overline></Reveal>
          <Headline text={T(H.title)} className="display" style={{ marginTop: 22 }} />
          <Reveal delay="2"><p className="lede">{T(H.body)}</p></Reveal>
          <Reveal delay="3"><div className="hero-actions">
            <Cta size="lg" icon="arrow-up-right" onClick={() => onNavigate("contact")}>{T(window.OLV.cta.consult)}</Cta>
            <LinkBtn onClick={() => onNavigate("portfolio")}>{T({ en: "View Portfolio", hi: "पोर्टफ़ोलियो देखें" })}</LinkBtn>
          </div></Reveal>
          <Reveal delay="4"><div className="hero-note"><span className="hairline" style={{ width: 32 }} />{T(H.note)}</div></Reveal>
        </div>
        <Reveal delay="2" className="hero-photo">
          <img ref={photoRef} src="assets/hero.jpg" alt="OLIVEARCH luxury villa, golden-hour exterior" />
          <span className="hero-frame" />
        </Reveal>
      </div>
      <div className="scrollcue"><span>{T({ en: "Scroll", hi: "स्क्रॉल" })}</span><span className="bar" /></div>
    </header>
  );
}

/* --------------------------------- STATS ---------------------------------- */
function StatStrip({ lang }) {
  const T = (v) => window.t(v, lang);
  return (
    <section className="statstrip" aria-label="Key figures">
      {window.OLV.stats.map((s, i) => (
        <div className="statcell" key={i}>
          <div className="num"><CountUp value={s.value} prefix={s.prefix || ""} suffix={s.suffix || ""} /></div>
          <div className="lbl">{T(s.label)}</div>
        </div>
      ))}
    </section>
  );
}

/* ------------------------------ WHY (PMC) --------------------------------- */
function WhyPMC({ lang }) {
  const T = (v) => window.t(v, lang);
  const W = window.OLV.why;
  return (
    <section className="section section--alt" id="why">
      <div className="container">
        <div className="why-top">
          <div className="shead" style={{ maxWidth: 620 }}>
            <Reveal><Overline>{T(W.overline)}</Overline></Reveal>
            <Reveal delay="1"><h2 className="display" style={{ marginTop: 22 }}>{T(W.title)}</h2></Reveal>
          </div>
          <Reveal delay="2"><p className="why-lead">{T(W.lead)}</p></Reveal>
        </div>
        <div className="grid-auto g4" style={{ marginTop: 64 }}>
          {W.cards.map((c, i) => (
            <Reveal key={i} delay={String((i % 4) + 1)} className="ocard">
              <span className="kn">{c.n}</span>
              <h3>{T(c.title)}</h3>
              <p>{T(c.body)}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ------------------------- 4-STAGE SCROLL FLOW ---------------------------- */
const STAGE_SLOTS = [
  { id: "stage-planning-3d", ph: "AI 3D render — planning: isometric blueprint site model, drawings unrolling, gold-on-charcoal" },
  { id: "stage-formulation-3d", ph: "AI 3D render — formulation: 3D building framework / GFC wireframe mid-construction, gold accents" },
  { id: "stage-execution-3d", ph: "AI 3D render — execution: cutaway tower with cranes & progress data overlay, cinematic dark" },
  { id: "stage-interiors-3d", ph: "AI 3D render — interiors: luxury interior with visible MEP/lighting layers, warm gold light" },
];

/* per-stage context overlay layered over the live 3D build */
function SceneHUD({ active, lang }) {
  const T = (v) => window.t(v, lang);
  const chip = (arr) => <div className="hud-chips">{arr.map((c, i) => <span key={i} className="hud-chip">{T(c)}</span>)}</div>;

  const planning = (
    <div className="hud-card">
      <h5><Icon name="drafting" size={14} />{T({ en: "Blueprint & Survey", hi: "ब्लूप्रिंट व सर्वेक्षण" })}</h5>
      <svg className="hud-plan" viewBox="0 0 200 120" fill="none" stroke="#D4AF37" strokeWidth="1.4">
        <rect x="8" y="8" width="184" height="104" opacity=".7" />
        <path d="M8 60h120M128 8v104M128 60h64M60 60v52M60 86h68" opacity=".55" />
        <path d="M128 34h64M160 8v26" opacity=".4" />
        <circle cx="8" cy="8" r="2.5" fill="#D4AF37" /><circle cx="192" cy="8" r="2.5" fill="#D4AF37" /><circle cx="8" cy="112" r="2.5" fill="#D4AF37" /><circle cx="192" cy="112" r="2.5" fill="#D4AF37" />
        <text x="30" y="40" fill="#8a7a48" fontSize="7" stroke="none">18.0m</text>
      </svg>
      {chip([{ en: "Site Survey", hi: "साइट सर्वे" }, { en: "Soil Testing", hi: "मृदा परीक्षण" }, { en: "Master Schedule", hi: "मास्टर शेड्यूल" }])}
    </div>
  );

  const formulation = (
    <div className="hud-card">
      <h5><Icon name="users" size={14} />{T({ en: "Coordination & Vendors", hi: "समन्वय व वेंडर" })}</h5>
      <div className="hud-gantt">
        {[[{ en: "Tender", hi: "टेंडर" }, 90], [{ en: "GFC Drawings", hi: "जीएफसी" }, 72], [{ en: "MEP Coord.", hi: "एमईपी" }, 58], [{ en: "Mobilise", hi: "मोबिलाइज़" }, 40]].map((r, i) => (
          <div className="hud-grow" key={i}><span className="gl">{String(i + 1).padStart(2, "0")}</span><span className="gbar" style={{ maxWidth: r[1] + "%", animationDelay: (i * 0.12) + "s" }} /></div>
        ))}
      </div>
      {chip([{ en: "Vendor Selection", hi: "वेंडर चयन" }, { en: "Fortnightly Reviews", hi: "पाक्षिक समीक्षा" }])}
    </div>
  );

  const execution = (
    <div className="hud-card">
      <h5><Icon name="trending-up" size={14} />{T({ en: "Monthly Progress Report", hi: "मासिक प्रगति रिपोर्ट" })}</h5>
      <div className="hud-bars">{[34, 46, 55, 63, 72, 84].map((h, i) => <i key={i} style={{ height: h + "%", animationDelay: (i * 0.09) + "s" }} />)}</div>
      <div className="hud-report-foot">
        <span className="hud-pct">84%<small>{T({ en: "on schedule", hi: "समय पर" })}</small></span>
      </div>
      {chip([{ en: "QA / QC", hi: "क्यूए/क्यूसी" }, { en: "Doc Control", hi: "दस्तावेज़ नियंत्रण" }, { en: "As-Built", hi: "ऐज़-बिल्ट" }])}
    </div>
  );

  const integrated = (
    <div className="hud-card">
      <h5><Icon name="sparkle" size={14} />{T({ en: "Integrated Works", hi: "एकीकृत कार्य" })}</h5>
      <div className="hud-mep">
        {[["sparkle", { en: "Lighting", hi: "प्रकाश" }], ["layers", { en: "HVAC", hi: "एचवीएसी" }], ["flame", { en: "Fire Fighting", hi: "अग्निशमन" }], ["cpu", { en: "Automation", hi: "ऑटोमेशन" }], ["leaf", { en: "Landscaping", hi: "भूनिर्माण" }], ["sofa", { en: "Interiors", hi: "इंटीरियर" }]].map((m, i) => (
          <div key={i}><Icon name={m[0]} size={14} />{T(m[1])}</div>
        ))}
      </div>
    </div>
  );

  const panels = [planning, formulation, execution, integrated];
  return (
    <div className="scene-hud" aria-hidden="true">
      {panels.map((p, i) => <div key={i} className={"hud" + (i === active ? " on" : "")}>{p}</div>)}
    </div>
  );
}

function Stages({ lang }) {
  const T = (v) => window.t(v, lang);
  const S = window.OLV.stages, I = window.OLV.stagesIntro;
  const wrapRef = sR(null), railRef = sR(null), canvasRef = sR(null), progRef = sR(null);
  const [active, setActive] = sS(0);
  const [noWebGL, setNoWebGL] = sS(false);
  const activeRef = sR(0);

  /* mount the real-time WebGL building (all viewports) */
  sE(() => {
    if (!canvasRef.current) return;
    const B = window.OliveBuilding;
    if (!B) { setNoWebGL(true); return; }
    if (B.supported && !B.supported()) { setNoWebGL(true); return; }
    B.mount(canvasRef.current);
    B.setProgress(0);
    const ro = new ResizeObserver(() => B.resize && B.resize());
    ro.observe(canvasRef.current);
    return () => { ro.disconnect(); B.dispose && B.dispose(); };
  }, []);

  /* scroll → building progress + stepper + rail */
  sE(() => {
    const wrap = wrapRef.current;
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const r = wrap.getBoundingClientRect();
        const total = wrap.offsetHeight - window.innerHeight;
        const passed = Math.min(Math.max(-r.top, 0), total);
        const p = total > 0 ? passed / total : 0;                // 0..1 through section
        const idx = Math.min(S.length - 1, Math.floor(p * S.length + 0.001));
        if (railRef.current) railRef.current.style.height = (p * 100).toFixed(2) + "%";
        if (progRef.current) progRef.current.textContent = Math.round(p * 100) + "%";
        if (window.OliveBuilding) window.OliveBuilding.setProgress(p);
        if (idx !== activeRef.current) { activeRef.current = idx; setActive(idx); }
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [lang]);

  const goStep = (i) => {
    const wrap = wrapRef.current; if (!wrap) return;
    const top = wrap.getBoundingClientRect().top + window.scrollY;
    const total = wrap.offsetHeight - window.innerHeight;
    const targetP = (i + 0.5) / S.length;
    window.scrollTo({ top: top + targetP * total, behavior: "smooth" });
  };

  /* ---- sticky stepper + scroll-driven WebGL building (all viewports) ---- */
  return (
    <section className="section stageflow" id="stages" ref={wrapRef} style={{ height: `${S.length * 92 + 16}vh`, paddingBlock: 0 }}>
      <div className="stagepin">
        <div className="container" style={{ width: "100%" }}>
          <div className="stage-head">
            <Overline>{T(I.overline)}</Overline>
            <h2 className="display">{T(I.title)}</h2>
            <span className="stage-cue"><Icon name="chevron-down" size={14} />{T({ en: "Scroll — watch the project build itself, stage by stage.", hi: "स्क्रॉल करें — देखें प्रोजेक्ट को चरण-दर-चरण बनते हुए।" })}</span>
          </div>
          <div className="stage-layout">
            <div className="stage-col">
              <div className="stage-steps">
                <div className="stage-rail"><b ref={railRef} /></div>
                {S.map((s, i) => (
                  <button key={i} className={"step" + (i === active ? " on" : "")} onClick={() => goStep(i)} aria-current={i === active}>
                    <span className="num">{s.no} · {T(s.key)}</span>
                    <span className="ttl">{T(s.title)}</span>
                  </button>
                ))}
              </div>
              <div className="stage-copy-desk">
                {S.map((s, i) => (
                  <div key={i} className={"stage-slide" + (i === active ? " on" : "")} aria-hidden={i !== active}>
                    <h4 className="stage-slide-ttl">{T(s.title)}</h4>
                    <div className="stage-copy">
                      <p>{T(s.body)}</p>
                      <ul className="stage-points">{s.points.map((pt, j) => <li key={j}><span className="dot"><Icon name="check" size={15} /></span>{T(pt)}</li>)}</ul>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="stage-scene">
              <canvas className="building-canvas" ref={canvasRef} />
              {noWebGL && <div className="stage-scene-fallback">{T({ en: "Enable WebGL to view the live 3D build.", hi: "लाइव 3D निर्माण देखने हेतु WebGL सक्षम करें।" })}</div>}
              <SceneHUD active={active} lang={lang} />
              <span className="fig-no">{S[active].no} — {T(S[active].key)}</span>
              <div className="scene-phase">
                <span className="sp-live">{T({ en: "Real-time build", hi: "रीयल-टाइम निर्माण" })}</span>
                <span className="sp-prog" ref={progRef}>0%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------ PILLARS ----------------------------------- */
function Pillars({ lang }) {
  const T = (v) => window.t(v, lang);
  return (
    <section className="section" id="pillars">
      <div className="container">
        <ChooseGrid lang={lang} />
      </div>
    </section>
  );
}

function ChooseGrid({ lang }) {
  const T = (v) => window.t(v, lang);
  const C = window.OLV.choose;
  const icons = ["handshake", "shield-check", "clock", "compass", "trending-up", "award"];
  return (
    <div>
      <SectionHead overline={T(C.overline)} title={T(C.title)} align="center" maxWidth={720} />
      <div className="grid-auto g3" style={{ marginTop: 56 }}>
        {C.items.map((it, i) => (
          <Reveal key={i} delay={String((i % 3) + 1)} className="choose-item">
            <div className="choose-ic"><Icon name={icons[i]} size={20} /></div>
            <div><h4>{T(it.title)}</h4><p>{T(it.body)}</p></div>
          </Reveal>
        ))}
      </div>
    </div>
  );
}

/* ------------------------------ SERVICES ---------------------------------- */
function Services({ lang, onNavigate }) {
  const T = (v) => window.t(v, lang);
  const S = window.OLV.services;
  return (
    <section className="section section--alt" id="services">
      <div className="container">
        <SectionHead overline={T(S.overline)} title={T(S.title)} lead={T(S.sub)} maxWidth={760} />
        <div className="svc" style={{ marginTop: 56 }}>
          {S.items.map((it, i) => (
            <Reveal key={it.id} delay={String((i % 3) + 1)}>
              <article className="svc-card" onClick={() => onNavigate("portfolio")} data-cursor="grab">
                <img src={it.image} alt="" loading="lazy" />
                <span className="k">{String(i + 1).padStart(2, "0")}</span>
                <h3>{T(it.title)}</h3>
                <p>{T(it.body)}</p>
                <span className="more">{T({ en: "See related work", hi: "संबंधित कार्य देखें" })} <Icon name="arrow-right" size={15} /></span>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ------------------------------- ABOUT ------------------------------------ */
function About({ lang }) {
  const T = (v) => window.t(v, lang);
  const A = window.OLV.about;
  return (
    <section className="section" id="about">
      <div className="container">
        <div className="about-grid">
          <Reveal className="about-portrait">
            <img className="portrait-img" src="assets/col-satwant.jpg" alt="Col Satwant Singh Juneja (Retd), Founder & Director" />
            <img className="portrait-mark" src="assets/logo-mark.png" alt="" />
            <div className="portrait-cap">
              <div className="pc-name">Col Satwant Singh Juneja <span>(Retd)</span></div>
              <div className="pc-role">{T(A.role)}</div>
            </div>
          </Reveal>
          <div>
            <Reveal><Overline>{T(A.overline)}</Overline></Reveal>
            <Reveal delay="1"><h2 className="display" style={{ marginTop: 20, fontSize: "var(--fs-display)" }}>{T(A.title)}</h2></Reveal>
            <Reveal delay="1"><div style={{ fontFamily: "var(--font-display)", fontSize: "var(--fs-h3)", color: "var(--olv-gold-champagne)", marginTop: 8 }}>{A.name}</div></Reveal>
            <Reveal delay="2"><p style={{ fontFamily: "var(--font-body)", fontSize: "var(--fs-body-lg)", color: "var(--text-body)", lineHeight: "var(--leading-normal)", marginTop: 24 }}>{T(A.bio)}</p></Reveal>
          </div>
        </div>
        <Partners lang={lang} />
      </div>
    </section>
  );
}

function Partners({ lang }) {
  const T = (v) => window.t(v, lang);
  const P = window.OLV.partners;
  const loop = P.names.concat(P.names); // duplicate for seamless infinite scroll
  return (
    <div className="partners">
      <Reveal><div className="partners-head"><span className="hairline" /><Overline>{T(P.overline)}</Overline><span className="hairline" /></div></Reveal>
      <Reveal delay="1"><h3 className="partners-title">{T(P.title)}</h3></Reveal>
      <Reveal delay="2">
        <div className="belt" aria-label={T(P.title)}>
          <div className="belt-track">
            {loop.map((n, i) => <span key={i} className="belt-item" aria-hidden={i >= P.names.length}>{n}</span>)}
          </div>
        </div>
      </Reveal>
    </div>
  );
}

/* --------------------------- TESTIMONIALS --------------------------------- */
function Testimonials({ lang }) {
  const T = (v) => window.t(v, lang);
  const S = window.OLV.testimonials;
  return (
    <section className="section section--alt" id="testimonials">
      <div className="container">
        <SectionHead overline={T(S.overline)} title={T(S.title)} align="center" maxWidth={640} />
        <Reveal delay="1"><p className="tnote">{T(S.placeholderNote)}</p></Reveal>
        <div className="tgrid" style={{ marginTop: 40 }}>
          {S.items.map((it, i) => (
            <Reveal key={i} delay={String((i % 3) + 1)} className="tcard">
              <Icon name="quote" size={30} style={{ color: "var(--olv-gold)" }} />
              <p className="q">{T(it.quote)}</p>
              <div className="hairline" style={{ width: 36, marginBottom: 14 }} />
              <div className="who">{T(it.author)}</div>
              <div className="role">{T(it.role)}</div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ------------------------------ CONTACT ----------------------------------- */
function Contact({ lang }) {
  const T = (v) => window.t(v, lang);
  const C = window.OLV.contact, B = window.OLV.brand;
  const [status, setStatus] = sS("idle"); // idle | sending | ok | err
  const [form, setForm] = sS({ name: "", email: "", phone: "", country: "", type: C.projectTypes[0], location: "", message: "", callback: false, consent: false });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.consent) return;
    setStatus("sending");
    try {
      // No-backend relay to the OLIVEARCH inbox. Replace the endpoint with your
      // own FormSubmit activation / form handler when you deploy.
      const res = await fetch("https://formsubmit.co/ajax/" + B.email, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          _subject: "New enquiry — olivearchprojects.com",
          Name: form.name, Email: form.email, Phone: form.phone, "Based in": form.country,
          "Project Type": form.type, "Project Location": form.location,
          "Requests callback": form.callback ? "Yes" : "No", Message: form.message,
        }),
      });
      if (!res.ok) throw new Error("bad");
      setStatus("ok");
      setForm({ name: "", email: "", phone: "", country: "", type: C.projectTypes[0], location: "", message: "", callback: false, consent: false });
    } catch (err) { setStatus("err"); }
  };

  const info = [
    { ic: "mail", lbl: T({ en: "Email", hi: "ईमेल" }), val: B.email, href: "mailto:" + B.email },
    { ic: "phone", lbl: T({ en: "Phone", hi: "फ़ोन" }), val: B.phones.join("  ·  "), href: "tel:" + B.phones[0].replace(/\s/g, "") },
    { ic: "map-pin", lbl: T({ en: "Office", hi: "कार्यालय" }), val: T(B.address) },
    { ic: "globe", lbl: T({ en: "Web", hi: "वेब" }), val: B.domain, href: "https://" + B.domain },
  ];

  return (
    <section className="section" id="contact">
      <div className="container">
        <div className="contact-grid">
          <div>
            <Reveal><Overline>{T(C.overline)}</Overline></Reveal>
            <Reveal delay="1"><h2 className="display" style={{ marginTop: 20, fontSize: "var(--fs-display)" }}>{T(C.title)}</h2></Reveal>
            <Reveal delay="2"><p style={{ fontFamily: "var(--font-body)", fontSize: "var(--fs-body-lg)", color: "var(--text-body)", lineHeight: "var(--leading-normal)", marginTop: 24, maxWidth: "46ch" }}>{T(C.sub)}</p></Reveal>
            <Reveal delay="3"><div style={{ marginTop: 32 }}>
              {info.map((it, i) => (
                <div className="cinfo-item" key={i}>
                  <span className="ic"><Icon name={it.ic} size={18} /></span>
                  <span className="cinfo-body"><span className="lbl">{it.lbl}</span>{it.href ? <a className="val" href={it.href} target={it.ic === "globe" ? "_blank" : undefined} rel="noreferrer">{it.val}</a> : <span className="val">{it.val}</span>}</span>
                </div>
              ))}
            </div></Reveal>
          </div>

          <Reveal delay="2">
            <form className="oform" onSubmit={submit}>
              <div className="nri-desk-tag"><Icon name="globe" size={15} /><span><b>{T(C.form.nriDesk)}</b> — {T(C.form.nriNote)}</span></div>
              <div className="f2">
                <div className="field"><label>{T(C.form.name)}</label><input value={form.name} onChange={set("name")} required autoComplete="name" /></div>
                <div className="field"><label>{T(C.form.email)}</label><input type="email" value={form.email} onChange={set("email")} required autoComplete="email" /></div>
              </div>
              <div className="f2">
                <div className="field"><label>{T(C.form.phone)}</label><input value={form.phone} onChange={set("phone")} autoComplete="tel" placeholder="+91 / +971 / +1 …" /></div>
                <div className="field"><label>{T(C.form.country)}</label><input value={form.country} onChange={set("country")} autoComplete="country-name" placeholder={T({ en: "e.g. Dubai, London, Singapore", hi: "जैसे दुबई, लंदन, सिंगापुर" })} /></div>
              </div>
              <div className="f2">
                <div className="field"><label>{T(C.form.type)}</label>
                  <select value={form.type} onChange={set("type")}>{C.projectTypes.map((t) => <option key={t}>{t}</option>)}</select>
                </div>
                <div className="field"><label>{T(C.form.location)}</label><input value={form.location} onChange={set("location")} /></div>
              </div>
              <div className="field"><label>{T(C.form.message)}</label><textarea value={form.message} onChange={set("message")} rows="4" /></div>
              <label className="consent"><input type="checkbox" checked={form.callback} onChange={set("callback")} />{T(C.form.callback)}</label>
              <label className="consent"><input type="checkbox" checked={form.consent} onChange={set("consent")} required />{T(C.form.consent)}</label>
              {status === "ok" && <div className="formmsg ok">{T(C.form.success)}</div>}
              {status === "err" && <div className="formmsg err">{T(C.form.error)}</div>}
              <Cta size="lg" icon="arrow-up-right" type="submit">{status === "sending" ? T(C.form.sending) : T(C.form.submit)}</Cta>
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, StatStrip, WhyPMC, Stages, Pillars, Services, About, Testimonials, Contact });
