const { useState: useStateHow, useEffect: useEffectHow } = React;

const STEPS = [
  {
    n: '01',
    title: 'We train the agent on your business',
    detail: "We feed the AI everything — your menu, services, pricing, policies, FAQs, booking rules. The agent speaks with your brand's voice and only says what's true about your business.",
    visual: 'training',
  },
  {
    n: '02',
    title: 'Your calls go to the AI',
    detail: 'Plug in your existing number or get a dedicated one. Every inbound call goes straight to the agent — no ringing, no hold music, instant answer.',
    visual: 'routing',
  },
  {
    n: '03',
    title: 'AI handles the full conversation',
    detail: 'The agent greets, understands, and resolves — orders, bookings, FAQs, complaints — in a natural conversational tone. Urdu and English both supported.',
    visual: 'conversation',
  },
  {
    n: '04',
    title: 'Complex calls transfer to a human',
    detail: "If the AI hits something it can't resolve, it smoothly transfers to your team — live, in real time. No awkward handoffs, no frustrated customers.",
    visual: 'handoff',
  },
  {
    n: '05',
    title: 'Everything logs to your dashboard',
    detail: 'Every call recorded and transcribed. You see who called, what was discussed, what action was taken, and what needs follow-up. Full visibility, always.',
    visual: 'dashboard',
  },
];

function How() {
  const [active, setActive] = useStateHow(0);

  // Auto-advance
  useEffectHow(() => {
    const t = setInterval(() => setActive((a) => (a + 1) % STEPS.length), 4500);
    return () => clearInterval(t);
  }, []);

  return (
    <section id="how" style={{
      background: 'var(--ink)',
      color: 'var(--bg)',
      padding: '120px 0',
      position: 'relative',
    }}>
      <div style={{ maxWidth: 1440, margin: '0 auto', padding: '0 48px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 72 }}>
          <div>
            <div className="mono" style={{
              fontSize: 11, color: 'oklch(0.6 0.01 60)',
              letterSpacing: '0.1em', marginBottom: 16,
            }}>
              02 — HOW IT WORKS
            </div>
            <h2 style={{
              fontSize: 'clamp(40px, 4.6vw, 64px)',
              lineHeight: 1.02,
              letterSpacing: '-0.02em',
              maxWidth: 800,
            }}>
              <span className="serif">Five steps. </span>
              <span className="serif italic">Forty-eight hours.</span>
              <br/>
              <span style={{ fontWeight: 400 }}>Live on your line.</span>
            </h2>
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'oklch(0.55 0.01 60)', letterSpacing: '0.08em' }}>
            STEP {String(active + 1).padStart(2, '0')} / 05
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 80, alignItems: 'start' }}>
          {/* Steps list */}
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {STEPS.map((s, i) => (
              <button
                key={i}
                onClick={() => setActive(i)}
                style={{
                  textAlign: 'left',
                  padding: '24px 0',
                  borderTop: '1px solid oklch(0.28 0.01 60)',
                  borderBottom: i === STEPS.length - 1 ? '1px solid oklch(0.28 0.01 60)' : 'none',
                  display: 'flex', gap: 20,
                  alignItems: 'flex-start',
                  position: 'relative',
                  cursor: 'pointer',
                  transition: 'all 0.3s',
                }}
              >
                {/* progress bar on left when active */}
                <div style={{
                  position: 'absolute', left: -2, top: 0, bottom: 0,
                  width: 2,
                  background: i === active ? 'var(--accent)' : 'transparent',
                  transition: 'background 0.3s',
                }}/>
                <div className="mono" style={{
                  fontSize: 12,
                  color: i === active ? 'var(--accent)' : 'oklch(0.55 0.01 60)',
                  paddingTop: 6,
                  flexShrink: 0,
                  width: 28,
                  letterSpacing: '0.04em',
                }}>
                  {s.n}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontSize: 20,
                    fontWeight: 500,
                    color: i === active ? 'var(--bg)' : 'oklch(0.7 0.01 60)',
                    letterSpacing: '-0.01em',
                    marginBottom: i === active ? 12 : 0,
                    transition: 'all 0.3s',
                  }}>
                    {s.title}
                  </div>
                  {i === active && (
                    <div style={{
                      fontSize: 14,
                      color: 'oklch(0.75 0.01 60)',
                      lineHeight: 1.5,
                      animation: 'fadeUp 0.4s ease-out',
                    }}>
                      {s.detail}
                    </div>
                  )}
                </div>
              </button>
            ))}
          </div>

          {/* Visual */}
          <StepVisual active={active} />
        </div>
      </div>
    </section>
  );
}

