// --- Note Vocali — versione Libro ---------------------------------------
// Registra audio dal microfono, trascrive via Whisper, estrae task via Claude.

function VoiceScreen() {
  const [tab, setTab] = useState('record'); // record | upload
  const [projects, setProjects] = useState([]);
  const [defaultProjectId, setDefaultProjectId] = useState('');
  const [recording, setRecording] = useState(false);
  const [audioBlob, setAudioBlob] = useState(null);
  const [audioUrl, setAudioUrl] = useState(null);
  const [step, setStep] = useState('idle'); // idle | transcribing | extracting | review
  const [transcription, setTranscription] = useState('');
  const [extractedTasks, setExtractedTasks] = useState([]);
  const [err, setErr] = useState('');
  const [duration, setDuration] = useState(0);
  const mediaRecorder = useRef(null);
  const startedAt = useRef(null);

  useEffect(() => {
    apiT('/api/projects').then(setProjects).catch(() => {});
  }, []);

  const reset = () => {
    setAudioBlob(null); setAudioUrl(null);
    setTranscription(''); setExtractedTasks([]); setStep('idle');
    setErr(''); setDuration(0);
    if (mediaRecorder.current && mediaRecorder.current.state !== 'inactive') mediaRecorder.current.stop();
  };

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mime = MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : 'audio/mp4';
      const rec = new MediaRecorder(stream, { mimeType: mime });
      const chunks = [];
      rec.ondataavailable = (e) => chunks.push(e.data);
      rec.onstop = () => {
        const blob = new Blob(chunks, { type: mime });
        setAudioBlob(blob); setAudioUrl(URL.createObjectURL(blob));
        stream.getTracks().forEach((t) => t.stop());
        clearInterval(durInterval.current);
      };
      mediaRecorder.current = rec;
      rec.start();
      startedAt.current = Date.now();
      durInterval.current = setInterval(() => setDuration(Math.floor((Date.now() - startedAt.current) / 1000)), 500);
      setRecording(true);
    } catch (e) { setErr(e.message); }
  };

  const durInterval = useRef(null);

  const stopRecording = () => {
    if (mediaRecorder.current && mediaRecorder.current.state !== 'inactive') {
      mediaRecorder.current.stop();
      setRecording(false);
    }
  };

  const onFileUpload = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setAudioBlob(f); setAudioUrl(URL.createObjectURL(f));
  };

  const process = async () => {
    if (!audioBlob) return;
    setStep('transcribing'); setErr('');
    try {
      const fd = new FormData();
      fd.append('audio', audioBlob, audioBlob.name || 'recording.webm');
      const tr = await fetch('/api/voice/transcribe', { method: 'POST', credentials: 'include', body: fd }).then(async (r) => {
        const j = await r.json(); if (!r.ok) throw new Error(j.error); return j;
      });
      setTranscription(tr.text || tr.transcription || '');
      setStep('extracting');
      const ex = await apiT('/api/voice/extract-tasks', {
        method: 'POST',
        body: { text: tr.text || tr.transcription || '', default_project_id: defaultProjectId || null },
      });
      setExtractedTasks((ex.tasks || []).map((t) => ({ ...t, _selected: true })));
      setStep('review');
    } catch (e) { setErr(e.message); setStep('idle'); }
  };

  const saveAll = async () => {
    const toSave = extractedTasks.filter((t) => t._selected);
    for (const t of toSave) {
      try {
        await apiT('/api/tasks', { method: 'POST', body: {
          title: t.title, description: t.description || null,
          project_id: t.project_id || defaultProjectId || null,
          urgency: t.urgency ? 1 : 0, importance: t.importance ? 1 : 0,
          due_date: t.due_date || null, estimated_minutes: t.estimated_minutes || null,
        }});
      } catch (e) { setErr(`Errore "${t.title}": ${e.message}`); return; }
    }
    alert(`✓ Salvate ${toSave.length} task`);
    reset();
  };

  return (
    <>
      <Topbar crumbs={['Gestionale', 'Produttività', 'Note Vocali']} />
      <div className="content" style={{ maxWidth: 780 }}>
        <div className="page-head">
          <div>
            <h1 className="page-title">Note <em>vocali</em></h1>
            <div className="page-sub">Registra · trascrive · estrae task in automatico (Whisper + Claude)</div>
          </div>
        </div>

        {err && <div className="err" style={{ marginBottom: 14 }}><Icon name="alert-circle" size={14} /> {err}</div>}

        <div className="tabs">
          <div className={`tab ${tab === 'record' ? 'active' : ''}`} onClick={() => setTab('record')}>Registra</div>
          <div className={`tab ${tab === 'upload' ? 'active' : ''}`} onClick={() => setTab('upload')}>Carica file</div>
        </div>

        <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 12, padding: 24 }}>
          {step === 'idle' && !audioBlob && (
            <>
              {tab === 'record' ? (
                <div style={{ textAlign: 'center', padding: 20 }}>
                  <button
                    onClick={recording ? stopRecording : startRecording}
                    style={{
                      width: 120, height: 120, borderRadius: '50%',
                      border: 'none', cursor: 'pointer',
                      background: recording ? 'var(--red)' : 'var(--accent)',
                      color: '#fff', fontSize: 40,
                      boxShadow: recording ? '0 0 0 10px rgba(239,68,68,0.18)' : '0 8px 24px rgba(99,102,241,0.25)',
                      animation: recording ? 'libroPulse 1.2s ease-in-out infinite' : 'none',
                    }}>
                    {recording ? '■' : '🎤'}
                  </button>
                  <style>{`@keyframes libroPulse { 0%,100%{ transform:scale(1)} 50%{transform:scale(1.06)} }`}</style>
                  <div style={{ marginTop: 18, fontSize: 15, color: recording ? 'var(--red)' : 'var(--ink-2)' }}>
                    {recording ? `Registrazione… ${Math.floor(duration/60)}:${String(duration%60).padStart(2,'0')}` : 'Tocca per iniziare'}
                  </div>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: 30 }}>
                  <Icon name="upload" size={28} style={{ color: 'var(--ink-3)', margin: '0 auto 12px' }} />
                  <input type="file" accept="audio/*" onChange={onFileUpload} />
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 10 }}>MP3 / M4A / WAV / WebM · max ~25MB</div>
                </div>
              )}
            </>
          )}

          {audioBlob && step === 'idle' && (
            <div style={{ textAlign: 'center' }}>
              <audio controls src={audioUrl} style={{ width: '100%', marginBottom: 16 }} />
              <div className="field" style={{ maxWidth: 320, margin: '0 auto 16px' }}>
                <label className="label">Progetto default (opzionale)</label>
                <select className="input" value={defaultProjectId} onChange={(e) => setDefaultProjectId(e.target.value)}>
                  <option value="">— nessuno —</option>
                  {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </div>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 10 }}>
                <button className="btn btn-ghost" onClick={reset}><Icon name="x" size={13} /> Scarta</button>
                <button className="btn btn-accent btn-lg" onClick={process}><Icon name="sparkles" size={14} /> Trascrivi + estrai task</button>
              </div>
            </div>
          )}

          {(step === 'transcribing' || step === 'extracting') && (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <span className="spinner" style={{ display: 'inline-block', width: 28, height: 28, border: '3px solid var(--rule)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
              <div style={{ marginTop: 14, fontSize: 14, color: 'var(--ink-2)' }}>
                {step === 'transcribing' ? 'Trascrizione in corso…' : 'Estrazione task…'}
              </div>
            </div>
          )}

          {step === 'review' && (
            <div>
              {transcription && (
                <div style={{ marginBottom: 16, padding: 12, background: 'var(--paper-2)', borderRadius: 8, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55 }}>
                  <div style={{ fontSize: 10, fontWeight: 500, color: 'var(--ink-3)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Trascrizione</div>
                  {transcription}
                </div>
              )}
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                Task estratte ({extractedTasks.filter((t) => t._selected).length} selezionate su {extractedTasks.length})
              </div>
              {extractedTasks.length === 0 ? (
                <div style={{ padding: 20, textAlign: 'center', color: 'var(--ink-3)' }}>Nessuna task rilevata nella registrazione</div>
              ) : extractedTasks.map((t, i) => (
                <div key={i} className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 8, padding: 12, marginBottom: 8, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <input type="checkbox" checked={!!t._selected} onChange={() => setExtractedTasks(extractedTasks.map((x, j) => j === i ? { ...x, _selected: !x._selected } : x))} style={{ marginTop: 4 }} />
                  <div style={{ flex: 1 }}>
                    <input className="input" style={{ marginBottom: 6 }} value={t.title} onChange={(e) => setExtractedTasks(extractedTasks.map((x, j) => j === i ? { ...x, title: e.target.value } : x))} />
                    <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', fontSize: 12, color: 'var(--ink-3)' }}>
                      <label><input type="checkbox" checked={!!t.urgency} onChange={(e) => setExtractedTasks(extractedTasks.map((x, j) => j === i ? { ...x, urgency: e.target.checked ? 1 : 0 } : x))} /> Urgente</label>
                      <label><input type="checkbox" checked={!!t.importance} onChange={(e) => setExtractedTasks(extractedTasks.map((x, j) => j === i ? { ...x, importance: e.target.checked ? 1 : 0 } : x))} /> Importante</label>
                      <select value={t.project_id || ''} onChange={(e) => setExtractedTasks(extractedTasks.map((x, j) => j === i ? { ...x, project_id: e.target.value } : x))} style={{ fontSize: 12, border: '1px solid var(--rule)', borderRadius: 4, padding: '2px 6px' }}>
                        <option value="">— progetto —</option>
                        {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
                      </select>
                      {t.due_date && <span>📅 {t.due_date}</span>}
                    </div>
                  </div>
                </div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
                <button className="btn btn-ghost" onClick={reset}><Icon name="x" size={13} /> Scarta tutto</button>
                <button className="btn btn-accent" onClick={saveAll} disabled={extractedTasks.filter((t) => t._selected).length === 0}>
                  <Icon name="save" size={13} /> Salva {extractedTasks.filter((t) => t._selected).length} task
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

window.VoiceScreen = VoiceScreen;
