/* DigiTicket — botão flutuante global de bug report / feedback */

const DigiTicket = ({ user }) => {
  const [open, setOpen]           = React.useState(false);
  const [text, setText]           = React.useState('');
  const [status, setStatus]       = React.useState('idle'); // idle | recording | processing | success | error
  const [errorMsg, setErrorMsg]   = React.useState('');
  const mediaRef                  = React.useRef(null);
  const chunksRef                 = React.useRef([]);

  const startRecording = async () => {
    setErrorMsg('');
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      chunksRef.current = [];
      const mr = new MediaRecorder(stream);
      mr.ondataavailable = e => { if (e.data.size > 0) chunksRef.current.push(e.data); };
      mr.onstop = async () => {
        stream.getTracks().forEach(t => t.stop());
        setStatus('processing');
        const blob = new Blob(chunksRef.current, { type: 'audio/webm' });
        const fd = new FormData();
        fd.append('audio', blob, 'ticket.webm');
        fd.append('screen', window.location.hash);
        try {
          const r = await fetch('/api/tickets', { method: 'POST', body: fd });
          const d = await r.json();
          if (!r.ok) throw new Error(d.error || 'Erro ao submeter');
          setStatus('success');
          setTimeout(() => { setOpen(false); resetForm(); }, 2500);
        } catch (e) {
          setErrorMsg(e.message);
          setStatus('error');
        }
      };
      mr.start();
      mediaRef.current = mr;
      setStatus('recording');
    } catch (e) {
      if (e.name === 'NotAllowedError') {
        setErrorMsg('Permissão de microfone negada. Usa a caixa de texto.');
      } else {
        setErrorMsg('Erro ao aceder ao microfone: ' + e.message);
      }
      setStatus('idle');
    }
  };

  const stopRecording = () => {
    if (mediaRef.current && mediaRef.current.state === 'recording') {
      mediaRef.current.stop();
    }
  };

  const submitText = async () => {
    if (!text.trim()) return;
    setStatus('processing');
    try {
      const r = await fetch('/api/tickets', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: text.trim(), screen: window.location.hash }),
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Erro ao submeter');
      setStatus('success');
      setTimeout(() => { setOpen(false); resetForm(); }, 2500);
    } catch (e) {
      setErrorMsg(e.message);
      setStatus('error');
    }
  };

  const resetForm = () => {
    setText('');
    setStatus('idle');
    setErrorMsg('');
    chunksRef.current = [];
  };

  if (!user) return null;

  const isProcessing = status === 'processing';
  const isRecording  = status === 'recording';
  const isSuccess    = status === 'success';

  const btnStyle = {
    position: 'fixed', bottom: 24, right: 24, zIndex: 1000,
    width: 44, height: 44, borderRadius: '50%',
    background: 'var(--dgd-bg-surface, #fff)',
    border: '1px solid var(--dgd-border-1, #e2e8f0)',
    boxShadow: '0 2px 12px rgba(0,0,0,0.12)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', color: 'var(--dgd-fg-3, #94a3b8)',
    transition: 'box-shadow 0.15s, color 0.15s',
  };

  return (
    <>
      {/* Botão flutuante */}
      {!open && (
        <button
          onClick={() => { setOpen(true); resetForm(); }}
          style={btnStyle}
          title="Reportar problema ou feedback"
          onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 20px rgba(0,0,0,0.18)'; e.currentTarget.style.color = 'var(--dgd-fg-1, #1e293b)'; }}
          onMouseLeave={e => { e.currentTarget.style.boxShadow = '0 2px 12px rgba(0,0,0,0.12)'; e.currentTarget.style.color = 'var(--dgd-fg-3, #94a3b8)'; }}
        >
          {/* Ícone flag/bug */}
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/>
            <line x1="4" y1="22" x2="4" y2="15"/>
          </svg>
        </button>
      )}

      {/* Modal overlay */}
      {open && (
        <div
          onClick={e => { if (e.target === e.currentTarget && !isRecording && !isProcessing) { setOpen(false); resetForm(); } }}
          style={{ position: 'fixed', inset: 0, zIndex: 1001, background: 'rgba(0,0,0,0.25)', display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end', padding: '0 24px 24px' }}
        >
          <div style={{ width: 340, background: 'var(--dgd-bg-surface, #fff)', border: '1px solid var(--dgd-border-1, #e2e8f0)', borderRadius: 12, boxShadow: '0 8px 32px rgba(0,0,0,0.18)', overflow: 'hidden' }}>
            {/* Header */}
            <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--dgd-border-1, #e2e8f0)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 10, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 2 }}>Farben AI · Feedback</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--dgd-fg-1, #1e293b)' }}>Reportar problema</div>
              </div>
              {!isRecording && !isProcessing && (
                <button onClick={() => { setOpen(false); resetForm(); }} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--dgd-fg-3, #94a3b8)', padding: 4 }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                </button>
              )}
            </div>

            {/* Corpo */}
            <div style={{ padding: 16 }}>
              {isSuccess ? (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <div style={{ fontSize: 28, marginBottom: 8 }}>✓</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#16a34a' }}>Report enviado!</div>
                  <div style={{ fontSize: 12, color: 'var(--dgd-fg-3, #94a3b8)', marginTop: 4 }}>Vais receber confirmação por email.</div>
                </div>
              ) : (
                <>
                  <textarea
                    value={text}
                    onChange={e => setText(e.target.value)}
                    placeholder="Descreve o problema ou feedback..."
                    disabled={isProcessing || isRecording}
                    rows={4}
                    style={{ width: '100%', boxSizing: 'border-box', padding: '8px 10px', fontSize: 13, fontFamily: 'var(--dgd-font-body, sans-serif)', border: '1px solid var(--dgd-border-1, #e2e8f0)', borderRadius: 6, resize: 'vertical', outline: 'none', color: 'var(--dgd-fg-1, #1e293b)', background: 'var(--dgd-bg, #f8fafc)', marginBottom: 10 }}
                  />

                  {/* Microfone */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                    <button
                      onClick={isRecording ? stopRecording : startRecording}
                      disabled={isProcessing}
                      style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 6, border: '1px solid', fontSize: 12, cursor: isProcessing ? 'not-allowed' : 'pointer', fontWeight: 500, background: isRecording ? '#fee2e2' : 'transparent', borderColor: isRecording ? '#fca5a5' : 'var(--dgd-border-1, #e2e8f0)', color: isRecording ? '#dc2626' : 'var(--dgd-fg-2, #64748b)' }}
                    >
                      {isRecording ? (
                        <>
                          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#dc2626', animation: 'pulse 1s infinite' }} />
                          Parar gravação
                        </>
                      ) : (
                        <>
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
                          Gravar áudio
                        </>
                      )}
                    </button>
                    {isProcessing && <span style={{ fontSize: 12, color: 'var(--dgd-fg-3, #94a3b8)' }}>A processar...</span>}
                  </div>

                  {errorMsg && (
                    <div style={{ fontSize: 12, color: '#dc2626', background: '#fee2e2', border: '1px solid #fca5a5', borderRadius: 6, padding: '6px 10px', marginBottom: 10 }}>{errorMsg}</div>
                  )}

                  <button
                    onClick={submitText}
                    disabled={!text.trim() || isProcessing || isRecording}
                    style={{ width: '100%', padding: '8px', borderRadius: 6, border: 'none', fontSize: 13, fontWeight: 600, cursor: (!text.trim() || isProcessing || isRecording) ? 'not-allowed' : 'pointer', background: (!text.trim() || isProcessing || isRecording) ? 'var(--dgd-border-1, #e2e8f0)' : '#112954', color: (!text.trim() || isProcessing || isRecording) ? 'var(--dgd-fg-3, #94a3b8)' : '#fff' }}
                  >
                    {isProcessing ? 'A enviar...' : 'Enviar report'}
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      <style>{`@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }`}</style>
    </>
  );
};

window.DigiTicket = DigiTicket;
