// chatbot-widget.jsx — Widget chatbot flottant en bas-droite
// Discute avec Claude en contexte du module actuel.

const { useState: _cwUseS, useEffect: _cwUseE, useRef: _cwUseR } = React;

function ChatbotWidget({ currentScreen }) {
  const [open, setOpen] = _cwUseS(false);
  const [history, setHistory] = _cwUseS([
    { role: 'assistant', content: '👋 Bonjour ! Je suis l\'assistant Audits Énergies. Posez-moi vos questions sur les dossiers CEE, FOST, calculs cumac, ou la navigation du cockpit.' },
  ]);
  const [input, setInput] = _cwUseS('');
  const [busy, setBusy] = _cwUseS(false);
  const scrollRef = _cwUseR(null);
  const API = (window.AE_API && window.AE_API.BASE) || '';

  _cwUseE(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [history, open]);

  const send = async (text) => {
    const message = (text != null ? text : input).trim();
    if (!message || busy) return;
    const newHistory = [...history, { role: 'user', content: message }];
    setHistory(newHistory);
    setInput('');
    setBusy(true);
    try {
      const r = await fetch(`${API}/api/agent/chat`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          history: newHistory.filter(m => m.role !== 'system'),
          context: { currentModule: currentScreen },
        }),
      }).then(r => r.json());
      if (r.ok) {
        setHistory(h => [...h, { role: 'assistant', content: r.reply }]);
      } else {
        setHistory(h => [...h, { role: 'assistant', content: `⚠ ${r.error || 'Erreur — réessayez'}${r.hint ? '\n\n💡 ' + r.hint : ''}` }]);
      }
    } catch (e) {
      setHistory(h => [...h, { role: 'assistant', content: `⚠ Erreur réseau : ${e.message}` }]);
    } finally {
      setBusy(false);
    }
  };

  const QUICK_PROMPTS = [
    'Comment calculer un BAR-EN-101 ?',
    'Différence FOST BAT vs BAR ?',
    'Process de dépôt EMMY',
    'Que faire avant un dépôt PNCEE ?',
  ];

  // O3 — Guides vidéos contextuels par module
  const VIDEO_GUIDES = {
    visites:    [{ title: '🎥 Lancer une visite IA', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '2:34' }],
    crm:        [{ title: '👥 Importer ses contacts Odoo', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '1:48' }],
    dossiers:   [{ title: '📁 Workflow d\'un dossier CEE', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '3:12' }],
    devis:      [{ title: '📄 Créer un devis natif', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '2:05' }],
    settings:   [{ title: '⚙️ Personnaliser le cockpit', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '1:55' }],
    audit:      [{ title: '⚡ Calculer un audit énergétique multi-FOST', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '4:20' }],
    pncee:      [{ title: '🏛️ Préparer un dépôt EMMY', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '3:00' }],
    solar:      [{ title: '☀️ Studio solaire : calpinage en 5 min', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ', duration: '5:12' }],
  };
  const guides = VIDEO_GUIDES[currentScreen] || [];
  const [showVideo, setShowVideo] = _cwUseS(null);

  return (
    <>
      {/* Bouton flottant */}
      {!open && (
        <button
          onClick={() => setOpen(true)}
          title="Assistant IA"
          style={{
            position: 'fixed', bottom: 24, right: 24, zIndex: 9998,
            width: 56, height: 56, borderRadius: '50%',
            background: 'linear-gradient(135deg, var(--plasma) 0%, var(--signal) 100%)',
            color: '#fff', border: 'none', cursor: 'pointer',
            boxShadow: '0 4px 16px rgba(107, 76, 255, 0.35)',
            fontSize: 22, display: 'grid', placeItems: 'center',
            transition: 'transform 200ms',
          }}
          onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
        >🤖</button>
      )}

      {/* Panel */}
      {open && (
        <div style={{
          position: 'fixed', bottom: 20, right: 20, zIndex: 9998,
          width: 380, height: 520, maxHeight: 'calc(100vh - 40px)',
          background: 'var(--paper)', border: '1px solid var(--line-2)', borderRadius: 12,
          boxShadow: 'var(--shadow-3)', display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
        }}>
          {/* Header */}
          <div style={{
            padding: '12px 14px', borderBottom: '1px solid var(--line)',
            display: 'flex', alignItems: 'center', gap: 10,
            background: 'linear-gradient(135deg, var(--plasma-tint) 0%, var(--signal-tint) 100%)',
          }}>
            <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'linear-gradient(135deg, var(--plasma) 0%, var(--signal) 100%)', display: 'grid', placeItems: 'center', fontSize: 16 }}>🤖</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Assistant Audits Énergies</div>
              <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>Claude {(currentScreen ? `· ${currentScreen}` : '')}</div>
            </div>
            <button onClick={() => setOpen(false)} title="Fermer" style={{ fontSize: 16, color: 'var(--ink-3)', padding: 4 }}>✕</button>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {history.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
                maxWidth: '85%',
                padding: '8px 12px', borderRadius: 10,
                background: m.role === 'user' ? 'var(--ink)' : 'var(--paper-2)',
                color: m.role === 'user' ? 'var(--paper)' : 'var(--ink)',
                fontSize: 12.5, lineHeight: 1.5, whiteSpace: 'pre-wrap',
              }}>
                {m.content}
              </div>
            ))}
            {busy && (
              <div style={{ alignSelf: 'flex-start', padding: '8px 12px', background: 'var(--paper-2)', borderRadius: 10, fontSize: 12, color: 'var(--ink-4)' }}>
                <span style={{ animation: 'breathe 1.2s ease-in-out infinite' }}>● ● ●</span>
              </div>
            )}
          </div>

          {/* Quick prompts + Video guides */}
          {history.length <= 1 && (
            <div style={{ padding: '0 14px 10px' }}>
              {guides.length > 0 && (
                <div style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>📹 Guide vidéo pour ce module</div>
                  {guides.map(g => (
                    <button key={g.title} onClick={() => setShowVideo(g)} style={{
                      width: '100%', textAlign: 'left', padding: '6px 10px', marginBottom: 4,
                      background: 'var(--plasma-tint)', border: '1px solid var(--plasma)',
                      borderRadius: 5, fontSize: 11, color: 'var(--ink-2)', cursor: 'pointer',
                      display: 'flex', alignItems: 'center', gap: 6,
                    }}>
                      <span style={{ flex: 1 }}>{g.title}</span>
                      <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>{g.duration}</span>
                      <span>▶</span>
                    </button>
                  ))}
                </div>
              )}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {QUICK_PROMPTS.map(q => (
                  <button key={q} onClick={() => send(q)} disabled={busy} style={{
                    fontSize: 10, padding: '4px 8px', background: 'var(--paper-2)',
                    border: '1px solid var(--line-2)', borderRadius: 999, color: 'var(--ink-3)', cursor: 'pointer',
                  }}>{q}</button>
                ))}
              </div>
            </div>
          )}

          {/* Video player overlay */}
          {showVideo && (
            <div onClick={() => setShowVideo(null)} style={{
              position: 'fixed', inset: 0, zIndex: 99999, background: 'rgba(0,0,0,0.85)',
              display: 'grid', placeItems: 'center', padding: 30,
            }}>
              <div onClick={e => e.stopPropagation()} style={{
                width: 'min(900px, 100%)', background: 'var(--paper)', borderRadius: 12, overflow: 'hidden',
                boxShadow: 'var(--shadow-3)',
              }}>
                <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>{showVideo.title}</span>
                  <button onClick={() => setShowVideo(null)} style={{ fontSize: 18, color: 'var(--ink-3)', padding: 4 }}>✕</button>
                </div>
                <div style={{ position: 'relative', paddingBottom: '56.25%', height: 0 }}>
                  <iframe src={showVideo.url}
                    style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 0 }}
                    title={showVideo.title}
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                  />
                </div>
              </div>
            </div>
          )}

          {/* Input */}
          <div style={{ padding: 12, borderTop: '1px solid var(--line)', display: 'flex', gap: 6 }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Posez votre question…"
              disabled={busy}
              style={{
                flex: 1, padding: '8px 12px', fontSize: 12,
                border: '1px solid var(--line-2)', borderRadius: 6,
                background: 'var(--paper-2)', fontFamily: 'inherit',
              }}
            />
            <button onClick={() => send()} disabled={busy || !input.trim()} style={{
              padding: '8px 14px', fontSize: 12, fontWeight: 600,
              background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 6, cursor: 'pointer',
            }}>↗</button>
          </div>
        </div>
      )}
    </>
  );
}

window.ChatbotWidget = ChatbotWidget;
