// data.jsx — shared mock data, i18n, helpers for NorthAuto OS
window.NA = window.NA || {};

// ============================================================
// i18n
// ============================================================
const STRINGS = {
  pt: {
    // Nav
    nav_dashboard: "Painel",
    nav_analysis: "Análise",
    nav_opportunities: "Oportunidades",
    nav_crm_kanban: "CRM Kanban",
    nav_acquisitions: "Aquisições",
    nav_maintenance: "Manutenção",
    nav_contracts: "Contratos",
    nav_lawyer: "Jurídico",
    nav_trackers: "Rastreadores",
    nav_reviews: "Avaliações",
    nav_financing: "Financiamento",
    nav_management: "Gestão",
    nav_lender: "Prestamista",
    nav_finance: "Financeiro",
    nav_cashbook: "Caixa",
    nav_team: "Equipe",
    nav_support: "Suporte",
    nav_plans: "Planos",
    nav_account: "Conta",
    nav_clients: "Clientes",
    nav_credit_api: "Crédito API",
    nav_modules: "Liberação de módulos",
    nav_bank_account: "Conta bancária",
    nav_support_panel: "Painel de suporte",
    // Groups
    group_operations: "Operação",
    group_finance: "Financeiro",
    group_admin: "Administração",
    group_super_admin: "Super administrador",
    // Common
    common_search: "Buscar",
    common_save: "Salvar",
    common_cancel: "Cancelar",
    common_new: "Novo",
    common_refresh: "Atualizar",
    common_export: "Exportar",
    common_filter: "Filtrar",
    common_all: "Todos",
    common_open: "Abrir",
    common_edit: "Editar",
    common_delete: "Excluir",
    common_view: "Ver",
    common_download: "Baixar",
    common_loading: "Carregando…",
    common_total: "Total",
    common_status: "Status",
    common_actions: "Ações",
    common_date: "Data",
    common_value: "Valor",
    common_description: "Descrição",
    common_type: "Tipo",
    common_category: "Categoria",
    common_brand: "Marca",
    common_model: "Modelo",
    common_year: "Ano",
    common_plate: "Placa",
    common_client: "Cliente",
    common_bank: "Banco",
    common_from: "De",
    common_to: "Até",
    common_logout: "Sair",
    common_saved: "Salvo com sucesso",
    common_analysis_saved: "Análise salva",
    dash_mentees_ranking: "Ranking de mentorados",
    dash_mentees_kpi: "Vendas por mentorado",
    dash_vehicles_sold: "veículos vendidos",
    dash_sale_value: "valor vendido",
    crm_stage_lead: "Lead",
    crm_stage_contact: "Contato",
    crm_stage_analysis: "Análise",
    crm_stage_proposal: "Proposta",
    crm_stage_negotiation: "Negociação",
    crm_stage_won: "Fechado",
    crm_subtitle: "Acompanhe leads e negociações por etapa",
    crm_new_deal: "Novo lead",
    crm_deals_total: "negócios ativos",
    crm_pipeline_value: "Valor no funil",
    crm_priority_high: "Alta",
    crm_priority_medium: "Média",
    crm_priority_low: "Baixa",
    crm_owner: "Responsável",
    crm_notes: "Observações",
    crm_move_stage: "Mover para etapa",
    // Status
    status_active: "Ativo",
    status_inactive: "Inativo",
    status_pending: "Pendente",
    status_overdue: "Em atraso",
    status_settled: "Quitado",
    status_in_process: "Em processo",
    status_in_stock: "Em estoque",
    status_in_settlement: "Em quitação",
    status_sold: "Vendido",
    status_trial: "Trial",
    status_expired: "Expirado",
    status_approved: "Aceito",
    status_rejected: "Recusado",
    status_draft: "Rascunho",
    status_converted: "Convertido",
  },
  en: {
    nav_dashboard: "Dashboard",
    nav_analysis: "Analysis",
    nav_opportunities: "Opportunities",
    nav_crm_kanban: "CRM Kanban",
    nav_acquisitions: "Acquisitions",
    nav_maintenance: "Maintenance",
    nav_contracts: "Contracts",
    nav_lawyer: "Legal",
    nav_trackers: "Trackers",
    nav_reviews: "Reviews",
    nav_financing: "Financing",
    nav_management: "Management",
    nav_lender: "Lender",
    nav_finance: "Finance",
    nav_cashbook: "Cashbook",
    nav_team: "Team",
    nav_support: "Support",
    nav_plans: "Plans",
    nav_account: "Account",
    nav_clients: "Clients",
    nav_credit_api: "Credit API",
    nav_modules: "Module access",
    nav_bank_account: "Bank account",
    nav_support_panel: "Support panel",
    group_operations: "Operations",
    group_finance: "Finance",
    group_admin: "Administration",
    group_super_admin: "Super admin",
    common_search: "Search",
    common_save: "Save",
    common_cancel: "Cancel",
    common_new: "New",
    common_refresh: "Refresh",
    common_export: "Export",
    common_filter: "Filter",
    common_all: "All",
    common_open: "Open",
    common_edit: "Edit",
    common_delete: "Delete",
    common_view: "View",
    common_download: "Download",
    common_loading: "Loading…",
    common_total: "Total",
    common_status: "Status",
    common_actions: "Actions",
    common_date: "Date",
    common_value: "Value",
    common_description: "Description",
    common_type: "Type",
    common_category: "Category",
    common_brand: "Brand",
    common_model: "Model",
    common_year: "Year",
    common_plate: "Plate",
    common_client: "Client",
    common_bank: "Bank",
    common_from: "From",
    common_to: "To",
    common_logout: "Log out",
    common_saved: "Saved successfully",
    common_analysis_saved: "Analysis saved",
    dash_mentees_ranking: "Mentees ranking",
    dash_mentees_kpi: "Sales by mentee",
    dash_vehicles_sold: "vehicles sold",
    dash_sale_value: "sales value",
    crm_stage_lead: "Lead",
    crm_stage_contact: "Contact",
    crm_stage_analysis: "Analysis",
    crm_stage_proposal: "Proposal",
    crm_stage_negotiation: "Negotiation",
    crm_stage_won: "Closed won",
    crm_subtitle: "Track leads and deals by stage",
    crm_new_deal: "New lead",
    crm_deals_total: "active deals",
    crm_pipeline_value: "Pipeline value",
    crm_priority_high: "High",
    crm_priority_medium: "Medium",
    crm_priority_low: "Low",
    crm_owner: "Owner",
    crm_notes: "Notes",
    crm_move_stage: "Move to stage",
    status_active: "Active",
    status_inactive: "Inactive",
    status_pending: "Pending",
    status_overdue: "Overdue",
    status_settled: "Settled",
    status_in_process: "In process",
    status_in_stock: "In stock",
    status_in_settlement: "Settling",
    status_sold: "Sold",
    status_trial: "Trial",
    status_expired: "Expired",
    status_approved: "Accepted",
    status_rejected: "Rejected",
    status_draft: "Draft",
    status_converted: "Converted",
  }
};

