// zp-phone.jsx — animated phone-texting demo (used in hero + standalone interactive demo)
function PhoneStatusBar() {
  return (
    <div className="statusbar">
      <span>9:41</span>
      <span style={{display:'inline-flex',gap:5,alignItems:'center'}}>
        <Ic.wifi style={{width:14,height:14}}/>
        <Ic.battery style={{width:22,height:11}}/>
      </span>
    </div>
  );
}

function ChatHeader({name="Aiden · Zap Pilot AI"}) {
  return (
    <div className="chathd">
      <div className="avatar">A</div>
      <div className="who">
        <b>{name}</b>
        <span>Replies in seconds</span>
      </div>
      <span className="meta">SMS</span>
    </div>
  );
}

// Auto-playing scripted demo for hero
function ScriptedPhone() {
  const script = React.useMemo(() => ([
    { who:'them', text:"Hi, looking for a quote on a roof leak above the kitchen.", t:'2:14 PM' },
    { who:'us',   text:"Hey John 👋 happy to help. Sorry to hear about the leak — sounds urgent. Is the water still actively coming in?", t:'2:14 PM', delay:1100 },
    { who:'them', text:"Just a slow drip. Saw it after last night's rain.", t:'2:15 PM', delay:2400 },
    { who:'us',   text:"Got it. We can get a tech out tomorrow morning. I have 8:30 AM or 10:15 AM open — which works?", t:'2:15 PM', delay:1400 },
    { who:'them', text:"10:15 works great.", t:'2:16 PM', delay:1800 },
    { who:'us',   text:"Booked ✅ Tuesday 10:15 AM, 1422 Maple St. You'll get a confirmation text. Anything else I should pass to the tech?", t:'2:16 PM', delay:1300 },
  ]), []);

  const [shown, setShown] = React.useState([]);
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    let cancelled = false;
    let timers = [];
    function loop() {
      setShown([]);
      let acc = 600;
      script.forEach((m, i) => {
        const d = m.delay ?? 1200;
        acc += d;
        if (m.who === 'us') {
          timers.push(setTimeout(() => { if(!cancelled) setTyping(true); }, acc - 700));
        }
        timers.push(setTimeout(() => {
          if (cancelled) return;
          setTyping(false);
          setShown(prev => [...prev, m]);
        }, acc));
      });
      timers.push(setTimeout(() => { if(!cancelled) loop(); }, acc + 4500));
    }
    loop();
    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, [script]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [shown, typing]);

  return (
    <PhoneShell>
      <PhoneStatusBar/>
      <ChatHeader/>
      <div className="messages" ref={scrollRef}>
        {shown.map((m, i) => (
          <div key={i} className={`msg ${m.who}`}>
            {m.text}
            <span className="ts">{m.t}</span>
          </div>
        ))}
        {typing && (
          <div className="typing"><span/><span/><span/></div>
        )}
      </div>
      <div className="input-bar">
        <input placeholder="Reply…" disabled />
        <button disabled aria-label="Send"><Ic.send style={{width:13,height:13}}/></button>
      </div>
    </PhoneShell>
  );
}

function PhoneShell({children}) {
  return (
    <div className="phone">
      <div className="notch"/>
      <div className="screen">{children}</div>
    </div>
  );
}

// Interactive AI texting demo — user types as the lead, fake AI replies
function InteractivePhone() {
  const seed = [
    { who:'us', text:"Hi! This is Aiden from Apex Roofing — I saw you're looking into a roof inspection. What's the address and is now a good time?", t:'just now' },
  ];
  const [msgs, setMsgs] = React.useState(seed);
  const [draft, setDraft] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, typing]);

  function aiReply(userText) {
    const t = userText.toLowerCase();
    let reply = "Got it — a tech can swing by this week. Want me to pencil in Tuesday 10:15 AM or Thursday 2:00 PM?";
    if (/(price|cost|how much|quote|estimate)/.test(t))
      reply = "Inspections are free, and most repairs land between $450–$1,800 depending on scope. Want me to book a free on-site quote? I have Tue 10:15 or Thu 2:00.";
    else if (/(leak|water|drip)/.test(t))
      reply = "That sounds urgent — let's get someone out fast. I can lock in tomorrow 8:30 AM or 10:15 AM. Which works?";
    else if (/(time|when|tomorrow|today|tuesday|monday|wednesday|thursday|friday|am|pm|\d)/.test(t))
      reply = "Booked ✅ I'll send a confirmation text and a Google Calendar invite. Anything the tech should know in advance?";
    else if (/(no|nothing|nope|all good|that's it|thanks)/.test(t))
      reply = "Perfect — you're set. We'll text you 30 min before the tech arrives. Have a great day! 👋";
    else if (/(yes|yeah|sure|please|ok|okay)/.test(t))
      reply = "Awesome. What's a good street address and zip so I can route the closest tech?";
    return reply;
  }

  function send() {
    const text = draft.trim();
    if (!text) return;
    const now = new Date();
    const t = now.toLocaleTimeString([],{hour:'numeric',minute:'2-digit'});
    setMsgs(m => [...m, {who:'them', text, t}]);
    setDraft("");
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMsgs(m => [...m, {who:'us', text:aiReply(text), t}]);
    }, 1100 + Math.random()*600);
  }

  function quickPrompt(p) {
    setDraft(p);
    setTimeout(() => {
      const now = new Date();
      const t = now.toLocaleTimeString([],{hour:'numeric',minute:'2-digit'});
      setMsgs(m => [...m, {who:'them', text:p, t}]);
      setDraft("");
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMsgs(m => [...m, {who:'us', text:aiReply(p), t}]);
      }, 1100);
    }, 100);
  }

  return (
    <div>
      <PhoneShell>
        <PhoneStatusBar/>
        <ChatHeader/>
        <div className="messages" ref={scrollRef}>
          {msgs.map((m, i) => (
            <div key={i} className={`msg ${m.who}`}>
              {m.text}
              <span className="ts">{m.t}</span>
            </div>
          ))}
          {typing && <div className="typing"><span/><span/><span/></div>}
        </div>
        <div className="input-bar">
          <input
            placeholder="Type a reply…"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if(e.key === 'Enter') send(); }}
          />
          <button onClick={send} disabled={!draft.trim()} aria-label="Send">
            <Ic.send style={{width:13,height:13}}/>
          </button>
        </div>
      </PhoneShell>
      <div className="demo-prompts">
        {["What's it cost?", "I have a leak", "How about Tuesday?"].map(p => (
          <button key={p} className="demo-prompt" onClick={() => quickPrompt(p)}>{p}</button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScriptedPhone, InteractivePhone, PhoneShell, PhoneStatusBar, ChatHeader });