function StepVisual({ active }) {
  const visuals = {
    0: <TrainingVisual />,
    1: <RoutingVisual />,
    2: <ConversationVisual />,
    3: <HandoffVisual />,
    4: <DashboardVisual />,
  };

  return (
    <div style={{
      background: 'oklch(0.22 0.01 60)',
      border: '1px solid oklch(0.28 0.01 60)',
      borderRadius: 20,
      padding: 28,
      minHeight: 460,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div key={active} style={{ animation: 'fadeUp 0.5s ease-out' }}>
        {visuals[active]}
      </div>
    </div>
  );
}

function VLabel({ children }) {
  return <div className="mono" style={{ fontSize: 10, color: 'oklch(0.6 0.01 60)', letterSpacing: '0.1em', marginBottom: 14 }}>{children}</div>;
}
function VCard({ children, style }) {
  return <div style={{ background: 'oklch(0.27 0.01 60)', border: '1px solid oklch(0.32 0.01 60)', borderRadius: 12, padding: 14, ...style }}>{children}</div>;
}

function TrainingVisual() {
  const items = [
    { label: 'menu.pdf', size: '2.4 MB', status: 'parsed' },
    { label: 'pricing.csv', size: '8 KB', status: 'parsed' },
    { label: 'faqs.txt', size: '14 KB', status: 'parsed' },
    { label: 'booking-rules.md', size: '6 KB', status: 'training' },
    { label: 'brand-voice.md', size: '3 KB', status: 'queued' },
  ];
  return (
    <>
      <VLabel>KNOWLEDGE BASE · 5 SOURCES</VLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, i) => (
          <VCard key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 32, height: 36, borderRadius: 4, background: 'oklch(0.32 0.01 60)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 1h6l3 3v9H3V1Z M9 1v3h3" stroke="oklch(0.7 0.01 60)" strokeWidth="1.2" strokeLinejoin="round"/></svg>
              </div>
              <div>
                <div className="mono" style={{ fontSize: 13, color: 'var(--bg)' }}>{it.label}</div>
                <div className="mono" style={{ fontSize: 10, color: 'oklch(0.6 0.01 60)' }}>{it.size}</div>
              </div>
            </div>
            <span className="mono" style={{
              fontSize: 10, letterSpacing: '0.08em',
              padding: '4px 8px', borderRadius: 999,
              background: it.status === 'parsed' ? 'oklch(0.94 0.05 145 / 0.15)' : it.status === 'training' ? 'oklch(0.7 0.15 50 / 0.15)' : 'oklch(0.32 0.01 60)',
              color: it.status === 'parsed' ? 'oklch(0.85 0.15 145)' : it.status === 'training' ? 'oklch(0.85 0.15 50)' : 'oklch(0.6 0.01 60)',
            }}>
              {it.status.toUpperCase()}
            </span>
          </VCard>
        ))}
      </div>
      <div style={{ marginTop: 16, padding: 14, background: 'oklch(0.94 0.05 145 / 0.08)', borderRadius: 10, border: '1px solid oklch(0.94 0.05 145 / 0.15)' }}>
        <div className="mono" style={{ fontSize: 11, color: 'oklch(0.85 0.15 145)' }}>
          ▸ Embedding 248 chunks · ETA 38s
        </div>
      </div>
    </>
  );
}

