/* ===========================================================
   SHARED — reveal hooks, marquee, motion-line for Pravi Way
   =========================================================== */

const { useState, useEffect, useRef, useLayoutEffect } = React;

/* IntersectionObserver-based reveal */
function useReveal(rootRef) {
  useEffect(() => {
    if (!rootRef.current) return;
    const els = rootRef.current.querySelectorAll('.reveal, .reveal-l, .reveal-r');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
        } else {
          // re-reveal on scroll up too (so navigating between pages re-plays)
          // but only if user has scrolled past again
        }
      });
    }, { threshold: 0.15, rootMargin: "0px 0px -80px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* Mouse-tracked parallax helper */
function useParallax(ref, strength = 14) {
  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    const onMove = (e) => {
      const rect = el.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const dx = (e.clientX - cx) / rect.width;
      const dy = (e.clientY - cy) / rect.height;
      el.style.setProperty('--px', `${-dx * strength}px`);
      el.style.setProperty('--py', `${-dy * strength}px`);
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, [strength]);
}

/* Marquee — duplicates children for seamless loop */
function Marquee({ children, speed = "normal", reverse = false, className = "" }) {
  return (
    <div className={`marquee ${speed === "fast" ? "fast" : speed === "slow" ? "slow" : ""} ${reverse ? "rev" : ""} ${className}`}>
      <div className="track">
        {children}
        {children}
      </div>
    </div>
  );
}

/* SVG roadmap with progress-trace tied to scroll position */
function RoadmapLine({ steps, accent = "#ea7321", lineColor = "rgba(0,0,0,0.18)", direction = "editorial" }) {
  const wrapRef = useRef(null);
  const lineRef = useRef(null);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    const onScroll = () => {
      const rect = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      // Progress 0 when top of wrap is at bottom of viewport, 1 when bottom of wrap is at top
      const total = rect.height + vh * 0.6;
      const passed = Math.min(Math.max(vh * 0.8 - rect.top, 0), total);
      setProgress(passed / total);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Determine layout: alternating left/right with center spine
  return (
    <div ref={wrapRef} className="pv-roadmap" style={{ position: "relative", padding: "40px 0" }}>
      {/* center spine */}
      <div style={{
        position: "absolute", left: "50%", top: 0, bottom: 0,
        width: 2, transform: "translateX(-50%)",
        background: lineColor,
      }} />
      <div ref={lineRef} style={{
        position: "absolute", left: "50%", top: 0,
        width: 3, transform: "translateX(-50%)",
        background: accent,
        height: `${progress * 100}%`,
        boxShadow: `0 0 12px ${accent}88`,
        transition: "height .15s linear",
      }} />

      {steps.map((s, i) => {
        const left = i % 2 === 0;
        const dotProgress = (i + 0.5) / steps.length;
        const active = progress >= dotProgress - 0.05;
        return (
          <div key={i} className="pv-step-row" style={{
            position: "relative",
            display: "grid",
            gridTemplateColumns: "1fr 90px 1fr",
            alignItems: "center",
            minHeight: 180,
            marginBottom: 30,
          }}>
            <div className={`reveal-l pv-col`} style={{ gridColumn: 1, textAlign: "right", paddingRight: 40, visibility: left ? "visible" : "hidden" }}>
              {left && <StepCard step={s} direction={direction} accent={accent} side="left" />}
            </div>
            <div className="pv-dot-col" style={{ gridColumn: 2, display: "flex", justifyContent: "center" }}>
              <div style={{
                width: 28, height: 28, borderRadius: "50%",
                background: active ? accent : "transparent",
                border: `2px solid ${accent}`,
                position: "relative", zIndex: 2,
                transition: "background .3s",
                boxShadow: active ? `0 0 0 6px ${accent}22` : "none",
              }}>
                <div style={{
                  position: "absolute", inset: -4, borderRadius: "50%",
                  border: `1px dashed ${accent}`,
                  animation: active ? "spin360 8s linear infinite" : "none",
                  opacity: active ? 1 : 0,
                }} />
              </div>
            </div>
            <div className={`reveal-r pv-col`} style={{ gridColumn: 3, paddingLeft: 40, visibility: left ? "hidden" : "visible" }}>
              {!left && <StepCard step={s} direction={direction} accent={accent} side="right" />}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function StepCard({ step, direction, accent, side }) {
  if (direction === "kinetic") {
    return (
      <div className="card" style={{ display: "inline-block", maxWidth: 440, textAlign: side === "left" ? "right" : "left" }}>
        <h3 style={{ fontFamily: 'DM Serif Display', fontWeight: 400, fontSize: 56, letterSpacing: '-0.03em', margin: '0 0 14px', color: 'var(--pravi-blue)', lineHeight: 1 }}>{step.t}</h3>
        <p style={{ fontSize: 15, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.6 }}>{step.d}</p>
      </div>
    );
  }
  if (direction === "architect") {
    return (
      <div style={{ display: "inline-block", maxWidth: 420, textAlign: side === "left" ? "right" : "left", borderTop: `2px solid ${accent}`, paddingTop: 16 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: accent, textTransform: 'uppercase' }}>STEP / {step.n}</div>
        <h3 className="mono" style={{ fontSize: 28, letterSpacing: '-0.01em', margin: '8px 0 12px', textTransform: "uppercase", color: 'var(--pravi-blue)' }}>{step.t}</h3>
        <p style={{ fontSize: 14, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.6, fontFamily: 'DM Sans' }}>{step.d}</p>
      </div>
    );
  }
  if (direction === "civic") {
    return (
      <div style={{ display: "inline-block", maxWidth: 440, textAlign: side === "left" ? "right" : "left" }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: accent, textTransform: 'uppercase' }}>· STEP {step.n} ·</div>
        <h3 style={{ fontFamily: 'Cormorant Garamond', fontWeight: 400, fontSize: 44, letterSpacing: '-0.02em', margin: '8px 0 14px', lineHeight: 1, color: 'var(--pravi-blue)' }}>{step.t}</h3>
        <p style={{ fontSize: 15.5, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.65 }}>{step.d}</p>
      </div>
    );
  }
  // editorial default
  return (
    <div style={{ display: "inline-block", maxWidth: 440, textAlign: side === "left" ? "right" : "left" }}>
      <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, letterSpacing: '0.22em', color: accent, textTransform: "uppercase" }}>Step № {step.n}</div>
      <h3 style={{ fontFamily: 'DM Serif Display', fontWeight: 400, fontSize: 56, letterSpacing: '-0.02em', margin: '8px 0 14px', lineHeight: 1, color: 'var(--pravi-blue)' }}>{step.t}</h3>
      <p style={{ fontSize: 16, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.6 }}>{step.d}</p>
    </div>
  );
}

/* Shared map block — abstract animated dotted map (brand-led) */
function MapBlock({ direction }) {
  const styles = {
    editorial: { bg: "var(--paper-deep)", ink: "var(--pravi-blue)", muted: "var(--rule)", accent: "var(--pravi-orange)" },
    kinetic:   { bg: "var(--white)",      ink: "var(--pravi-blue)", muted: "var(--rule)", accent: "var(--pravi-orange)" },
    architect: { bg: "var(--paper)",      ink: "var(--pravi-blue)", muted: "var(--rule)", accent: "var(--pravi-orange)" },
    civic:     { bg: "var(--white)",      ink: "var(--pravi-blue)", muted: "var(--rule)", accent: "var(--pravi-orange)" },
  }[direction];
  const P = window.PRAVI;
  // Generate a grid of dots
  const cols = 60, rows = 22;
  const dots = [];
  for (let y = 0; y < rows; y++) {
    for (let x = 0; x < cols; x++) {
      // make some empty zones to suggest landmass
      const dx = x - cols * 0.28;
      const dy = y - rows * 0.5;
      const r = Math.sqrt(dx * dx + dy * dy);
      if (r > 9 && Math.random() > 0.55) continue;
      dots.push({ x: x / cols, y: y / rows });
    }
  }
  return (
    <div style={{ background: styles.bg, position: "relative", padding: "100px 4vw", overflow: "hidden", borderTop: "1px solid var(--rule)" }}>
      <div className="container" style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 60, alignItems: "center", position: "relative" }}>
        <div className="reveal-l">
          <div className="section-num" style={{ color: styles.accent, marginBottom: 22 }}>SECTION · LOCATE US</div>
          <h2 style={{ fontSize: "clamp(40px, 5.4vw, 84px)", margin: 0, lineHeight: 1 }}>
            Find us in <span style={{ fontFamily: 'Italiana', color: styles.accent }}>Ahmedabad.</span>
          </h2>
          <div style={{ marginTop: 28, maxWidth: 480, fontSize: 17, color: "var(--ink-soft)", lineHeight: 1.55 }}>
            {P.brand.address}
          </div>
          <div style={{ marginTop: 32, display: "flex", flexWrap: "wrap", gap: 28, fontFamily: 'DM Mono, monospace', fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>
            <div>
              <div style={{ color: 'var(--ink-faint)' }}>EMAIL</div>
              <div style={{ marginTop: 4, fontSize: 14, textTransform: "none", letterSpacing: 0, color: 'var(--pravi-blue)', fontFamily: 'DM Sans', fontWeight: 500 }}>{P.brand.email}</div>
            </div>
            <div>
              <div style={{ color: 'var(--ink-faint)' }}>PHONE</div>
              <div style={{ marginTop: 4, fontSize: 14, letterSpacing: 0, color: 'var(--ink)', fontFamily: 'DM Sans', fontWeight: 500 }}>{P.brand.phone}</div>
            </div>
            <div>
              <div style={{ color: 'var(--ink-faint)' }}>COORDS</div>
              <div style={{ marginTop: 4, fontSize: 14, letterSpacing: 0, color: 'var(--ink)', fontFamily: 'DM Mono' }}>23.022° N · 72.571° E</div>
            </div>
          </div>
        </div>
        <div className="reveal-r" style={{ aspectRatio: "5/3", position: "relative", border: `1px solid ${styles.muted}`, overflow: "hidden", background: 'var(--paper)' }}>
          <svg viewBox="0 0 600 360" style={{ width: "100%", height: "100%", display: "block" }}>
            {dots.map((d, i) => (
              <circle key={i} cx={d.x * 600} cy={d.y * 360} r={1.4} fill={styles.ink} opacity={0.45} />
            ))}
            {/* office pin */}
            <g transform="translate(170, 160)">
              <circle r="18" fill={styles.accent} opacity="0.22">
                <animate attributeName="r" values="18;38;18" dur="2.6s" repeatCount="indefinite" />
                <animate attributeName="opacity" values="0.4;0;0.4" dur="2.6s" repeatCount="indefinite" />
              </circle>
              <circle r="7" fill={styles.accent} />
              <line x1="0" y1="0" x2="58" y2="-30" stroke={styles.accent} strokeWidth="1" strokeDasharray="3 3" />
            </g>
            <g transform="translate(228, 130)" fontFamily="DM Mono" fontSize="11" fill={styles.ink}>
              <text x="0" y="0" fontWeight="600">▸ AHMEDABAD</text>
              <text x="0" y="14" opacity="0.6" fontSize="9.5">PRAVI HQ · 380058</text>
            </g>
            {/* a few city pings */}
            {[[440, 100, "DELHI"], [490, 220, "MUMBAI"], [520, 270, "BENGALURU"]].map(([x, y, name], i) => (
              <g key={i} transform={`translate(${x}, ${y})`}>
                <circle r="3" fill={styles.ink} opacity="0.7" />
                <text x="8" y="3" fontFamily="DM Mono" fontSize="9.5" fill={styles.ink} opacity="0.65">{name}</text>
              </g>
            ))}
          </svg>
        </div>
      </div>
    </div>
  );
}

window.useReveal = useReveal;
window.useParallax = useParallax;
window.Marquee = Marquee;
window.RoadmapLine = RoadmapLine;
window.MapBlock = MapBlock;
