"""
Caixa MEI — Nirlene Contabilidade  •  v3.0
==========================================
Versão Python/Tkinter portando todas as melhorias do index_v3.0.html:

  Código morto:
    - Funções wrapper desnecessárias removidas
    - Parâmetros sem uso eliminados
    - Separação clara entre tabs de navegação e formulário modal

  Performance:
    - dirty-flags: cada aba só recalcula quando realmente suja
    - Cache de totais, lista filtrada e resumo mensal
    - Índice dicionário {id → lancamento} para lookups O(1)
    - Paginação na lista (PAGE_SIZE = 30)
    - Gráfico atualizado in-place (sem recriar Figure)

  Tratamento de erros:
    - save() captura exceções de disco e exibe mensagem ao usuário
    - load() avisa usuário quando CSV está corrompido
    - Import CSV: confirmação antes de importar linhas parcialmente válidas
    - Export CSV com try/except
    - PWA não se aplica; equivalente: erros de janela capturados

  Separação de responsabilidades:
    - FluxoCaixaManager  →  lógica de dados e persistência (backend)
    - Finance            →  cálculos VPL / TIR / Payback
    - LancamentoViewModel→  prepara dados brutos para exibição
    - FluxoCaixaMEIApp   →  orquestração de UI e navegação (frontend)
    - setup_*()          →  constroem widgets; atualizar_*() preenchem dados

  Tipagem:
    - dataclasses.dataclass para Lancamento (tipagem forte)
    - TypedDict para resumo mensal
    - Enums TIPO e ESCOPO (sem strings literais soltas)
    - CSV_COLS como lista de campos de Lancamento

Schema CSV compatível com index_v3.0.html (mesmo conjunto de colunas).
"""

from __future__ import annotations

import csv
import math
import os
import uuid
from dataclasses import dataclass, field, fields, asdict
from datetime import datetime
from enum import Enum
from itertools import accumulate
from typing import Optional, List, Dict, TypedDict

import tkinter as tk
from tkinter import ttk, messagebox, filedialog

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# ──────────────────────────────────────────────────────────────
# ENUMS  (T22 — sem strings literais soltas)
# ──────────────────────────────────────────────────────────────

class Tipo(str, Enum):
    ENTRADA = "entrada"
    SAIDA   = "saida"

class Escopo(str, Enum):
    PJ = "pj"
    PF = "pf"

# ──────────────────────────────────────────────────────────────
# DATACLASS  (T20 — tipagem forte para Lancamento)
# ──────────────────────────────────────────────────────────────

@dataclass
class Lancamento:
    """Representa um único lançamento financeiro. Schema compatível com o HTML v3.0."""
    id:                 str
    data:               str          # ISO: YYYY-MM-DD
    tipo:               str          # Tipo.ENTRADA | Tipo.SAIDA
    escopo:             str          # Escopo.PJ | Escopo.PF
    categoria:          str
    valor:              float
    descricao:          str          = ""
    fornecedorCliente:  Optional[str] = None
    meioPagamento:      Optional[str] = None

# T23 — CSV_COLS derivado dos nomes de campos de Lancamento (garante sincronia)
CSV_COLS: List[str] = [f.name for f in fields(Lancamento)]

# ──────────────────────────────────────────────────────────────
# PLANO DE CONTAS MEI  (mesmo conjunto do HTML v3.0)
# ──────────────────────────────────────────────────────────────

@dataclass(frozen=True)
class CategoriaDef:
    nome:   str
    tipo:   str
    escopo: str

