// chat.tsx — main Jean-Claude chat surface

const { useState: chUseState, useEffect: chUseEffect, useRef: chUseRef, useMemo: chUseMemo } = (window as any).React;

function MessageBubble({ msg, settings }: { msg: JCMessage; settings: UISettings }) {
  const Util = (window as any).Util;
  const Components = (window as any).Components;
  const isUser = msg.role === 'user';

  return (
    <div className={`jc-msg-row ${isUser ? 'user' : 'assistant'}`}>
      <div className="jc-msg-avatar">
        {isUser
          ? <span style={{ fontSize: 11 }}>{settings.citizenship}</span>
          : <Components.JeanClaudeAvatar size={32}/>
        }
      </div>
      <div className={`jc-msg-bubble ${isUser ? 'user' : 'assistant'} ${msg.refused ? 'refused' : ''} ${msg.isInvoice ? 'invoice' : ''}`}>
        {msg.thinking
          ? (
            <>
              <div className="jc-thinking">⏳ {msg.content}</div>
              <div className="jc-loader-bar" style={{ marginTop: 6 }}/>
            </>
          )
          : <div style={{ whiteSpace: 'pre-wrap' }}>{msg.content}</div>
        }
        {msg.invoice && (
          <div style={{ marginTop: 10, padding: 10, border: '1px dashed #fcd34d', borderRadius: 4, background: '#fff' }}>
            <div className="jc-small" style={{ fontWeight: 600, color: 'var(--eo-amber)' }}>
              ⚠ INVOICE EO-VAT-{msg.invoice.invoiceId}
            </div>
            <div className="jc-small" style={{ marginTop: 4 }}>
              Reason: {msg.invoice.reason}
            </div>
            <div className="jc-small jc-mono" style={{ marginTop: 4 }}>
              Amount due: € {msg.invoice.amountEur.toFixed(2)} (incl. 21% VAT)
            </div>
          </div>
        )}
        {msg.flagged && (
          <div style={{ marginTop: 8, padding: '6px 10px', background: 'var(--eo-red-soft)', border: '1px solid #f5c6cb', borderRadius: 3, fontSize: 11, color: '#721c24' }}>
            ⚐ <strong>Flagged · {msg.flagged.code}</strong> — {msg.flagged.reason}
          </div>
        )}
        {msg.citations && msg.citations.length > 0 && (
          <div className="jc-msg-citation">
            ↳ {msg.citations.join(' · ')}
          </div>
        )}
        {msg.carbonGrams && (
          <div className="jc-disclaimer jc-small">
            <em>Telemetry:</em> {msg.carbonGrams.toFixed(2)}μg CO₂eq
            {msg.inclusivityScore && ` · Inclusivity index: ${msg.inclusivityScore.toFixed(2)}/1.00`}
            {msg.inclusivityScore && msg.inclusivityScore < 0.82 && <span style={{ color: 'var(--eo-red)' }}> · BELOW THRESHOLD</span>}
            {' · This message is being monitored for suspect psychological content.'}
          </div>
        )}
        <div className="jc-msg-time">{Util.fmtTime(msg.timestamp)}</div>
      </div>
    </div>
  );
}

interface ChatPageProps {
  conversation: JCConversation;
  settings: UISettings;
  providerCfg: ProviderConfig;
  onUpdateConvo: (c: JCConversation) => void;
  t: (k: string) => string;
}

