/* global React */
// ============================================================
// APPROACH — how Mir works. A robot walks the pipeline, activating
// each stage in sequence (Discover → Build → Ship → Scale) while
// data flows down the connector and the active stage's icon works.
// Robot + line are aligned to measured circle centers. Loops.
// ============================================================

const STEPS = [
  { n:'01', key:'discover', t:'Discover', Icon: Search, d:'We embed with your team for a focused engagement to map the workflows where AI actually pays off, and rule out the ones where it doesn\u2019t.' },
  { n:'02', key:'build',    t:'Build',    Icon: Cpu,    d:'Senior engineers and ML practitioners build the real thing on your data: model-agnostic, evaluated, and wired into your existing systems.' },
  { n:'03', key:'ship',     t:'Ship',     Icon: Zap,    d:'It goes to production, not a sandbox. We deploy where your work happens and train your people to own it.' },
  { n:'04', key:'scale',    t:'Scale',    Icon: Trend,  d:'We measure the outcome, harden what works, and grow it, sometimes into a full product, the way Cothon grew.' },
];

function PipeBot() {
  return (
    <svg width="40" height="44" viewBox="0 0 40 44" style={{display:'block', overflow:'visible'}}>
      <defs>
        <linearGradient id="pbBeam" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="rgba(239,141,136,0.55)"/>
          <stop offset="1" stopColor="rgba(239,141,136,0)"/>
        </linearGradient>
      </defs>
      <polygon className="bot-beam" points="14,26 26,26 33,44 7,44" fill="url(#pbBeam)"/>
      <rect className="bot-scan" x="9" y="27" width="22" height="2" rx="1" fill="#EF8D88"/>
      <line x1="20" y1="7" x2="20" y2="2.5" stroke="#F0EADA" strokeWidth="1.4" strokeLinecap="round"/>
      <circle className="bot-ant" cx="20" cy="2.6" r="2.4" fill="#EF8D88"/>
      <rect x="6" y="7" width="28" height="20" rx="7" fill="#F0EADA" stroke="rgba(13,43,82,0.55)" strokeWidth="1.4"/>
      <rect x="2.6" y="14" width="3.2" height="6" rx="1.6" fill="#E8A08C"/>
      <rect x="34.2" y="14" width="3.2" height="6" rx="1.6" fill="#E8A08C"/>
      <rect x="10" y="11" width="20" height="12" rx="5" fill="#0D2B52"/>
      <circle className="bot-eye" cx="15.2" cy="17" r="2.1" fill="#EF8D88"/>
      <circle className="bot-eye" cx="24.8" cy="17" r="2.1" fill="#EF8D88"/>
    </svg>
  );
}