function RoutingVisual() {
  return (
    <>
      <VLabel>CALL ROUTING · LIVE</VLabel>
      <svg viewBox="0 0 480 320" style={{ width: '100%', height: 'auto' }}>
        <defs>
          <marker id="arrow" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">
            <path d="M0,0 L0,6 L9,3 z" fill="oklch(0.62 0.18 145)" />
          </marker>
        </defs>
        {/* Caller */}
        <g>
          <rect x="20" y="120" width="120" height="80" rx="10" fill="oklch(0.27 0.01 60)" stroke="oklch(0.32 0.01 60)"/>
          <text x="80" y="150" textAnchor="middle" fill="oklch(0.7 0.01 60)" fontSize="10" fontFamily="JetBrains Mono">CALLER</text>
          <text x="80" y="172" textAnchor="middle" fill="white" fontSize="13" fontFamily="JetBrains Mono">+92 312</text>
          <text x="80" y="188" textAnchor="middle" fill="white" fontSize="13" fontFamily="JetBrains Mono">456 7890</text>
        </g>
        {/* Number */}
        <g>
          <rect x="180" y="120" width="120" height="80" rx="10" fill="oklch(0.27 0.01 60)" stroke="oklch(0.62 0.18 145)" strokeDasharray="4 4">
            <animate attributeName="stroke-dashoffset" from="0" to="-16" dur="1s" repeatCount="indefinite"/>
          </rect>
          <text x="240" y="150" textAnchor="middle" fill="oklch(0.85 0.15 145)" fontSize="10" fontFamily="JetBrains Mono">YOUR NUMBER</text>
          <text x="240" y="172" textAnchor="middle" fill="white" fontSize="13" fontFamily="JetBrains Mono">021 1234</text>
          <text x="240" y="188" textAnchor="middle" fill="white" fontSize="13" fontFamily="JetBrains Mono">5678</text>
        </g>
        {/* AI */}
        <g>
          <rect x="340" y="100" width="120" height="120" rx="14" fill="oklch(0.94 0.05 145 / 0.1)" stroke="oklch(0.62 0.18 145)"/>
          <circle cx="400" cy="140" r="14" fill="oklch(0.62 0.18 145)"/>
          <text x="400" y="145" textAnchor="middle" fill="white" fontSize="11" fontFamily="JetBrains Mono" fontWeight="600">AI</text>
          <text x="400" y="180" textAnchor="middle" fill="white" fontSize="13" fontFamily="Inter" fontWeight="500">AxisAgent</text>
          <text x="400" y="198" textAnchor="middle" fill="oklch(0.7 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">PICKUP &lt; 0.4s</text>
        </g>
        {/* arrows */}
        <line x1="140" y1="160" x2="180" y2="160" stroke="oklch(0.62 0.18 145)" strokeWidth="2" markerEnd="url(#arrow)"/>
        <line x1="300" y1="160" x2="340" y2="160" stroke="oklch(0.62 0.18 145)" strokeWidth="2" markerEnd="url(#arrow)"/>

        {/* labels */}
        <text x="160" y="150" textAnchor="middle" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">DIAL</text>
        <text x="320" y="150" textAnchor="middle" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">FORWARD</text>

        {/* indicators */}
        <g>
          <circle cx="160" cy="80" r="3" fill="oklch(0.62 0.18 145)">
            <animate attributeName="opacity" values="1;0.2;1" dur="1.4s" repeatCount="indefinite"/>
          </circle>
          <text x="170" y="84" fill="oklch(0.7 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">RING</text>

          <circle cx="320" cy="80" r="3" fill="oklch(0.62 0.18 145)">
            <animate attributeName="opacity" values="1;0.2;1" dur="1.4s" begin="0.5s" repeatCount="indefinite"/>
          </circle>
          <text x="330" y="84" fill="oklch(0.7 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">RELAY</text>
        </g>

        {/* metrics */}
        <g transform="translate(20, 240)">
          <rect width="440" height="60" rx="10" fill="oklch(0.22 0.01 60)" stroke="oklch(0.28 0.01 60)"/>
          <text x="20" y="22" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">UPTIME</text>
          <text x="20" y="46" fill="white" fontSize="18" fontFamily="Instrument Serif">99.99%</text>

          <line x1="120" y1="14" x2="120" y2="46" stroke="oklch(0.32 0.01 60)"/>
          <text x="140" y="22" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">PICKUP</text>
          <text x="140" y="46" fill="white" fontSize="18" fontFamily="Instrument Serif">0.38s</text>

          <line x1="240" y1="14" x2="240" y2="46" stroke="oklch(0.32 0.01 60)"/>
          <text x="260" y="22" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">CONCURRENT</text>
          <text x="260" y="46" fill="white" fontSize="18" fontFamily="Instrument Serif">∞</text>

          <line x1="360" y1="14" x2="360" y2="46" stroke="oklch(0.32 0.01 60)"/>
          <text x="380" y="22" fill="oklch(0.6 0.01 60)" fontSize="9" fontFamily="JetBrains Mono">LANG</text>
          <text x="380" y="46" fill="white" fontSize="18" fontFamily="Instrument Serif">UR/EN</text>
        </g>
      </svg>
    </>
  );
}

