/* What BODE Does — v2's 3-column grid restored.
   Vizs render on a "screen" panel (always dark) inside each card,
   so the rich visualisations read in either light or dark mode. */

function VizIntegration() {
  return (
    <svg viewBox="0 0 320 220" style={{ width: '100%', height: '100%' }}>
      <defs>
        <radialGradient id="hub-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#E8513A" stopOpacity="0.35" />
          <stop offset="100%" stopColor="#E8513A" stopOpacity="0" />
        </radialGradient>
      </defs>
      {[0,1,2,3,4,5].map(i => {
        const y = 30 + i * 28;
        return (
          <g key={i}>
            <rect x="20" y={y - 8} width="60" height="16" fill="none" stroke="rgba(243,246,247,0.5)" strokeWidth="0.6" />
            <line x1="80" y1={y} x2="180" y2="110" stroke="#E8513A" strokeWidth="0.6" opacity="0.7">
              <animate attributeName="stroke-dasharray" values="0 220;120 100;220 0" dur="3.4s" repeatCount="indefinite" begin={`${i * 0.3}s`} />
            </line>
          </g>
        );
      })}
      <circle cx="180" cy="110" r="32" fill="url(#hub-glow)" />
      <circle cx="180" cy="110" r="12" fill="#E8513A" />
      <text x="180" y="113" textAnchor="middle" fontFamily="Host Grotesk" fontWeight="800" fontSize="9" fill="#fff">B</text>
      <line x1="192" y1="110" x2="280" y2="110" stroke="rgba(243,246,247,0.6)" strokeWidth="0.6" />
      <rect x="280" y="100" width="20" height="20" fill="rgba(243,246,247,0.85)" />
      <text x="290" y="135" textAnchor="middle" fontFamily="Space Mono, monospace" fontSize="8" letterSpacing="1.5" fill="#E8513A">UNIFIED</text>
    </svg>
  );
}

function VizInstant() {
  const [t, setT] = React.useState('');
  const [showAnswer, setShowAnswer] = React.useState(false);
  const target = "What is occupancy by region?";
  React.useEffect(() => {
    let i = 0; let cancelled = false;
    function step() {
      if (cancelled) return;
      i = (i + 1) % (target.length + 30);
      setT(target.slice(0, Math.min(i, target.length)));
      setShowAnswer(i > target.length + 4);
      setTimeout(step, 70);
    }
    step();
    return () => { cancelled = true; };
  }, []);
  return (
    <div style={{ padding: 18, height: '100%', display: 'flex', flexDirection: 'column', gap: 8, justifyContent: 'center' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: '#E8513A' }}>QUERY · 12:42:08</div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 300, fontSize: 15, letterSpacing: '-0.005em', minHeight: 30, color: 'rgba(243,246,247,0.95)' }}>
        {t}<span style={{ display: 'inline-block', width: 5, height: '1em', background: '#E8513A', verticalAlign: '-0.15em', marginLeft: 2, animation: 'caret 0.9s steps(1) infinite' }}></span>
      </div>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', height: 12, opacity: showAnswer ? 0 : 1, transition: 'opacity 0.3s' }}>
        {[0,1,2].map(i => (
          <span key={i} style={{ width: 5, height: 5, borderRadius: '50%', background: '#E8513A', animation: `pulse 1.2s ease-in-out ${i*0.18}s infinite` }} />
        ))}
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '0.14em', color: 'rgba(243,246,247,0.5)', marginLeft: 6 }}>QUERYING 7 SOURCES</span>
      </div>
      <div style={{ opacity: showAnswer ? 1 : 0, transition: 'opacity 0.5s' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: 'rgba(243,246,247,0.5)', marginBottom: 6 }}>RESPONSE · 2.3S</div>
        <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height: 36 }}>
          {[40, 70, 92, 55, 78, 50, 32].map((h, i) => (
            <div key={i} style={{
              flex: 1, height: showAnswer ? `${h}%` : '0%',
              background: i === 2 ? '#E8513A' : 'rgba(243,246,247,0.7)',
              transition: `height 0.6s cubic-bezier(0.34,1.56,0.64,1) ${i * 0.06 + 0.1}s`,
            }} />
          ))}
        </div>
      </div>
    </div>
  );
}

