// ============================================================
// HERO VARIANT 5 — "Scroll" — pinned scroll-cinema (4 acts)
// Acts: intro → product lines → building → CTA
// No React state for animation — zero React re-renders per frame.
// ============================================================

function HeroScroll({ setRoute }) {
  const wrapRef = React.useRef(null);
  const [now, setNow] = React.useState("");

  const revRef         = React.useRef(null);
  const scrollPctRef   = React.useRef(null);
  const progressDotRef = React.useRef(null);
  const act5Ref        = React.useRef(null);
  const lineCardRefs   = React.useRef([]);
  const windowRectsRef = React.useRef([]);

  React.useEffect(() => {
    const fmt = () => {
      const d = new Date();
      const pad = n => String(n).padStart(2, "0");
      setNow(`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} IST`);
    };
    fmt();
    const id = setInterval(fmt, 1000);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => {
    let raf = 0;
    const clamp = (v, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, v));
    const seg   = (s, e, p)  => clamp((p - s) / (e - s));

    const update = () => {
      raf = 0;
      const el = wrapRef.current;
      if (!el) return;
      const rect  = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      const p     = total > 0 ? clamp(-rect.top / total) : 0;

      // Timings — building gets full dwell before CTA
      const a1   = seg(0.00, 0.18, p); // title in
      const a2   = seg(0.15, 0.40, p); // product lines fly
      const a3   = seg(0.36, 0.60, p); // building rises
      const aWin = seg(0.42, 0.68, p); // windows light (trails building)
      const a5   = seg(0.72, 0.92, p); // CTA — leaves building fully visible 0.60–0.72

      // CSS custom properties
      el.style.setProperty("--p",        p.toFixed(4));
      el.style.setProperty("--a1",       a1.toFixed(4));
      el.style.setProperty("--a2",       a2.toFixed(4));
      el.style.setProperty("--a3",       a3.toFixed(4));
      el.style.setProperty("--a5",       a5.toFixed(4));
      el.style.setProperty("--sub-op",   clamp(clamp((a1-0.85)/0.15) * clamp(1-a2*1.6)).toFixed(4));
      el.style.setProperty("--hint-op",  clamp(clamp((a1-0.9)/0.1)   * clamp(1-a2*2)).toFixed(4));
      el.style.setProperty("--title-op", clamp(1-a5*0.4).toFixed(4));
      el.style.setProperty("--act3-op",  clamp(a3*1.2-a5).toFixed(4));
      el.style.setProperty("--lines-op", clamp(a2*1.2).toFixed(4));
      el.style.setProperty("--act5-stop",`${(100 - 70*a5).toFixed(1)}%`);

      // Text / pointer-events DOM updates
      if (revRef.current)
        revRef.current.textContent = `REV ${(27+Math.floor(p*9)).toString().padStart(2,"0")}`;
      if (scrollPctRef.current)
        scrollPctRef.current.textContent = `● SCROLL · ${Math.round(p*100)}%`;
      if (progressDotRef.current)
        progressDotRef.current.style.top = `${p*100}%`;
      if (act5Ref.current)
        act5Ref.current.style.pointerEvents = a5 > 0.4 ? "auto" : "none";

      // Per-card transforms
      lineCardRefs.current.forEach((card, i) => {
        if (!card) return;
        const local = clamp((a2 - i*0.05) / 0.6);
        card.style.transform = `translateX(${((i%2===0?-600:600)*(1-local)).toFixed(1)}px) translateY(${(-160*a3).toFixed(1)}px)`;
        card.style.opacity   = (clamp(local) * Math.max(0, 1-a3*1.5)).toFixed(3);
      });

      // SVG window fills
      const W = windowRectsRef.current;
      const towers = [
        { s:0,   n:52, t:aWin*52  },
        { s:52,  n:48, t:aWin*48  },
        { s:100, n:50, t:aWin*50  },
        { s:150, n:34, t:aWin*34  },
        { s:184, n:36, t:aWin*36  },
      ];
      towers.forEach(({ s, n, t }) => {
        for (let j = 0; j < n; j++) {
          const r = W[s+j];
          if (r) r.setAttribute("fill", j < t ? "var(--accent)" : "var(--bg)");
        }
      });
    };

    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  const lines = [
    { code:"CND", label:"Conduit Pipes",   c:"var(--accent)" },
    { code:"WRC", label:"Wires & Cables",  c:"var(--ink)" },
    { code:"SWS", label:"Switchgear",      c:"var(--ink)" },
    { code:"MCB", label:"MCB & RCCB",      c:"var(--accent)" },
    { code:"CBL", label:"Cable Trays",     c:"var(--ink)" },
    { code:"ENC", label:"Earthing Solution", c:"var(--ink)" },
    { code:"ACC", label:"Accessories",     c:"var(--ink)" },
    { code:"LTG", label:"Lighting",        c:"var(--accent)" },
  ];

  const regWin = React.useCallback((el, i) => { if (el) windowRectsRef.current[i] = el; }, []);

  return (
    <section
      ref={wrapRef}
      className="hs-section"
      style={{ position:"relative", height:"400vh", background:"var(--bg)" }}>

      <style>{`
        @keyframes prismLetterIn {
          0%   { transform:translateY(110%); opacity:0; }
          60%  { opacity:1; }
          100% { transform:translateY(0);   opacity:1; }
        }
        .hs-grid {
          transform: translateY(calc(var(--p,0) * -120px));
          will-change: transform;
        }
        .hs-stamp {
          position: absolute;
          top:  calc(28% - 16% * var(--a2,0));
          left: calc(8%  -  4% * var(--a2,0));
          opacity: var(--a1,0);
          transform: rotate(calc((-8 + 4*var(--a2,0)) * 1deg))
                     scale(calc(0.6 + 0.4*var(--a1,0)));
          will-change: transform, opacity;
        }
        .hs-title-wrap {
          transform: scale(calc(1 - 0.68*var(--a2,0)))
                     translateY(calc(-260px * var(--a2,0)));
          transform-origin: center center;
          opacity: var(--title-op,1);
          will-change: transform, opacity;
        }
        .hs-eyebrow { opacity: var(--a1,0); }
        .hs-sub {
          opacity:   var(--sub-op,0);
          transform: translateY(calc(20px * (1 - clamp(0, calc((var(--a1,0)-0.85)/0.15), 1))));
          will-change: transform, opacity;
        }
        .hs-hint { opacity: var(--hint-op,0); }
        .hs-lines { opacity: var(--lines-op,0); }
        .hs-act3 { opacity: var(--act3-op,0); }
        .hs-building {
          transform: translateY(calc((1 - var(--a3,0)) * 460px));
          will-change: transform;
        }
        .hs-annot { opacity: clamp(0, calc((var(--a3,0)-0.5)/0.5), 1); }
        .hs-power  { stroke-dashoffset: calc(var(--p,0) * -200); }
        .hs-act5 {
          opacity: var(--a5,0);
          background: linear-gradient(180deg, transparent 0%, var(--bg) var(--act5-stop,100%));
          pointer-events: none;
        }
        .hs-cta {
          transform: translateY(calc(80px*(1 - var(--a5,0))));
          will-change: transform;
        }
      `}</style>

      <div className="hs-sticky" style={{ position:"sticky", top:0, height:"100vh", overflow:"hidden" }}>

        {/* Grid */}
        <div className="hs-grid" style={{
          position:"absolute", inset:0,
          backgroundImage:"linear-gradient(var(--border) 1px,transparent 1px),linear-gradient(90deg,var(--border) 1px,transparent 1px)",
          backgroundSize:"48px 48px", opacity:0.35,
        }} />

        {/* Header */}
        <div className="hs-hdr" style={{
          position:"absolute", top:0, left:0, right:0,
          padding:"14px 20px",
          display:"grid", gridTemplateColumns:"1fr 1fr 1fr 1fr 1fr",
          fontFamily:"var(--f-mono)", fontSize:10,
          letterSpacing:"0.16em", color:"var(--ink-dim)",
          borderBottom:"1px solid var(--border)",
          background:"var(--bg)", zIndex:5,
        }}>
          <span>DOC · PRS-HERO-04</span>
          <span ref={revRef} className="hs-hdr-hide">REV 27</span>
          <span className="hs-hdr-hide">SHEET 01 / 04</span>
          <span ref={scrollPctRef} style={{ color:"var(--accent)" }}>● SCROLL · 0%</span>
          <span style={{ textAlign:"right" }}>{now}</span>
        </div>

        {/* Footer */}
        <div className="hs-footer" style={{
          position:"absolute", bottom:0, left:0, right:0,
          padding:"14px 32px",
          display:"flex", justifyContent:"space-between",
          fontFamily:"var(--f-mono)", fontSize:10,
          letterSpacing:"0.16em", color:"var(--ink-soft)",
          borderTop:"1px solid var(--border)",
          background:"var(--bg)", zIndex:5,
        }}>
          <span>↓ KEEP SCROLLING</span>
          <span className="hs-footer-mid">PRISM SALES CORPORATION · AHMEDABAD · EST. 2020</span>
          <span>A1 · N.T.S</span>
        </div>

        {/* Progress rail — hidden on mobile */}
        <div className="hs-rail" style={{
          position:"absolute", left:22, top:"20%", bottom:"20%",
          width:1, background:"var(--border)", zIndex:5,
        }}>
          <div ref={progressDotRef} style={{
            position:"absolute", left:-3, top:"0%",
            width:7, height:7, background:"var(--accent)",
            borderRadius:0, transform:"translateY(-50%) rotate(45deg)",
          }} />
          {[0.18, 0.40, 0.60, 0.72].map((m,i) => (
            <div key={i} style={{
              position:"absolute", left:-2, top:`${m*100}%`,
              width:5, height:1, background:"var(--ink-dim)",
            }} />
          ))}
        </div>

        {/* ACT 1 — Title */}
        <div style={{
          position:"absolute", inset:0,
          display:"flex", alignItems:"center", justifyContent:"center",
          pointerEvents:"none",
        }}>
          <div className="hs-stamp" style={{
            border:"2px solid var(--accent)", color:"var(--accent)",
            padding:"8px 14px",
            fontFamily:"var(--f-mono)", fontSize:10,
            letterSpacing:"0.2em", fontWeight:700,
          }}>
            ◉ AUTHENTIC<br/>STOCK · 2020
          </div>

          <div className="hs-title-wrap" style={{ textAlign:"center" }}>
            <div className="mono hs-eyebrow" style={{
              fontSize:11, letterSpacing:"0.4em", color:"var(--ink-dim)", marginBottom:12,
            }}>
              AHMEDABAD · OGNAJ · SINCE 2020
            </div>
            <h1 style={{
              fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
              fontSize:"clamp(96px,20vw,280px)",
              lineHeight:0.82, letterSpacing:"-0.04em",
              margin:0, fontWeight:900, color:"var(--ink)", textTransform:"uppercase",
            }}>
              {["P","R","I","S","M"].map((ch,i) => (
                <span key={i} style={{
                  display:"inline-block",
                  animation:`prismLetterIn 720ms cubic-bezier(0.2,0.8,0.2,1) ${i*90}ms both`,
                }}>{ch}</span>
              ))}
            </h1>
            <div className="hs-sub" style={{
              fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
              fontSize:"clamp(20px,3vw,42px)",
              letterSpacing:"0.04em", marginTop:18, color:"var(--ink)",
            }}>
              SALES CORPORATION
              <span style={{
                background:"var(--accent)", color:"var(--bg)",
                padding:"2px 10px", marginLeft:14, fontSize:"0.7em",
              }}>EST. 2020</span>
            </div>
            <div className="mono hs-hint" style={{
              fontSize:12, color:"var(--ink-dim)", marginTop:22, letterSpacing:"0.3em",
            }}>
              ↓ SCROLL TO INSPECT
            </div>
          </div>
        </div>

        {/* ACT 2 — Product line ribbons */}
        <div className="hs-lines" style={{
          position:"absolute", top:"26%", left:0, right:0, pointerEvents:"none",
        }}>
          <div className="hs-lines-grid" style={{
            maxWidth:1100, margin:"0 auto",
            display:"grid", gridTemplateColumns:"repeat(4,1fr)",
            gap:16, padding:"0 20px",
          }}>
            {lines.map((ln,i) => (
              <div key={ln.code}
                ref={el => { lineCardRefs.current[i] = el; }}
                style={{
                  border:"1.5px solid var(--ink)",
                  background:"var(--surface,var(--bg))",
                  padding:"16px 18px", position:"relative",
                  opacity:0, willChange:"transform,opacity",
                  transform: i%2===0 ? "translateX(-600px)" : "translateX(600px)",
                }}>
                <div style={{
                  position:"absolute", top:0, left:0,
                  width:6, height:"100%", background:ln.c,
                }} />
                <div style={{ paddingLeft:12 }}>
                  <div className="mono" style={{ fontSize:9, color:"var(--ink-dim)", letterSpacing:"0.2em" }}>
                    LINE — {String(i+1).padStart(2,"0")}
                  </div>
                  <div style={{
                    fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
                    fontSize:22, lineHeight:1.1, marginTop:6, letterSpacing:"0.02em",
                  }}>
                    {ln.label}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* ACT 3 — Building */}
        <div className="hs-act3" style={{
          position:"absolute", left:0, right:0, bottom:60,
          display:"flex", justifyContent:"center", pointerEvents:"none",
        }}>
          <svg viewBox="0 0 800 460" style={{ width:"min(860px,80vw)", height:"auto" }}>
            <defs>
              <pattern id="hatchHero" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
                <line x1="0" y1="0" x2="0" y2="6" stroke="currentColor" strokeWidth="0.6" opacity="0.35"/>
              </pattern>
            </defs>

            <line x1="0" y1="440" x2="800" y2="440" stroke="var(--ink)" strokeWidth="1.2"/>
            <text x="20" y="455" fontFamily="JetBrains Mono,monospace" fontSize="9" fill="var(--ink-dim)">GROUND ↘ 0.00 m</text>

            <g className="hs-building" style={{ color:"var(--ink)" }}>
              {/* Tower 1 — 52 windows */}
              <rect x="180" y="180" width="90" height="260" fill="url(#hatchHero)" stroke="currentColor" strokeWidth="1"/>
              {Array.from({length:13}).map((_,r) => Array.from({length:4}).map((_,c) => (
                <rect key={`t1-${r}-${c}`} ref={el => regWin(el,r*4+c)}
                  x={188+c*20} y={188+r*18} width="12" height="10" fill="var(--bg)"/>
              )))}
              <line x1="225" y1="180" x2="225" y2="140" stroke="currentColor" strokeWidth="1"/>
              <circle cx="225" cy="138" r="3" fill="var(--accent)"/>

              {/* Tower 2 — 48 windows */}
              <rect x="290" y="120" width="80" height="320" fill="url(#hatchHero)" stroke="currentColor" strokeWidth="1"/>
              {Array.from({length:16}).map((_,r) => Array.from({length:3}).map((_,c) => (
                <rect key={`t2-${r}-${c}`} ref={el => regWin(el,52+r*3+c)}
                  x={300+c*22} y={128+r*19} width="14" height="11" fill="var(--bg)"/>
              )))}
              <line x1="330" y1="120" x2="330" y2="80" stroke="currentColor" strokeWidth="1"/>
              <line x1="320" y1="80" x2="340" y2="80" stroke="currentColor" strokeWidth="1"/>

              {/* Tower 3 — 50 windows */}
              <rect x="390" y="240" width="120" height="200" fill="url(#hatchHero)" stroke="currentColor" strokeWidth="1"/>
              {Array.from({length:10}).map((_,r) => Array.from({length:5}).map((_,c) => (
                <rect key={`t3-${r}-${c}`} ref={el => regWin(el,100+r*5+c)}
                  x={398+c*22} y={248+r*18} width="14" height="10" fill="var(--bg)"/>
              )))}

              {/* Tower 4 — 34 windows */}
              <rect x="530" y="100" width="60" height="340" fill="url(#hatchHero)" stroke="currentColor" strokeWidth="1"/>
              {Array.from({length:17}).map((_,r) => Array.from({length:2}).map((_,c) => (
                <rect key={`t4-${r}-${c}`} ref={el => regWin(el,150+r*2+c)}
                  x={540+c*22} y={108+r*19} width="14" height="11" fill="var(--bg)"/>
              )))}
              <line x1="560" y1="100" x2="560" y2="50" stroke="currentColor" strokeWidth="1"/>
              <circle cx="560" cy="48" r="3" fill="var(--accent)"/>

              {/* Tower 5 — 36 windows */}
              <rect x="610" y="200" width="70" height="240" fill="url(#hatchHero)" stroke="currentColor" strokeWidth="1"/>
              {Array.from({length:12}).map((_,r) => Array.from({length:3}).map((_,c) => (
                <rect key={`t5-${r}-${c}`} ref={el => regWin(el,184+r*3+c)}
                  x={618+c*20} y={208+r*18} width="12" height="10" fill="var(--bg)"/>
              )))}
            </g>

            <g style={{ color:"var(--accent)" }}>
              {[420,425,430].map((y,i) => (
                <path key={i} className="hs-power"
                  d={`M 0 ${y} Q 80 ${y-18-i*6} 160 ${y-6+i*2} T 800 ${y-6}`}
                  fill="none" stroke="currentColor" strokeWidth="0.8"
                  opacity={0.7-i*0.2} strokeDasharray="4 4"/>
              ))}
            </g>

          </svg>
        </div>

        {/* ACT 4 (was 5) — CTA */}
        <div ref={act5Ref} className="hs-act5" style={{
          position:"absolute", inset:0,
          display:"flex", alignItems:"center", justifyContent:"center",
        }}>
          <div className="hs-cta" style={{ textAlign:"center", maxWidth:760, padding:"0 32px" }}>
            <div className="mono" style={{ fontSize:11, color:"var(--accent)", letterSpacing:"0.3em", marginBottom:18 }}>
              ◉ READY WHEN YOU ARE
            </div>
            <h2 style={{
              fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
              fontSize:"clamp(48px,7vw,96px)",
              lineHeight:0.95, letterSpacing:"-0.03em",
              margin:0, color:"var(--ink)", textTransform:"uppercase",
            }}>
              Send us<br/>
              your <span style={{ background:"var(--accent)", color:"var(--bg)", padding:"0 14px" }}>BOQ.</span><br/>
              Quote by sundown.
            </h2>
            <div style={{ marginTop:38, display:"flex", gap:14, justifyContent:"center", flexWrap:"wrap" }}>
              <button className="btn btn-primary" onClick={() => setRoute("contact")}
                style={{
                  background:"var(--ink)", color:"var(--bg)", border:"none",
                  padding:"18px 32px",
                  fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
                  fontSize:14, letterSpacing:"0.16em", cursor:"pointer", textTransform:"uppercase",
                }}>
                Request Quote ↗
              </button>
              <button onClick={() => setRoute("catalog")}
                style={{
                  background:"transparent", color:"var(--ink)",
                  border:"1.5px solid var(--ink)", padding:"18px 32px",
                  fontFamily:"var(--f-display-black,'Archivo Black',sans-serif)",
                  fontSize:14, letterSpacing:"0.16em", cursor:"pointer", textTransform:"uppercase",
                }}>
                Browse Catalog →
              </button>
            </div>
            <div className="mono" style={{ fontSize:10, color:"var(--ink-dim)", marginTop:24, letterSpacing:"0.2em" }}>
              ↓ CONTINUE FOR FULL DATASHEET
            </div>
          </div>
        </div>

      </div>
    </section>
  );
}

window.HeroScroll = HeroScroll;
