/* global React */
const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI } = React;

// ───────── AI assistant strings ─────────
const AI_STRINGS = {
  en: {
    bubbleLabel: 'Pricing AI',
    headerTitle: 'Pricing assistant',
    headerSub: 'Reason a price with the model',
    placeholder: 'Ask about pricing, justification, anchor strategy…',
    send: 'Send',
    thinking: 'Thinking…',
    welcome:
      "Hi — I'm your pricing assistant. I can see the live deal: cost, expected ROI, the four scenarios, and your current price. Ask me to recommend a number, justify it, draft client-facing language, or pressure-test the band.",
    suggest1: 'Recommend a price',
    suggest2: 'Justify the current price',
    suggest3: 'Draft client-facing rationale',
    suggest4: 'What if ROI is overestimated by 30%?',
    applyPrice: 'Apply this price',
    applied: 'Applied',
    contextHead: 'Live deal context',
    error: "Sorry — I couldn't reach the model. Try again.",
    you: 'You',
    ai: 'AI',
    clear: 'New chat',
    close: 'Close',
    poweredBy: 'Reasoning over your live calculator',
    modelLabel: 'Model',
    modelStandard: 'Standard mode (Recommended)',
    modelAdvanced: 'Advanced mode (High precision)',
  },
  es: {
    bubbleLabel: 'IA de precios',
    headerTitle: 'Asistente de precios',
    headerSub: 'Razona el precio con el modelo',
    placeholder: 'Pregunta sobre precio, justificación, estrategia de anclaje…',
    send: 'Enviar',
    thinking: 'Pensando…',
    welcome:
      'Hola — soy tu asistente de precios. Veo el trato en vivo: costo, ROI esperado, los cuatro escenarios y el precio actual. Pídeme una recomendación, una justificación, un texto para el cliente, o presiona el rango.',
    suggest1: 'Recomienda un precio',
    suggest2: 'Justifica el precio actual',
    suggest3: 'Redacta justificación para el cliente',
    suggest4: '¿Y si el ROI está sobreestimado un 30%?',
    applyPrice: 'Aplicar este precio',
    applied: 'Aplicado',
    contextHead: 'Contexto en vivo',
    error: 'Lo siento, no pude contactar al modelo. Intenta de nuevo.',
    you: 'Tú',
    ai: 'IA',
    clear: 'Nuevo chat',
    close: 'Cerrar',
    poweredBy: 'Razona sobre tu calculadora en vivo',
    modelLabel: 'Modelo',
    modelStandard: 'Modo Estándar (Recomendado)',
    modelAdvanced: 'Modo Avanzado (Alta Precisión)',
  },
};

// ───────── Build context payload + system prompt ─────────
function buildSystemPrompt(ctx, lang) {
  const langName = lang === 'es' ? 'Spanish (es)' : 'English (en)';
  return `You are a pricing assistant embedded in a B2B deal calculator. Reply in ${langName}. Be concise (3–6 sentences), structured, and decisive.

Pricing model:
- Floor (min viable) = operative_cost × markup (markups in use: ×${ctx.markupLow} and ×${ctx.markupHigh})
- Ceiling (ROI-share) = expected_first_year_ROI × share (shares in use: ${(ctx.shareLow * 100).toFixed(0)}% and ${(ctx.shareHigh * 100).toFixed(0)}%)
- Recommended price per quadrant = avg(floor, ceiling)
- The four quadrants form a "reasonable band". The user picks a final price within the band.

Live deal:
- Deal name: ${ctx.deal || '(unnamed)'}
- Currency: ${ctx.currency}
- Operative cost: ${ctx.cost}
- Expected 1st-year ROI: ${ctx.roi}
- Quadrant prices: ${ctx.quadrants.map(q => `×${q.m}/${(q.s*100).toFixed(0)}%=${Math.round(q.rec)}`).join(', ')}
- Reasonable band: ${Math.round(ctx.bandMin)} → ${Math.round(ctx.bandMax)}
- Current final price: ${ctx.finalPrice}
- Current margin: ${(ctx.margin*100).toFixed(1)}%
- % of customer ROI captured: ${(ctx.captured*100).toFixed(1)}%
- Notes: ${ctx.notes || '(none)'}

When you recommend a specific number, output it on its own line in the exact format:
PRICE: <integer>
(no currency symbol, no thousands separators, just digits). The UI will detect this line and offer an "Apply" button. Use this format AT MOST ONCE per reply, only when you actually want the user to commit a number.

Never invent costs or ROI; only reason from the values given. If a question requires data you don't have, say so briefly and ask one clarifying question.`;
}