function VizStrategic() {
  return (
    <svg viewBox="0 0 320 220" style={{ width: '100%', height: '100%' }}>
      {Array.from({length: 60}).map((_, i) => {
        const x = (i % 12) * 25 + 14;
        const y = Math.floor(i / 12) * 22 + 30;
        return <circle key={i} cx={x} cy={y} r="1.4" fill="rgba(243,246,247,0.55)" opacity={0.3 + (i % 3) * 0.15} />;
      })}
      <path d="M 14 170 Q 80 140, 140 110 T 304 60" stroke="#E8513A" strokeWidth="2" fill="none">
        <animate attributeName="stroke-dasharray" values="0 500;500 0;500 500" dur="3.2s" repeatCount="indefinite" />
      </path>
      <circle cx="304" cy="60" r="5" fill="#E8513A">
        <animate attributeName="r" values="5;7;5" dur="1.8s" repeatCount="indefinite" />
      </circle>
      <text x="14" y="200" fontFamily="Space Mono, monospace" fontSize="9" letterSpacing="1.5" fill="rgba(243,246,247,0.6)">OPERATIONAL DATA</text>
      <text x="200" y="48" fontFamily="Space Mono, monospace" fontSize="9" letterSpacing="1.5" fill="#E8513A">→ STRATEGIC INSIGHT</text>
    </svg>
  );
}

function VizRoles() {
  const roles = [
    { r: "Operator", k: "Daily ops" },
    { r: "Analyst", k: "Trend signals" },
    { r: "Director", k: "Portfolio view" },
    { r: "Investor", k: "Returns clarity" },
  ];
  return (
    <div style={{ padding: 18, height: '100%', display: 'flex', flexDirection: 'column', gap: 6, justifyContent: 'center' }}>
      {roles.map((r, i) => (
        <div key={r.r} style={{
          display: 'grid', gridTemplateColumns: '24px 1fr auto', alignItems: 'center', gap: 12,
          padding: '8px 12px',
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 4,
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
          color: 'rgba(243,246,247,0.92)',
          transform: `translateX(${i * 5}px)`,
          animation: `slideIn 0.6s ease ${i * 0.1}s both`,
        }}>
          <span style={{ color: '#E8513A' }}>{String(i+1).padStart(2,'0')}</span>
          <span>{r.r}</span>
          <span style={{ color: 'rgba(243,246,247,0.5)', textTransform: 'none', letterSpacing: '0.04em' }}>{r.k}</span>
        </div>
      ))}
      <style>{`@keyframes slideIn { from { opacity:0; transform: translateX(-12px); } to { opacity: 1; } }`}</style>
    </div>
  );
}

function VizNoRip() {
  return (
    <svg viewBox="0 0 320 220" style={{ width: '100%', height: '100%' }}>
      {[0,1,2,3,4].map(i => (
        <g key={i}>
          <rect x={20 + i * 56} y="150" width="48" height="48" fill="rgba(243,246,247,0.85)" opacity={0.14 + i * 0.04} />
          <text x={44 + i * 56} y="178" textAnchor="middle" fontFamily="Space Mono, monospace" fontSize="8" fill="rgba(243,246,247,0.7)">
            {['PMS','FIN','ENR','CRM','CX'][i]}
          </text>
        </g>
      ))}
      <text x="20" y="218" fontFamily="Space Mono, monospace" fontSize="8" letterSpacing="1.5" fill="rgba(243,246,247,0.5)">EXISTING STACK · UNTOUCHED</text>
      {[0,1,2,3,4].map(i => (
        <line key={i} x1={44 + i * 56} y1="150" x2={160} y2="80" stroke="#E8513A" strokeWidth="0.5" opacity="0.5" strokeDasharray="2 3">
          <animate attributeName="stroke-dashoffset" values="0;-10" dur="2s" repeatCount="indefinite" />
        </line>
      ))}
      <rect x="80" y="40" width="160" height="48" fill="#E8513A" />
      <text x="160" y="73" fontFamily="Host Grotesk" fontWeight="800" fontSize="22" textAnchor="middle" fill="#fff" letterSpacing="-0.02em">BODE</text>
      <text x="160" y="20" fontFamily="Space Mono, monospace" fontSize="8" letterSpacing="1.5" fill="#E8513A" textAnchor="middle">INTELLIGENCE LAYER · NEW</text>
    </svg>
  );
}

function VizSector() {
  const sectors = ["PBSA", "BTR", "RETAIL", "HOSPITALITY", "UTILITIES", "FS"];
  return (
    <div style={{ padding: 18, height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 2 }}>
      {sectors.map((s, i) => (
        <div key={s} style={{
          fontFamily: 'var(--font-display)', fontWeight: 800,
          fontSize: 18, letterSpacing: '-0.02em', lineHeight: 1.05,
          animation: `pulseColor 7s ease-in-out ${i * 0.5}s infinite`,
        }}>{s}</div>
      ))}
      <style>{`
        @keyframes pulseColor {
          0%, 100% { color: rgba(243,246,247,0.4); }
          50% { color: #E8513A; }
        }
      `}</style>
    </div>
  );
}

