// Problem section + What QTG builds (system diagram) + Modular architecture
const ProblemSection = () => {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setInView(true); io.disconnect(); } }, { threshold: 0, rootMargin: '0px 0px -10% 0px' });
    io.observe(el); return () => io.disconnect();
  }, []);
  return (
    <section className="section-pad" id="what" ref={ref}>
      <div className="container">
        <div className="section-head">
          <div>
            <div className="section-num" style={{ color: 'var(--accent)' }}>THE PROBLEM</div>
            <h2 className="mt-4">Trading businesses are scaling faster than their infrastructure.</h2>
          </div>
          <p className="lead">
            Operators run on disconnected tools — separate CRMs, risk dashboards, payout sheets, and support tickets. Every
            new product line adds another vendor, another export, another reconciliation job. QTG replaces that fragmentation
            with one connected operating environment.
          </p>
        </div>
        <div className="what-compare" style={{display:'grid', gridTemplateColumns:'1fr auto 1fr', gap:48, alignItems:'center'}}>
          <FragmentedColumn inView={inView} />
          <ArrowDivider inView={inView} />
          <div className="qtg-flow-mobile" aria-hidden="true">
            <span className="qtg-flow-stem"/>
            <span className="qtg-flow-label">QTG replaces this with<br/>one connected environment</span>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M6 13l6 6 6-6"/></svg>
          </div>
          <UnifiedColumn inView={inView} />
        </div>
      </div>
    </section>
  );
};

const FragmentedColumn = ({ inView }) => {
  const tools = [
    {n:'Spreadsheet · Payouts', t:'manual'}, {n:'Generic CRM · Traders', t:'no-trader-context'},
    {n:'Email · Risk alerts', t:'lossy'},      {n:'Vendor A · Challenges', t:'siloed'},
    {n:'Vendor B · Reporting', t:'export-only'},{n:'Slack · Support triage', t:'untracked'},
    {n:'Vendor C · KYC', t:'reconciled-by-hand'},{n:'Sheet · Affiliate splits', t:'manual'},
  ];
  return (
    <div>
      <div className="kicker" style={{marginBottom:12}}>BEFORE · FRAGMENTED STACK</div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
        {tools.map((t,i)=>{
          const baseRot = (i%3-1)*0.4;
          return (
            <div key={i} className="card qtg-frag-card" style={{
              padding:'12px 14px',
              transform:`rotate(${baseRot}deg)`,
              opacity: inView ? 1 : 0,
              transitionProperty:'opacity, transform',
              transitionDuration:'.5s',
              transitionDelay: `${i*70}ms`,
              animation: inView ? `qtgJitter${i%3} ${3.5+i*0.2}s ease-in-out ${1.2+i*0.1}s infinite` : 'none',
            }}>
              <div style={{fontSize:12.5, color:'var(--text-2)'}}>{t.n}</div>
              <div className="mono" style={{fontSize:10, color:'var(--text-4)', marginTop:4, letterSpacing:'0.05em'}}>{t.t}</div>
            </div>
          );
        })}
      </div>
      <div style={{marginTop:18, fontSize:13, color:'var(--text-3)', opacity: inView ? 1 : 0, transition:'opacity .6s ease 1.2s'}}>
        <span className="mono" style={{color:'var(--danger)', fontSize:11, letterSpacing:'0.1em', marginRight:8, animation: inView ? 'qtgFrictionPulse 2.4s ease-in-out infinite' : 'none', display:'inline-block'}}>HIGH FRICTION</span>
        Reconciliation runs nightly. Risk sees yesterday's data.
      </div>
    </div>
  );
};

