/* Proof strip, How it works, Demo, Industries */
function StatStrip() {
  const stats = [
    ['5', '', 'Minutes. The window to win the job', 'MIT / InsideSales study'],
    ['7', 'x', 'More likely to land the lead', 'Harvard Business Review'],
    ['64', '%', 'Of customers call first', 'ServiceTitan 2025 report'],
    ['10', '', 'Minutes. What buyers expect', 'HubSpot Research'],
    ['78', '%', 'Often choose the first responder', 'Lead Connect'],
  ];
  return (
    <section className="stats" id="proof">
      <div className="site">
        {stats.map((s, i) => (
          <div className="stat" key={i}>
            <div className="n">{s[0]}<small>{s[1]}</small></div>
            <div className="l">{s[2]}</div>
            <div className="s">{s[3]}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function HowItWorks() {
  const steps = [
    ['phoneVolume', 'The call comes in', 'A new customer calls at 2 p.m. or 2 a.m., weekday or holiday. A real job, ready to book.', 'step-1.jpg', 'A tradesperson checking the phone in the workshop', 'Most shops send it to voicemail. Yours won\'t.'],
    ['headset', 'ReplyFirst picks up first', 'A natural voice answers in your company name, every single time. No hold music, no "we\'re closed," no robotic script.', 'step-2.jpg', 'A headset on a desk, ready to take the call', 'The caller feels heard and stays on the line.'],
    ['clipboardCheck', 'The job gets qualified', 'It asks the right questions, takes the name, address, and problem, then scores how urgent the work is.', 'step-3.jpg', 'A work-order clipboard and tools on a bench', 'You get the whole job, not a missed-call alert.'],
    ['share', 'The lead hits your phone', 'Urgent jobs are texted and called straight to you in seconds, details attached. Everything else waits in your inbox.', 'step-4.jpg', 'A technician reading the job on the phone by the van', 'You win it before they call the next guy.'],
  ];
  return (
    <section className="light" id="how">
      <div className="site sec-pad">
        <div className="sec-head" style={{ textAlign: 'center' }}>
          <div className="eyebrow">How it works</div>
          <h2 className="display">From missed call to <span className="yl">booked job</span></h2>
          <p className="how-sub">Every missed call is a customer dialing the next company on the list. ReplyFirst turns that ring into a job on your schedule, in under a minute.</p>
        </div>
        <div className="how">
          {steps.map((s, i) => (
            <div className="how-wrap" key={i}>
              <div className="step">
                <div className="step-img">
                  <img src={'assets/' + s[3]} alt={s[4]} loading="lazy" width="420" height="260" />
                  <span className="step-no">{i + 1}</span>
                </div>
                <div className="ico"><Icon name={s[0]} /></div>
                <h3>{s[1]}</h3>
                <p>{s[2]}</p>
                <div className="step-result">{s[5]}</div>
              </div>
              {i < 3 && <span className="how-arrow"><Icon name="arrowRight" size={20} /></span>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* Demo with a live, animated waveform + revealing call transcript. */
function Demo({ playing, onToggle }) {
  const bars = [6, 12, 20, 32, 24, 14, 28, 38, 22, 12, 26, 34, 18, 10, 22, 30, 16, 9, 20, 14, 24, 36, 20, 12, 8, 18, 28, 14];
  const DUR = 14; // seconds
  const [prog, setProg] = useState(0);
  // Typewriter: lines reveal + type one at a time. Triggered on scroll-in, restarted on play.
  const transRef = useRef(null);
  const [tw, setTw] = useState({ li: -1, ci: 0, done: false });
  const reduce = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  // Real audio: drop a recording at assets/demo-call.mp3 and the play button
  // plays it. Falls back silently to the animation if the file isn't there yet.
  const audioRef = useRef(null);
  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    if (playing) { a.currentTime = 0; a.play().catch(() => {}); }
    else { a.pause(); }
  }, [playing]);

  useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProg(p => {
        const n = p + 0.2 / DUR;
        return n >= 1 ? 1 : n;
      });
    }, 200);
    return () => clearInterval(id);
  }, [playing]);

  useEffect(() => { if (playing && prog >= 1) setProg(0); }, [playing]);

  const lines = [
    { who: 'Caller', txt: '“My garage door is stuck halfway and my car is trapped inside.”', ico: 'phone', at: 0.06 },
    { who: 'AI Receptionist', txt: '“I can get someone out tonight. What\'s the service address?”', ico: 'headset', ai: true, at: 0.30 },
    { who: 'Caller', txt: '“412 Cedar Street. Please hurry, I have work in the morning.”', ico: 'phone', at: 0.55 },
    { who: 'AI Receptionist', txt: '“Got it. Flagging this as urgent and routing to the owner now.”', ico: 'clipboardCheck', ai: true, at: 0.78 },
  ];
  const active = Math.round(prog * bars.length);
  const cur = Math.floor(prog * DUR);
  const tt = `00:${String(cur).padStart(2, '0')}`;
  const routed = prog >= 0.95;

  // Reduced motion: show the whole transcript immediately, no typing.
  useEffect(() => { if (reduce) setTw({ li: lines.length, ci: 0, done: true }); }, []);

  // Kick off when the transcript scrolls into view (once).
  useEffect(() => {
    if (reduce) return;
    const el = transRef.current;
    if (!el || typeof IntersectionObserver === 'undefined') { setTw(t => (t.li < 0 ? { li: 0, ci: 0, done: false } : t)); return; }
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { setTw(t => (t.li < 0 ? { li: 0, ci: 0, done: false } : t)); io.disconnect(); } });
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Restart the type-out from the top each time the sample call is played.
  useEffect(() => { if (playing && !reduce) setTw({ li: 0, ci: 0, done: false }); }, [playing]);

  // The stepper: type the active line char-by-char, pause, then reveal the next.
  useEffect(() => {
    if (reduce || tw.li < 0 || tw.done) return;
    if (tw.li >= lines.length) { setTw(t => ({ ...t, done: true })); return; }
    const full = lines[tw.li].txt;
    if (tw.ci < full.length) {
      const id = setTimeout(() => setTw(t => ({ ...t, ci: t.ci + 1 })), 17);
      return () => clearTimeout(id);
    }
    const id = setTimeout(() => setTw(t => ({ li: t.li + 1, ci: 0, done: false })), 360);
    return () => clearTimeout(id);
  }, [tw, reduce]);

  return (
    <section className="dark" id="demo">
      <div className="site">
        <div className="demo-card">
          <div className="demo-left">
            <div className="eyebrow">Available 24/7</div>
            <h2 className="display" style={{ marginTop: 12 }}>Hear it in action</h2>
            <p className="demo-lead" style={{ marginTop: 14 }}>Call the demo line and try it yourself. Or press play to hear a sample emergency call.</p>
            <div className="demo-num">(604) 900-REPLY</div>
            <div style={{ marginTop: 18 }}>
              <Button variant="primary" icon={playing ? 'xmark' : 'play'} onClick={onToggle}>{playing ? 'Stop sample call' : 'Play a sample emergency call'}</Button>
            </div>
          </div>
          <div className="demo-right">
            <div className="player">
              <audio ref={audioRef} src="assets/demo-call.mp3" preload="none" onEnded={() => { if (playing) onToggle(); }}></audio>
              <div className="top">
                <button className="play-btn" onClick={onToggle}><Icon name={playing ? 'xmark' : 'play'} /></button>
                <div className="wave">
                  {bars.map((b, i) => (
                    <span key={i} className={i < active ? 'on' : ''}
                      style={{ height: b + 'px', animation: playing && i < active ? `wavep .9s ease-in-out ${(i % 6) * 0.08}s infinite` : 'none' }}></span>
                  ))}
                </div>
                <span className="time">{playing || prog > 0 ? tt : '00:00'} / 00:14</span>
              </div>
              <div className="cap">Real demo call with the AI receptionist · garage door emergency</div>
            </div>
            <div className="transcript" ref={transRef}>
              {lines.map((l, i) => {
                const shown = tw.done || i < tw.li ? l.txt : i === tw.li ? l.txt.slice(0, tw.ci) : '';
                const visible = tw.done || i <= tw.li;
                const typing = !tw.done && i === tw.li && tw.li < lines.length;
                return (
                  <div key={i} className={'tline' + (l.ai ? ' ai' : '') + (visible ? ' show' : '')}>
                    <span className="ava"><Icon name={l.ico} size={13} /></span>
                    <div><div className="who">{l.who}</div>
                      <div className="txt">{shown}{typing && <span className="tw-caret" aria-hidden="true"></span>}</div></div>
                  </div>
                );
              })}
              <span className={'demo-tag' + (tw.done ? ' show' : '')}><Icon name="circleCheck" size={12} /> Routed to owner · Priority: High</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Industries() {
  const inds = [
    ['warehouse', 'Garage door repair', 'Stuck doors, broken springs, trapped cars.'],
    ['faucetDrip', 'Drain cleaning', 'Backups and blockages that can\'t wait.'],
    ['droplet', 'Water damage', 'Flooded basements, burst pipes, restoration.'],
    ['key', 'Locksmiths', 'Lockouts and after-hours access calls.'],
    ['houseChimney', 'Roofing repair', 'Storm damage and active leaks.'],
    ['bug', 'Pest control', 'Urgent infestations and call-backs.'],
    ['fan', 'Appliance repair', 'No heat, no cooling, no hot water.'],
    ['building', 'Strata & property', 'Building emergencies and dispatch.'],
  ];
  return (
    <section className="light">
      <div className="site sec-pad">
        <div className="sec-head" style={{ textAlign: 'center' }}>
          <h2 className="display">Built for urgent service businesses</h2>
        </div>
        <div className="inds">
          {inds.map((x, i) => (
            <div className="ind" key={i}>
              <div className="ico"><Icon name={x[0]} /></div>
              <h3>{x[1]}</h3>
              <p>{x[2]}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { StatStrip, HowItWorks, Demo, Industries });
