// Mobile screens — part 2: Detalhe de Processo (LLM resumo), Editor Petição, Acervo IA

// ─── Detalhe de Processo com Resumo IA ───────────────────
function MProcessoDetalhe() {
  const t = useTheme();
  const nav = useNav();
  const [tab, setTab] = React.useState('resumo');
  return <div style={{ background: t.bg, minHeight: '100%', paddingBottom: 92, color: t.text, fontFamily: 'Inter, system-ui' }}>
    {/* Header */}
    <div style={{ padding: '8px 18px 4px', display: 'flex', alignItems: 'center', gap: 10 }}>
      <button onClick={() => nav.back()} style={{ background: t.elevated, border: `1px solid ${t.border}`, borderRadius: 10, width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.text, cursor: 'pointer' }}><Icon name="chevronL" size={16}/></button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10, color: t.muted, fontWeight: 600, letterSpacing: 0.4 }}>0023421-12.2025.8.26.0100</div>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>Vellozo S/A vs Construtora Bahia</div>
      </div>
      <IconBtn name="share"/>
      <IconBtn name="dots"/>
    </div>

    <div style={{ padding: '8px 18px 12px' }}>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        <Pill tone="accent">Cível · M&A</Pill>
        <Pill tone="neutral">TJSP · 4ª Vara</Pill>
        <Pill tone="danger">Audiência hoje 09:30</Pill>
      </div>
    </div>

    <div style={{ padding: '0 18px 12px' }}>
      <Tabs value={tab} onChange={setTab} compact items={[
        { id: 'resumo', label: 'Resumo IA' },
        { id: 'partes', label: 'Partes' },
        { id: 'oitivas', label: 'Oitivas' },
        { id: 'docs', label: 'Autos' },
      ]}/>
    </div>

    {tab === 'resumo' && <>
      {/* IA Summary card */}
      <div style={{ padding: '0 18px 12px' }}>
        <Card pad={14} style={{ background: t.raised, borderColor: t.border }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <div style={{ width: 26, height: 26, borderRadius: 8, background: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}><Icon name="spark" size={14}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Resumo Inteligente</div>
              <div style={{ fontSize: 10, color: t.subtext }}>gerado há 12min · 47 peças analisadas</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: t.text, lineHeight: 1.55 }}>
            Ação de <b>rescisão contratual c/c indenização</b> ajuizada em 03/2025. Vellozo S/A alega descumprimento de cláusulas 4ª e 7ª do contrato de M&A. Réu apresentou contestação alegando força maior. <b>Réplica favorável</b> à autora. Audiência de conciliação hoje.
          </div>
        </Card>
      </div>

      {/* Subsunção fato → norma */}
      <div style={{ padding: '0 18px 12px' }}>
        <h3 style={{ fontFamily: '"Playfair Display", serif', fontSize: 14, fontWeight: 600, margin: '0 0 8px', color: t.text }}>Subsunção fato → norma</h3>
        <Card pad={0}>
          {[
            { fato: 'Descumprimento de cláusula 4ª (entrega 60d)', norma: 'CC art. 475', tone: 'accent' },
            { fato: 'Recusa de aceite por vício oculto',           norma: 'CC art. 441–446', tone: 'accent' },
            { fato: 'Alegação de força maior pelo réu',           norma: 'CC art. 393 (rejeitada)', tone: 'danger' },
          ].map((s, i, a) => <div key={i} style={{
            padding: '11px 13px', borderBottom: i < a.length - 1 ? `1px solid ${t.borderSoft}` : 'none',
          }}>
            <div style={{ fontSize: 12.5, color: t.text, fontWeight: 500, marginBottom: 4 }}>{s.fato}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="chevron" size={10} color={t.muted}/>
              <Pill tone={s.tone}>{s.norma}</Pill>
            </div>
          </div>)}
        </Card>
      </div>

      {/* Timeline cronológica */}
      <div style={{ padding: '0 18px 12px' }}>
        <h3 style={{ fontFamily: '"Playfair Display", serif', fontSize: 14, fontWeight: 600, margin: '0 0 8px', color: t.text }}>Linha do tempo</h3>
        <div style={{ position: 'relative', paddingLeft: 22 }}>
          <div style={{ position: 'absolute', left: 7, top: 6, bottom: 6, width: 1, background: t.border }}/>
          {[
            { d: '03/03/25', t: 'Distribuição', sub: 'Petição inicial protocolada', acc: false },
            { d: '20/03/25', t: 'Citação',       sub: 'Réu citado por OJ',            acc: false },
            { d: '15/04/25', t: 'Contestação',  sub: 'Alegação de força maior',      acc: false },
            { d: '02/05/25', t: 'Réplica',       sub: 'Refutação técnica · 18 pgs',  acc: true },
            { d: '18/05/25', t: 'Oitiva test.',  sub: 'Maria T. (eng. responsável)',  acc: false },
            { d: '05/06/25', t: 'Audiência',     sub: 'Conciliação · HOJE',           acc: true, hoje: true },
          ].map((e, i) => <div key={i} style={{ paddingBottom: 11, position: 'relative' }}>
            <div style={{
              position: 'absolute', left: -22, top: 3, width: 14, height: 14, borderRadius: '50%',
              background: e.hoje ? t.accent : (e.acc ? t.text : t.elevated),
              border: `2px solid ${e.hoje ? t.accent : t.border}`,
            }}/>
            <div style={{ fontSize: 10, color: t.muted, fontWeight: 600 }}>{e.d}</div>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: e.hoje ? t.accent : t.text, marginTop: 1 }}>{e.t}</div>
            <div style={{ fontSize: 11, color: t.subtext, marginTop: 1 }}>{e.sub}</div>
          </div>)}
        </div>
      </div>
    </>}

    {tab === 'oitivas' && <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
      {[
        { n: 'Maria Trindade', f: 'Eng. responsável · Testemunha autora', d: '18/05/25', txt: 'Confirmou atraso de 47 dias na entrega e ausência de comunicação do fornecedor.', rel: 92 },
        { n: 'João Brizolla',  f: 'Diretor financeiro · Testemunha réu',  d: '18/05/25', txt: 'Não soube precisar datas exatas; mencionou eventos climáticos sem prova documental.', rel: 38 },
        { n: 'Hélio Vellozo',  f: 'CEO · Depoimento pessoal autora',       d: '18/05/25', txt: 'Apresentou cronograma original e comprovação dos prejuízos operacionais sofridos.', rel: 88 },
      ].map((o, i) => <Card key={i} pad={13}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 8 }}>
          <Avatar name={o.n} size={36}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{o.n}</div>
            <div style={{ fontSize: 11, color: t.subtext }}>{o.f}</div>
          </div>
          <div style={{ fontSize: 10, color: t.muted }}>{o.d}</div>
        </div>
        <div style={{
          fontSize: 12, color: t.textDim, lineHeight: 1.5,
          padding: '8px 11px', background: t.elevated, borderRadius: 8,
          borderLeft: `3px solid ${t.accent}`,
        }}>"{o.txt}"</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 9 }}>
          <div style={{ fontSize: 10.5, color: t.muted, fontWeight: 600 }}>Relevância para a tese</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, marginLeft: 10 }}>
            <ProgressBar value={o.rel/100} color={o.rel > 70 ? t.positive : o.rel > 50 ? t.warn : t.danger}/>
            <span style={{ fontSize: 11, fontWeight: 700, color: t.text, minWidth: 26, textAlign: 'right' }}>{o.rel}%</span>
          </div>
        </div>
      </Card>)}
    </div>}

    {tab === 'partes' && <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
      {[
        { n: 'Vellozo S/A', p: 'Autora', adv: 'Dr. Augusto Mendes (você)', tone: 'accent' },
        { n: 'Construtora Bahia Ltda', p: 'Ré', adv: 'Dra. Helena Castro · OAB/SP 123.456', tone: 'danger' },
        { n: 'Maria Trindade', p: 'Testemunha autora', adv: 'Eng. civil · 12 anos exp.', tone: 'neutral' },
        { n: 'João Brizolla', p: 'Testemunha ré', adv: 'Diretor financeiro', tone: 'neutral' },
      ].map((p, i) => <Card key={i} pad={12}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <Avatar name={p.n} size={38}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{p.n}</div>
            <div style={{ fontSize: 11, color: t.subtext, marginTop: 1 }}>{p.adv}</div>
          </div>
          <Pill tone={p.tone}>{p.p}</Pill>
        </div>
      </Card>)}
    </div>}

    {tab === 'docs' && <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
      {[
        'Petição inicial · 24 pgs',
        'Procuração · assinada',
        'Contrato M&A 14.03.24 · ANEXO 1',
        'Contestação ré · 18 pgs',
        'Réplica autora · 18 pgs',
        'Ata audiência 18/05',
        'Laudo pericial preliminar',
      ].map((d, i) => <Card key={i} pad={11}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: t.chipBg, color: t.chipText, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="doc" size={15}/></div>
          <div style={{ flex: 1, fontSize: 12.5, color: t.text }}>{d}</div>
          <Icon name="chevron" size={14} color={t.muted}/>
        </div>
      </Card>)}
    </div>}

    <BottomNav items={NAV_ITEMS} value="proc"/>
  </div>;
}

