/* Chat mode — real API */

function ChatMode({ onHome, initialStep = 'select', initialProject = null }) {
  const [step, setStep]       = React.useState(initialStep);
  const [project, setProject] = React.useState(initialProject);
  const [messages, setMessages] = React.useState([]);
  const [draft, setDraft]     = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [arcProposal, setArcProposal] = React.useState(null);
  const [finalizing, setFinalizing] = React.useState(false);

  // Hooks must be declared before any conditional returns (Rules of Hooks)
  const bodyRef = React.useRef(null);
  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages]);

  const startChat = async (proj) => {
    setProject(proj);
    setMessages([]);
    setArcProposal(null);
    try {
      const res = await API.chatStart(proj);
      if (res?.status === 'queued') {
        setStep('queued');
      } else {
        setStep('chat');
      }
    } catch (e) {
      if (e.status === 202) {
        setStep('queued');
      } else {
        alert('Ошибка запуска чата: ' + e.message);
      }
    }
  };

  const send = async () => {
    if (!draft.trim() || sending) return;
    const text = draft.trim();
    setDraft('');
    setMessages(m => [...m, { role: 'user', text }]);
    setSending(true);
    try {
      const res = await API.chatMessage(project, text);
      setMessages(m => [...m, { role: 'agent', text: res.reply }]);
      if (res.has_arc_proposal) {
        // fetch updated arcs via project endpoint — they're embedded in the reply text as JSON
        // parse from reply or mark for finalize
        setArcProposal('pending'); // signal to user
      }
    } catch (e) {
      setMessages(m => [...m, { role: 'error', text: 'Ошибка: ' + e.message }]);
    } finally {
      setSending(false);
    }
  };

  const finalize = async () => {
    setFinalizing(true);
    try {
      const res = await API.chatFinalize(project);
      setMessages(m => [...m, {
        role: 'agent',
        text: `✓ Сохранено ${res.arcs_saved} арок: ${(res.arc_titles || []).join(', ')}. Агент начнёт планирование.`
      }]);
      setArcProposal(null);
      setStep('done');
    } catch (e) {
      alert('Ошибка финализации: ' + e.message);
    } finally {
      setFinalizing(false);
    }
  };

  const releaseChat = async () => {
    try { await API.chatRelease(project); } catch {}
    setStep('select');
    setProject(null);
    setMessages([]);
    setArcProposal(null);
  };

  if (step === 'select') {
    return <ChatSelect onHome={onHome} onStart={startChat} />;
  }
  if (step === 'queued') {
    return <ChatQueued project={project} onHome={onHome} onReady={() => setStep('chat')} onBack={() => { releaseChat(); }} />;
  }
  if (step === 'done') {
    return (
      <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Header title="Chat" sub={project} onHome={onHome} />
        <div className="app-body">
          <div className="empty">
            <div style={{ width: 48, height: 48, borderRadius: 12, background: 'rgba(77,191,125,0.12)', color: 'var(--ag-ok)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ico name="check" size={26} />
            </div>
            <div className="e-title">Арки сохранены</div>
            <div className="e-sub">Планировщик запустит генерацию фаз автоматически. Следи за прогрессом в Inbox.</div>
            <button className="btn ghost sm" onClick={() => { setStep('select'); setProject(null); }}>Новый чат</button>
          </div>
        </div>
      </div>
    );
  }

  // step === 'chat'
  const hasProposal = arcProposal === 'pending';

  return (
    <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <Header
        title="Chat"
        sub={project}
        meta={<><span className={`dot ${sending ? 'warn pulse' : ''}`} /> {sending ? 'M1 думает…' : 'M1 active'}</>}
        onHome={onHome}
      />
      <div className="app-body" ref={bodyRef} style={{ flex: 1 }}>
        {messages.length === 0 && (
          <div style={{ padding: '24px 16px', color: 'var(--tg-theme-hint-color)', fontSize: 14, textAlign: 'center' }}>
            Опишите проект, что хотите построить. M1 предложит арки.
          </div>
        )}
        <div style={{ padding: '12px 12px 8px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {messages.map((m, i) => (
            <div key={i} className={`chat-msg ${m.role === 'error' ? 'agent' : m.role}`}
              style={m.role === 'error' ? { color: 'var(--ag-fail)' } : {}}>
              {m.text}
              <div className="meta">{m.role === 'user' ? 'you' : m.role === 'error' ? 'error' : 'M1'}</div>
            </div>
          ))}
          {sending && (
            <div className="chat-msg agent" style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              <span style={{ animation: 'spin 0.8s linear infinite', display: 'inline-block' }}>⟳</span>
              <span style={{ color: 'var(--tg-theme-hint-color)', fontSize: 13 }}>M1 обрабатывает…</span>
            </div>
          )}
        </div>
      </div>
      <div style={{ borderTop: '0.5px solid var(--tg-theme-section-separator-color)', background: 'var(--tg-theme-bg-color)' }}>
        {hasProposal && (
          <div style={{ padding: '10px 12px 0' }}>
            <button className="btn success full" onClick={finalize} disabled={finalizing}>
              <Ico name="check" size={16} />{finalizing ? 'Сохранение…' : 'Finalize Arcs → сохранить в базу'}
            </button>
          </div>
        )}
        <div style={{ display: 'flex', gap: 8, padding: 10, alignItems: 'flex-end' }}>
          <textarea
            className="input"
            placeholder="Сообщение M1…"
            value={draft}
            onChange={e => setDraft(e.target.value)}
            rows={1}
            style={{ minHeight: 38, maxHeight: 120, padding: '9px 12px', fontSize: 14.5 }}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
          />
          <button className="btn" onClick={send} disabled={sending || !draft.trim()}
            style={{ width: 38, height: 38, padding: 0, borderRadius: 19, flexShrink: 0 }}>
            <Ico name="send" size={16} />
          </button>
        </div>
        <div style={{ padding: '0 10px 6px', display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn link" style={{ fontSize: 11, padding: '2px 4px', color: 'var(--tg-theme-hint-color)' }} onClick={releaseChat}>
            завершить сессию
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Project select with real project list ─────────────────────
function ChatSelect({ onHome, onStart }) {
  const projectsQ = useApi(() => API.projects(), []);
  const [newName, setNewName] = React.useState('');
  const [creating, setCreating] = React.useState(false);

  const projects = (projectsQ.data?.projects || []).filter(p => !p.archived && p.status !== 'done');
  const setupProjs = projects.filter(p => p.mode === 'setup');
  const otherProjs = projects.filter(p => p.mode !== 'setup');

  const createAndStart = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      await API.project(newName.trim()).catch(() => null); // check exists
      const created = await apiFetch('/projects', { method: 'POST', body: JSON.stringify({ name: newName.trim(), mode: 'setup' }) });
      onStart(created.name);
    } catch (e) {
      alert('Ошибка: ' + e.message);
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="view-fade">
      <Header title="Chat" sub="select project" meta={<><span className="dot" /> M1 ready</>} onHome={onHome} />
      <div className="app-body">
        {projectsQ.loading
          ? <LoadingSpinner />
          : projectsQ.error
            ? <ErrorRetry message={projectsQ.error} onRetry={projectsQ.reload} />
            : <>
                {setupProjs.length > 0 && (
                  <div className="section" style={{ marginTop: 14 }}>
                    <div className="section-header">setup · определение арок</div>
                    <div className="section-body">
                      {setupProjs.map(p => (
                        <div key={p.name} className="row tappable" onClick={() => onStart(p.name)}>
                          <div className="row-main">
                            <div className="row-title">
                              {p.name}
                              {p.parent_id && <span className="chip tiny">[sub]</span>}
                            </div>
                            <div className="row-sub">{p.mode} · {p.status}</div>
                          </div>
                          <span className="row-chev"><Ico name="chev" size={16} /></span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {otherProjs.length > 0 && (
                  <div className="section" style={{ marginTop: 14 }}>
                    <div className="section-header">expansion · переопределить</div>
                    <div className="section-body">
                      {otherProjs.map(p => (
                        <div key={p.name} className="row tappable" onClick={() => onStart(p.name)}>
                          <div className="row-main">
                            <div className="row-title">{p.name}</div>
                            <div className="row-sub">{p.mode} · {p.status}</div>
                          </div>
                          <span className="row-chev"><Ico name="chev" size={16} /></span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {projects.length === 0 && (
                  <div style={{ padding: '16px', textAlign: 'center', color: 'var(--tg-theme-hint-color)', fontSize: 14 }}>
                    Нет проектов. Создайте первый.
                  </div>
                )}
              </>}

        <div className="section" style={{ marginTop: 14 }}>
          <div className="section-header">создать новый проект</div>
          <div className="section-body">
            <div className="row" style={{ paddingTop: 14, paddingBottom: 14 }}>
              <input className="input" placeholder="my_new_project" value={newName}
                onChange={e => setNewName(e.target.value.replace(/[^a-zA-Z0-9_]/g, ''))}
                style={{ marginRight: 8 }} />
              <button className="btn sm" onClick={createAndStart} disabled={creating || !newName.trim()}>
                <Ico name="plus" size={16} />{creating ? '…' : 'Create'}
              </button>
            </div>
          </div>
          <div className="section-footer">Alphanumeric + underscore, до 64 символов. Mode: setup.</div>
        </div>
      </div>
    </div>
  );
}

function ChatQueued({ project, onReady, onBack, onHome }) {
  // Poll status every 5s
  React.useEffect(() => {
    const t = setInterval(() => {
      API.chatStatus(project).then(res => {
        if (res?.status === 'ready') onReady();
      }).catch(() => {});
    }, 5000);
    return () => clearInterval(t);
  }, [project]);

  return (
    <div className="view-fade">
      <Header title="Chat" sub={project} meta={<><span className="dot warn pulse" /> M1 busy</>} onHome={onHome} />
      <div className="app-body">
        <div className="queued-card">
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
            <div className="ring" />
            <div>
              <div style={{ fontSize: 15, fontWeight: 500 }}>M1 занята другой задачей</div>
              <div style={{ fontSize: 12, color: 'var(--tg-theme-hint-color)', marginTop: 3, fontFamily: 'var(--ag-mono)' }}>
                queued · ожидание M1
              </div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: 'var(--tg-theme-subtitle-text-color)', lineHeight: 1.5 }}>
            Уведомлю через SSE-событие <span className="mono">m1_ready</span> когда освободится. Чат запустится автоматически.
          </div>
          <div className="kv" style={{ marginTop: 14 }}>
            <span className="k">Fallback poll:</span>
            <span className="v">/projects/{project}/chat/status</span>
          </div>
        </div>
        <div style={{ padding: 16, display: 'flex', gap: 8 }}>
          <button className="btn ghost full" onClick={onBack}><Ico name="back" size={16} />Отмена</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ChatMode });