// ============================================================
// VEHICLES (matching the print data — Audi A5, Ford Ka, etc.)
// ============================================================
const VEHICLES_MOCK = [
  {
    id: "v1", plate: "AEY7D33", brand: "Audi", model: "A5 Sportback 2.0 16V TFSI 180cv Multi.",
    year: 2014, owner: "Patrick Peres Batista", bank: "BV",
    purchasePrice: 23232336.50/1000, settlementValue: 22323950, clientValue: 9008.80,
    parcels: { total: 60, paid: 47, overdue: 3 }, acquiredOn: "04/05/2026",
    status: "overdue", trackerStatus: "active", maintenance: ["pintura"],
    fipeMin: 32000, fipeMax: 38000,
  },
  {
    id: "v2", plate: "SEM-PLACA", brand: "GM - Chevrolet", model: "ONIX HATCH Joy 1.0 8V Flex 5p Mec.",
    year: 2019, owner: "GM - Chevrolet ONIX HATCH Joy 1.0 8V Flex 5p Mec.", bank: "BV",
    purchasePrice: 15001.73, settlementValue: 8420.60, clientValue: 6580,
    parcels: { total: 50, paid: 38, overdue: 0 }, acquiredOn: "04/05/2026",
    status: "in_settlement", trackerStatus: "active", maintenance: ["elétrica", "pintura"],
    fipeMin: 28000, fipeMax: 34000,
  },
  {
    id: "v3", plate: "NRN1F61", brand: "Citroën", model: "C4 Picasso/Pic. La Luna 2.0 16V Aut.",
    year: 2010, owner: "Citroën C4 Picasso/Pic. La Luna 2.0 16V Aut.", bank: "Digimais",
    purchasePrice: 9420.60, settlementValue: 0, clientValue: 5277,
    parcels: { total: 50, paid: 38, overdue: 3 }, acquiredOn: "04/05/2026",
    status: "in_stock", trackerStatus: "active", maintenance: [],
    fipeMin: 21000, fipeMax: 28000,
  },
  {
    id: "v4", plate: "QUF4CA2", brand: "Ford", model: "Ka 1.5 Sedan SE 12V Flex 4p Aut.",
    year: 2019, owner: "Ford Ka 1.5 Sedan SE 12V Flex 4p Aut.", bank: "BV",
    purchasePrice: 18469.50, settlementValue: 13782.40, clientValue: 8825,
    parcels: { total: 60, paid: 8, overdue: 0 }, acquiredOn: "04/05/2026",
    status: "in_settlement", trackerStatus: "active", maintenance: [],
    fipeMin: 33000, fipeMax: 42000,
  },
  {
    id: "v5", plate: "FFK5C25", brand: "Ford", model: "Ka 1.5 SE/SE PLUS 16V Flex 5p",
    year: 2015, owner: "Ford Ka 1.5 SE/SE PLUS 16V Flex 5p", bank: "BV",
    purchasePrice: 11782.40, settlementValue: 13782.40, clientValue: 3365.40,
    parcels: { total: 48, paid: 36, overdue: 12 }, acquiredOn: "04/05/2026",
    status: "overdue", trackerStatus: "active", maintenance: [],
    fipeMin: 30000, fipeMax: 36000,
  },
  {
    id: "v6", plate: "SIV0D28", brand: "GM - Chevrolet", model: "MONTANA LT 1.2 Turbo Flex 12V 4p Mec.",
    year: 2024, owner: "GM - Chevrolet MONTANA LT 1.2 Turbo Flex 12V 4p Mec.", bank: "BV",
    purchasePrice: 54731.75, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "26/04/2026",
    status: "settled", trackerStatus: "active", maintenance: ["pintura", "mecânica"],
    fipeMin: 92000, fipeMax: 110000,
  },
  {
    id: "v7", plate: "FFK5C25", brand: "Ford", model: "Ka 1.5 SE/SE PLUS 16V Flex 5p",
    year: 2015, owner: "Ford Ka 1.5 SE/SE PLUS 16V Flex 5p", bank: "PAM",
    purchasePrice: 18782.40, settlementValue: 13782.40, clientValue: 11782.40,
    parcels: { total: 48, paid: 36, overdue: 0 }, acquiredOn: "28/04/2026",
    status: "overdue", trackerStatus: "active", maintenance: [],
    fipeMin: 30000, fipeMax: 36000,
  },
  {
    id: "v8", plate: "FVR5E94", brand: "Yamaha", model: "NMAX Connected 160 ABS",
    year: 2023, owner: "YAMAHA NMAX Connected 160 ABS", bank: "Santander",
    purchasePrice: 5683.50, settlementValue: 8420.60, clientValue: 19782.40,
    parcels: { total: 48, paid: 2, overdue: 1 }, acquiredOn: "19/04/2026",
    status: "overdue", trackerStatus: "active", maintenance: [],
    fipeMin: 18000, fipeMax: 22000,
  },
  {
    id: "v9", plate: "BPRL9A", brand: "GM - Chevrolet", model: "ONIX SEDAN Plus LTZ 1.0 12V TB Flex Mec.",
    year: 2021, owner: "Dione Alves", bank: "BV",
    purchasePrice: 20100.00, settlementValue: 13782.40, clientValue: 4735.20,
    parcels: { total: 50, paid: 39, overdue: 2 }, acquiredOn: "04/01/2026",
    status: "overdue", trackerStatus: "active", maintenance: [],
    fipeMin: 70000, fipeMax: 85000,
  },
  {
    id: "v10", plate: "SEM-PLACA", brand: "ASTON MARTIN", model: "DBX 4.0 V8 550cv",
    year: 2023, owner: "Aymoré", bank: "Aymoré",
    purchasePrice: 1166439.40, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "sold", trackerStatus: "inactive", maintenance: [],
    fipeMin: 1800000, fipeMax: 2100000,
    soldBy: "admin", salePrice: 392549.10,
  },
  {
    id: "v11", plate: "SEM-PLACA", brand: "Agrale", model: "MARRUÁ AM 100 2.8 CS TDI Diesel",
    year: 2014, owner: "Itaú", bank: "Itaú",
    purchasePrice: 35436.80, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "sold", trackerStatus: "inactive", maintenance: [],
    fipeMin: 110000, fipeMax: 135000,
    soldBy: "manager", salePrice: 10124.80,
  },
  {
    id: "v12", plate: "GFD2J66", brand: "BMW", model: "118i M Sport 1.5 TB 12V Aut. 5p",
    year: 2023, owner: "Bradesco", bank: "Bradesco",
    purchasePrice: 162915.00, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "in_stock", trackerStatus: "active", maintenance: [],
    fipeMin: 240000, fipeMax: 280000,
  },
  {
    id: "v13", plate: "HGF2K22", brand: "BMW", model: "118i M Sport 1.5 TB 12V Aut. 5p",
    year: 2024, owner: "dione Alves", bank: "BV",
    purchasePrice: 0, settlementValue: 0, clientValue: 24000,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "17/04/2026",
    status: "sold", trackerStatus: "active", maintenance: [],
    fipeMin: 260000, fipeMax: 290000,
    soldBy: "ops", salePrice: 24000,
  },
  {
    id: "v14", plate: "SEM-PLACA", brand: "Baby Buggy", model: "1.6/ TST/ RS 1.6 4-Lug.",
    year: 2018, owner: "Bradesco", bank: "Bradesco",
    purchasePrice: 9590.70, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "in_stock", trackerStatus: "inactive", maintenance: [],
    fipeMin: 15000, fipeMax: 22000,
  },
  {
    id: "v15", plate: "SEM-PLACA", brand: "ASTON MARTIN", model: "DBX707 4.0 V8 707cv",
    year: 2026, owner: "BV", bank: "BV",
    purchasePrice: 1166439.40, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "settled", trackerStatus: "inactive", maintenance: [],
    fipeMin: 1900000, fipeMax: 2200000,
  },
  {
    id: "v16", plate: "SEM-PLACA", brand: "ASTON MARTIN", model: "DBS Coupe 5.2 V12 725cv",
    year: 2022, owner: "Aymoré", bank: "Aymoré",
    purchasePrice: 392549.10, settlementValue: 0, clientValue: 0,
    parcels: { total: 0, paid: 0, overdue: 0 }, acquiredOn: "—",
    status: "in_stock", trackerStatus: "inactive", maintenance: [],
    fipeMin: 1100000, fipeMax: 1350000,
  },
];

