/* ============================================================================
 * AIVA CHAT — Floating Chat-Assistant
 * ----------------------------------------------------------------------------
 * Klassische Chat-Bubble unten rechts (nur auf funnel.html geladen).
 *   - Verwendet AivaEngine (Backend-Call mit Claude-Fallback)
 *   - Dispatcht aiva:action Events → pricing-calculator hört zu
 *   - Liest window.__aivaCalcState (vom pricing-calculator publiziert)
 * ========================================================================= */

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA, useCallback: useCallbackA } = React;

const AIVA_GREETING = "Hallo, ich bin **Aiva** — Ihre digitale IT-Beraterin. Ich helfe Ihnen das passende Paket zusammenzustellen und beantworte Ihre Fragen zu Cyber-Sicherheit, NIS-2 oder Versicherbarkeit. Womit darf ich anfangen?";

const AIVA_DEFAULT_QUICK_REPLIES = [
  "Welches Paket passt zu uns?",
  "Was bedeutet NIS-2 für uns?",
  "Wie macht Ihr unsere IT versicherbar?"
];

/* ───────── Hilfs-Renderer für **fett**-Markdown ───────────────────────── */
function AivaMarkdown({ text }) {
  if (!text) return null;
  const parts = String(text).split(/(\*\*[^*]+\*\*)/g);
  return (
    <>
      {parts.map((p, i) => {
        if (p.startsWith('**') && p.endsWith('**')) {
          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>
        ));
      })}
    </>
  );
}

/* ───────── Aiva-Avatar (SVG-Logo) ─────────────────────────────────────── */
function AivaAvatar({ size = 32, animated = false }) {
  return (
    <div className={`aiva-avatar ${animated ? 'aiva-avatar-animated' : ''}`} style={{ width: size, height: size }}>
      <svg viewBox="0 0 32 32" width={size} height={size}>
        <defs>
          <linearGradient id="aivaGrad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#FFB703"/>
            <stop offset="100%" stopColor="#FF8C00"/>
          </linearGradient>
        </defs>
        <circle cx="16" cy="16" r="15" fill="url(#aivaGrad)"/>
        <path d="M16 7 L19.5 14.5 L26 16 L19.5 17.5 L16 25 L12.5 17.5 L6 16 L12.5 14.5 Z"
              fill="#000926" opacity="0.9"/>
      </svg>
    </div>
  );
}

/* ───────── Kontakt-Fallback-Card ───────────────────────────────────────── */
function AivaContactCard() {
  const c = window.AIVA_CONFIG.contact;
  return (
    <div className="aiva-contact-card">
      <div className="aiva-cc-title">Direkter Draht zum Team</div>
      <a href={`tel:${c.phone.replace(/\s/g, '')}`} className="aiva-cc-row">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
        <div>
          <div className="aiva-cc-label">Anrufen</div>
          <div className="aiva-cc-val">{c.phone}</div>
        </div>
      </a>
      <a href={`mailto:${c.email}`} className="aiva-cc-row">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
        <div>
          <div className="aiva-cc-label">E-Mail</div>
          <div className="aiva-cc-val">{c.email}</div>
        </div>
      </a>
      <div className="aiva-cc-meta">{c.hours}</div>
    </div>
  );
}

/* ───────── Single Message ──────────────────────────────────────────────── */
function MessageBubble({ message }) {
  const isUser = message.role === 'user';
  if (isUser) {
    return (
      <div className="aiva-msg aiva-msg-user">
        <div className="aiva-msg-bubble aiva-msg-bubble-user">
          <AivaMarkdown text={message.text}/>
        </div>
      </div>
    );
  }
  return (
    <div className="aiva-msg aiva-msg-assistant">
      <AivaAvatar size={28}/>
      <div className="aiva-msg-body">
        <div className="aiva-msg-bubble aiva-msg-bubble-assistant">
          <AivaMarkdown text={message.text}/>
        </div>
        {message.showContact && <AivaContactCard/>}
      </div>
    </div>
  );
}