CATEGORIAS: List[CategoriaDef] = [
    # PJ Entradas
    CategoriaDef("Vendas de Produtos",    Tipo.ENTRADA, Escopo.PJ),
    CategoriaDef("Prestação de Serviços", Tipo.ENTRADA, Escopo.PJ),
    CategoriaDef("Outras Receitas PJ",    Tipo.ENTRADA, Escopo.PJ),
    # PJ Saídas
    CategoriaDef("DAS-MEI",               Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Fornecedores",           Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Aluguel Comercial",      Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Energia/Internet (PJ)",  Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Marketing",              Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Funcionário (até 1)",    Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Equipamentos",           Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Pró-labore",             Tipo.SAIDA,   Escopo.PJ),
    CategoriaDef("Outras Despesas PJ",     Tipo.SAIDA,   Escopo.PJ),
    # PF Entradas
    CategoriaDef("Pró-labore (recebido)",  Tipo.ENTRADA, Escopo.PF),
    CategoriaDef("Outras Receitas PF",     Tipo.ENTRADA, Escopo.PF),
    # PF Saídas
    CategoriaDef("Moradia",       Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Alimentação",   Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Transporte",    Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Saúde",         Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Lazer",         Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Educação",      Tipo.SAIDA, Escopo.PF),
    CategoriaDef("Outras Despesas PF", Tipo.SAIDA, Escopo.PF),
]

MEIOS_PAGAMENTO = ["", "pix", "dinheiro", "debito", "credito", "transferencia", "boleto"]
LIMITE_MEI      = 81_000.0  # R$ 81.000 / ano

# ──────────────────────────────────────────────────────────────
# FINANCE NAMESPACE  (T17 — cálculos isolados do frontend)
# ──────────────────────────────────────────────────────────────

class Finance:
    """Cálculos financeiros: VPL, TIR e Payback. Sem dependências de UI."""

    @staticmethod
    def vpl(taxa: float, fluxos: List[float]) -> float:
        return sum(cf / (1 + taxa) ** i for i, cf in enumerate(fluxos))

    @staticmethod
    def tir(fluxos: List[float], tol: float = 1e-7, max_iter: int = 1_000) -> float:
        if not any(v > 0 for v in fluxos) or not any(v < 0 for v in fluxos):
            return math.nan
        a, b = -0.999, 10.0
        fa, fb = Finance.vpl(a, fluxos), Finance.vpl(b, fluxos)
        if fa * fb > 0:
            return math.nan
        for _ in range(max_iter):
            c  = (a + b) / 2
            fc = Finance.vpl(c, fluxos)
            if abs(fc) < tol or (b - a) / 2 < tol:
                return c
            if fa * fc < 0:
                b, fb = c, fc
            else:
                a, fa = c, fc
        return (a + b) / 2

    @staticmethod
    def payback(fluxos: List[float], tma: float) -> Dict[str, float]:
        acs = acd = 0.0
        ps  = pd  = math.nan
        for i, f in enumerate(fluxos):
            acs += f
            acd += f / (1 + tma) ** i
            if math.isnan(ps) and acs >= 0:
                ps = float(i)
            if math.isnan(pd) and acd >= 0:
                pd = float(i)
        return {"simples": ps, "descontado": pd}

# ──────────────────────────────────────────────────────────────
# VIEW-MODEL  (T16 — separação entre dado bruto e exibição)
# ──────────────────────────────────────────────────────────────

@dataclass
class LancamentoViewModel:
    id:               str
    data_fmt:         str
    tipo_label:       str
    categoria:        str
    descricao:        str
    fornecedor:       str
    valor_fmt:        str
    sinal:            str
    row_tag:          str   # "entrada" | "saida" — para colorir a Treeview

def lancamento_view_model(l: Lancamento) -> LancamentoViewModel:
    """Transforma um Lancamento em dados prontos para exibição."""
    y, m, d   = l.data.split("-")
    data_fmt  = f"{d}/{m}/{y}"
    eh_entrada = l.tipo == Tipo.ENTRADA
    return LancamentoViewModel(
        id            = l.id,
        data_fmt      = data_fmt,
        tipo_label    = "Entrada" if eh_entrada else "Saída",
        categoria     = l.categoria,
        descricao     = l.descricao or "",
        fornecedor    = l.fornecedorCliente or "",
        valor_fmt     = f"R$ {l.valor:,.2f}",
        sinal         = "+" if eh_entrada else "−",
        row_tag       = "entrada" if eh_entrada else "saida",
    )

# ──────────────────────────────────────────────────────────────
# RESUMO MENSAL TypedDict
# ──────────────────────────────────────────────────────────────

class ResumoMes(TypedDict):
    mes:        str    # YYYY-MM
    entradas:   float
    saidas:     float
    saldo:      float
    saldo_acum: float

# ──────────────────────────────────────────────────────────────
# BACKEND — FluxoCaixaManager
# ──────────────────────────────────────────────────────────────

class FluxoCaixaManager:
    """
    Camada de dados: carrega, salva e consulta lançamentos.
    Todas as mutações passam por métodos explícitos (T18).
    Índice por id para lookups O(1) (T7).
    """

    STORAGE_FILE = "caixa_mei_v3.csv"

    def __init__(self, data_path: str = "."):
        self._path       = os.path.join(data_path, self.STORAGE_FILE)
        self._lancamentos: List[Lancamento]      = []
        self._index:       Dict[str, Lancamento] = {}   # T7 — Map id → Lancamento

        # Caches (T5)
        self._cache_totais:  Optional[Dict]           = None
        self._cache_escopo:  Optional[List[Lancamento]] = None
        self._cache_resumo:  Optional[List[ResumoMes]]  = None
        self._cache_escopo_key: Optional[str]           = None

        self._carregar()

    # ── Persistência ──────────────────────────────────────────

    def _carregar(self) -> None:
        """T11 — avisa o usuário quando os dados estão corrompidos."""
        if not os.path.exists(self._path):
            return
        try:
            with open(self._path, newline="", encoding="utf-8") as f:
                reader = csv.DictReader(f)
                for row in reader:
                    result = self._parse_row(row, linha=0)
                    if result["ok"]:
                        l = result["lancamento"]
                        self._lancamentos.append(l)
                        self._index[l.id] = l
        except Exception as e:
            print(f"[WARN] Falha ao carregar {self._path}: {e}")
            # O aviso visual é dado pelo chamador (App.__init__)
            self._lancamentos = []
            self._index = {}

    def salvar(self, show_error_cb=None) -> bool:
        """T10 — captura erros de disco e notifica via callback."""
        try:
            with open(self._path, "w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=CSV_COLS)
                writer.writeheader()
                for l in self._lancamentos:
                    writer.writerow(asdict(l))
            return True
        except Exception as e:
            print(f"[ERROR] Falha ao salvar: {e}")
            if show_error_cb:
                show_error_cb(f"Erro ao salvar dados:\n{e}")
            return False

    # ── Mutações controladas (T18) ─────────────────────────────

    def _invalidar_caches(self) -> None:
        self._cache_totais  = None
        self._cache_escopo  = None
        self._cache_resumo  = None

    def upsert(self, l: Lancamento, show_error_cb=None) -> bool:
        """Adiciona ou atualiza um lançamento."""
        if l.id in self._index:
            idx = next(i for i, x in enumerate(self._lancamentos) if x.id == l.id)
            self._lancamentos[idx] = l
        else:
            self._lancamentos.append(l)
        self._index[l.id] = l
        self._invalidar_caches()
        return self.salvar(show_error_cb)

    def deletar(self, lid: str, show_error_cb=None) -> bool:
        """Remove um lançamento pelo id."""
        if lid not in self._index:
            return False
        self._lancamentos = [x for x in self._lancamentos if x.id != lid]
        del self._index[lid]
        self._invalidar_caches()
        return self.salvar(show_error_cb)

    def limpar_tudo(self, show_error_cb=None) -> bool:
        self._lancamentos = []
        self._index = {}
        self._invalidar_caches()
        return self.salvar(show_error_cb)

    # ── Consultas com cache (T5) ───────────────────────────────

    def lancamentos_escopo(self, escopo: str) -> List[Lancamento]:
        if self._cache_escopo is not None and self._cache_escopo_key == escopo:
            return self._cache_escopo
        result = sorted(
            [l for l in self._lancamentos if l.escopo == escopo],
            key=lambda l: l.data,
            reverse=True,
        )
        self._cache_escopo     = result
        self._cache_escopo_key = escopo
        return result

    def totais(self, escopo: str) -> Dict[str, float]:
        if self._cache_totais is not None:
            return self._cache_totais
        entradas = saidas = 0.0
        for l in self._lancamentos:
            if l.escopo != escopo:
                continue
            if l.tipo == Tipo.ENTRADA:
                entradas += l.valor
            else:
                saidas += l.valor
        self._cache_totais = {"entradas": entradas, "saidas": saidas, "saldo": entradas - saidas}
        return self._cache_totais

    def resumo_mensal(self, escopo: str) -> List[ResumoMes]:
        if self._cache_resumo is not None:
            return self._cache_resumo
        mapa: Dict[str, Dict[str, float]] = {}
        for l in self._lancamentos:
            if l.escopo != escopo:
                continue
            mes = l.data[:7]  # YYYY-MM
            acc = mapa.setdefault(mes, {"entradas": 0.0, "saidas": 0.0})
            if l.tipo == Tipo.ENTRADA:
                acc["entradas"] += l.valor
            else:
                acc["saidas"]   += l.valor

        meses = sorted(mapa.keys())
        acum  = 0.0
        result: List[ResumoMes] = []
        for mes in meses:
            e = mapa[mes]["entradas"]
            s = mapa[mes]["saidas"]
            saldo = e - s
            acum += saldo
            result.append(ResumoMes(mes=mes, entradas=e, saidas=s, saldo=saldo, saldo_acum=acum))

        self._cache_resumo = result
        return result

    def get_by_id(self, lid: str) -> Optional[Lancamento]:
        """T7 — lookup O(1)."""
        return self._index.get(lid)

    # ── Import / Export CSV ────────────────────────────────────

    def exportar_csv(self, filepath: str, show_error_cb=None) -> bool:
        """T15 — exportação com try/except."""
        try:
            with open(filepath, "w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=CSV_COLS)
                writer.writeheader()
                for l in self._lancamentos:
                    writer.writerow(asdict(l))
            return True
        except Exception as e:
            if show_error_cb:
                show_error_cb(f"Erro ao exportar CSV:\n{e}")
            return False

    def importar_csv(self, filepath: str, show_error_cb=None):
        """
        T12, T21 — valida cada linha, retorna (novos, erros) para
        que o chamador confirme antes de persistir.
        """
        novos:  List[Lancamento] = []
        erros:  List[str]        = []
        try:
            with open(filepath, newline="", encoding="utf-8") as f:
                reader = csv.DictReader(f)
                for i, row in enumerate(reader, start=2):
                    result = self._parse_row(row, linha=i)
                    if result["ok"]:
                        novos.append(result["lancamento"])
                    else:
                        erros.append(result["motivo"])
        except Exception as e:
            if show_error_cb:
                show_error_cb(f"Não foi possível ler o arquivo:\n{e}")
            return [], []
        return novos, erros

    def confirmar_importacao(self, novos: List[Lancamento], show_error_cb=None) -> bool:
        for l in novos:
            if l.id in self._index:
                l = Lancamento(**{**asdict(l), "id": str(uuid.uuid4())})
            self._lancamentos.append(l)
            self._index[l.id] = l
        self._invalidar_caches()
        return self.salvar(show_error_cb)

    # ── Validação de linha CSV (T21) ───────────────────────────

    @staticmethod
    def _parse_row(row: Dict[str, str], linha: int) -> Dict:
        """Valida e converte uma linha do CSV em Lancamento."""
        try:
            valor = float(row.get("valor", ""))
        except (ValueError, TypeError):
            return {"ok": False, "motivo": f"Linha {linha}: valor inválido '{row.get('valor')}'"}

        tipo   = row.get("tipo", "")
        escopo = row.get("escopo", "")
        data   = row.get("data", "")
        cat    = row.get("categoria", "")

        if not data:
            return {"ok": False, "motivo": f"Linha {linha}: data ausente"}
        if tipo not in (Tipo.ENTRADA, Tipo.SAIDA):
            return {"ok": False, "motivo": f"Linha {linha}: tipo inválido '{tipo}'"}
        if escopo not in (Escopo.PJ, Escopo.PF):
            return {"ok": False, "motivo": f"Linha {linha}: escopo inválido '{escopo}'"}
        if not cat:
            return {"ok": False, "motivo": f"Linha {linha}: categoria ausente"}
        if not math.isfinite(valor):
            return {"ok": False, "motivo": f"Linha {linha}: valor não numérico"}

        lid = row.get("id") or str(uuid.uuid4())
        return {
            "ok": True,
            "lancamento": Lancamento(
                id                = lid,
                data              = data,
                tipo              = tipo,
                escopo            = escopo,
                categoria         = cat,
                valor             = valor,
                descricao         = row.get("descricao") or "",
                fornecedorCliente = row.get("fornecedorCliente") or None,
                meioPagamento     = row.get("meioPagamento")     or None,
            ),
        }

# ──────────────────────────────────────────────────────────────
# FRONTEND — FluxoCaixaMEIApp
# ──────────────────────────────────────────────────────────────

PAGE_SIZE = 30  # T8 — paginação da lista

class FluxoCaixaMEIApp:
    """
    Orquestrador de UI. Toda lógica de dados fica em FluxoCaixaManager.
    Abas renderizadas sob demanda via dirty-flags (T5).
    """

    # Abas da nav bar (equivalente a NAV_TABS do JS, T4)
    NAV_TABS = {"dashboard", "lancamentos", "relatorios", "analise", "config"}

    def __init__(self, root: tk.Tk):
        self.root    = root
        self.root.title("Caixa MEI — Nirlene Contabilidade  v3.0")
        self.root.geometry("1100x720")
        self.root.minsize(900, 600)

        self.manager = FluxoCaixaManager()
        self._avisar_corrompido = False  # sinalizado durante load se necessário

        # Estado (T20)
        self.escopo:     str          = Escopo.PJ
        self.tipo_form:  str          = Tipo.SAIDA
        self.editando_id: Optional[str] = None
        self.pagina_atual: int        = 0

        # Dirty-flags (T5)
        self.dirty = {k: True for k in self.NAV_TABS}

        # Gráfico: criado uma única vez (T6)
        self._fig: Optional[plt.Figure] = None
        self._ax:  Optional[plt.Axes]   = None
        self._canvas: Optional[FigureCanvasTkAgg] = None

        self._build_ui()
        self._show_tab("dashboard")

        # T11 — aviso pós-inicialização
        if self._avisar_corrompido:
            messagebox.showwarning(
                "Dados corrompidos",
                "O arquivo de dados estava corrompido e foi ignorado.\n"
                "O app iniciou vazio. Importe um CSV de backup se disponível.",
            )

    # ── Construção da UI ───────────────────────────────────────

    def _build_ui(self):
        # Frame superior (header)
        header = tk.Frame(self.root, bg="#1f5e6a", pady=8)
        header.pack(fill="x")

        tk.Label(
            header, text="Caixa MEI", bg="#1f5e6a", fg="white",
            font=("Segoe UI", 14, "bold"),
        ).pack(side="left", padx=16)

        # Toggle Empresa / Pessoal
        tog = tk.Frame(header, bg="#1f5e6a")
        tog.pack(side="right", padx=16)
        self.btn_pj = tk.Button(
            tog, text="Empresa", font=("Segoe UI", 9, "bold"),
            command=lambda: self._set_escopo(Escopo.PJ),
            relief="flat", cursor="hand2",
        )
        self.btn_pj.pack(side="left", padx=2)
        self.btn_pf = tk.Button(
            tog, text="Pessoal", font=("Segoe UI", 9, "bold"),
            command=lambda: self._set_escopo(Escopo.PF),
            relief="flat", cursor="hand2",
        )
        self.btn_pf.pack(side="left", padx=2)
        self._atualizar_toggle()

        # Notebook (abas)
        style = ttk.Style()
        style.configure("TNotebook.Tab", font=("Segoe UI", 9))
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill="both", expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # Frames das abas
        self.frames = {}
        tabs_def = [
            ("dashboard",   "🏠 Início"),
            ("lancamentos", "📝 Lançar"),
            ("relatorios",  "📊 Relatórios"),
            ("analise",     "💹 Análise"),
            ("config",      "⚙️ Ajustes"),
        ]
        for key, label in tabs_def:
            f = ttk.Frame(self.notebook)
            self.notebook.add(f, text=label)
            self.frames[key] = f

        # Constrói widgets de cada aba
        self._setup_dashboard()
        self._setup_lancamentos()
        self._setup_relatorios()
        self._setup_analise()
        self._setup_config()

        # Frame do formulário (modal embutido, fora do notebook, T4)
        self.frame_form = ttk.Frame(self.root)
        self._setup_form()

    # ── Navegação (T4, T5) ─────────────────────────────────────

    def _show_tab(self, tab_key: str):
        """Exibe a aba e renderiza somente se dirty."""
        if tab_key not in self.NAV_TABS:
            return
        idx = list(self.frames.keys()).index(tab_key)
        self.notebook.select(idx)
        if self.dirty.get(tab_key, True):
            getattr(self, f"_render_{tab_key}")()
            self.dirty[tab_key] = False

    def _on_tab_changed(self, _event):
        idx = self.notebook.index(self.notebook.select())
        key = list(self.frames.keys())[idx]
        if self.dirty.get(key, True):
            getattr(self, f"_render_{key}")()
            self.dirty[key] = False

    def _set_escopo(self, escopo: str):
        self.escopo = escopo
        self.manager._invalidar_caches()
        self.dirty = {k: True for k in self.NAV_TABS}
        self._atualizar_toggle()
        # Força re-render do tab atual
        idx = self.notebook.index(self.notebook.select())
        key = list(self.frames.keys())[idx]
        self.dirty[key] = True
        getattr(self, f"_render_{key}")()
        self.dirty[key] = False

    def _atualizar_toggle(self):
        pj_is_active = self.escopo == Escopo.PJ
        self.btn_pj.config(
            bg="#ffffff" if pj_is_active else "#2d7a8a",
            fg="#1f5e6a" if pj_is_active else "#ffffff",
        )
        self.btn_pf.config(
            bg="#ffffff" if not pj_is_active else "#2d7a8a",
            fg="#1f5e6a" if not pj_is_active else "#ffffff",
        )

    def _invalidar_todos(self):
        self.dirty = {k: True for k in self.NAV_TABS}
        self.manager._invalidar_caches()

    # ── ABA: DASHBOARD ────────────────────────────────────────

    def _setup_dashboard(self):
        f = self.frames["dashboard"]

        hero = tk.Frame(f, bg="#1f5e6a", padx=20, pady=18)
        hero.pack(fill="x", padx=16, pady=(16, 8))

        tk.Label(hero, text="💼 Saldo acumulado", bg="#1f5e6a", fg="#ffffffcc",
                 font=("Segoe UI", 9)).pack(anchor="w")
        self.lbl_saldo = tk.Label(hero, text="R$ 0,00", bg="#1f5e6a", fg="white",
                                  font=("Segoe UI", 22, "bold"))
        self.lbl_saldo.pack(anchor="w")
        self.lbl_saldo_hint = tk.Label(hero, text="", bg="#1f5e6a", fg="#ffffffaa",
                                       font=("Segoe UI", 9))
        self.lbl_saldo_hint.pack(anchor="w")

        grid = tk.Frame(f)
        grid.pack(fill="x", padx=16, pady=(0, 8))
        grid.columnconfigure(0, weight=1)
        grid.columnconfigure(1, weight=1)

        card_in = ttk.LabelFrame(grid, text="↑ Entradas (total)")
        card_in.grid(row=0, column=0, sticky="ew", padx=(0, 6))
        self.lbl_total_in = tk.Label(card_in, text="R$ 0,00",
                                     font=("Segoe UI", 13, "bold"), fg="#2f8a6b")
        self.lbl_total_in.pack(padx=8, pady=6)

        card_out = ttk.LabelFrame(grid, text="↓ Saídas (total)")
        card_out.grid(row=0, column=1, sticky="ew", padx=(6, 0))
        self.lbl_total_out = tk.Label(card_out, text="R$ 0,00",
                                      font=("Segoe UI", 13, "bold"), fg="#c0524a")
        self.lbl_total_out.pack(padx=8, pady=6)

        ttk.Label(f, text="Recentes", font=("Segoe UI", 10, "bold")).pack(
            anchor="w", padx=16, pady=(4, 4))

        tree_frame = ttk.Frame(f)
        tree_frame.pack(fill="both", expand=True, padx=16, pady=(0, 12))

        cols = ("Data", "Tipo", "Categoria", "Valor")
        self.tree_dash = ttk.Treeview(tree_frame, columns=cols, show="headings", height=8)
        for c in cols:
            self.tree_dash.heading(c, text=c)
            self.tree_dash.column(c, width=130)
        self.tree_dash.tag_configure("entrada", foreground="#2f8a6b")
        self.tree_dash.tag_configure("saida",   foreground="#c0524a")

        sb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree_dash.yview)
        self.tree_dash.configure(yscrollcommand=sb.set)
        self.tree_dash.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")

    def _render_dashboard(self):
        t = self.manager.totais(self.escopo)
        self.lbl_saldo.config(text=f"R$ {t['saldo']:,.2f}")
        self.lbl_total_in.config(text=f"R$ {t['entradas']:,.2f}")
        self.lbl_total_out.config(text=f"R$ {t['saidas']:,.2f}")

        if not self.manager._lancamentos:
            hint = "Comece registrando seus lançamentos."
        elif t["saldo"] >= 0:
            hint = "Saudável — continue separando as contas."
        else:
            hint = "Atenção: saldo negativo."
        self.lbl_saldo_hint.config(text=hint)

        # Recentes (últimos 5)
        self.tree_dash.delete(*self.tree_dash.get_children())
        recentes = self.manager.lancamentos_escopo(self.escopo)[:5]
        for l in recentes:
            vm = lancamento_view_model(l)
            self.tree_dash.insert("", "end",
                values=(vm.data_fmt, vm.tipo_label, vm.categoria, vm.valor_fmt),
                tags=(vm.row_tag,))

    # ── ABA: LANÇAMENTOS ──────────────────────────────────────

    def _setup_lancamentos(self):
        f = self.frames["lancamentos"]

        top = tk.Frame(f)
        top.pack(fill="x", padx=12, pady=(12, 6))

        ttk.Label(top, text="🔎").pack(side="left")
        self.ent_busca = ttk.Entry(top, font=("Segoe UI", 10))
        self.ent_busca.pack(side="left", fill="x", expand=True, padx=(4, 8))
        self.ent_busca.bind("<KeyRelease>", lambda _: self._render_lancamentos())

        ttk.Button(top, text="+ Novo", command=self._abrir_form).pack(side="right")

        tree_frame = ttk.Frame(f)
        tree_frame.pack(fill="both", expand=True, padx=12)

        cols = ("Data", "Tipo", "Categoria", "Descrição", "Valor")
        self.tree_lanc = ttk.Treeview(tree_frame, columns=cols, show="headings")
        for c in cols:
            self.tree_lanc.heading(c, text=c)
        self.tree_lanc.column("Data",      width=90,  stretch=False)
        self.tree_lanc.column("Tipo",      width=70,  stretch=False)
        self.tree_lanc.column("Categoria", width=180)
        self.tree_lanc.column("Descrição", width=200)
        self.tree_lanc.column("Valor",     width=110, stretch=False)
        self.tree_lanc.tag_configure("entrada", foreground="#2f8a6b")
        self.tree_lanc.tag_configure("saida",   foreground="#c0524a")

        sb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree_lanc.yview)
        self.tree_lanc.configure(yscrollcommand=sb.set)
        self.tree_lanc.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree_lanc.bind("<Double-1>", self._on_double_click_lanc)

        # Botões de ação por linha
        btn_frame = tk.Frame(f)
        btn_frame.pack(fill="x", padx=12, pady=4)
        ttk.Button(btn_frame, text="✏️ Editar selecionado",
                   command=self._editar_selecionado).pack(side="left", padx=(0, 6))
        ttk.Button(btn_frame, text="🗑️ Remover selecionado",
                   command=self._remover_selecionado).pack(side="left")

        # Paginação (T8)
        pg_frame = tk.Frame(f)
        pg_frame.pack(fill="x", padx=12, pady=(0, 8))
        self.btn_pg_prev = ttk.Button(pg_frame, text="← Anterior",
                                      command=lambda: self._mudar_pagina(-1))
        self.btn_pg_prev.pack(side="left")
        self.lbl_pg_info = ttk.Label(pg_frame, text="")
        self.lbl_pg_info.pack(side="left", padx=12)
        self.btn_pg_next = ttk.Button(pg_frame, text="Próximo →",
                                      command=lambda: self._mudar_pagina(1))
        self.btn_pg_next.pack(side="left")
        self.frame_pg = pg_frame

    def _render_lancamentos(self):
        q = self.ent_busca.get().strip().lower()
        todos = [
            l for l in self.manager.lancamentos_escopo(self.escopo)
            if not q
            or q in l.categoria.lower()
            or q in (l.descricao or "").lower()
            or q in (l.fornecedorCliente or "").lower()
        ]

        total        = len(todos)
        total_pags   = max(1, math.ceil(total / PAGE_SIZE))
        if self.pagina_atual >= total_pags:
            self.pagina_atual = total_pags - 1

        inicio = self.pagina_atual * PAGE_SIZE
        pagina = todos[inicio: inicio + PAGE_SIZE]

        self.tree_lanc.delete(*self.tree_lanc.get_children())
        for l in pagina:
            vm = lancamento_view_model(l)
            self.tree_lanc.insert("", "end", iid=vm.id,
                values=(vm.data_fmt, vm.tipo_label, vm.categoria, vm.descricao, vm.valor_fmt),
                tags=(vm.row_tag,))

        # Paginação
        if total <= PAGE_SIZE:
            self.frame_pg.pack_forget()
        else:
            self.frame_pg.pack(fill="x", padx=12, pady=(0, 8))
            self.lbl_pg_info.config(text=f"{self.pagina_atual + 1} / {total_pags}")
            self.btn_pg_prev.state(["disabled"] if self.pagina_atual == 0 else ["!disabled"])
            self.btn_pg_next.state(["disabled"] if self.pagina_atual >= total_pags - 1 else ["!disabled"])

    def _mudar_pagina(self, delta: int):
        self.pagina_atual += delta
        self.dirty["lancamentos"] = False
        self._render_lancamentos()

    def _on_double_click_lanc(self, _event):
        self._editar_selecionado()

    def _editar_selecionado(self):
        sel = self.tree_lanc.selection()
        if not sel:
            return
        self._abrir_form(lid=sel[0])

    def _remover_selecionado(self):
        sel = self.tree_lanc.selection()
        if not sel:
            return
        lid = sel[0]
        l   = self.manager.get_by_id(lid)
        if not l:
            return
        y, m, d = l.data.split("-")
        if not messagebox.askyesno(
            "Confirmar remoção",
            f'Remover "{l.categoria}" de {d}/{m}/{y}?',
        ):
            return
        self.manager.deletar(lid, show_error_cb=lambda e: messagebox.showerror("Erro", e))
        self._invalidar_todos()
        self._render_lancamentos()
        self.dirty["lancamentos"] = False

    # ── FORMULÁRIO (modal embutido, T4) ───────────────────────

    def _setup_form(self):
        f = self.frame_form

        # Cabeçalho
        top = tk.Frame(f)
        top.pack(fill="x", padx=16, pady=(16, 8))
        self.lbl_form_titulo = tk.Label(top, text="Novo lançamento",
                                        font=("Segoe UI", 13, "bold"))
        self.lbl_form_titulo.pack(side="left")
        ttk.Button(top, text="✕", width=3,
                   command=self._fechar_form).pack(side="right")

        # Segmento Entrada / Saída
        seg = tk.Frame(f, bg="#ecf2f2")
        seg.pack(fill="x", padx=16, pady=(0, 10))
        self.btn_seg_entrada = tk.Button(
            seg, text="Entrada", font=("Segoe UI", 10, "bold"),
            command=lambda: self._set_tipo(Tipo.ENTRADA),
            relief="flat", cursor="hand2", pady=6,
        )
        self.btn_seg_entrada.pack(side="left", fill="x", expand=True, padx=4, pady=4)
        self.btn_seg_saida = tk.Button(
            seg, text="Saída", font=("Segoe UI", 10, "bold"),
            command=lambda: self._set_tipo(Tipo.SAIDA),
            relief="flat", cursor="hand2", pady=6,
        )
        self.btn_seg_saida.pack(side="left", fill="x", expand=True, padx=4, pady=4)

        def campo(label_text, widget_factory):
            row = ttk.Frame(f)
            row.pack(fill="x", padx=16, pady=3)
            ttk.Label(row, text=label_text, font=("Segoe UI", 9),
                      foreground="#6b7d80").pack(anchor="w")
            w = widget_factory(row)
            w.pack(fill="x")
            return w

        self.ent_f_valor = campo("Valor (R$)", lambda p: ttk.Entry(p, font=("Segoe UI", 11)))
        self.cmb_f_cat   = campo("Categoria",  lambda p: ttk.Combobox(p, state="readonly"))
        self.ent_f_data  = campo("Data",       lambda p: ttk.Entry(p, font=("Segoe UI", 11)))
        self.lbl_forn_label = ttk.Label(f, text="Fornecedor (opcional)",
                                        font=("Segoe UI", 9), foreground="#6b7d80")
        self.lbl_forn_label.pack(anchor="w", padx=16)
        row_forn = ttk.Frame(f)
        row_forn.pack(fill="x", padx=16, pady=3)
        self.ent_f_forn = ttk.Entry(row_forn, font=("Segoe UI", 11))
        self.ent_f_forn.pack(fill="x")

        self.cmb_f_meio = campo(
            "Meio de pagamento (opcional)",
            lambda p: ttk.Combobox(p, values=MEIOS_PAGAMENTO, state="readonly"),
        )
        self.ent_f_desc = campo(
            "Descrição (opcional)",
            lambda p: tk.Text(p, height=2, font=("Segoe UI", 11)),
        )

        # Botões
        btn_row = tk.Frame(f)
        btn_row.pack(fill="x", padx=16, pady=(12, 16))
        ttk.Button(btn_row, text="Cancelar",
                   command=self._fechar_form).pack(side="left", fill="x", expand=True, padx=(0, 6))
        ttk.Button(btn_row, text="Salvar",
                   command=self._salvar_lancamento).pack(side="left", fill="x", expand=True)

    def _abrir_form(self, lid: Optional[str] = None):
        # T9 — popular categorias antes de setar valor
        self.editando_id = lid
        if lid:
            l = self.manager.get_by_id(lid)
            if not l:
                return
            self.lbl_form_titulo.config(text="Editar lançamento")
            self._set_tipo(l.tipo)
            self.ent_f_valor.delete(0, "end")
            self.ent_f_valor.insert(0, str(l.valor))
            self.ent_f_data.delete(0, "end")
            y, m, d = l.data.split("-")
            self.ent_f_data.insert(0, f"{d}/{m}/{y}")
            self.ent_f_forn.delete(0, "end")
            self.ent_f_forn.insert(0, l.fornecedorCliente or "")
            self.cmb_f_meio.set(l.meioPagamento or "")
            self.ent_f_desc.delete("1.0", "end")
            self.ent_f_desc.insert("1.0", l.descricao or "")
            # Categoria disponível imediatamente (categorias já populadas por _set_tipo)
            self.cmb_f_cat.set(l.categoria)
        else:
            self.lbl_form_titulo.config(text="Novo lançamento")
            self._set_tipo(Tipo.SAIDA)
            self.ent_f_valor.delete(0, "end")
            self.ent_f_data.delete(0, "end")
            self.ent_f_data.insert(0, datetime.now().strftime("%d/%m/%Y"))
            self.ent_f_forn.delete(0, "end")
            self.cmb_f_meio.set("")
            self.ent_f_desc.delete("1.0", "end")

        # Exibe formulário sobre o notebook
        self.notebook.pack_forget()
        self.frame_form.pack(fill="both", expand=True)

    def _fechar_form(self):
        self.editando_id = None
        self.frame_form.pack_forget()
        self.notebook.pack(fill="both", expand=True)

    def _set_tipo(self, tipo: str):
        """T2 — sem parâmetro extra; popula categorias imediatamente (T9)."""
        self.tipo_form = tipo
        eh_entrada = tipo == Tipo.ENTRADA

        self.btn_seg_entrada.config(
            bg="#2f8a6b" if eh_entrada else "#ecf2f2",
            fg="white"   if eh_entrada else "#6b7d80",
        )
        self.btn_seg_saida.config(
            bg="#c0524a" if not eh_entrada else "#ecf2f2",
            fg="white"   if not eh_entrada else "#6b7d80",
        )
        self.lbl_forn_label.config(
            text="Cliente (opcional)" if eh_entrada else "Fornecedor (opcional)"
        )

        # T9 — categorias populadas aqui, sincronamente
        cats = [c.nome for c in CATEGORIAS if c.escopo == self.escopo and c.tipo == tipo]
        self.cmb_f_cat["values"] = cats
        if cats:
            self.cmb_f_cat.set(cats[0])

    def _salvar_lancamento(self):
        try:
            valor_str = self.ent_f_valor.get().strip().replace(",", ".")
            valor = float(valor_str)
        except ValueError:
            messagebox.showwarning("Validação", "Valor inválido.")
            return

        data_str = self.ent_f_data.get().strip()
        try:
            dt = datetime.strptime(data_str, "%d/%m/%Y")
            data_iso = dt.strftime("%Y-%m-%d")
        except ValueError:
            messagebox.showwarning("Validação", "Data inválida. Use dd/mm/aaaa.")
            return

        categoria = self.cmb_f_cat.get().strip()
        if not categoria:
            messagebox.showwarning("Validação", "Selecione uma categoria.")
            return
        if valor <= 0:
            messagebox.showwarning("Validação", "Valor deve ser maior que zero.")
            return

        l = Lancamento(
            id                = self.editando_id or str(uuid.uuid4()),
            data              = data_iso,
            tipo              = self.tipo_form,
            escopo            = self.escopo,
            categoria         = categoria,
            valor             = valor,
            descricao         = self.ent_f_desc.get("1.0", "end").strip(),
            fornecedorCliente = self.ent_f_forn.get().strip() or None,
            meioPagamento     = self.cmb_f_meio.get() or None,
        )

        ok = self.manager.upsert(l, show_error_cb=lambda e: messagebox.showerror("Erro", e))
        if ok:
            self._invalidar_todos()
            self._fechar_form()
            self._show_tab("lancamentos")

    # ── ABA: RELATÓRIOS ───────────────────────────────────────

    def _setup_relatorios(self):
        f = self.frames["relatorios"]

        # Tabela mensal
        ttk.Label(f, text="Tabela mensal", font=("Segoe UI", 10, "bold")).pack(
            anchor="w", padx=16, pady=(12, 4))

        tbl_frame = ttk.Frame(f)
        tbl_frame.pack(fill="x", padx=16)
        cols = ("Mês", "Entradas", "Saídas", "Saldo", "Saldo Acumulado")
        self.tree_rel = ttk.Treeview(tbl_frame, columns=cols, show="headings", height=8)
        for c in cols:
            self.tree_rel.heading(c, text=c)
            self.tree_rel.column(c, width=130)
        self.tree_rel.tag_configure("positivo", foreground="#2f8a6b")
        self.tree_rel.tag_configure("negativo", foreground="#c0524a")
        sb_rel = ttk.Scrollbar(tbl_frame, orient="vertical", command=self.tree_rel.yview)
        self.tree_rel.configure(yscrollcommand=sb_rel.set)
        self.tree_rel.pack(side="left", fill="both", expand=True)
        sb_rel.pack(side="right", fill="y")

        # Gráfico (T6 — criado uma vez aqui)
        ttk.Label(f, text="Evolução do saldo", font=("Segoe UI", 10, "bold")).pack(
            anchor="w", padx=16, pady=(12, 4))

        chart_frame = ttk.Frame(f)
        chart_frame.pack(fill="both", expand=True, padx=16, pady=(0, 12))

        self._fig, self._ax = plt.subplots(figsize=(7, 3.5))
        self._fig.subplots_adjust(left=0.1, right=0.97, bottom=0.15, top=0.88)
        self._canvas = FigureCanvasTkAgg(self._fig, master=chart_frame)
        self._canvas.get_tk_widget().pack(fill="both", expand=True)

    def _render_relatorios(self):
        resumo = self.manager.resumo_mensal(self.escopo)

        # Tabela
        self.tree_rel.delete(*self.tree_rel.get_children())
        if not resumo:
            self.tree_rel.insert("", "end", values=("—", "—", "—", "—", "—"))
        else:
            for r in resumo:
                tag = "positivo" if r["saldo_acum"] >= 0 else "negativo"
                self.tree_rel.insert("", "end", values=(
                    r["mes"],
                    f"R$ {r['entradas']:,.2f}",
                    f"R$ {r['saidas']:,.2f}",
                    f"R$ {r['saldo']:,.2f}",
                    f"R$ {r['saldo_acum']:,.2f}",
                ), tags=(tag,))

        # Gráfico in-place (T6 — sem recriar Figure)
        self._ax.clear()
        if resumo:
            labels   = [r["mes"] for r in resumo]
            saldos   = [r["saldo_acum"] for r in resumo]
            entradas = [r["entradas"]   for r in resumo]
            saidas   = [r["saidas"]     for r in resumo]
            x = range(len(labels))
            self._ax.fill_between(x, saldos, alpha=0.15, color="#1f5e6a")
            self._ax.plot(x, saldos,   color="#1f5e6a", linewidth=2,   label="Saldo acum.")
            self._ax.plot(x, entradas, color="#2f8a6b", linewidth=1.5, label="Entradas", linestyle="--")
            self._ax.plot(x, saidas,   color="#c0524a", linewidth=1.5, label="Saídas",   linestyle="--")
            self._ax.set_xticks(list(x))
            self._ax.set_xticklabels(labels, rotation=30, ha="right", fontsize=8)
            self._ax.legend(fontsize=8)
            self._ax.set_title("Evolução do saldo acumulado", fontsize=10)
        else:
            self._ax.text(0.5, 0.5, "Sem dados ainda", ha="center", va="center",
                          transform=self._ax.transAxes, fontsize=11, color="gray")
        self._canvas.draw()

    # ── ABA: ANÁLISE FINANCEIRA ───────────────────────────────

    def _setup_analise(self):
        f = self.frames["analise"]

        params = ttk.LabelFrame(f, text=" Parâmetros ")
        params.pack(fill="x", padx=16, pady=(16, 8))

        p_row = tk.Frame(params)
        p_row.pack(fill="x", padx=8, pady=8)
        p_row.columnconfigure(0, weight=1)
        p_row.columnconfigure(1, weight=1)

        ttk.Label(p_row, text="Investimento inicial (R$)").grid(row=0, column=0, sticky="w")
        self.ent_inv = ttk.Entry(p_row)
        self.ent_inv.insert(0, "10000")
        self.ent_inv.grid(row=1, column=0, sticky="ew", padx=(0, 8), pady=(2, 0))

        ttk.Label(p_row, text="TMA (% ao mês)").grid(row=0, column=1, sticky="w")
        self.ent_tma = ttk.Entry(p_row)
        self.ent_tma.insert(0, "1.0")
        self.ent_tma.grid(row=1, column=1, sticky="ew", pady=(2, 0))

        ttk.Button(f, text="Calcular VPL / TIR / Payback",
                   command=self._render_analise).pack(fill="x", padx=16, pady=(0, 12))

        result_frame = ttk.Frame(f)
        result_frame.pack(fill="both", expand=True, padx=16, pady=(0, 12))

        self.txt_analise = tk.Text(result_frame, font=("Consolas", 10),
                                   state="disabled", wrap="none", height=14)
        sb_a = ttk.Scrollbar(result_frame, orient="vertical", command=self.txt_analise.yview)
        self.txt_analise.configure(yscrollcommand=sb_a.set)
        self.txt_analise.pack(side="left", fill="both", expand=True)
        sb_a.pack(side="right", fill="y")

        # Limite MEI
        mei_frame = ttk.LabelFrame(f, text=" 🛡️ Monitoramento Limite MEI ")
        mei_frame.pack(fill="x", padx=16, pady=(0, 16))

        self.lbl_faturamento = ttk.Label(mei_frame, text="Faturamento anual: R$ 0,00",
                                         font=("Segoe UI", 10, "bold"))
        self.lbl_faturamento.pack(pady=(8, 4))
        self.progress_mei = ttk.Progressbar(mei_frame, length=500, mode="determinate")
        self.progress_mei.pack(pady=4)
        self.lbl_status_mei = ttk.Label(mei_frame, text="Status: Regular")
        self.lbl_status_mei.pack(pady=(4, 8))

    def _render_analise(self):
        resumo = self.manager.resumo_mensal(self.escopo)

        # ── Limite MEI ────────────────────────────────────────
        ano_atual    = datetime.now().year
        faturamento  = sum(
            l.valor for l in self.manager._lancamentos
            if l.escopo == self.escopo
            and l.tipo  == Tipo.ENTRADA
            and l.data[:4] == str(ano_atual)
        )
        pct = min((faturamento / LIMITE_MEI) * 100, 100)
        self.lbl_faturamento.config(
            text=f"Faturamento {ano_atual}: R$ {faturamento:,.2f} "
                 f"(limite R$ {LIMITE_MEI:,.2f})")
        self.progress_mei["value"] = pct
        if faturamento > LIMITE_MEI:
            self.lbl_status_mei.config(
                text="⚠️ ALERTA: Limite MEI excedido!", foreground="#c0524a")
        else:
            self.lbl_status_mei.config(
                text=f"Status: Regular — {pct:.1f}% do limite utilizado",
                foreground="#2f8a6b")

        # ── VPL / TIR / Payback ───────────────────────────────
        self.txt_analise.config(state="normal")
        self.txt_analise.delete("1.0", "end")

        if not resumo:
            self.txt_analise.insert("end",
                "Cadastre lançamentos mensais para calcular VPL, TIR e Payback.")
            self.txt_analise.config(state="disabled")
            return

        try:
            inv = -abs(float(self.ent_inv.get() or "0"))
            tma = (float(self.ent_tma.get() or "0")) / 100
        except ValueError:
            messagebox.showwarning("Parâmetros", "Investimento e TMA devem ser números.")
            self.txt_analise.config(state="disabled")
            return

        fluxos = [inv] + [r["saldo"] for r in resumo]
        v = Finance.vpl(tma, fluxos)
        t = Finance.tir(fluxos)
        p = Finance.payback(fluxos, tma)

        # T13 — mensagem de TIR em linguagem simples
        if math.isfinite(t):
            tir_desc = (f"{t*100:.2f}% a.m.  →  "
                        + ("Atrativo (TIR > TMA)." if t > tma
                           else "Abaixo da TMA — rende menos que o investimento mínimo."))
        else:
            tir_desc = "Não calculável — registre entradas e saídas em meses diferentes."

        pb_s = f"{int(p['simples'])} meses"    if math.isfinite(p["simples"])    else "Não recupera"
        pb_d = f"{int(p['descontado'])} meses" if math.isfinite(p["descontado"]) else "Não recupera"

        # DRE do mês atual
        mes_atual = datetime.now().month
        rec  = sum(l.valor for l in self.manager._lancamentos
                   if l.escopo == self.escopo
                   and l.tipo  == Tipo.ENTRADA
                   and int(l.data[5:7]) == mes_atual)
        desp = sum(l.valor for l in self.manager._lancamentos
                   if l.escopo == self.escopo
                   and l.tipo  == Tipo.SAIDA
                   and int(l.data[5:7]) == mes_atual)
        lucro  = rec - desp
        margem = (lucro / rec * 100) if rec > 0 else 0.0

        texto = (
            f"  VPL (Valor Presente Líquido)\n"
            f"  {'R$ ' + f'{v:,.2f}':>20}  {'Viável' if v >= 0 else 'Inviável'} a essa TMA.\n\n"
            f"  TIR (Taxa Interna de Retorno)\n"
            f"  {tir_desc}\n\n"
            f"  Payback simples:     {pb_s}\n"
            f"  Payback descontado:  {pb_d}\n\n"
            f"  {'─'*52}\n"
            f"  DRE — Mês {mes_atual:02d}/{datetime.now().year}\n"
            f"  {'─'*52}\n"
            f"  (+) Receita bruta:         R$ {rec:>12,.2f}\n"
            f"  (-) Custos e despesas:     R$ {desp:>12,.2f}\n"
            f"  {'─'*52}\n"
            f"  (=) Lucro/Prejuízo:        R$ {lucro:>12,.2f}\n"
            f"      Margem de lucro:            {margem:>9.1f}%\n\n"
            f"  Fluxos usados ({len(fluxos)}):\n"
            + "".join(
                f"    {'Inicial' if i == 0 else 'Mês ' + str(i):12s}: "
                f"R$ {ff:>12,.2f}\n"
                for i, ff in enumerate(fluxos)
            )
        )
        self.txt_analise.insert("end", texto)
        self.txt_analise.config(state="disabled")

    # ── ABA: CONFIGURAÇÕES ─────────────────────────────────────

    def _setup_config(self):
        f = self.frames["config"]

        csv_frame = ttk.LabelFrame(f, text=" Backup CSV ")
        csv_frame.pack(fill="x", padx=20, pady=(20, 10))
        ttk.Label(csv_frame,
                  text="Schema compatível com index_v3.0.html (mesmo conjunto de colunas).",
                  foreground="#6b7d80").pack(pady=(6, 4), padx=10, anchor="w")
        ttk.Button(csv_frame, text="⬇️  Exportar CSV",
                   command=self._exportar_csv).pack(fill="x", padx=10, pady=3)
        ttk.Button(csv_frame, text="⬆️  Importar CSV",
                   command=self._importar_csv).pack(fill="x", padx=10, pady=(0, 10))

        danger = ttk.LabelFrame(f, text=" ⚠️ Zona perigosa ")
        danger.pack(fill="x", padx=20, pady=10)
        ttk.Label(danger,
                  text="Apaga permanentemente todos os dados deste dispositivo.",
                  foreground="#c0524a").pack(pady=(6, 4), padx=10, anchor="w")
        ttk.Button(danger, text="🗑️  Apagar todos os dados",
                   command=self._limpar_tudo).pack(fill="x", padx=10, pady=(0, 10))

        ttk.Label(f, text="Caixa MEI · Nirlene Contabilidade · v3.0",
                  foreground="#6b7d80", font=("Segoe UI", 9)).pack(pady=20)

    def _render_config(self):
        pass  # estática — nada a recalcular

    def _exportar_csv(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".csv",
            filetypes=[("CSV", "*.csv")],
            initialfile=f"caixa_mei_{datetime.now().strftime('%Y-%m-%d')}.csv",
        )
        if not path:
            return
        ok = self.manager.exportar_csv(
            path,
            show_error_cb=lambda e: messagebox.showerror("Erro ao exportar", e),
        )
        if ok:
            messagebox.showinfo("Exportado", f"{len(self.manager._lancamentos)} registro(s) exportado(s).")

    def _importar_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        novos, erros = self.manager.importar_csv(
            path,
            show_error_cb=lambda e: messagebox.showerror("Erro ao importar", e),
        )
        if not novos and not erros:
            return

        # T12 — confirmação quando há erros parciais
        if erros:
            detalhe = "\n".join(erros[:5]) + ("\n..." if len(erros) > 5 else "")
            msg = (f"{len(novos)} registro(s) válido(s), {len(erros)} com erro.\n\n"
                   f"Primeiro(s) erro(s):\n{detalhe}\n\n"
                   f"Importar apenas os válidos?")
            if not messagebox.askyesno("Importar CSV", msg):
                return
        elif novos:
            if not messagebox.askyesno("Importar CSV",
                                       f"{len(novos)} registro(s) encontrado(s). Importar?"):
                return

        ok = self.manager.confirmar_importacao(
            novos,
            show_error_cb=lambda e: messagebox.showerror("Erro ao salvar", e),
        )
        if ok:
            self._invalidar_todos()
            messagebox.showinfo("Importado",
                                f"{len(novos)} importado(s)"
                                + (f", {len(erros)} ignorado(s)." if erros else "."))
            self._show_tab("dashboard")

    def _limpar_tudo(self):
        if not messagebox.askyesno(
            "Apagar tudo",
            "Apagar TODOS os lançamentos?\nEsta ação não pode ser desfeita.",
            icon="warning",
        ):
            return
        self.manager.limpar_tudo(
            show_error_cb=lambda e: messagebox.showerror("Erro", e)
        )
        self._invalidar_todos()
        self._show_tab("dashboard")

# ──────────────────────────────────────────────────────────────
# ENTRYPOINT
# ──────────────────────────────────────────────────────────────

if __name__ == "__main__":
    root = tk.Tk()
    app  = FluxoCaixaMEIApp(root)
    root.mainloop()