function ConversationVisual() {
  const lines = [
    { s: 'caller', t: 'Bhai, do family pizza aur coke chahiye', lang: 'UR' },
    { s: 'agent', t: '✓ Two family pizzas + Coke. Toppings?', lang: 'EN' },
    { s: 'caller', t: 'Pepperoni aur chicken tikka, please', lang: 'UR' },
    { s: 'agent', t: 'Got it. Delivery to 24 Khayaban-e-Shahbaz?', lang: 'EN' },
    { s: 'caller', t: 'Haan, wahi address.', lang: 'UR' },
    { s: 'agent', t: 'Total: Rs 3,400. ETA 35 min.', lang: 'EN' },
  ];
  return (
    <>
      <VLabel>LIVE CONVERSATION · BILINGUAL</VLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {lines.map((l, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: l.s === 'agent' ? 'row' : 'row-reverse', gap: 8, alignItems: 'flex-start' }}>
            <div style={{
              flexShrink: 0,
              width: 22, height: 22, borderRadius: 999,
              background: l.s === 'agent' ? 'var(--accent)' : 'oklch(0.32 0.01 60)',
              color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 9, fontWeight: 600,
            }} className="mono">
              {l.s === 'agent' ? 'AI' : 'C'}
            </div>
            <div style={{ flex: 1, maxWidth: '80%' }}>
              <div style={{
                background: l.s === 'agent' ? 'oklch(0.94 0.05 145 / 0.15)' : 'oklch(0.32 0.01 60)',
                color: l.s === 'agent' ? 'oklch(0.92 0.06 145)' : 'white',
                padding: '8px 12px', borderRadius: 12,
                fontSize: 13, lineHeight: 1.4,
              }}>
                {l.t}
              </div>
              <div className="mono" style={{ fontSize: 9, color: 'oklch(0.55 0.01 60)', marginTop: 3, padding: '0 4px', textAlign: l.s === 'agent' ? 'left' : 'right' }}>
                {l.lang} · {(i * 1.2 + 0.4).toFixed(1)}s
              </div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 18, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {['INTENT: ORDER', 'EXTRACTED: 2 ITEMS', 'PAYMENT: COD', 'STATUS: CONFIRMED'].map((tag) => (
          <span key={tag} className="mono" style={{
            fontSize: 9, padding: '4px 8px', borderRadius: 999,
            background: 'oklch(0.27 0.01 60)', color: 'oklch(0.7 0.01 60)',
            letterSpacing: '0.06em',
          }}>{tag}</span>
        ))}
      </div>
    </>
  );
}

function HandoffVisual() {
  return (
    <>
      <VLabel>SMART HANDOFF · ESCALATION DETECTED</VLabel>
      <VCard style={{ marginBottom: 12, borderColor: 'oklch(0.7 0.15 50 / 0.4)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <span className="mono" style={{ fontSize: 10, color: 'oklch(0.85 0.15 50)' }}>⚠ COMPLEX REQUEST</span>
          <span className="mono" style={{ fontSize: 10, color: 'oklch(0.6 0.01 60)' }}>00:42</span>
        </div>
        <div style={{ fontSize: 13, color: 'white', marginBottom: 6 }}>
          "I want to dispute three months of charges and speak to your billing manager."
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'oklch(0.6 0.01 60)' }}>
          confidence: 0.34 · policy: ESCALATE
        </div>
      </VCard>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '10px 0' }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M12 4v14m-4-4 4 4 4-4" stroke="oklch(0.62 0.18 145)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>

      <VCard style={{ borderColor: 'var(--accent)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ width: 32, height: 32, borderRadius: 999, background: 'oklch(0.7 0.05 30)' }}/>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'white' }}>Sara Iqbal</div>
            <div className="mono" style={{ fontSize: 10, color: 'oklch(0.6 0.01 60)' }}>BILLING · ON-CALL</div>
          </div>
          <span className="live-dot" style={{ marginLeft: 'auto', width: 8, height: 8, borderRadius: 999, background: 'var(--accent)' }}/>
        </div>
        <div style={{ fontSize: 12, color: 'oklch(0.75 0.01 60)', lineHeight: 1.5, marginBottom: 12 }}>
          Caller context, transcript so far, and detected intent are pre-loaded for Sara before pickup.
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'oklch(0.85 0.15 145)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent)' }}/>
          TRANSFERRING IN 2.1s · NO HOLD MUSIC
        </div>
      </VCard>
    </>
  );
}