// ─── Editor de petição com IA inline ────────────────────
function MEditorPeticao() {
  const t = useTheme();
  const nav = useNav();
  return <div style={{ background: t.bg, minHeight: '100%', color: t.text, fontFamily: 'Inter, system-ui', display: 'flex', flexDirection: 'column' }}>
    {/* Header */}
    <div style={{ padding: '8px 18px 8px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${t.borderSoft}` }}>
      <button onClick={() => nav.back()} style={{ background: 'transparent', border: 'none', color: t.text, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevronL" size={20}/></button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10, color: t.muted, fontWeight: 600 }}>Recurso de Apelação · rascunho v3</div>
        <div style={{ fontSize: 13, fontWeight: 700, color: t.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>Vellozo S/A vs Construtora Bahia</div>
      </div>
      <Btn size="sm" variant="primary">Salvar</Btn>
    </div>

    {/* Toolbar */}
    <div style={{ padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 6, borderBottom: `1px solid ${t.borderSoft}`, background: t.surface }}>
      {['I.', 'II.', 'III.'].map(s => <button key={s} style={{ width: 30, height: 28, borderRadius: 7, background: t.elevated, border: `1px solid ${t.border}`, color: t.text, fontSize: 11, fontWeight: 700, fontFamily: '"Playfair Display"' }}>{s}</button>)}
      <div style={{ width: 1, height: 18, background: t.border, margin: '0 4px' }}/>
      {['B','I','U'].map(s => <button key={s} style={{ width: 28, height: 28, borderRadius: 7, background: t.elevated, border: `1px solid ${t.border}`, color: t.text, fontSize: 12, fontWeight: 700, fontStyle: s === 'I' ? 'italic' : 'normal', textDecoration: s === 'U' ? 'underline' : 'none' }}>{s}</button>)}
      <div style={{ flex: 1 }}/>
      <IconBtn name="spark" active/>
    </div>

    {/* Document */}
    <div style={{ flex: 1, padding: '14px 20px 20px', background: t.surface, overflow: 'auto', fontFamily: 'Georgia, "Playfair Display", serif' }}>
      <div style={{ textAlign: 'center', fontSize: 13, fontWeight: 700, color: t.text, marginBottom: 14, textTransform: 'uppercase', letterSpacing: 0.5 }}>EXCELENTÍSSIMO SENHOR DESEMBARGADOR RELATOR</div>

      <div style={{ fontSize: 11, color: t.text, lineHeight: 1.7, textAlign: 'justify' }}>
        <p style={{ margin: '0 0 10px' }}>Autos nº <b>0023421-12.2025.8.26.0100</b></p>
        <p style={{ margin: '0 0 10px' }}><b>VELLOZO S/A</b>, já qualificada nos autos do processo em epígrafe, vem, respeitosamente, por seus advogados que esta subscrevem, com fundamento no art. 1.009 do CPC, interpor o presente</p>
        <p style={{ textAlign: 'center', margin: '14px 0', fontWeight: 700, color: t.text }}>RECURSO DE APELAÇÃO</p>
        <p style={{ margin: '0 0 10px' }}>em face da r. sentença de fls. 412/427, requerendo o seu recebimento e regular processamento, conforme razões anexas.</p>
        <p style={{ fontWeight: 700, fontSize: 12, color: t.text, margin: '14px 0 8px' }}>I. DOS FATOS</p>
        <p style={{ margin: '0 0 4px' }}>Trata-se de ação de rescisão contratual cumulada com indenização por perdas e danos, ajuizada em face da</p>

        {/* IA inline suggestion */}
        <div contentEditable={false} style={{
          margin: '8px 0', padding: '10px 12px',
          background: t.raised, border: `1px solid ${t.accent}`, borderRadius: 10,
          fontFamily: 'Inter, system-ui', textAlign: 'left',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <Icon name="spark" size={12} color={t.accent}/>
            <span style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Sugestão da IA</span>
          </div>
          <div style={{ fontSize: 11.5, color: t.text, lineHeight: 1.45 }}>
            Cite <b>REsp 1.987.443/SP</b> (STJ, 3ª Turma, 2024) para fortalecer a tese de descumprimento essencial.
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
            <Btn size="sm" variant="primary">Inserir</Btn>
            <Btn size="sm" variant="ghost">Por quê?</Btn>
            <Btn size="sm" variant="ghost">Dispensar</Btn>
          </div>
        </div>

        <p style={{ margin: '0 0 10px' }}>Construtora Bahia Ltda, em razão do <span style={{ background: t.chipBg, color: t.chipText, padding: '1px 4px', borderRadius: 3 }}>descumprimento essencial</span> das cláusulas 4ª e 7ª…</p>
      </div>
    </div>

    {/* AI dock */}
    <div style={{ borderTop: `1px solid ${t.border}`, background: t.surface, padding: '10px 14px 14px' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: t.elevated, border: `1px solid ${t.border}`,
        borderRadius: 12, padding: '8px 12px',
      }}>
        <Icon name="spark" size={16} color={t.accent}/>
        <input placeholder="Pergunte ao copiloto…" style={{
          flex: 1, background: 'transparent', border: 'none', outline: 'none',
          color: t.text, fontSize: 13, fontFamily: 'inherit',
        }}/>
        <button style={{ background: 'transparent', border: 'none', color: t.accent, cursor: 'pointer' }}><Icon name="mic" size={16}/></button>
        <button style={{ background: t.accent, color: '#fff', border: 'none', borderRadius: 8, width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="send" size={13}/></button>
      </div>
    </div>
  </div>;
}

// ─── Acervo IA — busca de jurisprudência ────────────────
function MAcervoIA() {
  const t = useTheme();
  const nav = useNav();
  const [tab, setTab] = React.useState('jur');
  return <div style={{ background: t.bg, minHeight: '100%', paddingBottom: 92, color: t.text, fontFamily: 'Inter, system-ui' }}>
    <ScreenHeader sub="Acervo · IA" title="Pesquisar" right={<IconBtn name="dots"/>}/>

    {/* AI search bar */}
    <div style={{ padding: '0 18px 12px' }}>
      <div style={{
        background: t.elevated, border: `1px solid ${t.border}`, borderRadius: 14,
        padding: 12, display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: t.accent, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="spark" size={15}/></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 4 }}>Sua pergunta</div>
          <div style={{ fontSize: 13, color: t.text, lineHeight: 1.5, fontStyle: 'italic' }}>"Qual a tese mais recente do STJ sobre rescisão por inadimplemento essencial em contrato de M&A?"</div>
        </div>
      </div>
    </div>

    {/* Filtros por tipo */}
    <div style={{ padding: '0 18px 12px' }}>
      <Tabs value={tab} onChange={setTab} compact items={[
        { id: 'jur', label: 'Jurisprud. · 47' },
        { id: 'lei', label: 'Leis · 12' },
        { id: 'dou', label: 'Doutrina · 8' },
      ]}/>
    </div>

    {/* IA answer card */}
    <div style={{ padding: '0 18px 12px' }}>
      <Card pad={14} style={{ background: t.raised }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
          <Icon name="spark" size={13} color={t.accent}/>
          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Síntese do copiloto</div>
        </div>
        <div style={{ fontSize: 12.5, color: t.text, lineHeight: 1.55 }}>
          O <b>STJ</b> tem reiterado que o <b>inadimplemento substancial</b> autoriza a rescisão quando comprometida a finalidade econômica do contrato (CC art. 475). Em M&A, exige-se análise do <i>impacto na operação</i> e não da mera mora.
        </div>
        <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
          <Pill tone="accent">3 acórdãos chave</Pill>
          <Pill tone="neutral">2024–2026</Pill>
          <Pill tone="positive">92% confiança</Pill>
        </div>
      </Card>
    </div>

    <div style={{ padding: '0 18px 6px', fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Acórdãos relacionados</div>

    <div style={{ padding: '4px 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
      {[
        { id: 'REsp 1.987.443/SP', t: 'STJ · 3ª Turma · 11.2024', tese: 'Inadimplemento essencial enseja rescisão imediata', rel: 'altamente relevante', tone: 'positive' },
        { id: 'AgInt no REsp 1.876.231', t: 'STJ · 4ª Turma · 06.2024', tese: 'Mora não substantiva ≠ inadimplemento', rel: 'relevante', tone: 'warn' },
        { id: 'REsp 1.755.911/RS', t: 'STJ · 3ª Turma · 02.2024', tese: 'Adoção da Teoria do Adimplemento Substancial', rel: 'fundamental', tone: 'accent' },
      ].map(j => <Card key={j.id} pad={12}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontFamily: '"Playfair Display"', fontSize: 14, fontWeight: 700, color: t.text }}>{j.id}</div>
            <div style={{ fontSize: 10.5, color: t.subtext, marginTop: 2 }}>{j.t}</div>
          </div>
          <Pill tone={j.tone}>{j.rel}</Pill>
        </div>
        <div style={{ fontSize: 12, color: t.textDim, lineHeight: 1.5, marginTop: 4 }}>{j.tese}</div>
        <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
          <Btn size="sm" variant="soft" icon="pin">Salvar</Btn>
          <Btn size="sm" variant="ghost" onClick={() => nav.go('editor')}>Inserir na peça</Btn>
        </div>
      </Card>)}
    </div>

    <BottomNav items={NAV_ITEMS} value="pet"/>
  </div>;
}

Object.assign(window, { MProcessoDetalhe, MEditorPeticao, MAcervoIA });
