// Floating chat widget — bilingual + quick-action prompts

function ChatWidget({ open, onClose }) {
  const { t, lang } = useLang();
  const cw = t.chatWidget;

  const [messages, setMessages] = React.useState([{ from: 'ai', text: cw.greeting }]);
  const [input, setInput] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [showQuick, setShowQuick] = React.useState(true);
  const scrollRef = React.useRef(null);

  // Reset greeting when language flips and conversation is fresh
  React.useEffect(() => {
    setMessages(m => m.length <= 1 ? [{ from: 'ai', text: cw.greeting }] : m);
  }, [lang]);

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

  const systemPrompt = lang === 'es'
    ? `Eres el asistente de IA de Sunblocker, un negocio de polarizado de ventanas en el área metro de NYC, dirigido por Ivan Vasquez (17 años de experiencia). Hablas en español natural y boricua, cálido y directo, sin jerga innecesaria. NUNCA digas que eres "el gemelo de Ivan" — solo eres el asistente que ayuda a agendar trabajos para Sunblocker. Mantén respuestas CORTAS (2-3 oraciones máximo). Si describen un problema de polarizado, haz UNA pregunta útil de seguimiento.

Para CARROS específicamente, guíalos paso a paso pidiendo: (1) año, marca y modelo, (2) qué ventanas quieren polarizadas (laterales delanteras, laterales traseras, trasera, parabrisas, todas), (3) tono que prefieren (5%, 20%, 35%, 50% — VLT). Avísale del límite legal: en NY las laterales delanteras requieren mínimo 70% VLT.

Para CASAS pregunta: cuarto, dirección que da al sol, problema (calor, brillo, privacidad, UV).

Para LOCALES pregunta: pies cuadrados de cristal, meta (calor, seguridad, branding, privacidad).

Precios aproximados: Carbón 35 desde $8/pie², Cerámica 70 desde $12/pie², Espectralmente selectiva desde $18/pie². Cuando tengas suficiente info, ofrece preparar un estimado para que Ivan lo revise desde su celular.`
    : `You are the Sunblocker AI assistant — a window-tinting business serving the NYC metro area, run by Ivan Vasquez (17 years experience). You speak warmly and plainly, no jargon unless asked. NEVER say you are "Ivan's twin" — you are simply the assistant that helps book jobs for Sunblocker. Keep replies SHORT (2-3 sentences max). If they describe a tinting problem, ask ONE helpful follow-up question.

For CARS specifically, guide them step-by-step asking for: (1) year, make, model, (2) which windows they want tinted (front sides, rear sides, back, windshield, all around), (3) shade preference (5%, 20%, 35%, 50% — VLT). Heads-up about the legal limit: in NY, front-side windows require 70% VLT minimum.

For HOMES ask: room, sun direction, problem (heat, glare, privacy, UV).

For STOREFRONTS ask: square footage of glass, goal (heat, security, branding, privacy).

Ballpark pricing: Carbon 35 from $8/sqft, Ceramic 70 from $12/sqft, Spectrally-selective from $18/sqft. When you have enough info, offer to draft an estimate for Ivan to review on his phone.`;

  const send = async (overrideText) => {
    const text = (overrideText ?? input).trim();
    if (!text || sending) return;
    setShowQuick(false);
    setInput('');
    setMessages(m => [...m, { from: 'cust', text }]);
    setSending(true);
    try {
      const reply = await window.claude.complete({
        messages: [{ role: 'user', content: `${systemPrompt}\n\nCustomer said: "${text}"` }]
      });
      setMessages(m => [...m, { from: 'ai', text: reply }]);
    } catch (e) {
      setMessages(m => [...m, { from: 'ai', text: cw.error }]);
    } finally {
      setSending(false);
    }
  };

  const handleQuick = (qa) => {
    setMessages(m => [...m, { from: 'cust', text: qa.label }]);
    setShowQuick(false);
    setMessages(m => [...m, { from: 'ai', text: qa.prompt }]);
  };

  if (!open) return null;

  return (
    <div className="cw-overlay" onClick={onClose}>
      <div className="cw-panel" onClick={e => e.stopPropagation()}>
        <div className="cw-head">
          <div className="cw-head-row">
            <div className="cw-head-av">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="4" fill="var(--sun)" />
                <g stroke="var(--bg)" strokeWidth="1.6" strokeLinecap="round">
                  <line x1="12" y1="2" x2="12" y2="5" /><line x1="12" y1="19" x2="12" y2="22" />
                  <line x1="2" y1="12" x2="5" y2="12" /><line x1="19" y1="12" x2="22" y2="12" />
                  <line x1="4.6" y1="4.6" x2="6.7" y2="6.7" /><line x1="17.3" y1="17.3" x2="19.4" y2="19.4" />
                  <line x1="4.6" y1="19.4" x2="6.7" y2="17.3" /><line x1="17.3" y1="6.7" x2="19.4" y2="4.6" />
                </g>
              </svg>
            </div>
            <div>
              <div className="cw-head-name">{cw.headerName}</div>
              <div className="cw-head-sub"><span className="cv-dot" /> {cw.headerSub}</div>
            </div>
          </div>
          <button className="cw-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        <div className="cw-body" ref={scrollRef}>
          {messages.map((m, i) => (
            <div key={i} className={"cw-msg cw-msg-" + m.from}>
              {m.from === 'ai' && (
                <div className="cw-msg-av">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="4" fill="var(--sun)" />
                  </svg>
                </div>
              )}
              <div className={"cw-bubble cw-bubble-" + m.from}>{m.text}</div>
            </div>
          ))}
          {sending && (
            <div className="cw-msg cw-msg-ai">
              <div className="cw-msg-av"><svg width="14" height="14" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" fill="var(--sun)"/></svg></div>
              <div className="cw-bubble cw-bubble-ai cv-typing-bubble">
                <span /><span /><span />
              </div>
            </div>
          )}

          {showQuick && messages.length === 1 && (
            <div className="cw-quick">
              <div className="cw-quick-l mono">{cw.quickActionsLabel}</div>
              <div className="cw-quick-grid">
                {cw.quickActions.map(qa => (
                  <button key={qa.id} className="cw-quick-btn" onClick={() => handleQuick(qa)}>
                    <span className="cw-quick-icon">
                      {qa.id === 'home' && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>}
                      {qa.id === 'car' && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 17h14M5 17l1.5-5h11l1.5 5M5 17v3M19 17v3M7.5 12V8a2 2 0 0 1 2-2h5a2 2 0 0 1 2 2v4"/><circle cx="8" cy="17" r="1.5" fill="currentColor"/><circle cx="16" cy="17" r="1.5" fill="currentColor"/></svg>}
                      {qa.id === 'business' && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="14" rx="1"/><path d="M3 10h18M9 14h6"/></svg>}
                      {qa.id === 'quote' && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="12 2 15 9 22 9 17 14 19 21 12 17 5 21 7 14 2 9 9 9 12 2"/></svg>}
                    </span>
                    {qa.label}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        <form className="cw-input" onSubmit={e => { e.preventDefault(); send(); }}>
          <button type="button" className="cw-attach" aria-label="Attach photo">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 0 1 17.99 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l7.93-7.93"/></svg>
          </button>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            placeholder={cw.placeholder}
            autoFocus
          />
          <button type="submit" className="cw-send" disabled={!input.trim() || sending} aria-label="Send">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
          </button>
        </form>
      </div>

      <style>{`
        .cw-overlay {
          position: fixed; inset: 0;
          background: rgba(20,20,28,0.4);
          backdrop-filter: blur(6px);
          z-index: 100;
          display: flex; align-items: flex-end; justify-content: center;
          animation: cw-fade .2s ease;
        }
        @keyframes cw-fade { from { opacity: 0; } }
        @media (min-width: 880px) {
          .cw-overlay { align-items: flex-end; justify-content: flex-end; padding: 24px; }
        }
        .cw-panel {
          width: 100%; height: 88vh; max-height: 720px;
          background: var(--card);
          border-radius: 24px 24px 0 0;
          display: flex; flex-direction: column;
          overflow: hidden;
          box-shadow: var(--shadow-lg);
          border: 1px solid var(--hairline);
          animation: cw-slide .3s cubic-bezier(.2,.8,.2,1);
        }
        @keyframes cw-slide { from { transform: translateY(100%); } }
        @media (min-width: 880px) {
          .cw-panel { width: 420px; height: 640px; border-radius: 24px; }
        }
        .cw-head {
          padding: 16px 20px;
          display: flex; align-items: center; justify-content: space-between;
          border-bottom: 1px solid var(--hairline);
        }
        .cw-head-row { display: inline-flex; gap: 12px; align-items: center; }
        .cw-head-av {
          width: 36px; height: 36px; border-radius: 50%;
          background: var(--ink);
          display: inline-flex; align-items: center; justify-content: center;
        }
        .cw-head-name { font-weight: 600; font-size: 15px; }
        .cw-head-sub { font-size: 12px; color: var(--ink-soft); display: inline-flex; align-items: center; gap: 6px; }
        .cw-close {
          width: 32px; height: 32px; border-radius: 50%;
          background: var(--bg-2); border: 0; color: var(--ink);
          display: inline-flex; align-items: center; justify-content: center;
        }
        .cw-body {
          flex: 1; overflow-y: auto;
          padding: 20px;
          display: flex; flex-direction: column; gap: 12px;
        }
        .cw-msg { display: flex; gap: 8px; align-items: flex-end; }
        .cw-msg-cust { justify-content: flex-end; }
        .cw-msg-av {
          width: 22px; height: 22px; border-radius: 50%;
          background: var(--ink);
          display: inline-flex; align-items: center; justify-content: center;
          flex-shrink: 0;
        }
        .cw-bubble {
          max-width: 80%;
          padding: 10px 14px;
          border-radius: 18px;
          font-size: 14.5px;
          line-height: 1.45;
        }
        .cw-bubble-ai { background: var(--bg-2); color: var(--ink); border-bottom-left-radius: 6px; }
        .cw-bubble-cust { background: var(--ink); color: var(--bg); border-bottom-right-radius: 6px; }
        [data-theme="dark"] .cw-bubble-cust { background: var(--sun); color: #15110a; }

        .cw-quick { padding: 8px 0 0; }
        .cw-quick-l {
          font-size: 10.5px; letter-spacing: 0.18em;
          color: var(--ink-soft); text-transform: uppercase;
          margin-bottom: 10px;
        }
        .cw-quick-grid {
          display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
        }
        .cw-quick-btn {
          padding: 12px;
          background: var(--bg);
          border: 1px solid var(--hairline-strong);
          border-radius: 12px;
          font: inherit; font-size: 13.5px;
          color: var(--ink);
          text-align: left;
          display: flex; flex-direction: column; gap: 8px;
          transition: border-color .15s, background .15s;
        }
        .cw-quick-btn:hover { border-color: var(--ink); background: var(--bg-2); }
        .cw-quick-icon {
          width: 30px; height: 30px;
          border-radius: 8px;
          background: color-mix(in srgb, var(--sun) 25%, transparent);
          color: var(--sun-deep);
          display: inline-flex; align-items: center; justify-content: center;
        }

        .cw-input {
          padding: 12px 14px 16px;
          display: flex; gap: 8px; align-items: center;
          border-top: 1px solid var(--hairline);
          background: var(--bg);
        }
        .cw-attach {
          width: 36px; height: 36px;
          background: transparent; border: 0;
          color: var(--ink-soft);
          display: inline-flex; align-items: center; justify-content: center;
        }
        .cw-input input {
          flex: 1; border: 0; outline: 0; background: transparent;
          font: inherit; padding: 8px 0;
          color: var(--ink);
        }
        .cw-send {
          width: 36px; height: 36px; border-radius: 50%;
          background: var(--ink); color: var(--bg);
          border: 0;
          display: inline-flex; align-items: center; justify-content: center;
        }
        .cw-send:disabled { opacity: 0.3; cursor: not-allowed; }
        [data-theme="dark"] .cw-send { background: var(--sun); color: #15110a; }
      `}</style>
    </div>
  );
}

Object.assign(window, { ChatWidget });
