/* Inbox mode — real API data */

function InboxMode({ onHome, initialSelected = null }) {
  const [selected, setSelected] = React.useState(initialSelected);
  const [filter, setFilter] = React.useState('all');
  const inboxQ = useApi(() => API.inbox(), []);

  const notifs = inboxQ.data?.items || [];

  if (selected) {
    return (
      <NotifDetail
        id={selected}
        onBack={() => setSelected(null)}
        onHome={onHome}
        onReplied={() => { setSelected(null); inboxQ.reload(); }}
      />
    );
  }

  if (inboxQ.loading) {
    return (
      <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Header title="Inbox" sub="загрузка…" />
        <div className="app-body"><LoadingSpinner /></div>
      </div>
    );
  }

  if (inboxQ.error) {
    return (
      <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Header title="Inbox" sub="ошибка" />
        <div className="app-body"><ErrorRetry message={inboxQ.error} onRetry={inboxQ.reload} /></div>
      </div>
    );
  }

  if (notifs.length === 0) {
    return (
      <div className="view-fade">
        <Header title="Inbox" sub="0 pending" meta={<><span className="dot" /> all clear</>} />
        <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">Агент работает автономно. Когда потребуется решение — появится здесь.</div>
          </div>
        </div>
      </div>
    );
  }

  const KINDS = ['all', 'phase', 'todo', 'cons', 'system'];
  const filtered = filter === 'all' ? notifs : notifs.filter(n => notifIcon(n.type).kind === filter);

  return (
    <div className="view-fade">
      <Header
        title="Inbox"
        sub={`${notifs.length} pending`}
        meta={<><span className="dot warn pulse" /> awaiting</>}
      />
      <div className="app-body">
        <div style={{ padding: '10px 12px 0' }}>
          <div className="seg">
            {[['all', 'Все'], ['phase', 'Phase'], ['todo', 'Todo'], ['cons', 'Consilium'], ['system', 'System']].map(([id, l]) => (
              <button key={id} className={filter === id ? 'on' : ''} onClick={() => setFilter(id)}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 10 }}>
          {filtered.map(n => {
            const ico = notifIcon(n.type);
            return (
              <div key={n.id} className="notif" onClick={() => setSelected(n.id)}>
                <div className={`nf-icon t-${ico.kind}`}>{ico.label}</div>
                <div className="nf-body">
                  <div className="nf-top">
                    <div className="nf-title">{n.label || n.type}</div>
                    <div className="nf-time">{relTime(n.created_at)}</div>
                  </div>
                  <div className="nf-summary">{n.project} · {n.scope_entity_type || n.type}</div>
                  <div className="nf-tags">
                    <span className="chip tiny info">{n.project}</span>
                    <span className="chip tiny">{n.label || n.type}</span>
                    {n.scope_entity_id && <span className="chip tiny">{n.scope_entity_id}</span>}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Detail view — loads full notification ─────────────────────
function NotifDetail({ id, onBack, onHome, onReplied }) {
  const detailQ = useApi(() => API.notification(id), [id]);
  const [sending, setSending] = React.useState(false);
  const [replyText, setReplyText] = React.useState('');

  const sendReply = async (response) => {
    setSending(true);
    try {
      await API.replyNotif(id, response || replyText);
      onReplied();
    } catch (e) {
      alert('Ошибка: ' + e.message);
    } finally {
      setSending(false);
    }
  };

  if (detailQ.loading) {
    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={onBack} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Inbox</button>
          </div>
        </div>
        <div className="app-body"><LoadingSpinner /></div>
      </div>
    );
  }

  if (!detailQ.data || detailQ.error) {
    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={onBack} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Inbox</button>
          </div>
        </div>
        <div className="app-body"><ErrorRetry message={detailQ.error} onRetry={detailQ.reload} /></div>
      </div>
    );
  }

  const notif = detailQ.data;
  const ico   = notifIcon(notif.type);
  const ctx   = notif.context || {};
  const scope = [notif.scope_entity_type, notif.scope_entity_id].filter(Boolean).join(' · ');

  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={onBack} style={{ padding: 0, gap: 4 }}><Ico name="back" size={18} />Inbox</button>
          <div className="h-meta" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {scope && <span className="chip tiny">{scope}</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, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div className={`nf-icon t-${ico.kind}`} style={{ width: 36, height: 36, borderRadius: 9 }}>{ico.label}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{notif.label || notif.type}</div>
            <div style={{ fontSize: 11, color: 'var(--tg-theme-hint-color)', fontFamily: 'var(--ag-mono)', marginTop: 2 }}>
              {notif.project} · {relTime(notif.created_at)} ago
            </div>
          </div>
        </div>
      </div>
      <div className="app-body" style={{ flex: 1 }}>
        {notif.type === 'phase_plan_review' && (
          <PhaseReview ctx={ctx} notif={notif} sendReply={sendReply} sending={sending} />
        )}
        {notif.type === 'consilium_iteration_review' && (
          <ConsiliumReview ctx={ctx} replyText={replyText} setReplyText={setReplyText} sendReply={sendReply} sending={sending} />
        )}
        {notif.type === 'todo_escalation' && (
          <TodoEscalation ctx={ctx} replyText={replyText} setReplyText={setReplyText} sendReply={sendReply} sending={sending} />
        )}
        {notif.type === 'todo_unsure' && (
          <TodoUnsure ctx={ctx} replyText={replyText} setReplyText={setReplyText} sendReply={sendReply} sending={sending} />
        )}
        {notif.type === 'ultimate_replacement_confirm' && (
          <UltimateReplace ctx={ctx} sendReply={sendReply} sending={sending} />
        )}
        {notif.type === 'subproject_merge_approval' && (
          <SubprojectMerge ctx={ctx} sendReply={sendReply} sending={sending} />
        )}
        {(notif.type === 'arc_closure' || notif.type === 'linter_degraded') && (
          <Acknowledge ctx={ctx} notif={notif} replyText={replyText} setReplyText={setReplyText} sendReply={sendReply} sending={sending} />
        )}
        {!['phase_plan_review','consilium_iteration_review','todo_escalation','todo_unsure',
            'ultimate_replacement_confirm','subproject_merge_approval','arc_closure','linter_degraded'].includes(notif.type) && (
          <GenericReply ctx={ctx} notif={notif} replyText={replyText} setReplyText={setReplyText} sendReply={sendReply} sending={sending} />
        )}
      </div>
    </div>
  );
}

// ── Type-specific detail UIs ──────────────────────────────────

function PhaseReview({ ctx, notif, sendReply, sending }) {
  const phases = ctx.phases || [];
  const handleApprove = () => {
    if (ctx.arc_id && notif.project) {
      API.approveArc(notif.project, ctx.arc_id).then(() => sendReply('approve')).catch(e => sendReply('approve'));
    } else {
      sendReply('approve');
    }
  };
  return (
    <div>
      <div className="section">
        <div className="section-header">арка</div>
        <div className="section-body">
          <div className="row">
            <div className="row-main">
              <div className="row-title">{ctx.arc_title || ctx.arc_id || '—'}</div>
              <div className="row-sub">{ctx.arc_id} · auto_proceed = {ctx.auto_proceed ? '1' : '0'}</div>
            </div>
            <span className="chip warn">awaiting</span>
          </div>
        </div>
      </div>
      {phases.length > 0 && (
        <div className="section">
          <div className="section-header">план фаз · {phases.length} шт</div>
          <div className="section-body">
            {phases.map((p, i) => (
              <div key={i} className="row" style={{ alignItems: 'flex-start', padding: '12px 16px' }}>
                <div style={{ flex: '0 0 28px', fontFamily: 'var(--ag-mono)', fontSize: 11, color: 'var(--tg-theme-hint-color)', paddingTop: 2 }}>
                  {String(i + 1).padStart(2, '0')}
                </div>
                <div className="row-main">
                  <div className="row-title" style={{ fontSize: 14 }}>{p.title}</div>
                  {p.desc && <div style={{ fontSize: 12.5, color: 'var(--tg-theme-subtitle-text-color)', marginTop: 3, lineHeight: 1.45 }}>{p.desc}</div>}
                  {p.est && <div className="row-sub" style={{ marginTop: 5 }}>est: {p.est}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      <div style={{ padding: 12, display: 'flex', gap: 6, flexDirection: 'column' }}>
        <button className="btn success full" onClick={handleApprove} disabled={sending}>
          <Ico name="check" size={18} />{sending ? 'Отправка…' : 'Approve · начать генерацию todos'}
        </button>
        <button className="btn danger full" onClick={() => sendReply('reject')} disabled={sending}>
          <Ico name="x" size={16} />Reject
        </button>
      </div>
    </div>
  );
}

function ConsiliumReview({ ctx, replyText, setReplyText, sendReply, sending }) {
  return (
    <div>
      <div className="section">
        <div className="section-header">change · iteration {ctx.iteration}/{ctx.max}</div>
        <div className="section-body">
          <div style={{ padding: '12px 16px', fontSize: 13.5, lineHeight: 1.5 }}>{ctx.change}</div>
        </div>
      </div>
      {(ctx.m1 || ctx.m2) && (
        <div className="section">
          <div className="section-header">независимые оценки</div>
          <div className="consilium-cols">
            {ctx.m1 && (
              <div className="col">
                <div className="col-h"><span className="dot" style={{ background: 'var(--ag-info)' }} />M1</div>
                <div className="kv"><span className="k">compat:</span><span className="v" style={{ color: 'var(--ag-warn)' }}>{ctx.m1.compatibility}</span></div>
                <div className="kv"><span className="k">rec:</span><span className="v" style={{ color: 'var(--ag-warn)' }}>{ctx.m1.recommendation}</span></div>
                {ctx.m1.warning && (
                  <div style={{ fontSize: 11.5, color: 'var(--tg-theme-subtitle-text-color)', lineHeight: 1.5, padding: '8px 0', borderTop: '0.5px dashed var(--tg-theme-section-separator-color)', marginTop: 6 }}>
                    ⚠ {ctx.m1.warning}
                  </div>
                )}
              </div>
            )}
            {ctx.m2 && (
              <div className="col">
                <div className="col-h"><span className="dot" style={{ background: 'var(--ag-violet)' }} />M2</div>
                <div className="kv"><span className="k">compat:</span><span className="v" style={{ color: 'var(--ag-fail)' }}>{ctx.m2.compatibility}</span></div>
                <div className="kv"><span className="k">rec:</span><span className="v" style={{ color: 'var(--ag-fail)' }}>{ctx.m2.recommendation}</span></div>
                {ctx.m2.warning && (
                  <div style={{ fontSize: 11.5, color: 'var(--tg-theme-subtitle-text-color)', lineHeight: 1.5, padding: '8px 0', borderTop: '0.5px dashed var(--tg-theme-section-separator-color)', marginTop: 6 }}>
                    ⚠ {ctx.m2.warning}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
      <div style={{ padding: 12 }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
          {ctx.m1 && <button className="btn ghost full" style={{ color: 'var(--ag-info)' }} onClick={() => sendReply('approve_m1')} disabled={sending}>Approve M1</button>}
          {ctx.m2 && <button className="btn ghost full" style={{ color: 'var(--ag-violet)' }} onClick={() => sendReply('approve_m2')} disabled={sending}>Approve M2</button>}
        </div>
        <textarea className="input" placeholder="Или дай feedback — запустить следующий iteration…" rows={2} value={replyText} onChange={e => setReplyText(e.target.value)} />
        <button className="btn full" style={{ marginTop: 8 }} onClick={() => sendReply()} disabled={sending || !replyText.trim()}>
          {sending ? 'Отправка…' : 'Send feedback'}
        </button>
      </div>
    </div>
  );
}

function TodoEscalation({ ctx, replyText, setReplyText, sendReply, sending }) {
  const errors = ctx.lint_errors || [];
  return (
    <div>
      <div className="section">
        <div className="section-header">todo</div>
        <div className="section-body">
          <div style={{ padding: '12px 16px' }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{ctx.todo_title}</div>
            <div className="row-sub" style={{ marginTop: 4 }}>arc: {ctx.arc} · attempts: {ctx.attempts}</div>
          </div>
        </div>
      </div>
      {errors.length > 0 && (
        <div className="section">
          <div className="section-header">M2 lint errors</div>
          <div className="section-body">
            {errors.map((e, i) => (
              <div key={i} className="row" style={{ alignItems: 'flex-start', padding: '10px 16px', minHeight: 0 }}>
                <span className="chip tiny fail" style={{ flex: '0 0 auto', marginTop: 2 }}>E{i + 1}</span>
                <div style={{ flex: 1, fontSize: 13, lineHeight: 1.4 }}>{e}</div>
              </div>
            ))}
          </div>
        </div>
      )}
      <div style={{ padding: 12 }}>
        <textarea className="input" placeholder="Дай инструкцию по исправлению…" rows={4} value={replyText} onChange={e => setReplyText(e.target.value)} />
        <button className="btn full" style={{ marginTop: 8 }} onClick={() => sendReply()} disabled={sending || !replyText.trim()}>
          <Ico name="send" size={16} />{sending ? 'Отправка…' : 'Отправить инструкцию'}
        </button>
      </div>
    </div>
  );
}

function TodoUnsure({ ctx, replyText, setReplyText, sendReply, sending }) {
  const opts = ctx.options || [];
  return (
    <div>
      <div className="section">
        <div className="section-header">todo</div>
        <div className="section-body">
          <div style={{ padding: '12px 16px', fontSize: 14, fontWeight: 500 }}>{ctx.todo_title}</div>
        </div>
      </div>
      {ctx.m1_thoughts && (
        <div className="section">
          <div className="section-header">M1 размышление</div>
          <div className="section-body">
            <div style={{ padding: '12px 16px', fontSize: 13, lineHeight: 1.5, color: 'var(--tg-theme-subtitle-text-color)' }}>
              {ctx.m1_thoughts}
            </div>
          </div>
        </div>
      )}
      {opts.length > 0 && (
        <div className="section">
          <div className="section-header">варианты от M1</div>
          <div className="section-body">
            {opts.map((o, i) => (
              <div key={i} className="row tappable" onClick={() => sendReply(`option_${i + 1}: ${o}`)}>
                <div style={{ flex: '0 0 28px', fontFamily: 'var(--ag-mono)', fontSize: 11, color: 'var(--ag-info)' }}>OPT{i + 1}</div>
                <div className="row-main"><div className="row-title" style={{ fontSize: 13.5 }}>{o}</div></div>
                <span className="row-chev"><Ico name="chev" size={16} /></span>
              </div>
            ))}
          </div>
        </div>
      )}
      <div style={{ padding: 12 }}>
        <textarea className="input" placeholder="Или укажи направление текстом…" rows={3} value={replyText} onChange={e => setReplyText(e.target.value)} />
        <button className="btn full" style={{ marginTop: 8 }} onClick={() => sendReply()} disabled={sending || !replyText.trim()}>
          <Ico name="send" size={16} />{sending ? 'Отправка…' : 'Send'}
        </button>
      </div>
    </div>
  );
}

function UltimateReplace({ ctx, sendReply, sending }) {
  return (
    <div>
      {ctx.current && (
        <div className="ult-banner" style={{ marginTop: 16 }}>
          <div className="ub-bolt"><Ico name="bolt" size={18} /></div>
          <div className="ub-body">
            <div className="ub-label">currently active</div>
            <div className="ub-target">{ctx.current.name}</div>
            <div className="ub-meta">{ctx.current.type} · {ctx.current.project}</div>
          </div>
        </div>
      )}
      {ctx.proposed && (
        <>
          <div style={{ textAlign: 'center', padding: '14px 0', color: 'var(--tg-theme-hint-color)', fontFamily: 'var(--ag-mono)', fontSize: 11 }}>↓ replace with ↓</div>
          <div className="ult-banner" style={{ marginTop: 0, opacity: 0.7 }}>
            <div className="ub-bolt"><Ico name="bolt" size={18} /></div>
            <div className="ub-body">
              <div className="ub-label">proposed</div>
              <div className="ub-target">{ctx.proposed.name}</div>
              <div className="ub-meta">{ctx.proposed.type}</div>
            </div>
          </div>
        </>
      )}
      <div style={{ padding: 12, display: 'flex', gap: 6, marginTop: 16 }}>
        <button className="btn ghost full" onClick={() => sendReply('cancel')} disabled={sending}><Ico name="x" size={16} />Cancel</button>
        <button className="btn full" style={{ background: 'linear-gradient(135deg,#f5b840,#ec3942)' }} onClick={() => sendReply('confirm')} disabled={sending}>
          <Ico name="check" size={16} />{sending ? '…' : 'Confirm'}
        </button>
      </div>
    </div>
  );
}

function SubprojectMerge({ ctx, sendReply, sending }) {
  const arcs = ctx.arcs || [];
  return (
    <div>
      <div className="section">
        <div className="section-header">subproject · все арки done</div>
        <div className="section-body">
          {ctx.parent && (
            <div className="row"><div className="row-main"><div className="row-title">parent</div><div className="row-sub">{ctx.parent}</div></div></div>
          )}
          {arcs.map((a, i) => (
            <div key={i} className="row" style={{ minHeight: 38 }}>
              <span className="chip tiny ok"><Ico name="check" size={10} />done</span>
              <div className="row-main"><div className="row-title" style={{ fontSize: 13.5 }}>{a.title}</div></div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button className="btn full" onClick={() => sendReply('merge')} disabled={sending} style={{ justifyContent: 'flex-start' }}>
          Merge → parent
        </button>
        <button className="btn ghost full" onClick={() => sendReply('spinoff')} disabled={sending} style={{ justifyContent: 'flex-start' }}>
          Spin-off → standalone
        </button>
        <button className="btn danger full" onClick={() => sendReply('drop')} disabled={sending} style={{ justifyContent: 'flex-start' }}>
          Drop → archive
        </button>
      </div>
    </div>
  );
}

function Acknowledge({ ctx, notif, replyText, setReplyText, sendReply, sending }) {
  const isClosure = notif.type === 'arc_closure';
  return (
    <div>
      <div className="section">
        <div className="section-header">{isClosure ? 'арка закрыта' : 'system info'}</div>
        <div className="section-body">
          {isClosure && ctx.arc_title && (
            <div style={{ padding: '14px 16px', fontSize: 14 }}>{ctx.arc_title}</div>
          )}
          {ctx.duration && <div className="row"><div className="row-main"><div className="row-title">duration</div></div><div className="row-detail">{ctx.duration}</div></div>}
          {ctx.phases && <div className="row"><div className="row-main"><div className="row-title">phases</div></div><div className="row-detail">{ctx.phases}</div></div>}
          {ctx.todos && <div className="row"><div className="row-main"><div className="row-title">todos</div></div><div className="row-detail">{ctx.todos}</div></div>}
          {ctx.cycles_failed !== undefined && <div className="row"><div className="row-main"><div className="row-title">cycles failed</div></div><div className="row-detail">{ctx.cycles_failed}</div></div>}
          {ctx.last_success && <div className="row"><div className="row-main"><div className="row-title">last success</div></div><div className="row-detail">{ctx.last_success}</div></div>}
        </div>
      </div>
      <div style={{ padding: 12 }}>
        <textarea className="input" rows={2} value={replyText} onChange={e => setReplyText(e.target.value)}
          placeholder="Acknowledge…"
          defaultValue={isClosure ? 'noted' : 'investigating'} />
        <button className="btn full" style={{ marginTop: 8 }} onClick={() => sendReply(replyText || (isClosure ? 'noted' : 'investigating'))} disabled={sending}>
          <Ico name="check" size={16} />{sending ? 'Отправка…' : 'Acknowledge'}
        </button>
      </div>
    </div>
  );
}

function GenericReply({ ctx, notif, replyText, setReplyText, sendReply, sending }) {
  return (
    <div>
      <div className="section">
        <div className="section-header">context</div>
        <div className="section-body">
          <div style={{ padding: '12px 16px', fontFamily: 'var(--ag-mono)', fontSize: 11, color: 'var(--tg-theme-hint-color)', lineHeight: 1.6, wordBreak: 'break-all' }}>
            {JSON.stringify(ctx, null, 2)}
          </div>
        </div>
      </div>
      <div style={{ padding: 12 }}>
        <textarea className="input" rows={3} placeholder="Ответ…" value={replyText} onChange={e => setReplyText(e.target.value)} />
        <button className="btn full" style={{ marginTop: 8 }} onClick={() => sendReply()} disabled={sending || !replyText.trim()}>
          <Ico name="send" size={16} />{sending ? 'Отправка…' : 'Send'}
        </button>
      </div>
    </div>
  );
}

window.InboxMode = InboxMode;
