// hero.jsx — Hero section with three variants: before/after slider, constellation, single shot.

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

// ─────────────────────────────────────────────────────────────────────────────
// SplitText — wrap any inline label to get the per-character "slide up + replace
// from below" hover animation. CSS handles the transform; this stacks two
// copies of each char and adds a per-char transition-delay for the stagger.
// The hover trigger is in the *parent* (.cta-pill, .btn, .card-link), not on
// SplitText itself.
function extractText(node) {
  if (node == null || typeof node === 'boolean') return '';
  if (typeof node === 'string' || typeof node === 'number') return String(node);
  if (Array.isArray(node)) return node.map(extractText).join('');
  if (node.props && node.props.children !== undefined) return extractText(node.props.children);
  return '';
}

function SplitText({ children, stagger = 0.018 }) {
  const text = extractText(children);
  const chars = [...text];
  return (
    <span className="split-text" aria-label={text}>
      {chars.map((c, i) => {
        const display = c === ' ' ? '\u00A0' : c;
        return (
          <span key={i} className="split-text-char" aria-hidden="true">
            <span className="split-text-inner" style={{ transitionDelay: `${i * stagger}s` }}>
              <span className="split-text-line">{display}</span>
              <span className="split-text-line">{display}</span>
            </span>
          </span>
        );
      })}
    </span>
  );
}
window.SplitText = SplitText;

// ─────────────────────────────────────────────────────────────────────────────
// Stylized venue illustrations (SVG). Used as fallbacks in before/after.
// ─────────────────────────────────────────────────────────────────────────────

function EmptyVenueIllustration() {
  // School cafeteria / theater — empty, fluorescent, folding chairs
  return (
    <svg viewBox="0 0 1200 720" preserveAspectRatio="xMidYMid slice" style={{width: '100%', height: '100%', display: 'block'}}>
      <defs>
        <linearGradient id="emptyBg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#5a5d62" />
          <stop offset="100%" stopColor="#2c2e32" />
        </linearGradient>
        <linearGradient id="floorGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#3a3c40" />
          <stop offset="100%" stopColor="#1d1e21" />
        </linearGradient>
        <pattern id="floorTile" width="60" height="60" patternUnits="userSpaceOnUse">
          <rect width="60" height="60" fill="url(#floorGrad)" />
          <line x1="0" y1="0" x2="60" y2="0" stroke="#1a1a1c" strokeWidth="0.5" />
          <line x1="0" y1="0" x2="0" y2="60" stroke="#1a1a1c" strokeWidth="0.5" />
        </pattern>
      </defs>
      {/* Back wall + ceiling */}
      <rect x="0" y="0" width="1200" height="380" fill="url(#emptyBg)" />
      {/* Floor with perspective */}
      <polygon points="0,380 1200,380 1200,720 0,720" fill="url(#floorTile)" />

      {/* Ceiling fluorescent lights */}
      {[160, 360, 560, 760, 960].map(x => (
        <g key={x}>
          <rect x={x} y="40" width="80" height="14" fill="#cfd2d6" opacity="0.85" />
          <rect x={x} y="40" width="80" height="3" fill="#fff" opacity="0.9" />
        </g>
      ))}

      {/* Back wall — basketball hoop hint */}
      <rect x="540" y="180" width="120" height="80" fill="none" stroke="#4a4d52" strokeWidth="2" />
      <line x1="600" y1="180" x2="600" y2="260" stroke="#4a4d52" strokeWidth="1.5" />
      <circle cx="600" cy="285" r="22" fill="none" stroke="#6a4a2a" strokeWidth="2.5" />

      {/* Side wall — door + EXIT sign hint */}
      <rect x="60" y="220" width="100" height="160" fill="#1f2125" />
      <rect x="60" y="220" width="100" height="22" fill="#7a3a1a" opacity="0.5" />

      {/* Folding chairs scattered — stylized */}
      <g fill="#4a4d52" stroke="#1a1a1c" strokeWidth="0.5">
        {[
          [180, 480], [260, 510], [340, 490], [420, 530], [500, 500],
          [580, 540], [660, 510], [740, 540], [820, 510], [900, 540],
          [220, 580], [340, 600], [460, 600], [580, 620], [700, 600], [820, 620], [940, 600],
          [140, 660], [280, 680], [420, 670], [560, 680], [700, 670], [840, 680], [980, 670],
        ].map(([x, y], i) => (
          <g key={i} transform={`translate(${x},${y}) rotate(${(i % 7) * 8 - 28})`}>
            <rect x="-12" y="-10" width="24" height="4" />
            <rect x="-10" y="-6" width="20" height="14" />
            <line x1="-8" y1="8" x2="-8" y2="20" stroke="#1a1a1c" strokeWidth="1" />
            <line x1="8" y1="8" x2="8" y2="20" stroke="#1a1a1c" strokeWidth="1" />
          </g>
        ))}
      </g>

      {/* Stacked chairs in corner */}
      <g fill="#3a3c40" stroke="#1a1a1c" strokeWidth="0.5">
        <rect x="1040" y="500" width="80" height="180" rx="2" />
        <line x1="1040" y1="520" x2="1120" y2="520" />
        <line x1="1040" y1="540" x2="1120" y2="540" />
        <line x1="1040" y1="560" x2="1120" y2="560" />
        <line x1="1040" y1="580" x2="1120" y2="580" />
        <line x1="1040" y1="600" x2="1120" y2="600" />
        <line x1="1040" y1="620" x2="1120" y2="620" />
        <line x1="1040" y1="640" x2="1120" y2="640" />
      </g>

      {/* Trash bin */}
      <rect x="980" y="380" width="40" height="80" fill="#2a2c30" rx="2" />
      <rect x="976" y="378" width="48" height="6" fill="#3a3c40" rx="1" />

      {/* Cones */}
      <polygon points="120,720 130,640 110,640" fill="#a05028" />
      <polygon points="105,720 115,680 95,680" fill="#a05028" opacity="0.7" />
    </svg>
  );
}