function DashboardVisual() {
  const calls = [
    { t: '14:02', from: '+92 333 ··· 8821', intent: 'Order',     status: 'resolved', dur: '1:48' },
    { t: '13:51', from: '+92 312 ··· 4567', intent: 'Booking',   status: 'resolved', dur: '2:14' },
    { t: '13:44', from: '+92 300 ··· 1102', intent: 'Complaint', status: 'transferred', dur: '0:54' },
    { t: '13:30', from: '+92 345 ··· 9988', intent: 'FAQ',       status: 'resolved', dur: '0:42' },
    { t: '13:18', from: '+92 321 ··· 7733', intent: 'Order',     status: 'resolved', dur: '2:01' },
  ];
  return (
    <>
      <VLabel>DASHBOARD · TODAY</VLabel>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 16 }}>
        {[
          { l: 'CALLS', v: '247', d: '+18%' },
          { l: 'RESOLVED', v: '231', d: '93%' },
          { l: 'TRANSFERS', v: '16', d: '7%' },
          { l: 'AVG TIME', v: '1:42', d: '-12s' },
        ].map((m, i) => (
          <VCard key={i} style={{ padding: 10 }}>
            <div className="mono" style={{ fontSize: 8, color: 'oklch(0.6 0.01 60)', letterSpacing: '0.08em', marginBottom: 4 }}>{m.l}</div>
            <div className="serif" style={{ fontSize: 22, color: 'white', lineHeight: 1 }}>{m.v}</div>
            <div className="mono" style={{ fontSize: 9, color: 'oklch(0.85 0.15 145)', marginTop: 4 }}>{m.d}</div>
          </VCard>
        ))}
      </div>

      <div style={{ background: 'oklch(0.27 0.01 60)', border: '1px solid oklch(0.32 0.01 60)', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '60px 1fr 90px 100px 60px', gap: 10, padding: '10px 14px', borderBottom: '1px solid oklch(0.32 0.01 60)', background: 'oklch(0.24 0.01 60)' }}>
          {['TIME','FROM','INTENT','STATUS','DUR'].map((h) => (
            <span key={h} className="mono" style={{ fontSize: 9, color: 'oklch(0.55 0.01 60)', letterSpacing: '0.08em' }}>{h}</span>
          ))}
        </div>
        {calls.map((c, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '60px 1fr 90px 100px 60px', gap: 10, padding: '10px 14px', borderBottom: i < calls.length - 1 ? '1px solid oklch(0.30 0.01 60)' : 'none', alignItems: 'center' }}>
            <span className="mono" style={{ fontSize: 11, color: 'oklch(0.7 0.01 60)' }}>{c.t}</span>
            <span className="mono" style={{ fontSize: 11, color: 'white' }}>{c.from}</span>
            <span style={{ fontSize: 11, color: 'oklch(0.85 0.01 60)' }}>{c.intent}</span>
            <span className="mono" style={{
              fontSize: 9, padding: '3px 7px', borderRadius: 999,
              background: c.status === 'resolved' ? 'oklch(0.94 0.05 145 / 0.15)' : 'oklch(0.7 0.15 50 / 0.15)',
              color: c.status === 'resolved' ? 'oklch(0.85 0.15 145)' : 'oklch(0.85 0.15 50)',
              letterSpacing: '0.06em',
              justifySelf: 'start',
            }}>{c.status.toUpperCase()}</span>
            <span className="mono" style={{ fontSize: 11, color: 'oklch(0.7 0.01 60)' }}>{c.dur}</span>
          </div>
        ))}
      </div>
    </>
  );
}

window.How = How;
