/* ============================================================================
 * FLUXO ZAP · Mock Server
 * ----------------------------------------------------------------------------
 * Servidor fake em memória — intercepta chamadas do api/client.jsx quando
 * FluxoConfig.USE_MOCKS = true e devolve dados do src/data.jsx.
 *
 * Útil pra:
 *   - Desenvolver UI sem backend rodando
 *   - Demos / testes E2E sem rede
 *   - Validar contratos antes de implementar no servidor real
 *
 * Quando você implementar o backend de verdade, basta colocar
 * FluxoConfig.USE_MOCKS = false e tudo passa a chamar /v1/* HTTP.
 * ========================================================================= */

const latency = (min = 80, max = 240) =>
  new Promise(r => setTimeout(r, min + Math.random() * (max - min)));

const matchPath = (path, pattern) => {
  // Suporta :param e querystring (ignora qs no match)
  const [actualPath] = path.split('?');
  const parts = actualPath.split('/').filter(Boolean);
  const pParts = pattern.split('/').filter(Boolean);
  if (parts.length !== pParts.length) return null;
  const params = {};
  for (let i = 0; i < parts.length; i++) {
    if (pParts[i].startsWith(':')) params[pParts[i].slice(1)] = decodeURIComponent(parts[i]);
    else if (pParts[i] !== parts[i]) return null;
  }
  // Parse query
  const query = {};
  const qs = path.includes('?') ? path.split('?')[1] : '';
  if (qs) qs.split('&').forEach(p => {
    const [k, v] = p.split('=');
    query[k] = decodeURIComponent(v || '');
  });
  return { params, query };
};

const routes = [];
const route = (method, pattern, handler) => routes.push({ method, pattern, handler });

// ── Routes ─────────────────────────────────────────────────────────────────

// Leads
route('GET', '/leads', ({ query }) => {
  let list = window.mockLeads;
  if (query.stage) list = list.filter(l => l.stage === query.stage);
  if (query.temp) list = list.filter(l => l.temp === query.temp);
  if (query.aiActive) list = list.filter(l => String(l.aiActive) === query.aiActive);
  return { data: list, total: list.length };
});

route('GET', '/leads/:id', ({ params }) => {
  const lead = window.mockLeads.find(l => l.id === +params.id);
  if (!lead) throw new FluxoHttpError('Lead not found', 404);
  return lead;
});

route('PATCH', '/leads/:id', ({ params, body }) => {
  const lead = window.mockLeads.find(l => l.id === +params.id);
  if (!lead) throw new FluxoHttpError('Lead not found', 404);
  Object.assign(lead, body);
  return lead;
});

route('PATCH', '/leads/:id/stage', ({ params, body }) => {
  const lead = window.mockLeads.find(l => l.id === +params.id);
  if (!lead) throw new FluxoHttpError('Lead not found', 404);
  lead.stage = body.stage;
  return lead;
});

route('GET', '/leads/:id/timeline', ({ params }) => {
  // Timeline fictícia (poderia vir de uma tabela events no seu backend)
  return [
    { icon: 'Bot', color: '#10B981', title: 'IA transferiu pra você', sub: 'Negociação acima do limite (R$ 1.000)', time: '09:20' },
    { icon: 'Chat', color: '#5B8DEF', title: 'IA respondeu negociação', sub: 'Ofereceu combo família com 15% OFF · cupom BLACK10', time: '09:17' },
    { icon: 'Sparkles', color: '#A78BFA', title: 'IA classificou como QUENTE', sub: 'Score subiu de 54 para 87', time: '09:16' },
    { icon: 'Whatsapp', color: '#10B981', title: 'Mensagem inicial', sub: 'Cliente perguntou sobre combo Black Friday', time: '09:14' },
    { icon: 'Plus', color: '#5B8DEF', title: 'Lead capturado', sub: 'Via Instagram Ads — campanha #BF26', time: '09:14' },
  ];
});

route('GET', '/leads/:id/ai-insights', ({ params }) => {
  const lead = window.mockLeads.find(l => l.id === +params.id) || window.mockLeads[0];
  return {
    conversionProbability: lead.score / 100,
    urgency: lead.temp === 'quente' ? 'high' : lead.temp === 'morno' ? 'medium' : 'low',
    expectedCycleHours: lead.temp === 'quente' ? 6 : 24,
    expectedTicket: lead.value,
    objections: [
      { label: 'Sensível a preço', confidence: 0.84 },
      { label: 'Quer fechamento rápido', confidence: 0.92 },
    ],
    nextAction: lead.nextAction,
    summary: lead.summary,
  };
});

// Conversas
route('GET', '/conversations', () => {
  return window.mockLeads.map(l => ({
    leadId: l.id,
    leadName: l.name,
    avatar: l.avatar,
    color: l.color,
    lastMessage: l.lastMsg,
    lastMessageAt: l.lastTime,
    unread: l.unread,
    aiActive: l.aiActive,
  }));
});

route('GET', '/conversations/:leadId/messages', ({ params }) => {
  // Por enquanto a mesma conversa pra qualquer lead
  return window.conversation;
});

route('POST', '/conversations/:leadId/messages', ({ params, body }) => {
  const msg = {
    id: 'm_' + Date.now(),
    from: 'me',
    who: body.via || 'human',
    text: body.text,
    time: new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }),
    read: false,
    leadId: +params.leadId,
  };
  window.conversation.push(msg);
  return msg;
});

