// ai-closer.jsx — the AI text-closer demo: phone convo + simple step strip
const { useEffect: useAiEffect, useState: useAiState, useRef: useAiRef } = React;

const CONVO = [
  { from: "lead", text: "Hey, saw your ad — looking to get my car detailed in the next few weeks" },
  { from: "ai", text: "Awesome, happy to help! What's the year, make, and model?" },
  { from: "lead", text: "2021 Honda Accord" },
  { from: "ai", text: "Got it. What ZIP code are you in? Just checking we service that area." },
  { from: "lead", text: "85032" },
  { from: "ai", text: "We cover that area! Our next opening is July 27 at 10:00 AM — does that work?" },
  { from: "lead", text: "10am doesn't work, when else are you free?" },
  { from: "ai", text: "We also have July 29 at 10:00 AM open. Better?" },
  { from: "lead", text: "Yes the 29th works. Do you bring your own water and power, or do I need to provide that?" },
  { from: "ai", text: "We bring our own — no need to provide anything. You're booked — July 29 at 10:00 AM. I'll send a reminder that morning!" },
];

const AI_STEPS = [
  { n: "01", t: "A lead texts in", d: "Any hour, any day — the number's always answered." },
  { n: "02", t: "It qualifies them", d: "Asks what they need, quotes it, works out a time." },
  { n: "03", t: "It's booked", d: "Goes straight on your calendar. You just show up." },
];

function PhoneDemo() {
  const [shown, setShown] = useAiState(0);
  const [typing, setTyping] = useAiState(false);
  const [active, setActive] = useAiState(false);
  const wrapRef = useAiRef(null);
  const chatRef = useAiRef(null);
  const timers = useAiRef([]);

  useAiEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => setActive(e.isIntersecting));
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  useAiEffect(() => {
    const el = chatRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [shown, typing]);

  useAiEffect(() => {
    timers.current.forEach(clearTimeout);
    timers.current = [];
    if (!active) return;
    if (motionLevel() === "off") { setShown(CONVO.length); setTyping(false); return; }

    let t = 400;
    const run = () => {
      setShown(0); setTyping(false);
      CONVO.forEach((m, i) => {
        if (m.from === "ai") {
          timers.current.push(setTimeout(() => setTyping(true), t));
          t += 900;
        }
        timers.current.push(setTimeout(() => { setTyping(false); setShown(i + 1); }, t));
        t += m.from === "ai" ? 1500 : 1100;
      });
      timers.current.push(setTimeout(run, t + 3200));
    };
    run();
    return () => timers.current.forEach(clearTimeout);
  }, [active]);

  return (
    <div className="ai-phone" ref={wrapRef}>
      <div className="ai-phone-head">
        <Ball size={26} pulse={false} />
        <div>
          <div className="ai-phone-name">New Lead</div>
          <div className="mono-tag dim">Text message</div>
        </div>
        <span className="ai-phone-live"><span></span></span>
      </div>
      <div className="ai-chat" ref={chatRef}>
        {CONVO.slice(0, shown).map((m, i) => (
          <div className={`chat-bubble ${m.from}`} key={i}>{m.text}</div>
        ))}
        {typing && <div className="chat-bubble ai typing"><span></span><span></span><span></span></div>}
      </div>
    </div>
  );
}

function AICloser({ onBook }) {
  return (
    <section className="sec ai-sec" id="ai-closer" data-screen-label="AI text closer">
      <div className="wrap">
        <div className="sec-head">
          <div className="eyebrow">How the AI texting works</div>
          <Reveal as="h2" className="sec-h2">It answers so<br /><span className="ig-em">you don't have to.</span></Reveal>
          <Reveal as="p" className="sec-lede" delay={80}>
            A lead texts in at 11pm on a Saturday. It asks what they need, quotes the job, and gets them on your calendar — before you've even seen the message.
          </Reveal>
        </div>
        <div className="ai-grid">
          <Reveal className="ai-phone-wrap">
            <PhoneDemo />
          </Reveal>
          <Reveal className="ai-side" delay={100}>
            <div className="ai-steps">
              {AI_STEPS.map((s, i) => (
                <div className="ai-step" key={i}>
                  <div className="ai-step-n mono-tag">{s.n}</div>
                  <h3 className="ai-step-t">{s.t}</h3>
                  <p className="ai-step-d">{s.d}</p>
                </div>
              ))}
            </div>
            <p className="ai-side-note">
              No scripts to write, no app to babysit. It's built into how you already get leads — it just never sleeps.
            </p>
            <Magnetic strength={0.2}>
              <button className="btn btn-primary" onClick={onBook}>See it on your number<span className="arrow">→</span></button>
            </Magnetic>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { AICloser });