function DeployedVenueIllustration() {
  // Same venue — deployed with stage, lighting, signage, kids check-in
  return (
    <svg viewBox="0 0 1200 720" preserveAspectRatio="xMidYMid slice" style={{width: '100%', height: '100%', display: 'block'}}>
      <defs>
        <linearGradient id="deployedBg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#1a1417" />
          <stop offset="60%" stopColor="#0e0a0c" />
          <stop offset="100%" stopColor="#070506" />
        </linearGradient>
        <linearGradient id="stageGlow" x1="0.5" y1="0" x2="0.5" y2="1">
          <stop offset="0%" stopColor="#fd7b03" stopOpacity="0.35" />
          <stop offset="100%" stopColor="#fd7b03" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="floorWarm" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#262022" />
          <stop offset="100%" stopColor="#0a0809" />
        </linearGradient>
      </defs>

      <rect x="0" y="0" width="1200" height="380" fill="url(#deployedBg)" />
      <rect x="0" y="380" width="1200" height="340" fill="url(#floorWarm)" />

      {/* Stage glow */}
      <ellipse cx="600" cy="380" rx="500" ry="180" fill="url(#stageGlow)" />

      {/* Lighting truss across the top */}
      <line x1="180" y1="60" x2="1020" y2="60" stroke="#4a4a4a" strokeWidth="3" />
      <line x1="180" y1="80" x2="1020" y2="80" stroke="#3a3a3a" strokeWidth="3" />
      {[220, 320, 420, 520, 620, 720, 820, 920].map(x => (
        <line key={x} x1={x} y1="60" x2={x} y2="80" stroke="#3a3a3a" strokeWidth="2" />
      ))}
      {/* Hanging lights */}
      {[
        {x: 260, color: '#ffd9a8'}, {x: 360, color: '#ffe0b5'},
        {x: 460, color: '#fd7b03'}, {x: 560, color: '#ffd9a8'},
        {x: 640, color: '#ffd9a8'}, {x: 740, color: '#fd7b03'},
        {x: 840, color: '#ffe0b5'}, {x: 940, color: '#ffd9a8'},
      ].map((l, i) => (
        <g key={i}>
          <rect x={l.x - 8} y="78" width="16" height="20" fill="#1a1a1a" />
          <ellipse cx={l.x} cy="120" rx="80" ry="60" fill={l.color} opacity="0.18" />
          <circle cx={l.x} cy="100" r="3" fill={l.color} />
        </g>
      ))}

      {/* Stage platform */}
      <rect x="380" y="330" width="440" height="80" fill="#1a1416" stroke="#2a2225" strokeWidth="1" />
      <rect x="380" y="330" width="440" height="6" fill="#3a2f33" />

      {/* Stage backdrop — branded panel */}
      <rect x="420" y="160" width="360" height="180" fill="#0a0708" stroke="#2a2225" strokeWidth="1" />
      <text x="600" y="240" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="34" fontWeight="700" fill="#fff" letterSpacing="-0.02em">CALVARY</text>
      <text x="600" y="276" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="34" fontWeight="700" fill="#fff" letterSpacing="-0.02em">FORGE</text>
      <line x1="490" y1="298" x2="710" y2="298" stroke="#fd7b03" strokeWidth="2" />
      <text x="600" y="318" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="11" fill="#aaa" letterSpacing="0.1em">EST. 2024 · CHICAGO IL</text>

      {/* Stage instruments — drums, mic stands */}
      <g fill="#2a2225" stroke="#4a3a3f" strokeWidth="1">
        <circle cx="700" cy="370" r="22" />
        <circle cx="700" cy="370" r="16" fill="#1a1416" />
        <rect x="730" y="350" width="14" height="36" />
        <rect x="660" y="360" width="3" height="26" />
        <circle cx="661" cy="356" r="4" fill="#3a2f33" />
      </g>
      <g stroke="#fd7b03" strokeWidth="2" fill="none">
        <line x1="500" y1="350" x2="500" y2="395" />
        <circle cx="500" cy="346" r="4" fill="#fd7b03" />
      </g>
      <g stroke="#5a4a4f" strokeWidth="2" fill="none">
        <line x1="560" y1="350" x2="560" y2="395" />
        <circle cx="560" cy="346" r="3" fill="#3a2f33" />
      </g>

      {/* Front of house — silhouettes of people */}
      <g fill="#0a0708" opacity="0.85">
        {[
          [120, 540], [180, 530], [240, 545], [300, 535], [360, 545],
          [840, 540], [900, 530], [960, 545], [1020, 535], [1080, 545],
          [160, 600], [220, 605], [280, 595], [340, 605], [400, 600],
          [800, 600], [860, 605], [920, 595], [980, 605], [1040, 600],
        ].map(([x, y], i) => (
          <g key={i} transform={`translate(${x},${y})`}>
            <circle cx="0" cy="-20" r="12" />
            <rect x="-14" y="-10" width="28" height="40" rx="6" />
          </g>
        ))}
      </g>

      {/* Side: lobby signage / kids check-in column */}
      <g>
        <rect x="50" y="180" width="14" height="280" fill="#2a2225" />
        <rect x="40" y="180" width="34" height="60" fill="#fd7b03" />
        <text x="57" y="218" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="14" fontWeight="700" fill="#fff">K</text>
        <rect x="40" y="250" width="34" height="60" fill="#fff" />
        <line x1="48" y1="262" x2="66" y2="262" stroke="#020108" strokeWidth="1.5" />
        <line x1="48" y1="270" x2="66" y2="270" stroke="#020108" strokeWidth="1.5" />
        <line x1="48" y1="278" x2="60" y2="278" stroke="#020108" strokeWidth="1.5" />
      </g>

      {/* Right column: branded directional sign */}
      <g>
        <rect x="1130" y="200" width="14" height="260" fill="#2a2225" />
        <rect x="1120" y="200" width="34" height="50" fill="#fff" />
        <text x="1137" y="232" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="13" fontWeight="700" fill="#020108">→</text>
        <rect x="1120" y="260" width="34" height="50" fill="#fff" />
        <text x="1137" y="291" textAnchor="middle" fontFamily="SF Pro Display, sans-serif" fontSize="10" fontWeight="600" fill="#020108">WORSHIP</text>
      </g>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Before/after draggable slider
// ─────────────────────────────────────────────────────────────────────────────

function BeforeAfterSlider() {
  const [pos, setPos] = useState(50);
  const ref = useRef(null);
  const dragging = useRef(false);

  const updatePos = useCallback((clientX) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const next = Math.max(2, Math.min(98, ((clientX - r.left) / r.width) * 100));
    setPos(next);
  }, []);

  useEffect(() => {
    const move = (e) => {
      if (!dragging.current) return;
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      updatePos(x);
    };
    const up = () => { dragging.current = false; document.body.style.userSelect = ''; };
    window.addEventListener('mousemove', move);
    window.addEventListener('touchmove', move, { passive: true });
    window.addEventListener('mouseup', up);
    window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchend', up);
    };
  }, [updatePos]);

  const startDrag = (e) => {
    dragging.current = true;
    document.body.style.userSelect = 'none';
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    updatePos(x);
  };

  return (
    <div
      ref={ref}
      className="beforeafter"
      style={{ '--ba-pos': pos + '%' }}
      onMouseDown={startDrag}
      onTouchStart={startDrag}
    >
      <div className="ba-side">
        <img src="hero-before.jpg" alt="Empty school gym before deployment" className="ba-photo" />
      </div>
      <div className="ba-side ba-after-wrap" style={{ clipPath: `inset(0 0 0 ${pos}%)` }}>
        <img src="hero-after.jpg" alt="Gym deployed for worship service" className="ba-photo" />
      </div>

      <span className="ba-tag before">BEFORE · 06:42 AM</span>
      <span className="ba-tag after">AFTER · 09:00 AM</span>

      <div className="ba-divider" style={{ left: pos + '%' }}></div>
      <div className="ba-handle" style={{ left: pos + '%' }}>
        <svg viewBox="0 0 24 24">
          <polyline points="9,6 3,12 9,18"></polyline>
          <polyline points="15,6 21,12 15,18"></polyline>
        </svg>
      </div>

      <div className="ba-caption">SAME ROOM · TWO HOURS APART · DRAG TO COMPARE</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Constellation hero variant — squircle orbit
// ─────────────────────────────────────────────────────────────────────────────

const constellationGradients = [
  'linear-gradient(135deg, #2c2c2c, #555)',
  'linear-gradient(140deg, #b8956f, #6d4c2a)',
  'linear-gradient(135deg, #4a4a4a, #1a1a1a)',
  'linear-gradient(135deg, #c4a484, #8b6f47)',
  'linear-gradient(135deg, #5a6f4a, #2d3a26)',
  'linear-gradient(135deg, #6b7c8a, #3a4a55)',
  'linear-gradient(135deg, #d4c5a9, #8a7a5a)',
  'linear-gradient(135deg, #7a3a1a, #fd7b03)',
];

function ConstellationHero() {
  // Eight thumbs orbiting a center
  const items = [
    { angle: -90, radius: 220, size: 150, rot: -7 },
    { angle: -45, radius: 240, size: 140, rot: 5 },
    { angle: 0,   radius: 260, size: 150, rot: -4 },
    { angle: 45,  radius: 240, size: 140, rot: 6 },
    { angle: 90,  radius: 220, size: 150, rot: -5 },
    { angle: 135, radius: 240, size: 140, rot: 4 },
    { angle: 180, radius: 260, size: 150, rot: -6 },
    { angle: 225, radius: 240, size: 140, rot: 7 },
  ];
  return (
    <div className="hero-constellation">
      <div className="constellation-thumbs">
        {items.map((it, i) => {
          const rad = (it.angle * Math.PI) / 180;
          const cx = 50 + (Math.cos(rad) * it.radius) / 12;
          const cy = 50 + (Math.sin(rad) * it.radius) / 12;
          return (
            <div
              key={i}
              className="const-thumb"
              style={{
                left: `calc(${cx}% - ${it.size/2}px)`,
                top: `calc(${cy}% - ${it.size/2}px)`,
                width: it.size, height: it.size + 20,
                transform: `rotate(${it.rot}deg)`,
                background: constellationGradients[i % constellationGradients.length],
              }}
            ></div>
          );
        })}
        <div className="const-center">
          <svg viewBox="0 0 24 24">
            <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
          </svg>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Single shot hero variant — atmospheric deployed venue
// ─────────────────────────────────────────────────────────────────────────────

function SingleHero() {
  return (
    <div className="hero-single">
      <DeployedVenueIllustration />
      <div className="ba-caption" style={{ position: 'absolute', bottom: 32, left: '50%', transform: 'translateX(-50%)' }}>
        CALVARY FORGE · SUNDAY · 09:00 AM
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Hero shell
// ─────────────────────────────────────────────────────────────────────────────

function Hero({ variant = 'beforeafter' }) {
  return (
    <section className="hero container" data-screen-label="01 Hero">
      <div className="hero-eyebrow" data-reveal data-reveal-onload style={{ '--reveal-delay': '40ms' }}>
        <p className="section-label">Arkwright Systems · for the church on the move</p>
      </div>

      <h1 className="headline hero-headline" data-reveal data-reveal-onload style={{ '--reveal-delay': '120ms' }}>
        For churches with more <br /><span className="muted">vision than building.</span>
      </h1>

      <div className="hero-bottom" data-reveal data-reveal-onload style={{ '--reveal-delay': '240ms' }}>
        <div>
          <p className="hero-subhead">
            Arkwright builds complete systems for portable ministries — design, cases, trailers, equipment, delivery, training — so your team can focus on the people Sunday morning is for.
          </p>
          <div className="hero-cta-row">
            <a className="cta-pill" href="#build"><SplitText>Build a system →</SplitText></a>
            <a className="cta-ghost" href="#how"><SplitText>See how it works →</SplitText></a>
          </div>
        </div>

        <div className="hero-meta">
          <div className="row"><strong>Drag</strong><span>to compare</span></div>
          <div className="row"><strong>Loaded in by</strong><span>06:42 AM</span></div>
          <div className="row"><strong>Service-ready by</strong><span>09:00 AM</span></div>
          <div className="row"><strong>Sunday-ready in</strong><span>4–5 months</span></div>
        </div>
      </div>

      <div className="hero-stage" data-reveal data-reveal-onload style={{ '--reveal-delay': '360ms' }}>
        {variant === 'beforeafter' && <BeforeAfterSlider />}
        {variant === 'constellation' && <ConstellationHero />}
        {variant === 'single' && <SingleHero />}
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