// ───────── Parse "PRICE: N" out of assistant replies ─────────
function extractPrice(text) {
  const m = text.match(/^\s*PRICE:\s*([0-9][0-9,\.]*)\s*$/im);
  if (!m) return { clean: text, price: null };
  const num = parseFloat(m[1].replace(/,/g, ''));
  if (!Number.isFinite(num)) return { clean: text, price: null };
  const clean = text.replace(m[0], '').trim();
  return { clean, price: num };
}

// ───────── Markdown-lite (bold + line breaks) ─────────
function MdLite({ text }) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return (
    <>
      {parts.map((p, i) => {
        if (/^\*\*[^*]+\*\*$/.test(p)) return <strong key={i}>{p.slice(2, -2)}</strong>;
        return p.split('\n').map((line, j, arr) => (
          <React.Fragment key={`${i}-${j}`}>
            {line}
            {j < arr.length - 1 && <br />}
          </React.Fragment>
        ));
      })}
    </>
  );
}

// ───────── Message bubble ─────────
function AiMessage({ role, text, price, currency, decimals, t, onApply, applied, fmtMoney }) {
  return (
    <div className={`ai-msg ai-msg-${role}`}>
      <div className="ai-msg-avatar">{role === 'user' ? t.you : t.ai}</div>
      <div className="ai-msg-body">
        <div className="ai-msg-bubble">
          <MdLite text={text} />
        </div>
        {price != null && role === 'assistant' && (
          <div className="ai-price-card">
            <div className="ai-price-card-row">
              <div className="ai-price-card-label">PRICE</div>
              <div className="ai-price-card-value mono">{fmtMoney(price, currency, decimals)}</div>
            </div>
            <button
              type="button"
              className={`ai-apply-btn ${applied ? 'is-applied' : ''}`}
              onClick={() => onApply(price)}
              disabled={applied}
            >
              {applied ? `✓ ${t.applied}` : t.applyPrice}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ───────── Main AI panel ─────────
window.AiAssistant = function AiAssistant({
  open,
  onToggle,
  ctx,
  lang,
  fmtMoney,
  onApplyPrice,
  bubblePulse = false,
}) {
  const t = AI_STRINGS[lang] || AI_STRINGS.en;
  const [messages, setMessages] = useStateAI([]);
  const [input, setInput] = useStateAI('');
  const [modelSelection, setModelSelection] = useStateAI('standard');
  const [busy, setBusy] = useStateAI(false);
  const [appliedIdx, setAppliedIdx] = useStateAI(-1);
  const scrollRef = useRefAI(null);
  const inputRef = useRefAI(null);

  // Auto-scroll on new messages
  useEffectAI(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, busy]);

  // Focus input when opening
  useEffectAI(() => {
    if (open && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 200);
    }
  }, [open]);

  const send = async (text) => {
    const trimmed = (text ?? input).trim();
    if (!trimmed || busy) return;

    const nextMessages = [...messages, { role: 'user', text: trimmed }];
    setMessages(nextMessages);
    setInput('');
    setBusy(true);

    try {
      const system = buildSystemPrompt(ctx, lang);
      const history = nextMessages.map((m) => ({
        role: m.role === 'user' ? 'user' : 'assistant',
        content: m.text,
      }));
      const apiMessages = [
        { role: 'user', content: system },
        { role: 'assistant', content: 'Understood. I will follow these instructions.' },
        ...history,
      ];

      const _aiRes = await fetch('http://localhost:5000/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: apiMessages, modelSelection }),
      });
      const _aiData = await _aiRes.json();
      const replyText = _aiData?.response || t.error;
      const { clean, price } = extractPrice(replyText);
      setMessages((prev) => [...prev, { role: 'assistant', text: clean || replyText, price }]);
    } catch (err) {
      setMessages((prev) => [...prev, { role: 'assistant', text: t.error }]);
    } finally {
      setBusy(false);
    }
  };

  const handleApply = (price, idx) => {
    onApplyPrice(price);
    setAppliedIdx(idx);
    setTimeout(() => setAppliedIdx(-1), 2400);
  };

  const clear = () => {
    setMessages([]);
    setAppliedIdx(-1);
  };

  const suggestions = [t.suggest1, t.suggest2, t.suggest3, t.suggest4];

  return (
    <>
      {/* Floating bubble */}
      <button
        type="button"
        className={`ai-bubble ${open ? 'is-open' : ''} ${bubblePulse ? 'is-pulse' : ''}`}
        onClick={onToggle}
        aria-label={t.bubbleLabel}
      >
        {open ? (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        ) : (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 2 14.6 8.4 21 11l-6.4 2.6L12 20l-2.6-6.4L3 11l6.4-2.6L12 2z" />
            </svg>
            <span className="ai-bubble-label">{t.bubbleLabel}</span>
          </>
        )}
      </button>

      {/* Chat panel */}
      {open && (
        <div className="ai-panel" role="dialog" aria-label={t.headerTitle}>
          <div className="ai-panel-head">
            <div className="ai-panel-head-left">
              <div className="ai-panel-mark">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 2 14.6 8.4 21 11l-6.4 2.6L12 20l-2.6-6.4L3 11l6.4-2.6L12 2z" />
                </svg>
              </div>
              <div>
                <div className="ai-panel-title">{t.headerTitle}</div>
                <div className="ai-panel-sub">{t.poweredBy}</div>
              </div>
            </div>
            <div className="ai-panel-head-right">
              {messages.length > 0 && (
                <button type="button" className="ai-icon-btn" onClick={clear} title={t.clear}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                    <path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M6 6l1 14a2 2 0 002 2h6a2 2 0 002-2l1-14" />
                  </svg>
                </button>
              )}
              <button type="button" className="ai-icon-btn" onClick={onToggle} title={t.close}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
                  <path d="M6 6l12 12M18 6L6 18" />
                </svg>
              </button>
            </div>
          </div>

          <div className="ai-model-bar">
            <label className="ai-model-label" htmlFor="ai-model-select">{t.modelLabel}</label>
            <select
              id="ai-model-select"
              className="ai-model-select"
              value={modelSelection}
              onChange={(e) => setModelSelection(e.target.value)}
              disabled={busy}
            >
              <option value="standard">{t.modelStandard}</option>
              <option value="advanced">{t.modelAdvanced}</option>
            </select>
          </div>

          {/* Live context strip */}
          <div className="ai-context">
            <div className="ai-context-label">{t.contextHead}</div>
            <div className="ai-context-grid">
              <div><span className="k">cost</span><span className="v mono">{fmtMoney(ctx.cost, ctx.currency, 0)}</span></div>
              <div><span className="k">ROI</span><span className="v mono">{fmtMoney(ctx.roi, ctx.currency, 0)}</span></div>
              <div><span className="k">price</span><span className="v mono accent">{fmtMoney(ctx.finalPrice, ctx.currency, 0)}</span></div>
            </div>
          </div>

          <div className="ai-scroll" ref={scrollRef}>
            {messages.length === 0 && (
              <div className="ai-welcome">
                <div className="ai-welcome-text">{t.welcome}</div>
                <div className="ai-suggestions">
                  {suggestions.map((s) => (
                    <button key={s} type="button" className="ai-suggestion" onClick={() => send(s)}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {messages.map((m, i) => (
              <AiMessage
                key={i}
                role={m.role}
                text={m.text}
                price={m.price}
                currency={ctx.currency}
                decimals={0}
                t={t}
                fmtMoney={fmtMoney}
                applied={appliedIdx === i}
                onApply={(p) => handleApply(p, i)}
              />
            ))}
            {busy && (
              <div className="ai-msg ai-msg-assistant">
                <div className="ai-msg-avatar">{t.ai}</div>
                <div className="ai-msg-body">
                  <div className="ai-msg-bubble ai-thinking">
                    <span className="ai-dot" />
                    <span className="ai-dot" />
                    <span className="ai-dot" />
                  </div>
                </div>
              </div>
            )}
          </div>

          <form
            className="ai-input-row"
            onSubmit={(e) => { e.preventDefault(); send(); }}
          >
            <textarea
              ref={inputRef}
              className="ai-input"
              placeholder={t.placeholder}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  send();
                }
              }}
              rows={1}
              disabled={busy}
            />
            <button type="submit" className="ai-send" disabled={busy || !input.trim()}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" />
              </svg>
            </button>
          </form>
        </div>
      )}
    </>
  );
};