const CAPS = [
  { num: "01", title: "Cross-System Integration", body: "Every operational and commercial platform you already run, threaded into a single unified intelligence layer. No more siloed reporting or manual reconciliation.", Viz: VizIntegration },
  { num: "02", title: "Instant Insight on Demand", body: "Ask any question about your business and receive integrated answers in seconds, drawn from all your data sources simultaneously. What once took weeks of manual work, delivered instantly.", Viz: VizInstant },
  { num: "03", title: "Operational to Strategic", body: "Turn day-to-day operational data into forward-looking strategic intelligence. Spot patterns others miss, connect dots across your portfolio, and drive commercial outcomes with clarity.", Viz: VizStrategic },
  { num: "04", title: "Built for Every Role", body: "From the operator on the ground to the investor in the boardroom, BODE brings the voice of the user and the voice of the investor into one coherent platform, accessible to all.", Viz: VizRoles },
  { num: "05", title: "No Rip-and-Replace", body: "No migration, no re-platforming, no months-long rollout. Protect your current technology investments while gaining the intelligence layer your portfolio has always needed.", Viz: VizNoRip },
  { num: "06", title: "Sector-Native Intelligence", body: "Purpose-built for real estate: PBSA, BTR, retail, hospitality, utilities, financial services. BODE understands the language, data structures, and decisions that matter to your business.", Viz: VizSector },
];

function WhatBodeDoes() {
  const gridRef = React.useRef(null);

  React.useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const grid = gridRef.current;
    if (!grid) return;

    const cards = Array.from(grid.querySelectorAll('.cap'));
    if (!cards.length) return;

    // Pre-state: cards start lower, faded, slightly scaled down.
    gsap.set(cards, { opacity: 0, y: 36, scale: 0.985 });
    cards.forEach((card) => {
      gsap.set(card.querySelectorAll('.br'),       { opacity: 0, scale: 0.4, transformOrigin: 'center center' });
      gsap.set(card.querySelector('.cap__num'),    { opacity: 0, y: 8 });
      gsap.set(card.querySelector('.cap__viz'),    { opacity: 0, y: 14, scale: 0.97 });
      gsap.set(card.querySelector('.cap__title'),  { opacity: 0, y: 12 });
      gsap.set(card.querySelector('.cap__body'),   { opacity: 0, y: 10 });
    });

    // ScrollTrigger.batch staggers cards as they enter — row-by-row feels
    // natural in a 3-col grid because the rows cross the trigger threshold
    // at slightly different scroll positions.
    const triggers = ScrollTrigger.batch(cards, {
      start: 'top 88%',
      once: true,
      onEnter: (batch) => {
        batch.forEach((card, i) => {
          const tl = gsap.timeline({ delay: i * 0.09 });
          tl.to(card, { opacity: 1, y: 0, scale: 1, duration: 0.75, ease: 'expo.out' }, 0)
            .to(card.querySelectorAll('.br'),     { opacity: 0.45, scale: 1, duration: 0.45, stagger: 0.04, ease: 'back.out(2)' }, 0.1)
            .to(card.querySelector('.cap__num'),   { opacity: 1, y: 0, duration: 0.4, ease: 'power2.out' }, 0.18)
            .to(card.querySelector('.cap__viz'),   { opacity: 1, y: 0, scale: 1, duration: 0.6, ease: 'expo.out' }, 0.28)
            .to(card.querySelector('.cap__title'), { opacity: 1, y: 0, duration: 0.5, ease: 'expo.out' }, 0.42)
            .to(card.querySelector('.cap__body'),  { opacity: 1, y: 0, duration: 0.5, ease: 'expo.out' }, 0.5);
        });
      },
    });

    return () => triggers.forEach((t) => t.kill());
  }, []);

  return (
    <section id="capabilities" className="section what-bode-does" data-screen-label="03 What BODE does">
      <div className="container">
        <div className="section-head">
          <div className="section-head__num reveal">
            03<span className="small">WHAT BODE DOES</span>
          </div>
          <div>
            <h2 className="section-head__title reveal">The only<br/>intelligence<br/>layer<span className="bode-stop"></span></h2>
            <p className="section-head__intro reveal">BODE is the integration layer your stack has been waiting for. Sitting above the tools you already run, turning what they each see into one picture, accessible to every person in your organisation.</p>
          </div>
        </div>
        <div className="capabilities" ref={gridRef}>
          {CAPS.map((c) => {
            const V = c.Viz;
            return (
              <div className="cap" key={c.num}>
                <span className="br tl"></span><span className="br tr"></span>
                <span className="br bl"></span><span className="br br_"></span>
                <div className="cap__num"><span className="n">{c.num}</span> · CAPABILITY</div>
                <div className="cap__viz cap__viz--screen"><V /></div>
                <h3 className="cap__title">{c.title}</h3>
                <p className="cap__body">{c.body}</p>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.WhatBodeDoes = WhatBodeDoes;