const VEHICLES = VEHICLES_MOCK.map(v => ({ ...v }));

// Mentorados — equipe com vendas atribuídas (espelha perfis do shell)
const MENTEES = [
  { key: "admin", name: "Dione Alves", color: "" },
  { key: "manager", name: "Paloma Ferreira", color: "purple" },
  { key: "lawyer", name: "Dr. Wellton Reis", color: "orange" },
  { key: "ops", name: "Alex Santos", color: "cyan" },
];

function vehicleSaleValue(v) {
  if (v.salePrice != null && !isNaN(v.salePrice)) return Number(v.salePrice);
  if (v.clientValue) return Number(v.clientValue);
  return Number(v.purchasePrice || 0) * 1.15;
}

function getMenteeSalesRanking(vehicles, factor = 1) {
  const rows = MENTEES.map(m => ({ ...m, count: 0, value: 0 }));
  const byKey = Object.fromEntries(rows.map(r => [r.key, r]));
  (vehicles || []).filter(v => v.status === "sold").forEach(v => {
    const key = v.soldBy || "admin";
    const row = byKey[key];
    if (!row) return;
    row.count += 1;
    row.value += vehicleSaleValue(v);
  });
  return rows
    .map(r => ({ ...r, value: r.value * factor }))
    .sort((a, b) => b.value - a.value || b.count - a.count);
}