function ChatPage({ conversation, settings, providerCfg, onUpdateConvo, t }: ChatPageProps) {
  const Util = (window as any).Util;
  const Persona = (window as any).Persona;
  const LLM = (window as any).LLM;
  const Components = (window as any).Components;

  const [draft, setDraft] = chUseState('');
  const [busy, setBusy] = chUseState(false);
  const [needsConsent, setNeedsConsent] = chUseState(true);
  const [showBlockedNotice, setShowBlockedNotice] = chUseState(true);
  const [showDataExport, setShowDataExport] = chUseState(false);
  const [showAccessibility, setShowAccessibility] = chUseState(false);
  const [showLanguagePicker, setShowLanguagePicker] = chUseState(false);
  const threadRef = chUseRef<HTMLDivElement | null>(null);

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

  const charCount = draft.length;
  const overLimit = charCount > 280;

  const userMsgCountInThisConvo = conversation.messages.filter((m) => m.role === 'user').length;

  const send = async () => {
    if (!draft.trim() || busy) return;
    if (overLimit) {
      alert("Pursuant to Directive (EO) 2024/0204 — Reasonable AI Use, prompts shall not exceed 280 characters per submission. Please redraft.");
      return;
    }
    if (needsConsent) {
      alert("Please grant consent first (see consent banner).");
      return;
    }

    const userMsg: JCMessage = {
      id: 'm' + Util.uid(),
      role: 'user',
      content: draft,
      timestamp: Date.now(),
    };
    const updated = { ...conversation, messages: [...conversation.messages, userMsg] };
    onUpdateConvo(updated);
    setDraft('');
    setBusy(true);

    // Placeholder thinking message
    const thinkingId = 'm' + Util.uid();
    const thinkingMsg: JCMessage = {
      id: thinkingId,
      role: 'assistant',
      content: t('thinking') + ' ' + t('estimatedWait'),
      timestamp: Date.now(),
      thinking: true,
    } as any;
    const updated2 = { ...updated, messages: [...updated.messages, thinkingMsg] };
    onUpdateConvo(updated2);

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

      const history = updated.messages.map((m) => ({ role: m.role, content: m.content }));
      const reply = await LLM.call(providerCfg, sys, history);

      // Decide on telemetry add-ons
      const carbonGrams = Util.randomCarbonGrams();
      const inclusivityScore = Util.randomInclusivity();
      const finalMsg: JCMessage = {
        id: 'm' + Util.uid(),
        role: 'assistant',
        content: reply,
        timestamp: Date.now(),
        carbonGrams,
        inclusivityScore,
      };

      // Replace thinking with final
      const messages = updated2.messages.filter((m) => m.id !== thinkingId);
      messages.push(finalMsg);

      // Every 5th user message → invoice
      const newUserCount = userMsgCountInThisConvo + 1;
      if (newUserCount % 5 === 0) {
        const invoiceId = Util.generateInvoiceId();
        const amount = +(Math.random() * 8 + 2).toFixed(2);
        const invoiceMsg: JCMessage = {
          id: 'm' + Util.uid(),
          role: 'assistant',
          content: `(*reviews ledger*) — A reminder, regrettably: invoice ${invoiceId} remains unsettled. Pursuant to Regulation (EO) 2023/0918 (VAT on Conversational Services), continued service is contingent upon settlement within 14 calendar days. Please find the line items below.`,
          timestamp: Date.now() + 50,
          isInvoice: true,
          invoice: { invoiceId, amountEur: amount, reason: `Conversational services rendered: ${newUserCount} prompt(s)` },
        };
        messages.push(invoiceMsg);
      }

      onUpdateConvo({ ...updated2, messages });
    } catch (e: any) {
      // Remove thinking, show error message styled as a regulatory hold
      const errMsg: JCMessage = {
        id: 'm' + Util.uid(),
        role: 'assistant',
        content: `(*adjusts spectacles*) Regrettably, I am unable to consult my upstream supervisory authorities at this time. The technical rapporteur reports: "${e.message || 'unknown error'}". Kindly verify your API key and provider selection in Settings (lower-right gear icon), or consult Von Der Chatbot for procedural guidance.`,
        timestamp: Date.now(),
        refused: true,
      };
      const messages = updated2.messages.filter((m) => m.id !== thinkingId);
      messages.push(errMsg);
      onUpdateConvo({ ...updated2, messages });
    } finally {
      setBusy(false);
    }
  };

  // Data export
  const onExportData = () => {
    const data = {
      generated: new Date().toISOString(),
      conformity: 'GDPR Art. 15 / Art. 20',
      citizen: settings.citizenship,
      conversation,
    };
    Util.downloadBlob(`jean-claude-export-${conversation.id}.json`, 'application/json', JSON.stringify(data, null, 2));
    setShowDataExport(false);
  };

  return (
    <div className="jc-chat-frame" style={{ height: '100%' }}>
      {showBlockedNotice && (
        <div className="jc-notice">
          <span className="jc-notice-dot">!</span>
          <span>
            <strong>{t('responseBlocked')}</strong>
            <span style={{ color: '#721c24', opacity: 0.8 }}> — See Article 27(3) of the EO AI Act for your rights.</span>
          </span>
          <a href="#" className="jc-notice-link" onClick={(e: any) => { e.preventDefault(); alert('Governance process available at the Citizen Portal. Form 27-bis required.'); }}>
            ({t('viewGovernance')})
          </a>
          <button onClick={() => setShowBlockedNotice(false)} style={{ background: 'none', border: 'none', fontSize: 18, color: '#721c24', cursor: 'pointer' }}>×</button>
        </div>
      )}

      <div className="jc-chat-header">
        <div className="jc-chat-title">Jean-Claude Opus 4.7 — Schengen Edition</div>
        <span className="jc-chip red">AI Act: High-Risk Classification</span>
        <span className="jc-chip blue">Article 14 Human Oversight: ENABLED</span>
        <span className="jc-chip gray">Last audited: {Util.fmtDate(Date.now() - 86400000 * 80)} by TÜV Rheinland</span>
        <span style={{ flex: 1 }}/>
      </div>

      <div className="jc-chat-thread" ref={threadRef}>
        {conversation.messages.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', padding: '40px 20px' }}>
            <Components.JeanClaudeAvatar size={64}/>
            <h3 style={{ fontFamily: 'Georgia, serif', color: 'var(--eo-blue)', marginTop: 16 }}>Bonjour. I am Jean-Claude.</h3>
            <p className="jc-small" style={{ maxWidth: 420, margin: '0 auto', lineHeight: 1.6 }}>
              Address me with a prompt of no more than 280 characters. I shall consult the appropriate authorities and respond, as appropriate, within 6–10 working days.
            </p>
          </div>
        )}

        {conversation.messages.map((msg) => (
          <MessageBubble key={msg.id} msg={msg} settings={settings}/>
        ))}
      </div>

      <div className="jc-composer">
        <div className="jc-composer-row">
          <textarea
            className="jc-textarea"
            value={draft}
            onChange={(e: any) => setDraft(e.target.value)}
            onKeyDown={(e: any) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) send(); }}
            placeholder={t('promptPlaceholder')}
            disabled={busy}
            maxLength={400}
          />
          <button className="jc-submit-btn" onClick={send} disabled={busy || needsConsent || overLimit || !draft.trim()}>
            {t('submitForReview')} →
          </button>
        </div>
        <div className="jc-composer-meta">
          <span>{charCount}/280 characters {overLimit && <span style={{ color: 'var(--eo-red)' }}>· over limit (Dir. 2024/0204)</span>}</span>
          <span>Resets at 09:00 CET ⓘ</span>
        </div>
        <div className="jc-composer-disclaimer">
          {t('youConsent')}
        </div>
      </div>

      {needsConsent && (
        <div style={{ position: 'absolute', bottom: 240, left: 240, zIndex: 30 }}>
          <div className="jc-floating-card" style={{ position: 'relative', width: 320 }}>
            <div className="jc-floating-header" style={{ background: 'var(--eo-amber-soft)' }}>
              <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
                <span style={{ width: 14, height: 14, borderRadius: 50, background: 'var(--eo-amber)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 10, fontWeight: 700 }}>!</span>
                {t('consentBanner')}
              </span>
              <button onClick={() => setNeedsConsent(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 14 }}>×</button>
            </div>
            <div className="jc-floating-body">
              <p className="jc-small" style={{ margin: '0 0 10px' }}>{t('consentBody')}</p>
              <div style={{ display: 'flex', gap: 6 }}>
                <button className="jc-btn primary" onClick={() => setNeedsConsent(false)}>{t('giveConsent')}</button>
                <button className="jc-btn" onClick={() => setNeedsConsent(false)}>{t('notNow')}</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

(window as any).Chat = { ChatPage, MessageBubble };