function Approach() {
  const [ref, seen] = useInView({ threshold: 0.25 });
  const [active, setActive] = React.useState(0);
  const [moving, setMoving] = React.useState(false);
  const stepRefs = React.useRef([]);
  const [centers, setCenters] = React.useState([]);

  // Measure circle centres for pixel-perfect robot + line alignment.
  React.useLayoutEffect(() => {
    const measure = () => {
      const grid = ref.current;
      if (!grid) return;
      const gr = grid.getBoundingClientRect();
      const cs = stepRefs.current.map(el => {
        if (!el) return 0;
        const r = el.getBoundingClientRect();
        return r.left - gr.left + r.width / 2;
      });
      setCenters(cs);
    };
    measure();
    window.addEventListener('resize', measure);
    const id = setTimeout(measure, 400); // after fonts/layout settle
    return () => { window.removeEventListener('resize', measure); clearTimeout(id); };
  }, [seen]);

  React.useEffect(() => {
    if (!seen) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) { setActive(3); return; }
    let alive = true, a = 0, timer;
    setActive(0);
    const advance = () => {
      if (!alive) return;
      a += 1;
      if (a > 3) { a = 0; setActive(0); timer = setTimeout(advance, 1900); return; }
      setActive(a);
      timer = setTimeout(advance, a === 3 ? 2500 : 1700);
    };
    timer = setTimeout(advance, 1700);
    return () => { alive = false; clearTimeout(timer); };
  }, [seen]);

  // Beam fires only once the robot arrives at a stage.
  React.useEffect(() => {
    setMoving(true);
    const id = setTimeout(() => setMoving(false), 820);
    return () => clearTimeout(id);
  }, [active]);

  const measured = centers.length === 4 && centers[3] > 0;

  return (
    <Section id="approach" py={104} style={{background:'rgba(16,49,90,0.28)'}}>
      <Reveal>
        <div style={{textAlign:'center', maxWidth:760, margin:'0 auto'}}>
          <Eyebrow color="var(--cothon-coral)" mark>How we work</Eyebrow>
          <h2 style={{fontSize:'clamp(34px, 4.2vw, 56px)', fontWeight:600, letterSpacing:'-0.025em', lineHeight:1.05, margin:'16px 0 0'}}>
            From workflow to{' '}
            <span className="serif-italic" style={{color:'var(--cothon-sand)', fontWeight:400}}>production</span>, fast.
          </h2>
          <p style={{fontSize:17, color:'var(--cothon-sand)', lineHeight:1.6, margin:'18px auto 0', maxWidth:560}}>
            A senior team and a tight loop. No army of juniors, no six-month discovery deck:
            working software in front of your users in weeks.
          </p>
        </div>
      </Reveal>

      <div ref={ref} className="approach-grid" style={{position:'relative', display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:22, marginTop:72}}>
        {/* Pipeline connector — sits behind the (opaque) circles */}
        {measured && (
          <div className="approach-line" style={{
            position:'absolute', top:31, left:centers[0], width:centers[3] - centers[0],
            height:3, background:'var(--cothon-navy-border)', borderRadius:9999, overflow:'hidden', zIndex:0,
          }}>
            <div className="pipe-fill" style={{
              height:'100%', borderRadius:9999,
              width: centers[3] - centers[0] > 0 ? `${((centers[active] - centers[0]) / (centers[3] - centers[0])) * 100}%` : '0%',
              transition:'width 900ms var(--ease-out)',
            }}/>
          </div>
        )}

        {/* Robot walking the pipeline */}
        {measured && (
          <div className={`approach-robot ${moving ? 'moving' : 'working'}`} style={{
            position:'absolute', top:-46, left:centers[active],
            transform:'translateX(-50%)', transition:'left 800ms var(--ease-out)', zIndex:4, pointerEvents:'none',
          }}>
            <div className="botwrap" style={{position:'relative', animation:'botBob 2.4s ease-in-out infinite'}}>
              <PipeBot/>
              <span className="spark s1"/><span className="spark s2"/><span className="spark s3"/>
            </div>
          </div>
        )}

        {STEPS.map((s, i) => {
          const done = i < active, act = i === active;
          const accent = act ? 'var(--cothon-coral)' : done ? 'var(--cothon-mint)' : 'var(--cothon-sand)';
          return (
            <div key={s.n} ref={el => stepRefs.current[i] = el} style={{
              position:'relative', textAlign:'center',
              opacity: seen ? 1 : 0, transform: seen ? 'translateY(0)' : 'translateY(20px)',
              transition:`opacity 600ms var(--ease-out) ${i*180+300}ms, transform 600ms var(--ease-out) ${i*180+300}ms`,
            }}>
              <div style={{
                width:64, height:64, borderRadius:9999, margin:'0 auto 18px',
                display:'flex', alignItems:'center', justifyContent:'center',
                background:'var(--cothon-navy)',
                border:`1px solid ${act ? 'var(--cothon-coral)' : done ? 'rgba(163,235,177,0.6)' : 'rgba(194,178,128,0.3)'}`,
                position:'relative', zIndex:2,
                boxShadow: act
                  ? '0 0 0 7px var(--cothon-navy), 0 0 26px -2px rgba(239,141,136,0.5)'
                  : '0 0 0 7px var(--cothon-navy)',
                transform: act ? 'scale(1.09)' : 'scale(1)',
                transition:'transform 500ms var(--ease-out), border-color 500ms, box-shadow 500ms',
              }}>
                <span className="appr-icon">
                  <s.Icon size={24} color={act ? 'var(--cothon-coral)' : done ? 'var(--cothon-mint)' : 'var(--cothon-sand)'}/>
                </span>
                {act && <div className="appr-ping"/>}
                {/* completed check badge */}
                <div style={{
                  position:'absolute', right:-2, bottom:-2, width:20, height:20, borderRadius:9999,
                  background:'var(--cothon-navy)', border:'1px solid rgba(163,235,177,0.6)',
                  display:'flex', alignItems:'center', justifyContent:'center', zIndex:3,
                  opacity: done ? 1 : 0, transform: done ? 'scale(1)' : 'scale(0.5)',
                  transition:'opacity 400ms var(--ease-out), transform 400ms var(--ease-out)',
                }}>
                  <Check size={11} color="var(--cothon-mint)"/>
                </div>
              </div>
              <div style={{fontSize:11, fontFamily:'JetBrains Mono, monospace', color:accent, letterSpacing:'0.14em', marginBottom:8, transition:'color 500ms'}}>{s.n}</div>
              <h3 style={{fontSize:19, fontWeight:600, letterSpacing:'-0.01em', margin:'0 0 10px'}}>{s.t}</h3>
              <p style={{fontSize:13.5, color:'var(--cothon-sand)', lineHeight:1.6, margin:'0 auto', maxWidth:240}}>{s.d}</p>
            </div>
          );
        })}
      </div>
    </Section>
  );
}

Object.assign(window, { Approach });
