/* OpSpot — Courier floating chat widget. Scripted inbound flow that visibly
   routes through Recon / Comms / Redpen and ends in a CTA. */
const { useState, useEffect, useRef } = React;

const QUICK = {
  business: ['Plumbing', 'HVAC', 'Auto shop', 'Med spa', 'Roofing'],
  bottleneck: ['Missed calls', 'Slow follow-up', 'No-shows', 'Billing'],
};

function crewOf(id) { return CREW.find(c => c.id === id) || CREW[0]; }

function Courier() {
  const [open, setOpen] = useState(false);
  const [log, setLog] = useState([]);          // {kind:'msg'|'me'|'route'|'cta', ...}
  const [typing, setTyping] = useState(null);   // crew id currently "typing"
  const [awaiting, setAwaiting] = useState(null);
  const [cursor, setCursor] = useState(-1);
  const [input, setInput] = useState('');
  const started = useRef(false);
  const bodyRef = useRef(null);
  const timers = useRef([]);

  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const after = (ms, fn) => { const t = setTimeout(fn, ms); timers.current.push(t); return t; };

  useEffect(() => () => clearTimers(), []);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [log, typing]);

  const runFrom = (i) => {
    if (i >= COURIER_SCRIPT.length) return;
    const step = COURIER_SCRIPT[i];
    if (step.route) {
      setLog(l => [...l, { kind: 'route', crew: step.route, text: step.text }]);
      after(1250, () => runFrom(i + 1));
    } else {
      setTyping(step.from);
      after(950, () => {
        setTyping(null);
        setLog(l => [...l, { kind: 'msg', from: step.from, text: step.text, badge: step.badge, cta: step.cta }]);
        if (step.expect) { setAwaiting(step.expect); setCursor(i); }
        else if (step.cta) { /* end */ }
        else after(550, () => runFrom(i + 1));
      });
    }
  };

  const launch = () => {
    setOpen(true);
    if (!started.current) {
      started.current = true;
      after(450, () => runFrom(0));
    }
  };

  const send = (text) => {
    const t = (text || '').trim();
    if (!t || !awaiting) return;
    setLog(l => [...l, { kind: 'me', text: t }]);
    setInput('');
    const next = cursor + 1;
    setAwaiting(null);
    after(420, () => runFrom(next));
  };

  return (
    <React.Fragment>
      {!open && (
        <button className="courier-launch" onClick={launch} aria-label="Chat with Courier">
          <span className="cl-av"><Ico d={ICONS.chat} size={17} /></span>
          <span>Chat with Courier</span>
          <span className="cl-ping" />
        </button>
      )}
      {open && (
        <div className="courier-panel" role="dialog" aria-label="Courier chat">
          <div className="cp-head">
            <div className="cp-av"><Ico d={ICONS.chat} size={19} /></div>
            <div className="cp-who">
              <b>Courier</b>
              <small><span className="d" /> OpSpot’s front door · online</small>
            </div>
            <button className="cp-x" onClick={() => setOpen(false)} aria-label="Close"><Ico d={ICONS.x} size={17} /></button>
          </div>

          <div className="cp-body" ref={bodyRef}>
            {log.map((m, i) => {
              if (m.kind === 'route') {
                const c = crewOf(m.crew);
                return (
                  <div className="cp-route" key={i} style={{ '--c': c.c, '--c1': c.c1, '--c2': c.c2 }}>
                    <span className="ag"><Ico d={crewIcon(m.crew)} size={9} /></span>
                    <span>{m.text}</span>
                    <span className="spin" />
                  </div>
                );
              }
              if (m.kind === 'me') {
                return (
                  <div className="msg-row me" key={i}>
                    <div className="bubble">{m.text}</div>
                  </div>
                );
              }
              const c = crewOf(m.from);
              return (
                <div className="msg-row" key={i} style={{ '--c': c.c, '--c1': c.c1, '--c2': c.c2 }}>
                  <span className="msg-av">{c.name === 'Deal Desk' ? 'DD' : c.name[0]}</span>
                  <div className="bubble">
                    <span className="who">{c.name}</span>
                    {m.text}
                    {m.badge && <span className="badge"><Ico d={ICONS.check} size={11} />{m.badge}</span>}
                  </div>
                </div>
              );
            })}
            {typing && (() => {
              const c = crewOf(typing);
              return (
                <div className="msg-row" style={{ '--c1': c.c1, '--c2': c.c2 }}>
                  <span className="msg-av">{c.name === 'Deal Desk' ? 'DD' : c.name[0]}</span>
                  <div className="bubble typing"><span /><span /><span /></div>
                </div>
              );
            })()}
          </div>

          <div className="cp-foot">
            {log.some(m => m.cta) ? (
              <div className="cp-cta">
                <a href="#contact" className="btn btn-primary" onClick={(e) => { e.preventDefault(); setOpen(false); scrollToId('contact'); }}>Get my free audit →</a>
                <a href={CAL} target="_blank" rel="noopener" className="btn btn-ghost">Book a call</a>
              </div>
            ) : (
              <React.Fragment>
                {awaiting && QUICK[awaiting] && (
                  <div className="cp-quick">
                    {QUICK[awaiting].map(q => <button key={q} onClick={() => send(q)}>{q}</button>)}
                  </div>
                )}
                <div className="cp-input">
                  <input
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={(e) => { if (e.key === 'Enter') send(input); }}
                    placeholder={awaiting ? 'Type your answer…' : 'Courier is working…'}
                    disabled={!awaiting}
                  />
                  <button className="cp-send" onClick={() => send(input)} disabled={!awaiting || !input.trim()} aria-label="Send"><Ico d={ICONS.send} size={18} /></button>
                </div>
              </React.Fragment>
            )}
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { Courier });
