/* Kürsü'ye Sor — sesli/yazılı Q&A: soru → arşivden atıflı cevap → sesli dönüş */
const { useState: aUseState, useRef: aUseRef, useEffect: aUseEffect } = React;

const SAMPLE_Q = [
  'Sabır nedir, mümin nasıl sabretmeli?',
  'Komşu hakkı hakkında neler söylenmiş?',
  'Namazın önemi nedir?',
  'Tevekkül ile tembellik arasındaki fark nedir?',
];

function fmtAnswer(s) {
  const esc = String(s || '').replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
  return esc.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
}
function AskMsg({ m, base }) {
  const isUser = m.role === 'user';
  return (
    <div className={'ask-msg ' + (isUser ? 'is-user' : 'is-bot')}>
      <div className="ask-bubble">
        {m.pending ? <span className="ask-typing">●●●</span>
          : (isUser ? <p className="ask-text">{m.text}</p>
                    : <p className="ask-text" dangerouslySetInnerHTML={{ __html: fmtAnswer(m.text) }} />)}
        {m.audioUrl && <audio className="ask-audio" controls autoPlay src={m.audioUrl} />}
        {m.sources && m.sources.length > 0 && (
          <details className="ask-src">
            <summary>{m.sources.length} kaynak</summary>
            <ul>
              {m.sources.map(s => {
                const sec = Math.floor(s.t || 0);
                const ts = Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, '0');
                return (
                  <li key={s.n}>
                    <div className="ask-src-head">
                      <b>[{s.n}]</b> <a href={`watch.html?v=${encodeURIComponent(s.slug)}&t=${sec}`} target="_blank" rel="noopener">{s.title}</a>
                      <span className="ask-src-meta"> · {s.speaker} · {ts}</span>
                    </div>
                    {s.text && <blockquote className="ask-src-q">“{s.text}”</blockquote>}
                  </li>
                );
              })}
            </ul>
          </details>
        )}
      </div>
    </div>
  );
}

function AskApp() {
  const D = window.SK_DATA;
  const base = window.SK_API_BASE || '';
  const [msgs, setMsgs] = aUseState([]);
  const [input, setInput] = aUseState('');
  const [busy, setBusy] = aUseState(false);
  const [recording, setRecording] = aUseState(false);
  const recRef = aUseRef(null); const chunksRef = aUseRef([]);
  const listRef = aUseRef(null);
  aUseEffect(() => { if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight; }, [msgs, busy]);

  const ask = async (question) => {
    if (busy) return; setBusy(true);
    setMsgs(m => [...m, { role: 'user', text: question }, { role: 'assistant', pending: true }]);
    try {
      const tok = window.SK_API && window.SK_API.token && window.SK_API.token();
      const r = await fetch(base + '/api/ask', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, tok ? { Authorization: 'Bearer ' + tok } : {}), credentials: 'include', body: JSON.stringify({ question, speak: true }) });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Hata');
      setMsgs(m => { const c = m.filter(x => !x.pending); return [...c, { role: 'assistant', text: d.answer, sources: d.sources, audioUrl: d.audioUrl ? base + d.audioUrl : null }]; });
    } catch (e) {
      setMsgs(m => { const c = m.filter(x => !x.pending); return [...c, { role: 'assistant', text: 'Üzgünüm, bir hata oluştu: ' + e.message, error: true }]; });
    } finally { setBusy(false); }
  };

  const askVoice = async (blob) => {
    if (busy) return; setBusy(true);
    setMsgs(m => [...m, { role: 'user', text: '🎤 Sesli soru gönderildi…', pending: true }, { role: 'assistant', pending: true }]);
    try {
      const fd = new FormData(); fd.append('audio', blob, 'q.webm'); fd.append('speak', '1');
      const tok = window.SK_API && window.SK_API.token && window.SK_API.token();
      const r = await fetch(base + '/api/ask', { method: 'POST', headers: tok ? { Authorization: 'Bearer ' + tok } : {}, credentials: 'include', body: fd });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Hata');
      setMsgs(m => { const c = m.filter(x => !x.pending); return [...c, { role: 'user', text: d.question || '(sesli soru)' }, { role: 'assistant', text: d.answer, sources: d.sources, audioUrl: d.audioUrl ? base + d.audioUrl : null }]; });
    } catch (e) {
      setMsgs(m => { const c = m.filter(x => !x.pending); return [...c, { role: 'assistant', text: 'Ses işlenemedi: ' + e.message, error: true }]; });
    } finally { setBusy(false); }
  };

  const submit = (e) => { e.preventDefault(); const q = input.trim(); if (!q || busy) return; setInput(''); ask(q); };

  const toggleRec = async () => {
    if (recording) { if (recRef.current) recRef.current.stop(); return; }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mr = new MediaRecorder(stream); recRef.current = mr; chunksRef.current = [];
      mr.ondataavailable = e => { if (e.data.size) chunksRef.current.push(e.data); };
      mr.onstop = () => { stream.getTracks().forEach(t => t.stop()); setRecording(false); askVoice(new Blob(chunksRef.current, { type: 'audio/webm' })); };
      mr.start(); setRecording(true);
    } catch (e) { alert('Mikrofona erişilemedi. Tarayıcı izni gerekli.'); }
  };

  return (
    <>
      <Header />
      <main className="ask">
        <div className="wrap ask-wrap">
          <div className="ask-head">
            <span className="tag">Yapay Zekâ Destekli</span>
            <h1>Kürsü'ye Sor</h1>
            <p className="ask-sub">Sorunuzu yazın veya sesli sorun; arşivdeki sohbetlerden derlenmiş, <b>kaynaklı</b> bir cevap alın. Cevaplar yalnızca arşiv içeriğine dayanır.</p>
          </div>

          <div className="ask-list" ref={listRef}>
            {msgs.length === 0 && (
              <div className="ask-empty">
                <Icon name="quote" size={26} style={{ color: 'var(--accent-ink)' }} />
                <p>Bir soru sorarak başlayın:</p>
                <div className="ask-samples">
                  {SAMPLE_Q.map(q => <button key={q} className="ask-chip" onClick={() => !busy && ask(q)}>{q}</button>)}
                </div>
              </div>
            )}
            {msgs.map((m, i) => <AskMsg key={i} m={m} base={base} />)}
          </div>

          <form className="ask-form" onSubmit={submit}>
            <button type="button" className={'ask-mic' + (recording ? ' is-rec' : '')} onClick={toggleRec} disabled={busy && !recording}
              title={recording ? 'Kaydı durdur ve gönder' : 'Sesli sor'} aria-label="Sesli sor">
              {recording
                ? <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2" /></svg>
                : <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5 11a7 7 0 0014 0M12 18v3" /></svg>}
            </button>
            <input value={input} onChange={e => setInput(e.target.value)} disabled={busy}
              placeholder={recording ? 'Dinleniyor… bitince mikrofona tekrar bas' : 'Sorunuzu yazın…'} />
            <button type="submit" className="ask-send" disabled={busy || !input.trim()}>
              {busy ? '…' : <Icon name="arrow" size={20} />}
            </button>
          </form>
          <p className="ask-disclaimer">Cevaplar yapay zekâ tarafından, arşiv alıntılarından derlenir; birebir alıntı değildir. Kaynakları kontrol ediniz.</p>
        </div>
      </main>
      <Footer />
    </>
  );
}

(window.SK_READY || Promise.resolve()).then(() =>
  ReactDOM.createRoot(document.getElementById('root')).render(<AskApp />));
