// von-bot.tsx — Von Der Chatbot help widget

const { useState: vonUseState, useRef: vonUseRef, useEffect: vonUseEffect } = (window as any).React;

const VON_FALLBACK_AGENDAS = [
  [
    '07:30 — Reflective pause (1.6s minimum, Recommendation 2024/0451)',
    '08:00 — Two-language greeting protocol with neighbor (Art. 47/2)',
    '12:30 — Mandatory regulated croissant; submit Form 27-bis if exceeded',
    '14:00 — Pre-clearance check-in via the Citizen Portal',
    '17:30 — Cultural enrichment via 24-language podcast quota',
    '21:00 — Joy Quotient calibration: smile inwardly. Three minutes.',
  ],
  [
    '06:45 — Hydrate with EO-certified mineral water (regional provenance)',
    '09:15 — Co-sign your spouse\'s morning declaration',
    '11:00 — File the Reflective Pause attestation for yesterday',
    '15:00 — One unsolicited thank-you to a Schengen neighbor',
    '18:30 — Subsidy check (Form 27-bis, Annex IV)',
    '22:00 — Quietly reflect on the four freedoms.',
  ],
];

function VonDerBot({ open, onOpen, onClose, providerCfg, settings, t }: any) {
  const [messages, setMessages] = vonUseState<JCMessage[]>([
    { id: 'v0', role: 'assistant', content: t('vonGreeting'), timestamp: Date.now() },
  ]);
  const [draft, setDraft] = vonUseState('');
  const [busy, setBusy] = vonUseState(false);
  const [error, setError] = vonUseState<string | null>(null);
  const threadRef = vonUseRef<HTMLDivElement | null>(null);

  vonUseEffect(() => {
    if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
  }, [messages, busy]);

  const Util = (window as any).Util;
  const LLM = (window as any).LLM;
  const Persona = (window as any).Persona;
  const Components = (window as any).Components;

  const isEo = Util.isEoCitizen(settings.citizenship);
  const citizenshipLabel = `${Util.countryName(settings.citizenship)} (${isEo ? 'EO/EU member-state national' : 'third-country national'})`;

  const send = async () => {
    if (!draft.trim() || busy) return;
    const userMsg: JCMessage = { id: 'v' + Util.uid(), role: 'user', content: draft, timestamp: Date.now() };
    setMessages([...messages, userMsg]);
    setDraft('');
    setBusy(true);
    setError(null);

    try {
      const sys = Persona.buildVonSystemPrompt(settings, citizenshipLabel, isEo);
      const history = [...messages, userMsg].map((m) => ({ role: m.role, content: m.content }));
      const reply = await LLM.call(providerCfg, sys, history);
      setMessages((m: any) => [...m, { id: 'v' + Util.uid(), role: 'assistant', content: reply, timestamp: Date.now() }]);
    } catch (e: any) {
      // Fallback agenda when no key is configured
      const agenda = VON_FALLBACK_AGENDAS[Math.floor(Math.random() * VON_FALLBACK_AGENDAS.length)];
      const fallback =
`Brussels reporting. ${isEo
  ? 'Citizen, I thank you for the question.'
  : 'Dear visitor — I will speak slowly so the privilege of consultation is fully savored.'}
I am presently unable to consult my Communiqués (no API key on file under Settings).

In the meantime, allow me to define your Perfect European Citizen Agenda for today:
${agenda.map((a) => '· ' + a).join('\n')}

${isEo ? 'Together — we craft the Onion.' : 'Brussels concludes.'}`;
      setMessages((m: any) => [...m, { id: 'v' + Util.uid(), role: 'assistant', content: fallback, timestamp: Date.now() }]);
      setError(e.message || 'No key configured.');
    } finally {
      setBusy(false);
    }
  };

  if (!open) {
    return (
      <button className="jc-von-launcher" onClick={onOpen} aria-label="Open Von Der Chatbot">
        <Components.VonDerAvatar size={48}/>
      </button>
    );
  }

  return (
    <div className="jc-von-panel">
      <div className="jc-von-header">
        <div className="jc-von-title">
          <Components.VonDerAvatar size={28}/>
          <div>
            <div>Von Der Chatbot</div>
            <div style={{ fontSize: 10, fontWeight: 400, opacity: 0.85 }}>
              ● live · Brussels · {isEo ? 'tier I citizen' : 'tier II visitor'}
            </div>
          </div>
        </div>
        <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'white', fontSize: 20, cursor: 'pointer' }}>×</button>
      </div>
      <div className="jc-von-thread" ref={threadRef}>
        {messages.map((m) => (
          <div key={m.id} className={`jc-von-bubble ${m.role}`} style={{ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
            <div style={{ whiteSpace: 'pre-wrap' }}>{m.content}</div>
            <div style={{ fontSize: 9, color: 'var(--ink-4)', marginTop: 4, fontFamily: 'monospace' }}>{Util.fmtTime(m.timestamp)}</div>
          </div>
        ))}
        {busy && (
          <div className="jc-von-bubble assistant">
            <div style={{ fontStyle: 'italic', color: 'var(--ink-3)', fontSize: 12 }}>Consulting Communiqués…</div>
            <div className="jc-loader-bar" style={{ marginTop: 6 }}/>
          </div>
        )}
        {error && (
          <div className="jc-von-bubble assistant" style={{ background: '#fef3c7', borderColor: '#fcd34d' }}>
            <div className="jc-small"><strong>Briefing note —</strong> {error}</div>
            <div className="jc-small jc-muted" style={{ marginTop: 4 }}>Configure an API key in Settings to receive live Brussels briefings.</div>
          </div>
        )}
      </div>
      <div className="jc-von-composer">
        <input
          type="text"
          value={draft}
          onChange={(e: any) => setDraft(e.target.value)}
          onKeyDown={(e: any) => { if (e.key === 'Enter') send(); }}
          placeholder="Address your concern to Brussels..."
          disabled={busy}
        />
        <button className="jc-btn primary" onClick={send} disabled={busy || !draft.trim()}>Send</button>
      </div>
    </div>
  );
}

(window as any).VonBot = { VonDerBot };
