// JMAC chat assistant — floating chat bubble + panel.
// Talks to /api/chat (api/chat.js). Globals: React, Icon, HazardStripe.

const CHAT_ES = {
  'Questions? Ask us': '¿Preguntas? Escríbanos',
  'Chat with an AI agent': 'Chatee con un agente de IA',
  'AI Agent': 'Agente de IA',
  'Online now': 'En línea',
  'Ask about appointments, fees & pickup': 'Pregunte por citas, cargos y recogida',
  'Vehicle recovered?': '¿Le recuperaron el vehículo?',
  'Ask me how to book your appointment and get your car or belongings back.':
    'Pregúnteme cómo reservar su cita y recuperar su vehículo o pertenencias.',
  'Ask a question': 'Hacer una pregunta',
  'Dismiss': 'Cerrar',
  'JMAC Assistant': 'Asistente JMAC',
  'Assistant': 'Asistente',
  'JMAC AI Agent': 'Agente de IA de JMAC',
  'Close chat': 'Cerrar chat',
  'Automated assistant. It can’t look up accounts or vehicles. Fees and location are sent in your confirmation after you book.':
    'Asistente automático. No puede consultar cuentas ni vehículos. Los cargos y la ubicación se envían en su confirmación después de reservar.',
  'Hi, I can answer questions about JMAC, redemption appointments, and our services. How can I help?':
    'Hola, puedo responder preguntas sobre JMAC, las citas de redención y nuestros servicios. ¿En qué puedo ayudarle?',
  'How do I get my car back?': '¿Cómo recupero mi vehículo?',
  'How do I make an appointment?': '¿Cómo hago una cita?',
  'What are my fees?': '¿Cuáles son mis cargos?',
  'How do I get my belongings?': '¿Cómo recupero mis pertenencias?',
  'Can someone else pick up for me?': '¿Puede otra persona recogerlo por mí?',
  'Book appointment': 'Reservar cita',
  'Step-by-step guide': 'Guía paso a paso',
  'I’m a transporter. What do I need?': 'Soy transportista. ¿Qué necesito?',
  'Type your question': 'Escriba su pregunta',
  'Send': 'Enviar',
  'Typing…': 'Escribiendo…',
  'The assistant is unavailable right now. Please try again in a few minutes.':
    'El asistente no está disponible en este momento. Intente de nuevo en unos minutos.',
};
const APPOINTMENT_ANSWER = {
  en: 'The easiest way is our step-by-step guide. Tap Step-by-step guide below (or use the home page) and choose Get my car back, Get my belongings, or I’m a transporter. It asks a few quick yes/no questions, then opens the booking page.\n\nOn the booking page:\n1. Under Appointment Type, choose Vehicle Redemption, Property Redemption, or Transport Pickup.\n2. Enter the last 6 digits of the VIN and tap the orange VIN Check button.\n3. Confirm your info and enter your email and phone number.\n4. Choose text or email for your confirmation.\n5. Pick a date and time, then book.\n\nAppointments are processed in the order they are received, and some take 1 to 3 hours to be confirmed. Same-day appointments are not available. All fees and the location will be in your confirmation.',
  es: 'La forma más fácil es nuestra guía paso a paso. Toque Guía paso a paso abajo (o use la página de inicio) y elija Recuperar mi vehículo, Recuperar mis pertenencias o Soy transportista. Hace unas preguntas rápidas de sí/no y luego abre la página de reservas.\n\nEn la página de reservas:\n1. En Appointment Type, elija Vehicle Redemption, Property Redemption o Transport Pickup.\n2. Escriba los últimos 6 dígitos del VIN y toque el botón naranja VIN Check.\n3. Confirme sus datos e ingrese su correo y teléfono.\n4. Elija texto o correo para su confirmación.\n5. Elija fecha y hora, y reserve.\n\nLas citas se procesan en el orden en que se reciben, y algunas tardan de 1 a 3 horas en confirmarse. No hay citas para el mismo día. Todos los cargos y la ubicación estarán en su confirmación.',
};