// CRM Kanban — etapas e negócios (integrado ao módulo de Análise)
const CRM_STAGES_KEY = "nau_crm_stages_v2";
const CRM_STAGE_COLORS = [
  "var(--blue-4)", "var(--blue-5)", "var(--blue-6)", "var(--blue-7)",
  "var(--preset-orange)", "var(--preset-purple)", "var(--color-warning)",
  "var(--color-success)", "var(--color-error)", "var(--fg3)",
];

const CRM_STAGE_SOURCES = {
  manual: null,
  analysis_draft: "draft",
  analysis_pending: "pending",
  analysis_approved: "approved",
  analysis_rejected: "rejected",
  analysis_converted: "converted",
};

const CRM_SOURCE_OPTIONS = [
  { value: "manual", labelPt: "Lead externo (manual)", labelEn: "External lead (manual)" },
  { value: "analysis_draft", labelPt: "Análises realizadas", labelEn: "Analyses completed" },
  { value: "analysis_pending", labelPt: "Oportunidades", labelEn: "Opportunities" },
  { value: "analysis_approved", labelPt: "Oportunidade aceita", labelEn: "Accepted opportunity" },
  { value: "analysis_rejected", labelPt: "Recusado", labelEn: "Rejected" },
  { value: "analysis_converted", labelPt: "Convertido", labelEn: "Converted" },
];