/* ───────── Hauptkomponente ─────────────────────────────────────────────── */
function AivaChat() {
  const [open, setOpen] = useStateA(false);
  const [messages, setMessages] = useStateA(() => [{
    role: 'assistant',
    text: AIVA_GREETING,
    quickReplies: AIVA_DEFAULT_QUICK_REPLIES,
    showContact: false
  }]);
  const [input, setInput] = useStateA('');
  const [loading, setLoading] = useStateA(false);
  const [unread, setUnread] = useStateA(0);
  const scrollRef = useRefA(null);

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

  const getCalcState = () => window.__aivaCalcState || {};

  const send = useCallbackA(async (text) => {
    const trimmed = (text || '').trim();
    if (!trimmed || loading) return;

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

    const apiHistory = newHistory.map((m) => ({ role: m.role, content: m.text }));
    const result = await window.AivaEngine.sendMessage(
      apiHistory.slice(0, -1),
      trimmed,
      getCalcState()
    );

    window.AivaEngine.applyActions(result.actions);
    const hasContact = (result.actions || []).some((a) => a && a.type === 'show_contact');

    setMessages((m) => [...m, {
      role: 'assistant',
      text: result.text || '…',
      quickReplies: result.quickReplies || [],
      showContact: hasContact
    }]);
    setLoading(false);
    if (!open) setUnread((u) => u + 1);
  }, [messages, loading, open]);

  const toggleOpen = () => {
    const next = !open;
    setOpen(next);
    if (next) setUnread(0);
  };

  return (
    <div className="aiva-root">
      {open && (
        <div className="aiva-panel" role="dialog" aria-label="Aiva Chat">
          <header className="aiva-header">
            <div className="aiva-header-left">
              <AivaAvatar size={36}/>
              <div>
                <div className="aiva-header-name">Aiva</div>
                <div className="aiva-header-role">
                  <span className="aiva-online-dot"/>
                  <span>Online</span>
                  <span className="aiva-header-sep">·</span>
                  <span>IT-Beraterin MaliTech</span>
                </div>
              </div>
            </div>
            <button className="aiva-close" onClick={toggleOpen} aria-label="Schließen">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
            </button>
          </header>

          <div className="aiva-messages" ref={scrollRef}>
            {messages.map((m, i) => <MessageBubble key={i} message={m}/>)}
            {loading && (
              <div className="aiva-msg aiva-msg-assistant">
                <AivaAvatar size={28}/>
                <div className="aiva-msg-bubble aiva-msg-bubble-assistant">
                  <span className="aiva-typing"><span/><span/><span/></span>
                </div>
              </div>
            )}
          </div>

          {(() => {
            const last = [...messages].reverse().find((m) => m.role === 'assistant');
            const qr = last?.quickReplies || [];
            if (!qr.length || loading) return null;
            return (
              <div className="aiva-quick-replies">
                {qr.slice(0, 4).map((q, i) => (
                  <button key={i} className="aiva-chip" onClick={() => send(q)}>{q}</button>
                ))}
              </div>
            );
          })()}

          <form className="aiva-input-row" onSubmit={(e) => { e.preventDefault(); send(input); }}>
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Nachricht an Aiva …"
              disabled={loading}
              autoComplete="off"/>
            <button type="submit" disabled={loading || !input.trim()} className="aiva-send" aria-label="Senden">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" 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 className="aiva-disclaimer">
            Aiva ist ein KI-Assistent. Für verbindliche Angebote: <a href={`tel:${window.AIVA_CONFIG.contact.phone.replace(/\s/g,'')}`}>{window.AIVA_CONFIG.contact.phone}</a>
          </div>
        </div>
      )}

      <button
        type="button"
        className={`aiva-launcher ${open ? 'aiva-launcher-open' : ''}`}
        onClick={toggleOpen}
        aria-label={open ? 'Aiva schließen' : 'Aiva öffnen'}>
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
        ) : (
          <>
            <AivaAvatar size={32} animated/>
            {unread > 0 && <span className="aiva-launcher-badge">{unread}</span>}
          </>
        )}
      </button>
    </div>
  );
}

window.AivaChat = AivaChat;