const ct = (s, lang) => (lang === 'es' && CHAT_ES[s]) || s;

// Illustrated support agent with a headset (original artwork, no photo).
const AgentAvatar = ({ size = 48, online = true }) => {
  const clip = 'jmacAv' + React.useId().replace(/:/g, '');
  return (
  <span style={{ position: 'relative', display: 'inline-block', width: size, height: size, flexShrink: 0 }}>
    <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true" style={{ display: 'block' }}>
      <defs><clipPath id={clip}><circle cx="24" cy="24" r="24"/></clipPath></defs>
      <g clipPath={`url(#${clip})`}>
        <rect width="48" height="48" fill="#d6e3f5"/>
        <path d="M11 22c0-9 5.5-14.5 13-14.5S37 13 37 22v15c0 2.5-2.5 3.5-4.5 2.5H15.5C13.5 40.5 11 39.5 11 37z" fill="#3b2a20"/>
        <path d="M7 48c1.5-9 8.5-13 17-13s15.5 4 17 13z" fill="#163672"/>
        <path d="M20 29h8v7.5c0 2-1.8 3.5-4 3.5s-4-1.5-4-3.5z" fill="#d49a76"/>
        <ellipse cx="24" cy="22.5" rx="8.2" ry="9.3" fill="#e8b796"/>
        <path d="M15.6 21.5c.6-6.5 4.4-10.2 9-10.2 4.4 0 7.6 3.2 8.2 8-4.6-.3-9.4-2.3-12.4-5.6-1 3.4-2.6 6.2-4.8 7.8z" fill="#3b2a20"/>
        <circle cx="20.9" cy="23.6" r="1.05" fill="#2a1d16"/>
        <circle cx="27.1" cy="23.6" r="1.05" fill="#2a1d16"/>
        <path d="M21.3 27.4c1.6 1.4 3.8 1.4 5.4 0" stroke="#a5604a" strokeWidth="1.1" fill="none" strokeLinecap="round"/>
        <path d="M14.3 22.5a9.7 9.7 0 0 1 19.4 0" stroke="#0d1117" strokeWidth="2.2" fill="none"/>
        <rect x="12.4" y="20.4" width="4.4" height="7.4" rx="2.2" fill="#0d1117"/>
        <rect x="31.2" y="20.4" width="4.4" height="7.4" rx="2.2" fill="#0d1117"/>
        <path d="M14.6 27.4c0 4 2.8 5.9 6.6 5.9" stroke="#0d1117" strokeWidth="1.6" fill="none" strokeLinecap="round"/>
        <circle cx="21.8" cy="33.3" r="1.5" fill="#ffb81c"/>
      </g>
    </svg>
    {online && (
      <span style={{
        position: 'absolute', right: 0, bottom: 1, width: size * 0.26, height: size * 0.26,
        borderRadius: '50%', background: '#1f8a4c', border: '2px solid #000',
      }}/>
    )}
  </span>
  );
};