// IA
route('GET', '/ai/config', () => ({
  name: 'Kiko',
  version: '3.2',
  tone: 'amigavel',
  behavior: { formality: 35, proactivity: 72, empathy: 88, emojiUse: 50 },
  mission: 'Você é o Kiko, assistente comercial da Cestas da Lua...',
  limits: [
    { id: 'discount_15', label: 'Pode oferecer desconto até 15%', on: true },
    { id: 'schedule', label: 'Pode agendar visita/call', on: true },
    { id: 'payment_link', label: 'Pode emitir link de pagamento', on: false },
    { id: 'human_transfer', label: 'Transfere se cliente pedir humano', on: true },
    { id: '24_7', label: 'Responde 24/7', on: true },
    { id: 'auto_followup', label: 'Pode fazer follow-up automático', on: false },
  ],
  triggers: [
    { id: 1, trigger: '"falar com humano", "atendente"', action: 'Transferir imediatamente' },
    { id: 2, trigger: '"desconto", "consegue um preço melhor"', action: 'Aplicar regra de desconto + check' },
  ],
}));

route('POST', '/ai/suggest', ({ body }) => {
  const lead = window.mockLeads.find(l => l.id === body.leadId);
  return {
    text: lead ? lead.suggested : 'Posso te ajudar com mais alguma coisa?',
    confidence: 0.94,
    tone: 'amigável',
    reasoning: 'Cliente demonstrou urgência e sensibilidade a preço.',
  };
});

// Dashboard
route('GET', '/dashboard/kpis', () => ({
  newLeads: { value: 42, delta: 0.18, spark: [8,12,9,14,18,22,28,32,30,42] },
  messages: { value: 1284, delta: 0.34, spark: [200,340,280,420,510,640,820,1000,1100,1284] },
  hotLeads: { value: 11, delta: 3, spark: [3,4,3,5,7,6,8,9,10,11] },
  pipeline: { value: 24800, currency: 'BRL', delta: 0.12, spark: [10,12,15,14,18,20,22,21,23,24.8] },
}));

route('GET', '/dashboard/funnel', () => [
  { stage: 'recebidos', label: 'Leads recebidos', value: 284, color: '#5B8DEF' },
  { stage: 'qualificados', label: 'Qualificados pela IA', value: 196, color: '#A78BFA' },
  { stage: 'proposta', label: 'Proposta enviada', value: 92, color: '#F59E0B' },
  { stage: 'fechados', label: 'Fechados', value: 45, color: '#10B981' },
]);

route('GET', '/dashboard/ai-live', () => [
  { leadId: 1, leadName: 'Ana B.', stage: 'sugerindo fechamento', stageColor: '#F59E0B', startedAt: Date.now() - 3_000 },
  { leadId: 2, leadName: 'Rafael M.', stage: 'enviando tabela de frete', stageColor: '#5B8DEF', startedAt: Date.now() - 12_000 },
  { leadId: 5, leadName: 'Larissa M.', stage: 'cumprimentando', stageColor: '#A78BFA', startedAt: Date.now() - 34_000 },
  { leadId: 9, leadName: 'Mariana C.', stage: 'tirando dúvida de horário', stageColor: '#10B981', startedAt: Date.now() - 60_000 },
]);

// Pipeline
route('GET', '/pipeline/stages', () => window.stagesPipeline);

// Radar
route('GET', '/radar/prospects', () => [
  { id: 'p1', name: 'Sofia Andrade', handle: '@sofia.andrade', match: 94, channel: 'Instagram', signal: 'Comentou em 3 posts do nicho • interagiu com concorrente', city: 'São Paulo, SP', tags: ['Maternidade', 'Festas'], color: '#EC4899' },
  { id: 'p2', name: 'Vinícius Oliveira', handle: '@viny.oli', match: 88, channel: 'Instagram', signal: 'Buscou "cesta café da manhã SP" e clicou em ad concorrente', city: 'São Paulo, SP', tags: ['Romântico'], color: '#5B8DEF' },
]);

route('GET', '/radar/stats', () => ({
  opportunities: 23, opportunitiesDelta: 6,
  avgMatch: 0.78, target: 0.70,
  converted: 14, conversionRate: 0.22,
  accountsAnalyzedToday: 1847,
}));

// Knowledge
route('GET', '/knowledge/coverage', () => ({ coverage: 0.92, gaps: 6 }));

// Integrations
route('GET', '/integrations', () => [
  { id: 'whatsapp', name: 'WhatsApp API', desc: 'Conta oficial Meta (551199999999)', status: 'connected', logo: '#25D366' },
  { id: 'instagram', name: 'Instagram Direct', desc: 'Conectar conta do Instagram', status: 'disconnected', logo: '#E1306C' },
  { id: 'rd', name: 'RD Station CRM', desc: 'Sincronizar leads e deals', status: 'connected', logo: '#142032' },
  { id: 'gcal', name: 'Google Calendar', desc: 'Agendamentos automáticos pelo Kiko', status: 'connected', logo: '#4285F4' },
  { id: 'stripe', name: 'Stripe', desc: 'Pagamentos e links de cobrança', status: 'disconnected', logo: '#635BFF' },
]);

// ── Handler principal ──────────────────────────────────────────────────────
const FluxoMockServer = {
  async handle(path, opts = {}) {
    await latency();
    const method = opts.method || 'GET';
    const body = opts.body;
    for (const r of routes) {
      if (r.method !== method) continue;
      const m = matchPath(path, r.pattern);
      if (m) return r.handler({ params: m.params, query: m.query, body });
    }
    console.warn('[FluxoMockServer] no route matched:', method, path);
    throw new FluxoHttpError(`Mock route not found: ${method} ${path}`, 404);
  },

  // Simula eventos do WebSocket para realtime mode
  startRealtime(realtime) {
    // A cada 30s emite um "tick" do dashboard
    setInterval(() => realtime.emit('dashboard.tick', { ts: Date.now() }), 30_000);
  },
};

window.FluxoMockServer = FluxoMockServer;
