// chatbot.jsx — Solvy, l'assistente AI di Solvera.
// Wrapper attorno al chat embeddato di Chatwith.tools.
// La FAQ chiama window.openSolvy() per aprire il pannello.

const { useState: useChatState, useEffect: useChatEffect } = React;

const CHATWITH_URL = 'https://chatwith.tools/embed/972770f5-e707-4fcb-8ebc-e5514582522f';

function ChatBot() {
  const [open, setOpen] = useChatState(false);
  const [loaded, setLoaded] = useChatState(false);

  // Esponi window.openSolvy() per il bottone della FAQ
  useChatEffect(() => {
    window.openSolvy = () => setOpen(true);
    return () => { delete window.openSolvy; };
  }, []);

  // Chiusura con Esc
  useChatEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  if (!open) return null;

  return (
    <>
      {/* Backdrop su mobile */}
      <div
        onClick={() => setOpen(false)}
        style={{
          position: 'fixed', inset: 0,
          background: 'rgba(20, 24, 31, 0.55)',
          zIndex: 9997,
          animation: 'solvy-fade-in .2s ease',
        }}
      />

      {/* Pannello chat */}
      <div
        role="dialog"
        aria-label="Chat con Solvy"
        style={{
          position: 'fixed',
          bottom: 'min(40px, 5vh)',
          right: 'min(40px, 5vw)',
          width: 'min(400px, calc(100vw - 32px))',
          height: 'min(640px, calc(100vh - 80px))',
          background: 'var(--bg-2)',
          borderRadius: 20,
          border: '1px solid var(--rule)',
          boxShadow: '0 24px 60px -12px rgba(20,24,31,0.30), 0 8px 24px -8px rgba(20,24,31,0.18)',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          overscrollBehavior: 'contain',
          zIndex: 9998,
          fontFamily: 'var(--sans)',
          animation: 'solvy-pop-in .25s ease',
        }}>
        {/* Header */}
        <div style={{
          padding: '14px 16px',
          background: 'var(--fg)',
          color: 'var(--bg)',
          display: 'flex', alignItems: 'center', gap: 12,
          flexShrink: 0,
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: '50%',
            background: 'linear-gradient(135deg, var(--accent) 0%, var(--accent-deep) 100%)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18, fontWeight: 800, color: '#fff',
            border: '2px solid var(--bg-2)',
            boxShadow: '0 4px 12px -4px var(--accent)',
            flexShrink: 0,
          }}>S</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>
              Solvy
            </div>
            <div style={{
              fontSize: 12, color: 'var(--fg-mute)',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: 'var(--positive)',
                animation: 'solvy-pulse 1.6s ease-in-out infinite',
              }} />
              Online · Assistente AI di Solvera
            </div>
          </div>
          <button
            onClick={() => setOpen(false)}
            aria-label="Chiudi"
            style={{
              width: 32, height: 32, borderRadius: 8,
              border: 'none', background: 'transparent',
              color: 'var(--bg)', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              opacity: 0.7,
              flexShrink: 0,
            }}
            onMouseEnter={(e) => e.currentTarget.style.opacity = 1}
            onMouseLeave={(e) => e.currentTarget.style.opacity = 0.7}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <path d="M18 6L6 18M6 6l12 12"/>
            </svg>
          </button>
        </div>

        {/* Loading placeholder mostrato finché l'iframe non è caricato */}
        {!loaded && (
          <div style={{
            position: 'absolute',
            top: 66, left: 0, right: 0, bottom: 0,
            background: 'var(--bg-2)',
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            gap: 16,
            zIndex: 1,
          }}>
            <span style={{ display: 'inline-flex', gap: 6 }}>
              {[0, 1, 2].map(i => (
                <span key={i} style={{
                  width: 9, height: 9, borderRadius: '50%',
                  background: 'var(--accent)',
                  animation: `solvy-typing 1.2s ease-in-out ${i * 0.18}s infinite`,
                }} />
              ))}
            </span>
            <div style={{ fontSize: 13, color: 'var(--fg-mute)' }}>
              Solvy sta arrivando…
            </div>
          </div>
        )}

        {/* Iframe Chatwith */}
        <iframe
          src={CHATWITH_URL}
          title="Solvy — Assistente AI di Solvera"
          onLoad={() => setLoaded(true)}
          allow="microphone; clipboard-write"
          style={{
            flex: 1,
            width: '100%',
            border: 'none',
            background: 'var(--bg-2)',
            display: 'block',
          }}
        />
      </div>

      <style>{`
        @keyframes solvy-pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.5; transform: scale(0.85); }
        }
        @keyframes solvy-pop-in {
          0% { opacity: 0; transform: translateY(20px) scale(0.96); }
          100% { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes solvy-fade-in {
          0% { opacity: 0; }
          100% { opacity: 1; }
        }
        @keyframes solvy-typing {
          0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
          30% { opacity: 1; transform: translateY(-4px); }
        }
      `}</style>
    </>
  );
}

window.ChatBot = ChatBot;