const CRM_STAGES_DEFAULT = [
  { key: "lead_ext", label: "Lead externo", color: "var(--blue-4)", isFinal: false, source: "manual" },
  { key: "sys_analysis", label: "Análises realizadas", color: "var(--blue-6)", isFinal: false, source: "analysis_draft" },
  { key: "sys_pending", label: "Oportunidades", color: "var(--preset-orange)", isFinal: false, source: "analysis_pending" },
  { key: "sys_accepted", label: "Oportunidade aceita", color: "var(--color-success)", isFinal: false, source: "analysis_approved" },
  { key: "sys_rejected", label: "Recusado", color: "var(--color-error)", isFinal: false, source: "analysis_rejected" },
  { key: "sys_converted", label: "Convertido", color: "var(--blue-7)", isFinal: true, source: "analysis_converted" },
];

function crmStageSourceStatus(source) {
  return CRM_STAGE_SOURCES[source] ?? null;
}

function isAnalysisStage(stage) {
  return !!(stage?.source && String(stage.source).startsWith("analysis_"));
}

function normalizeCrmStage(s, i) {
  const def = CRM_STAGES_DEFAULT.find(d => d.key === s.key);
  return {
    key: s.key || ("stage_" + i),
    label: s.label || def?.label || s.key || "Etapa",
    color: s.color || def?.color || CRM_STAGE_COLORS[i % CRM_STAGE_COLORS.length],
    isFinal: !!s.isFinal,
    source: s.source || def?.source || "manual",
  };
}

function getCrmStages() {
  try {
    const raw = localStorage.getItem(CRM_STAGES_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed) && parsed.length) {
        const stages = parsed.map(normalizeCrmStage);
        if (!stages.some(s => s.isFinal)) stages[stages.length - 1].isFinal = true;
        return stages;
      }
    }
  } catch (e) {}
  return CRM_STAGES_DEFAULT.map(s => ({ ...s }));
}