const ChatWidget = ({ lang, onBook }) => {
  const [open, setOpen] = React.useState(false);
  const [teaser, setTeaser] = React.useState(false);

  // Show a one-time greeting card a few seconds after the page loads
  // (once per browser session, and never after the visitor has opened the chat).
  React.useEffect(() => {
    let seen = false;
    try { seen = sessionStorage.getItem('jmac-chat-teaser') === '1'; } catch {}
    // Greeting card turned off everywhere. To bring it back, restore the timer below.
    // if (!seen) { const t = setTimeout(() => setTeaser(true), 3500); return () => clearTimeout(t); }
  }, []);
  // Other parts of the site can open the chat: window.dispatchEvent(new CustomEvent('jmac:open-chat'))
  React.useEffect(() => {
    const onOpen = () => { setTeaser(false); try { sessionStorage.setItem('jmac-chat-teaser', '1'); } catch {} setOpen(true); };
    window.addEventListener('jmac:open-chat', onOpen);
    return () => window.removeEventListener('jmac:open-chat', onOpen);
  }, []);
  const hideTeaser = () => {
    setTeaser(false);
    try { sessionStorage.setItem('jmac-chat-teaser', '1'); } catch {}
  };
  const [messages, setMessages] = React.useState([]); // {role, content}
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const listRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const launcherRef = React.useRef(null);

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, busy, open]);

  React.useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
    const onKey = (e) => { if (e.key === 'Escape') close(); };
    window.addEventListener('keydown', onKey);
    return () => { clearTimeout(t); window.removeEventListener('keydown', onKey); };
  }, [open]);

  const close = () => {
    setOpen(false);
    setTimeout(() => launcherRef.current && launcherRef.current.focus(), 0);
  };

  const send = async (text, fixedReply) => {
    const q = (text || '').trim();
    if (!q || busy) return;
    if (fixedReply) {
      setMessages(m => [...m, { role: 'user', content: q }, { role: 'assistant', content: fixedReply }]);
      return;
    }
    const next = [...messages, { role: 'user', content: q }];
    setMessages(next);
    setInput('');
    setBusy(true);
    try {
      const r = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: next, lang }),
      });
      const data = await r.json().catch(() => ({}));
      const reply = r.ok && data.reply
        ? data.reply
        : (data.error || ct('The assistant is unavailable right now. Please try again in a few minutes.', lang));
      setMessages(m => [...m, { role: 'assistant', content: reply }]);
    } catch {
      setMessages(m => [...m, { role: 'assistant', content: ct('The assistant is unavailable right now. Please try again in a few minutes.', lang) }]);
    } finally {
      setBusy(false);
    }
  };

  const suggestions = [
    'How do I make an appointment?',
    'How do I get my car back?',
    'What are my fees?',
    'Can someone else pick up for me?',
    'I’m a transporter. What do I need?',
  ];

  // Open the step-by-step guide page and close the chat.
  const openGuide = () => {
    window.history.pushState({ page: 'start' }, '', '#/start');
    window.dispatchEvent(new PopStateEvent('popstate'));
    close();
  };

  const bubble = (role) => ({
    maxWidth: '85%',
    alignSelf: role === 'user' ? 'flex-end' : 'flex-start',
    background: role === 'user' ? 'var(--blue-700)' : 'var(--bg-muted)',
    color: role === 'user' ? '#fff' : 'var(--fg-1)',
    border: role === 'user' ? 'none' : '1px solid var(--border-1)',
    borderRadius: 'var(--radius-lg)',
    padding: '10px 13px',
    fontSize: 14, lineHeight: 1.5,
    whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
  });

  return (
    <>
      <style>{`
        .jmac-chat-panel { width: 380px; height: min(600px, calc(100vh - 120px)); }
        .jmac-chat-launcher:focus-visible, .jmac-chat-panel button:focus-visible,
        .jmac-chat-panel textarea:focus-visible { outline: none; box-shadow: var(--shadow-focus); }
        @media (max-width: 520px) {
          .jmac-chat-panel { width: calc(100vw - 16px); height: calc(100dvh - 96px); right: 8px !important; bottom: 84px !important; }
          .jmac-chat-launcher { right: 12px !important; bottom: 12px !important; padding: 6px !important; min-height: 0 !important; }
          .jmac-chat-launcher-text { display: none !important; }
          .jmac-chat-launcher-sub { display: none !important; }
          .jmac-chat-teaser { display: none !important; }
        }
        @media (prefers-reduced-motion: no-preference) {
          .jmac-chat-panel { animation: jmacChatIn 200ms cubic-bezier(.2,.7,.2,1); }
          @keyframes jmacChatIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
          .jmac-chat-teaser { animation: jmacChatIn 320ms cubic-bezier(.2,.7,.2,1); }
          .jmac-chat-launcher.is-calling::after {
            content: ''; position: absolute; inset: -2px; border-radius: inherit;
            box-shadow: 0 0 0 0 rgba(255,184,28,.65);
            animation: jmacPulse 1.8s ease-out 1s 3;
            pointer-events: none;
          }
          @keyframes jmacPulse { 0% { box-shadow: 0 0 0 0 rgba(255,184,28,.65); } 100% { box-shadow: 0 0 0 18px rgba(255,184,28,0); } }
        }
        .jmac-chat-launcher:hover { background: var(--amber-300) !important; }
      `}</style>

      {open && (
        <section className="jmac-chat-panel" role="dialog" aria-label={ct('JMAC Assistant', lang)}
          style={{
            position: 'fixed', right: 20, bottom: 100, zIndex: 60,
            display: 'flex', flexDirection: 'column',
            background: 'var(--bg-subtle)', borderRadius: 'var(--radius-xl)', overflow: 'hidden',
            boxShadow: 'var(--shadow-4)', border: '1px solid var(--border-1)',
          }}>
          <header style={{ background: 'var(--steel-900)', color: '#fff' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 14px 12px 16px' }}>
              <AgentAvatar size={40}/>
              <div style={{ flex: 1, lineHeight: 1.1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, letterSpacing: '0.02em' }}>
                  {ct('JMAC AI Agent', lang)}
                </div>
                <div style={{ fontSize: 12, color: 'var(--steel-300)', marginTop: 2 }}>{ct('Online now', lang)}</div>
              </div>
              <button onClick={close} aria-label={ct('Close chat', lang)}
                style={{ background: 'transparent', border: 0, padding: 6, cursor: 'pointer', borderRadius: 'var(--radius-md)', display: 'inline-flex' }}>
                <Icon name="x" size={20} color="#fff"/>
              </button>
            </div>
            <HazardStripe height={4}/>
          </header>

          <div style={{ padding: '10px 16px', fontSize: 12, lineHeight: 1.45, color: 'var(--fg-3)', borderBottom: '1px solid var(--divider)' }}>
            {ct('Automated assistant. It can’t look up accounts or vehicles. Fees and location are sent in your confirmation after you book.', lang)}
          </div>

          <div ref={listRef} aria-live="polite"
               style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={bubble('assistant')}>
              {ct('Hi, I can answer questions about JMAC, redemption appointments, and our services. How can I help?', lang)}
            </div>
            {messages.length === 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 8, marginTop: 4 }}>
                {suggestions.map(s => (
                  <button key={s} onClick={() => send(ct(s, lang), s === 'How do I make an appointment?' ? APPOINTMENT_ANSWER[lang === 'es' ? 'es' : 'en'] : null)}
                    style={{
                      background: 'var(--bg-subtle)', border: '1px solid var(--blue-300)', color: 'var(--blue-700)',
                      borderRadius: 'var(--radius-pill)', padding: '7px 13px', fontSize: 13, fontWeight: 600,
                      cursor: 'pointer', textAlign: 'left',
                    }}>
                    {ct(s, lang)}
                  </button>
                ))}
              </div>
            )}
            {messages.map((m, i) => (
              <div key={i} style={bubble(m.role)}>
                {m.content}
              </div>
            ))}
            {busy && <div style={{ ...bubble('assistant'), color: 'var(--fg-3)' }}>{ct('Typing…', lang)}</div>}
          </div>

          <div style={{ display: 'flex', gap: 8, padding: '8px 12px 0' }}>
            <button onClick={openGuide}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
                background: 'var(--amber-400)', color: '#fff', border: 0,
                borderRadius: 'var(--radius-md)', padding: '8px 12px', fontSize: 13, fontWeight: 700,
              }}>
              <Icon name="check" size={16} color="#fff"/> {ct('Step-by-step guide', lang)}
            </button>
          </div>

          <form onSubmit={(e) => { e.preventDefault(); send(input); }}
            style={{ display: 'flex', gap: 8, padding: 12, alignItems: 'flex-end' }}>
            <textarea ref={inputRef} value={input} rows={1} maxLength={1200}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(input); } }}
              placeholder={ct('Type your question', lang)} aria-label={ct('Type your question', lang)}
              style={{
                flex: 1, resize: 'none', fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.4,
                padding: '10px 12px', border: '1px solid var(--border-2)', borderRadius: 'var(--radius-md)',
                color: 'var(--fg-1)', maxHeight: 120,
              }}/>
            <button type="submit" disabled={busy || !input.trim()} aria-label={ct('Send', lang)}
              style={{
                background: 'var(--blue-700)', color: '#fff', border: 0, borderRadius: 'var(--radius-md)',
                width: 44, height: 44, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                cursor: busy || !input.trim() ? 'default' : 'pointer', opacity: busy || !input.trim() ? 0.5 : 1,
              }}>
              <Icon name="arrow" size={20} color="#fff"/>
            </button>
          </form>
        </section>
      )}

      {teaser && !open && (
        <div className="jmac-chat-teaser" role="status"
          style={{
            position: 'fixed', right: 20, bottom: 100, zIndex: 60, width: 300,
            background: 'var(--bg-subtle)', color: 'var(--fg-1)',
            borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-4)',
            border: '1px solid var(--border-1)', borderLeft: '5px solid var(--amber-400)',
            padding: '14px 40px 14px 16px',
          }}>
          <button onClick={hideTeaser} aria-label={ct('Dismiss', lang)}
            style={{ position: 'absolute', top: 8, right: 8, background: 'transparent', border: 0, padding: 4, cursor: 'pointer', display: 'inline-flex', borderRadius: 'var(--radius-md)' }}>
            <Icon name="x" size={16} color="var(--fg-3)"/>
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <AgentAvatar size={36}/>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: 1.1 }}>
              {ct('Vehicle recovered?', lang)}
            </div>
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.45, color: 'var(--fg-2)', marginBottom: 12 }}>
            {ct('Ask me how to book your appointment and get your car or belongings back.', lang)}
          </div>
          <button onClick={() => { hideTeaser(); setOpen(true); }}
            style={{
              background: 'var(--blue-700)', color: '#fff', border: 0, borderRadius: 'var(--radius-md)',
              padding: '9px 14px', fontSize: 14, fontWeight: 700, cursor: 'pointer',
            }}>
            {ct('Ask a question', lang)}
          </button>
        </div>
      )}

      <button ref={launcherRef} className={'jmac-chat-launcher' + (open ? '' : ' is-calling')}
        onClick={() => { hideTeaser(); open ? close() : setOpen(true); }}
        aria-expanded={open} aria-label={open ? ct('Close chat', lang) : ct('Chat with an AI agent', lang)}
        style={{
          position: 'fixed', right: 20, bottom: 20, zIndex: 60,
          display: 'inline-flex', alignItems: 'center', gap: 12,
          background: 'var(--amber-400)', color: '#fff',
          border: '2px solid var(--mk-blue-hi)', borderRadius: 'var(--radius-pill)',
          padding: open ? '14px 22px 14px 18px' : '12px 26px 12px 14px', minHeight: 64,
          fontFamily: 'var(--font-body)', boxShadow: '0 10px 28px rgba(13,17,23,.35), 0 2px 6px rgba(13,17,23,.2)',
          cursor: 'pointer', textAlign: 'left',
        }}>
        {open ? <span style={{ width: 46, height: 46, display: 'inline-grid', placeItems: 'center' }}><Icon name="x" size={24}/></span> : (
          <span style={{ borderRadius: '50%', boxShadow: '0 0 0 2px var(--steel-900)', display: 'inline-flex' }}>
            <AgentAvatar size={46}/>
          </span>
        )}
        <span className="jmac-chat-launcher-text" style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
          <span style={{ fontWeight: 800, fontSize: 17 }}>
            {open ? ct('Close chat', lang) : ct('Chat with an AI agent', lang)}
          </span>
          {!open && (
            <span className="jmac-chat-launcher-sub" style={{ fontWeight: 600, fontSize: 13, opacity: 0.85, marginTop: 2 }}>
              {ct('Ask about appointments, fees & pickup', lang)}
            </span>
          )}
        </span>
      </button>
    </>
  );
};