const UnifiedColumn = ({ inView }) => {
  const blocks = [
    {n:'Operations', d:'Traders · Accounts · Workflows'},
    {n:'Risk',       d:'QuantSentry · Rules · Alerts'},
    {n:'Payments',   d:'Payouts · Providers · Reconciliation'},
    {n:'Automation', d:'AI agents · Triage · Reporting'},
    {n:'Analytics',  d:'BI · Dashboards · Cohorts'},
    {n:'Support',    d:'Tickets · Escalation · SLA'},
  ];
  return (
    <div>
      <div className="kicker" style={{marginBottom:12, color:'var(--accent)'}}>AFTER · QTG INFRASTRUCTURE</div>
      <div style={{position:'relative', border:'1px solid var(--line-strong)', borderRadius:14, padding:18,
        background:'linear-gradient(180deg, rgba(255,255,255,0.015), transparent)',
        boxShadow: inView ? '0 0 0 1px rgba(34,211,238,0.18), 0 0 32px rgba(34,211,238,0.08)' : 'none',
        transition:'box-shadow 1s ease 1.4s'
      }}>
        <div className="mono" style={{position:'absolute', top:-10, left:16, padding:'3px 11px',
          background:'var(--bg)', fontSize:10, color:'var(--accent)', letterSpacing:'0.14em',
          border:'1px solid color-mix(in oklab, var(--accent) 30%, transparent)', borderRadius:100, lineHeight:1,
          opacity: inView ? 1 : 0, transform: inView ? 'translateY(0)' : 'translateY(-4px)',
          transition:'opacity .5s ease 1.0s, transform .5s ease 1.0s'}}>
          ONE CONNECTED ENVIRONMENT
        </div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
          {blocks.map((b,i)=>(
            <div key={i} style={{
              padding:'12px 14px', background:'rgba(255,255,255,0.025)',
              border:'1px solid var(--line)', borderRadius:8,
              opacity: inView ? 1 : 0,
              transform: inView ? 'translateY(0)' : 'translateY(8px)',
              transition: `opacity .5s ease ${1.3+i*0.08}s, transform .5s ease ${1.3+i*0.08}s`
            }}>
              <div style={{display:'flex', alignItems:'center', gap:6}}>
                <span style={{
                  width:5, height:5, borderRadius:'50%', background:'var(--accent)',
                  boxShadow:'0 0 6px rgba(34,211,238,0.5)',
                  animation: inView ? `qtgBreathe 2.8s ease-in-out ${1.6+i*0.2}s infinite` : 'none',
                }}/>
                <span style={{fontSize:13, color:'var(--text)'}}>{b.n}</span>
              </div>
              <div className="mono" style={{fontSize:10, color:'var(--text-3)', marginTop:4, letterSpacing:'0.04em'}}>{b.d}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{marginTop:18, fontSize:13, color:'var(--text-2)', opacity: inView ? 1 : 0, transition:'opacity .6s ease 2.0s'}}>
        <span className="mono" style={{color:'var(--accent)', fontSize:11, letterSpacing:'0.1em', marginRight:8}}>REAL-TIME</span>
        Operations, Risk, and Payouts Share One Source of Truth.
      </div>
    </div>
  );
};

const ArrowDivider = ({ inView }) => {
  // Five fragmented inputs fan in from the left, converge into one glowing
  // core, and leave as a single clean stream on the right.
  const NODE = { x: 70, y: 88 };
  const ins = [
    { p: 'M2 16 C 36 16, 44 88, 70 88',  dur: 2.3, begin: 0.0,  w: 1 },
    { p: 'M2 52 C 38 52, 50 88, 70 88',  dur: 1.9, begin: 0.7,  w: 1 },
    { p: 'M2 88 L 70 88',                 dur: 1.6, begin: 0.35, w: 1.2 },
    { p: 'M2 124 C 38 124, 50 88, 70 88', dur: 2.1, begin: 1.05, w: 1 },
    { p: 'M2 160 C 36 160, 44 88, 70 88', dur: 2.5, begin: 0.45, w: 1 },
  ];
  const outPath = 'M70 88 L 150 88';
  return (
    <svg width="118" height="176" viewBox="0 0 158 176" fill="none" style={{overflow:'visible'}}>
      <defs>
        <radialGradient id="qtgCoreGrad" cx="50%" cy="50%" r="50%">
          <stop offset="0%"  stopColor="var(--accent)" stopOpacity="1"/>
          <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.7"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
      </defs>

      {/* faint base wires for every input */}
      {ins.map((s,i)=>(
        <path key={'b'+i} d={s.p} stroke="var(--line-strong)" strokeWidth={s.w}
          strokeLinecap="round" fill="none"
          strokeDasharray="160" strokeDashoffset={inView ? 0 : 160}
          style={{transition:`stroke-dashoffset .9s ease ${0.2+i*0.08}s`}}/>
      ))}

      {/* animated dashed energy flowing along each input */}
      {inView && ins.map((s,i)=>(
        <path key={'f'+i} d={s.p} stroke="var(--accent)" strokeWidth={s.w}
          strokeLinecap="round" fill="none"
          strokeDasharray="3 13"
          style={{
            animation:`qtgFlow ${s.dur}s linear ${s.begin}s infinite, qtgInGlow ${s.dur*1.6}s ease-in-out ${s.begin}s infinite`,
            filter:'drop-shadow(0 0 2px rgba(34,211,238,0.6))',
          }}/>
      ))}

      {/* travelling packets that get absorbed into the core */}
      {inView && ins.map((s,i)=>(
        <circle key={'p'+i} r={i===2?2.4:1.8} fill="var(--accent)"
          style={{filter:'drop-shadow(0 0 4px rgba(34,211,238,0.9))'}}>
          <animateMotion dur={`${s.dur}s`} repeatCount="indefinite" begin={`${s.begin}s`} path={s.p}/>
          <animate attributeName="opacity" dur={`${s.dur}s`} repeatCount="indefinite"
            begin={`${s.begin}s`} values="0;1;1;0.2" keyTimes="0;0.15;0.8;1"/>
        </circle>
      ))}

      {/* convergence core */}
      <circle cx={NODE.x} cy={NODE.y} r="16" fill="url(#qtgCoreGrad)"
        className="qtg-ring"
        style={{ opacity: inView ? 1 : 0, transition:'opacity .6s ease 1s',
          animation: inView ? 'qtgRing 2.6s ease-out 1.2s infinite' : 'none' }}/>
      <circle cx={NODE.x} cy={NODE.y} r="5.5" fill="var(--accent)"
        className="qtg-core"
        style={{ filter:'drop-shadow(0 0 8px rgba(34,211,238,0.9))',
          opacity: inView ? 1 : 0,
          transition:'opacity .5s ease .9s',
          animation: inView ? 'qtgCore 2.2s ease-in-out 1.2s infinite' : 'none' }}/>

      {/* single clean output stream */}
      <path d={outPath} stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" fill="none"
        strokeDasharray="160" strokeDashoffset={inView ? 0 : 160}
        style={{transition:'stroke-dashoffset .9s ease 1.1s', filter:'drop-shadow(0 0 3px rgba(34,211,238,0.4))'}}/>
      <path d="M142 80 L150 88 L142 96" stroke="var(--accent)" strokeWidth="1.8"
        strokeLinecap="round" strokeLinejoin="round" fill="none"
        style={{opacity: inView ? 1 : 0, transition:'opacity .4s ease 1.7s'}}/>
      {inView && (
        <>
          <path d={outPath} stroke="var(--accent)" strokeWidth="2.4" strokeLinecap="round" fill="none"
            strokeDasharray="4 18"
            style={{animation:'qtgFlowSlow 1.4s linear 1.6s infinite', filter:'drop-shadow(0 0 4px rgba(34,211,238,0.9))'}}/>
          <circle r="2.6" fill="#fff"
            style={{filter:'drop-shadow(0 0 6px rgba(34,211,238,1))'}}>
            <animateMotion dur="1.4s" repeatCount="indefinite" begin="1.6s" path={outPath}/>
            <animate attributeName="opacity" dur="1.4s" repeatCount="indefinite" begin="1.6s"
              values="0;1;1;0" keyTimes="0;0.1;0.85;1"/>
          </circle>
        </>
      )}
    </svg>
  );
};

// ===== ARCHITECTURE DIAGRAM =====
const ArchitectureSection = () => (
  <section className="section-pad" id="architecture" style={{borderTop:'1px solid var(--line)', background:'var(--bg-2)'}}>
    <div className="container">
      <div className="section-head" style={{marginBottom:30}}>
        <div>
          <div className="section-num" style={{ color: 'var(--accent)' }}>WHAT WE BUILD</div>
          <h2 className="mt-4">Modular technology that connects every layer of a trading business.</h2>
        </div>
        <p className="lead">
          Each module operates independently, or composes into the broader QTG environment. Adopt one platform today —
          the rest plug in without re-platforming.
        </p>
      </div>
      <ArchitectureDiagram />
    </div>
  </section>
);

const ArchitectureDiagram = () => {
  // Three-layer stack
  const layers = [
    {label:'CHANNELS', items:['Trader portals','Admin dashboards','Mobile apps','Partner portals','Public APIs']},
    {label:'PLATFORMS', items:['YourPropFirm','Broker Infrastructure','QuantSentry','QuantCX','TradoPay','PropTradeGroup'], accent:true},
    {label:'COMPONENTS', items:['Prop CRM','Broker CRM','Risk & Rule Engine','AI Agents','BI & Reporting','Affiliate · IB','Trading Journal','Loyalty','Competitions']},
    {label:'INFRASTRUCTURE', items:['Identity','Event bus','Audit log','Observability','Data plane','Integrations']},
  ];
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  // Hot chip per layer (rotates).
  const [hot, setHot] = React.useState(layers.map(() => -1));
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setShown(true);
          io.disconnect();
        }
      });
    }, { threshold: 0.18 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  React.useEffect(() => {
    if (!shown) return;
    // Wait until cascade settles, then start pulses.
    const startDelay = setTimeout(() => {
      const id = setInterval(() => {
        setHot(prev => prev.map((_, li) => {
          const len = layers[li].items.length;
          // ~70% chance each layer has a hot chip, otherwise -1.
          return Math.random() < 0.7 ? Math.floor(Math.random() * len) : -1;
        }));
      }, 850);
      // Stash interval id on ref so cleanup works.
      ref.current.__pulseId = id;
    }, 1500);
    return () => {
      clearTimeout(startDelay);
      if (ref.current && ref.current.__pulseId) {
        clearInterval(ref.current.__pulseId);
      }
    };
  }, [shown]);
  return (
    <div ref={ref} style={{border:'1px solid var(--line)', borderRadius:14, overflow:'hidden', background:'var(--bg)'}}>
      {layers.map((l,i)=>(
        <div key={i} style={{
          display:'grid', gridTemplateColumns:'180px 1fr',
          borderBottom: i<layers.length-1?'1px solid var(--line)':'none',
          background: l.accent?'rgba(255,255,255,0.018)':'transparent',
          opacity: shown ? 1 : 0,
          transform: shown ? 'translateY(0)' : 'translateY(8px)',
          transition: `opacity 520ms ease ${i*120}ms, transform 520ms cubic-bezier(0.22, 0.61, 0.36, 1) ${i*120}ms`,
        }}>
          <div style={{padding:'24px 22px', borderRight:'1px solid var(--line)', display:'flex', flexDirection:'column', justifyContent:'center'}}>
            <div className="kicker" style={{color: l.accent?'var(--accent)':'var(--text-3)'}}>{l.label}</div>
            
          </div>
          <div style={{padding:'20px 22px', display:'flex', flexWrap:'wrap', gap:10, alignItems:'center'}}>
            {l.items.map((it,j)=>{
              const isHot = hot[i] === j;
              const baseBorder = l.accent?'var(--line-stronger)':'var(--line)';
              const baseBg = l.accent?'rgba(255,255,255,0.025)':'transparent';
              const baseColor = l.accent?'var(--text)':'var(--text-2)';
              const dotBase = l.accent?'var(--accent)':'var(--text-4)';
              return (
              <div key={j} style={{
                padding:'10px 14px',
                border:'1px solid ' + (isHot ? 'rgba(0,255,255,0.55)' : baseBorder),
                borderRadius:8,
                background: isHot ? 'rgba(0,255,255,0.08)' : baseBg,
                fontSize:13,
                color: isHot ? 'var(--accent)' : baseColor,
                display:'flex', alignItems:'center', gap:8,
                boxShadow: isHot ? '0 0 0 3px rgba(0,255,255,0.10)' : 'none',
                opacity: shown ? 1 : 0,
                transform: shown ? 'translateY(0)' : 'translateY(6px)',
                transition: `
                  opacity 380ms ease ${i*120 + j*40 + 200}ms,
                  transform 380ms cubic-bezier(0.22, 0.61, 0.36, 1) ${i*120 + j*40 + 200}ms,
                  border-color 360ms ease,
                  background 360ms ease,
                  color 360ms ease,
                  box-shadow 360ms ease
                `,
              }}>
                <span style={{
                  width:5, height:5, borderRadius:'50%',
                  background: isHot ? 'var(--accent)' : dotBase,
                  boxShadow: isHot ? '0 0 0 3px rgba(0,255,255,0.18)' : 'none',
                  transition:'box-shadow 360ms ease, background 360ms ease',
                }}/>
                {it}
              </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
};

Object.assign(window, { ProblemSection, ArchitectureSection });