function saveCrmStages(stages) {
  const normalized = (stages || []).map(normalizeCrmStage);
  if (!normalized.length) return;
  if (!normalized.some(s => s.isFinal)) normalized[normalized.length - 1].isFinal = true;
  try { localStorage.setItem(CRM_STAGES_KEY, JSON.stringify(normalized)); } catch (e) {}
  window.NA.crmStages = normalized;
}

function slugifyStageKey(label) {
  const base = String(label || "etapa").toLowerCase()
    .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "etapa";
  return base + "_" + Date.now().toString(36).slice(-4);
}

const CRM_STAGES = getCrmStages();

const CRM_DEALS_DEFAULT = [];

const CRM_DEALS_KEY = "nau_crm_deals";

function getCrmDeals() {
  try {
    const raw = localStorage.getItem(CRM_DEALS_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return CRM_DEALS_DEFAULT.map(d => ({ ...d }));
}

function saveCrmDeals(deals) {
  try { localStorage.setItem(CRM_DEALS_KEY, JSON.stringify(deals)); } catch (e) {}
}

function getCrmStageLabel(stageOrKey, lang) {
  if (stageOrKey && typeof stageOrKey === "object") {
    return stageOrKey.label || window.NA.t("crm_stage_" + stageOrKey.key, lang) || stageOrKey.key;
  }
  const key = stageOrKey;
  const found = getCrmStages().find(s => s.key === key);
  if (found?.label) return found.label;
  return window.NA.t("crm_stage_" + key, lang) || key;
}

// Module catalog — used by Portaria & sidebar
const MODULES = [
  // operations
  { key: "dashboard",      icon: "layout-dashboard", group: "operations",  i18n: "nav_dashboard" },
  { key: "analysis",       icon: "calculator",       group: "operations",  i18n: "nav_analysis" },
  { key: "opportunities",  icon: "history",          group: "operations",  i18n: "nav_opportunities" },
  { key: "crm_kanban",     icon: "columns-3",        group: "operations",  i18n: "nav_crm_kanban" },
  { key: "acquisitions",   icon: "archive",          group: "operations",  i18n: "nav_acquisitions" },
  { key: "maintenance",    icon: "wrench",           group: "operations",  i18n: "nav_maintenance" },
  { key: "contracts",      icon: "file-text",        group: "operations",  i18n: "nav_contracts" },
  { key: "lawyer",         icon: "scale",            group: "operations",  i18n: "nav_lawyer" },
  { key: "trackers",       icon: "radio",            group: "operations",  i18n: "nav_trackers" },
  { key: "reviews",        icon: "message-square",   group: "operations",  i18n: "nav_reviews" },
  // finance
  { key: "financing",      icon: "credit-card",      group: "finance",     i18n: "nav_financing" },
  { key: "management",     icon: "crown",            group: "finance",     i18n: "nav_management" },
  { key: "lender",         icon: "hand-coins",       group: "finance",     i18n: "nav_lender" },
  { key: "finance",        icon: "wallet",           group: "finance",     i18n: "nav_finance" },
  { key: "cashbook",       icon: "landmark",         group: "finance",     i18n: "nav_cashbook" },
  // admin
  { key: "team",           icon: "users",            group: "admin",       i18n: "nav_team" },
  { key: "support",        icon: "headphones",       group: "admin",       i18n: "nav_support" },
  { key: "plans",          icon: "gem",              group: "admin",       i18n: "nav_plans" },
  { key: "account",        icon: "user",             group: "admin",       i18n: "nav_account" },
  // super-admin
  { key: "clients",        icon: "users-2",          group: "super_admin", i18n: "nav_clients" },
  { key: "credit_api",     icon: "key-round",        group: "super_admin", i18n: "nav_credit_api" },
  { key: "modules",        icon: "shield-check",     group: "super_admin", i18n: "nav_modules" },
  { key: "bank_account",   icon: "banknote",         group: "super_admin", i18n: "nav_bank_account" },
  { key: "support_panel",  icon: "headset",          group: "super_admin", i18n: "nav_support_panel" },
];

// ============================================================
// FORMATTERS
// ============================================================
function fmtBRL(v) {
  if (v == null || isNaN(v)) return "R$ 0,00";
  return "R$ " + Number(v).toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtUSD(v) {
  if (v == null || isNaN(v)) return "$0.00";
  return "$" + Number(v).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtMoney(v, lang) {
  return lang === "en" ? fmtUSD(v) : fmtBRL(v);
}
function fmtInt(v) {
  if (v == null) return "0";
  return Number(v).toLocaleString("pt-BR");
}

async function getAnalyses() {
  if (!window.NA.db || !window.NA.db.isConfigured()) return [];
  try {
    await window.NA.db.ensureSession();
    const rows = await window.NA.db.listAnalyses();
    return rows.map(r => window.NA.db.rowToLegacyListItem(r));
  } catch (e) { return []; }
}

async function saveAnalysis(entry) {
  if (!window.NA.db || !window.NA.db.isConfigured()) {
    throw new Error("Supabase não configurado");
  }
  return window.NA.db.upsertAnalysis(entry);
}

async function getAnalysis(id) {
  if (!window.NA.db || !window.NA.db.isConfigured() || !id) return null;
  const row = await window.NA.db.getAnalysis(id);
  return row ? window.NA.db.rowToForm(row) : null;
}

async function getAcquisitions(filters) {
  if (!window.NA.db || !window.NA.db.isConfigured()) {
    return (window.NA.vehiclesMock || []).map(v => ({ ...v }));
  }
  const rows = await window.NA.db.listAcquisitions(filters);
  return rows.map(r => window.NA.db.acquisitionRowToVehicle(r));
}

async function saveAcquisition(vehicle) {
  if (!window.NA.db || !window.NA.db.isConfigured()) {
    throw new Error("Supabase não configurado");
  }
  return window.NA.db.saveAcquisition(vehicle);
}

async function createAcquisitionFromAnalysis(analysisId, options) {
  if (!window.NA.db || !window.NA.db.isConfigured()) {
    throw new Error("Supabase não configurado");
  }
  return window.NA.db.createAcquisitionFromAnalysis(analysisId, options);
}

async function lookupPlate(plate) {
  if (!window.NA.db) throw new Error("Supabase não configurado");
  return window.NA.db.lookupPlate(plate);
}

// ============================================================
// EXPORTS
// ============================================================
window.NA.strings = STRINGS;
window.NA.vehicles = VEHICLES;
window.NA.vehiclesMock = VEHICLES_MOCK;
window.NA.mentees = MENTEES;
window.NA.vehicleSaleValue = vehicleSaleValue;
window.NA.getMenteeSalesRanking = getMenteeSalesRanking;
window.NA.crmStages = CRM_STAGES;
window.NA.crmStageColors = CRM_STAGE_COLORS;
window.NA.crmStageSources = CRM_STAGE_SOURCES;
window.NA.crmSourceOptions = CRM_SOURCE_OPTIONS;
window.NA.crmStageSourceStatus = crmStageSourceStatus;
window.NA.isAnalysisStage = isAnalysisStage;
window.NA.getCrmStages = getCrmStages;
window.NA.saveCrmStages = saveCrmStages;
window.NA.slugifyStageKey = slugifyStageKey;
window.NA.getCrmDeals = getCrmDeals;
window.NA.saveCrmDeals = saveCrmDeals;
window.NA.getCrmStageLabel = getCrmStageLabel;
window.NA.modules = MODULES;
window.NA.fmtBRL = fmtBRL;
window.NA.fmtUSD = fmtUSD;
window.NA.fmtMoney = fmtMoney;
window.NA.fmtInt = fmtInt;
window.NA.getAnalyses = getAnalyses;
window.NA.saveAnalysis = saveAnalysis;
window.NA.getAnalysis = getAnalysis;
window.NA.getAcquisitions = getAcquisitions;
window.NA.saveAcquisition = saveAcquisition;
window.NA.createAcquisitionFromAnalysis = createAcquisitionFromAnalysis;
window.NA.lookupPlate = lookupPlate;
window.NA.t = function (key, lang) {
  return (STRINGS[lang || "pt"] && STRINGS[lang || "pt"][key]) || STRINGS.pt[key] || key;
};
