/* Inject, Status, Settings modes — real API */

// ── Inject ────────────────────────────────────────────────────
function InjectMode({ onHome }) {
  const [step, setStep]     = React.useState('select');
  const [project, setProject] = React.useState(null);
  const [type, setType]     = React.useState(null);
  const [text, setText]     = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const fileRef             = React.useRef(null);

  const projectsQ = useApi(() => API.projects(), []);
  const projects  = (projectsQ.data?.projects || []).filter(p => !p.archived);

  const saveText = async () => {
    if (!text.trim()) return;
    setSaving(true);
    try {
      await API.injectText(project, text);
      setText('');
      setStep('done');
    } catch (e) {
      alert('Ошибка: ' + e.message);
    } finally {
      setSaving(false);
    }
  };

  const saveFile = async (file) => {
    if (!file) return;
    setSaving(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      await API.injectFile(project, fd);
      setStep('done');
    } catch (e) {
      alert('Ошибка: ' + e.message);
    } finally {
      setSaving(false);
    }
  };

  if (step === 'done') {
    return (
      <div className="view-fade">
        <Header title="Inject" sub={project} meta={<span className="chip tiny ok">saved</span>} onHome={onHome} />
        <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">Сохранено в {project}</div>
          <div className="e-sub">
            {type === 'file'
              ? `Файл → projects/${project}/injected/. Embedder проиндексирует при следующем цикле.`
              : `Инструкция → projects/${project}/memory.md. M1 учтёт в следующем запросе.`}
          </div>
          <button className="btn ghost sm" onClick={() => { setStep('select'); setType(null); setText(''); }}>Inject ещё</button>
        </div>
      </div>
    );
  }

  if (step === 'select') {
    return (
      <div className="view-fade">
        <Header title="Inject" sub="select project" meta={<span className="mono" style={{ fontSize: 11, color: 'var(--tg-theme-hint-color)' }}>router · embedder</span>} onHome={onHome} />
        <div className="app-body">
          <div className="section" style={{ marginTop: 14 }}>
            <div className="section-header">в какой проект</div>
            <div className="section-body">
              {projectsQ.loading
                ? <div style={{ padding: 16 }}><LoadingSpinner /></div>
                : projectsQ.error
                  ? <ErrorRetry message={projectsQ.error} onRetry={projectsQ.reload} />
                  : projects.length === 0
                    ? <div style={{ padding: '14px 16px', color: 'var(--tg-theme-hint-color)', fontSize: 13 }}>Нет проектов</div>
                    : projects.map(p => (
                        <div key={p.name} className="row tappable" onClick={() => { setProject(p.name); setStep('type'); }}>
                          <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 className="section-footer">Inject — одноразовая сессия. M1/M2 не задействованы.</div>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'type') {
    return (
      <div className="view-fade">
        <div className="app-header">
          <div className="h-row">
            <button className="btn link" onClick={() => setStep('select')} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Project</button>
            <div className="h-meta mono" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span>target: {project}</span>
              {onHome && <button className="home-btn" onClick={onHome} aria-label="Home" style={{ width: 26, height: 26 }}><Ico name="home" size={14} /></button>}
            </div>
          </div>
          <div style={{ marginTop: 8, fontSize: 22, fontWeight: 600 }}>Тип инъекции</div>
        </div>
        <div className="app-body">
          <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <button className="btn ghost" style={{ flexDirection: 'row', justifyContent: 'flex-start', padding: '16px', gap: 14 }} onClick={() => { setType('file'); setStep('file'); }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(106,179,243,0.18)', color: 'var(--ag-info)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ico name="doc" size={22} /></div>
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>File</div>
                <div style={{ fontSize: 12, color: 'var(--tg-theme-hint-color)', marginTop: 3, fontFamily: 'var(--ag-mono)' }}>→ projects/{project}/injected/ · max 10MB</div>
              </div>
              <Ico name="chev" size={16} />
            </button>
            <button className="btn ghost" style={{ flexDirection: 'row', justifyContent: 'flex-start', padding: '16px', gap: 14 }} onClick={() => { setType('text'); setStep('text'); }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(232,169,59,0.18)', color: 'var(--ag-warn)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ico name="pen" size={22} /></div>
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>Instruction</div>
                <div style={{ fontSize: 12, color: 'var(--tg-theme-hint-color)', marginTop: 3, fontFamily: 'var(--ag-mono)' }}>→ projects/{project}/memory.md</div>
              </div>
              <Ico name="chev" size={16} />
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'file') {
    return (
      <div className="view-fade">
        <div className="app-header">
          <div className="h-row">
            <button className="btn link" onClick={() => setStep('type')} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Type</button>
            <div className="h-meta mono" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span>→ injected/</span>
              {onHome && <button className="home-btn" onClick={onHome} style={{ width: 26, height: 26 }}><Ico name="home" size={14} /></button>}
            </div>
          </div>
          <div style={{ marginTop: 8, fontSize: 22, fontWeight: 600 }}>Загрузка файла</div>
        </div>
        <div className="app-body">
          <div style={{ padding: 16 }}>
            <input ref={fileRef} type="file" style={{ display: 'none' }}
              onChange={e => e.target.files[0] && saveFile(e.target.files[0])} />
            <div style={{ border: '1px dashed var(--tg-theme-section-separator-color)', borderRadius: 14, padding: '32px 16px', textAlign: 'center', background: 'var(--tg-theme-section-bg-color)' }}>
              <div style={{ width: 48, height: 48, borderRadius: 12, background: 'rgba(106,179,243,0.12)', color: 'var(--ag-info)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
                <Ico name="attach" size={24} />
              </div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Выбери файл</div>
              <div style={{ fontSize: 11, color: 'var(--tg-theme-hint-color)', marginTop: 4, fontFamily: 'var(--ag-mono)' }}>любой формат · до 10 MB</div>
              <button className="btn sm" style={{ marginTop: 12 }} onClick={() => fileRef.current?.click()} disabled={saving}>
                {saving ? 'Загрузка…' : 'Выбрать файл'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // text instruction
  return (
    <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="app-header">
        <div className="h-row">
          <button className="btn link" onClick={() => setStep('type')} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Type</button>
          <div className="h-meta mono" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>→ memory.md</span>
            {onHome && <button className="home-btn" onClick={onHome} style={{ width: 26, height: 26 }}><Ico name="home" size={14} /></button>}
          </div>
        </div>
        <div style={{ marginTop: 8, fontSize: 22, fontWeight: 600 }}>Инструкция</div>
      </div>
      <div className="app-body" style={{ flex: 1 }}>
        <div style={{ padding: 16 }}>
          <textarea className="input" placeholder="Например: «Целевая аудитория — power-users…»"
            value={text} onChange={e => setText(e.target.value)} rows={6} />
          <div style={{ fontSize: 11, color: 'var(--tg-theme-hint-color)', marginTop: 8, fontFamily: 'var(--ag-mono)', lineHeight: 1.5 }}>
            Текст добавится в projects/{project}/memory.md под ## Injected Context с timestamp.
          </div>
        </div>
      </div>
      <div style={{ padding: 12, borderTop: '0.5px solid var(--tg-theme-section-separator-color)' }}>
        <button className="btn full" disabled={!text.trim() || saving} style={{ opacity: text.trim() ? 1 : 0.5 }} onClick={saveText}>
          <Ico name="check" size={16} />{saving ? 'Сохранение…' : 'Сохранить в memory.md'}
        </button>
      </div>
    </div>
  );
}

// ── Status ────────────────────────────────────────────────────
function StatusMode() {
  const statusQ = useApi(() => API.status(), []);
  const [lastCheck, setLastCheck] = React.useState(Date.now());

  const reload = React.useCallback(() => {
    statusQ.reload();
    setLastCheck(Date.now());
  }, [statusQ.reload]);

  React.useEffect(() => {
    const t = setInterval(reload, 30000);
    return () => clearInterval(t);
  }, [reload]);

  const projects  = (statusQ.data?.projects || []).slice().sort((a, b) => b.priority - a.priority);
  const health    = statusQ.data?.health || {};
  const ultimate  = statusQ.data?.ultimate_priority;
  const activeN   = projects.filter(p => p.status === 'active').length;
  const allOk     = health.M1 && health.router && health.embedder;

  const dotSt = (ok) => ok ? '' : 'fail';
  const statusColor = (s) =>
    s === 'active'  ? 'var(--ag-ok)'   :
    s === 'paused'  ? 'var(--ag-warn)' :
    s === 'done'    ? 'var(--ag-info)' :
    'var(--tg-theme-hint-color)';

  return (
    <div className="view-fade">
      <Header
        title="Status"
        sub={statusQ.loading ? '…' : `${activeN} active · ${projects.length} total`}
        meta={<>
          <span className={`dot${allOk ? '' : ' warn'}`} />
          {statusQ.loading ? '…' : allOk ? 'all systems' : 'partial'}
        </>}
      />
      <div className="app-body">
        {statusQ.loading && <LoadingSpinner />}
        {statusQ.error && <ErrorRetry message={statusQ.error} onRetry={reload} />}

        {!statusQ.loading && !statusQ.error && (
          <>
            {ultimate && (
              <div className="ult-banner">
                <div className="ub-bolt"><Ico name="bolt" size={18} /></div>
                <div className="ub-body">
                  <div className="ub-label">⚡ ultimate priority active</div>
                  <div className="ub-target">{ultimate.type} · {ultimate.name}</div>
                  <div className="ub-meta">project: {ultimate.project}</div>
                </div>
              </div>
            )}

            <div className="section">
              <div className="section-header">проекты · {projects.length}</div>
              <div className="section-body">
                {projects.length === 0 && (
                  <div style={{ padding: '14px 16px', color: 'var(--tg-theme-hint-color)', fontSize: 13 }}>Нет проектов</div>
                )}
                {projects.map(p => (
                  <div key={p.name} className="proj-row">
                    <div className="pr-body" style={{ paddingLeft: 0 }}>
                      <div className="pr-name">
                        <span>{p.name}</span>
                        {p.parent_id && <span className="chip tiny">[sub]</span>}
                        {p.priority >= 3 && <span className="chip tiny fail">P{p.priority}</span>}
                        {p.priority === 2 && <span className="chip tiny warn">P{p.priority}</span>}
                        {p.priority === 1 && <span className="chip tiny">P{p.priority}</span>}
                      </div>
                      <div className="pr-meta">
                        <span>{p.mode}</span>
                        <span>·</span>
                        <span style={{ color: statusColor(p.status) }}>{p.status}</span>
                      </div>
                    </div>
                    <span className="row-chev"><Ico name="chev" size={16} /></span>
                  </div>
                ))}
              </div>
            </div>

            <div className="section">
              <div className="section-header">system health</div>
              <div className="health-grid">
                <div className="health-cell">
                  <div className="hc-name">M1</div>
                  <div className="hc-status"><span className={`dot ${dotSt(health.M1)}`} />{health.M1 ? 'online' : 'offline'}</div>
                  <div className="hc-port">:8080</div>
                </div>
                <div className="health-cell">
                  <div className="hc-name">router</div>
                  <div className="hc-status"><span className={`dot ${dotSt(health.router)}`} />{health.router ? 'online' : 'offline'}</div>
                  <div className="hc-port">:8081</div>
                </div>
                <div className="health-cell">
                  <div className="hc-name">embedder</div>
                  <div className="hc-status"><span className={`dot ${dotSt(health.embedder)}`} />{health.embedder ? 'online' : 'offline'}</div>
                  <div className="hc-port">:8082</div>
                </div>
              </div>
              <div className="section-footer" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>обновлено {Math.round((Date.now() - lastCheck) / 1000)}s назад</span>
                <button className="btn link" style={{ fontSize: 11, padding: '2px 6px' }} onClick={reload}>обновить</button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Settings ──────────────────────────────────────────────────
function SettingsMode() {
  const modeQ    = useApi(() => API.settingsMode(), []);
  const [setting, setSetting] = React.useState(null); // local optimistic
  const [saving, setSaving]   = React.useState(false);

  const currentMode = setting ?? modeQ.data?.mode ?? 'balanced';
  const modes = [
    { id: 'fast',     title: 'Fast',     desc: 'Быстрые ответы без рассуждений',    icon: 'bolt',  color: 'orange', reasoning: 0,    ctx: 8192   },
    { id: 'balanced', title: 'Balanced', desc: 'Стандартная работа · оптимум',       icon: 'spark', color: 'blue',   reasoning: 1024, ctx: 65536  },
    { id: 'deep',     title: 'Deep',     desc: 'Сложные задачи · глубокий анализ',   icon: 'cpu',   color: 'violet', reasoning: 4096, ctx: 131072 },
  ];

  const setMode = async (m) => {
    setSetting(m);
    setSaving(true);
    try {
      await API.setSettingsMode(m);
    } catch (e) {
      setSetting(null);
      alert('Ошибка: ' + e.message);
    } finally {
      setSaving(false);
    }
  };

  const activeMode = modes.find(m => m.id === currentMode) || modes[1];
  const ctxK = (activeMode.ctx / 1024).toFixed(activeMode.ctx >= 102400 ? 0 : 0);

  const projectCmds = [
    ['/newproject {name}',                  'Создать новый проект (setup mode)',    'plus',  'blue'],
    ['/expand {project}',                   'Перевести setup → expansion',          'spark', 'violet'],
    ['/pause {project}',                    'Поставить на паузу',                   'pause', 'orange'],
    ['/resume {project}',                   'Возобновить выполнение',               'play',  'green'],
    ['/redefine_scope {project} "{desc}"',  'Consilium для пересмотра scope',       'cpu',   'violet'],
  ];

  const endpoints = [
    ['POST', '/settings/mode',  'смена режима инференса', 'post'],
    ['GET',  '/api/v1',         'базовый REST API',       'get'],
    ['POST', '/auth · JWT 24h', 'выдача access-токена',   'post'],
  ];

  return (
    <div className="view-fade">
      <Header title="Settings" />
      <div className="app-body">

        {/* — Mode picker — */}
        <div className="section">
          <div className="section-header">режим работы</div>
          <div className="section-body">
            {modeQ.loading
              ? <div style={{ padding: 16 }}><LoadingSpinner /></div>
              : modes.map(m => (
                  <div
                    key={m.id}
                    className={`row choice tappable${currentMode === m.id ? ' selected' : ''}`}
                    onClick={() => !saving && setMode(m.id)}
                  >
                    <div className={`row-ico ${m.color}`}><Ico name={m.icon} size={16} /></div>
                    <div className="row-main">
                      <div className="row-title">{m.title}</div>
                      <div className="row-sub">{m.desc}</div>
                    </div>
                    <span className="row-check"><Ico name="check" size={20} /></span>
                  </div>
                ))}
          </div>
          <div className="section-footer">
            Применяется ко всем новым AI-задачам{saving ? ' · сохранение…' : '.'}
          </div>
        </div>

        {/* — Inference params (live values for active mode) — */}
        <div className="section">
          <div className="section-header">параметры инференса</div>
          <div className="section-body">
            <div className="kv-grid">
              <div className="kv-cell">
                <div className="kv-k">reasoning</div>
                <div className="kv-v">{activeMode.reasoning}<span className="kv-u">tok</span></div>
              </div>
              <div className="kv-cell">
                <div className="kv-k">context</div>
                <div className="kv-v">{ctxK}<span className="kv-u">K</span></div>
              </div>
              <div className="kv-cell">
                <div className="kv-k">backend</div>
                <div className="kv-v" style={{ fontSize: 14 }}>local<span className="kv-u">llm</span></div>
              </div>
            </div>
          </div>
          <div className="section-footer">Активные значения для режима <span className="mono">{currentMode}</span>.</div>
        </div>

        {/* — Bot commands cheatsheet — */}
        <div className="section">
          <div className="section-header">команды бота</div>
          <div className="section-body">
            {projectCmds.map(([cmd, desc, ico, color]) => (
              <div key={cmd} className="cmd-row">
                <div className={`row-ico ${color}`}><Ico name={ico} size={15} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="cmd-name" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{cmd}</div>
                  <div className="cmd-desc">{desc}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="section-footer">Команды доступны в Telegram-боте.</div>
        </div>

        {/* — API endpoints (developer reference) — */}
        <div className="section">
          <div className="section-header">api endpoints</div>
          <div className="section-body">
            {endpoints.map(([method, path, desc, cls]) => (
              <div key={path} className="row" style={{ gap: 12 }}>
                <span className={`http-method ${cls}`}>{method}</span>
                <div className="row-main">
                  <div className="row-title mono" style={{ fontSize: 13 }}>{path}</div>
                  <div className="row-sub" style={{ fontFamily: 'var(--ag-sans)' }}>{desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* — About — */}
        <div className="section">
          <div className="section-header">о приложении</div>
          <div className="section-body">
            <div className="row">
              <div className="row-ico violet"><Ico name="spark" size={15} /></div>
              <div className="row-main"><div className="row-title">Версия</div></div>
              <span className="row-detail">1.0.0</span>
            </div>
            <div className="row">
              <div className="row-ico cyan"><Ico name="cpu" size={15} /></div>
              <div className="row-main"><div className="row-title">Движок</div></div>
              <span className="row-detail">local LLM</span>
            </div>
          </div>
        </div>

        <div className="app-footer">
          <span className="af-brand">Kinley Agent</span> · v1.0.0
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { InjectMode, StatusMode, SettingsMode });
