// LEXIA Data Layer — carrega dados reais da API
const COLORS = ['var(--toga-700)','var(--sela-500)','var(--selo-500)','var(--toga-600)','var(--sela-700)'];
const colorFor = (str) => COLORS[str ? str.charCodeAt(0) % COLORS.length : 0];

function fmtDate(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' });
}
function fmtTime(iso) {
  if (!iso) return '';
  return new Date(iso).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
}
function fmtMonthYear(iso) {
  if (!iso) return '';
  return new Date(iso).toLocaleDateString('pt-BR', { month: '2-digit', year: 'numeric' });
}
function relativeTime(iso) {
  if (!iso) return '—';
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'agora';
  if (mins < 60) return `há ${mins}min`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `há ${hrs}h`;
  const days = Math.floor(hrs / 24);
  if (days === 1) return 'ontem';
  if (days < 7) return `${days} dias`;
  return fmtDate(iso);
}

async function loadLEXIAData() {
  if (!window.LEXIA.getToken()) return;

  const safe = (p) => p.catch(() => []);

  const [clientes, processos, conversas, agenda] = await Promise.all([
    safe(window.LEXIA.Clientes.listar()),
    safe(window.LEXIA.Processos.listar()),
    safe(window.LEXIA.Conversas.listar()),
    safe(window.LEXIA.Agenda.listar()),
  ]);

  window.CLIENTS = (Array.isArray(clientes) ? clientes : []).map(c => ({
    id: c.id,
    name: c.nome,
    phone: c.whatsapp,
    email: c.email || '',
    cpf: c.cpf || '',
    rg: '',
    birth: '',
    addr: '',
    procs: parseInt(c.total_processos) || 0,
    since: fmtMonthYear(c.criado_em),
    last: relativeTime(c.ultimo_contato),
    notes: c.observacoes || '',
    processes: [],
    timeline: [],
    color: colorFor(c.nome),
  }));

  window.PROCESSES = (Array.isArray(processos) ? processos : []).map(p => ({
    id: p.id,
    cnj: p.cnj,
    client: p.cliente_nome || '',
    client_id: p.cliente_id,
    area: p.area || '',
    phase: p.fase || '',
    last: fmtDate(p.ultima_consulta),
    status: p.status === 'aberto' ? 'open' : p.status === 'encerrado' ? 'done' : 'open',
    court: [p.vara, p.tribunal].filter(Boolean).join(' · '),
    value: '—',
    opened: fmtDate(p.criado_em),
  }));

  // Enriquecer clientes com processos
  window.CLIENTS.forEach(c => {
    c.processes = window.PROCESSES.filter(p => p.client_id === c.id).map(p => p.cnj);
    c.procs = c.processes.length || c.procs;
  });

  window.CONVERSATIONS = (Array.isArray(conversas) ? conversas : []).map(c => ({
    id: c.id,
    name: c.cliente_nome || 'Cliente',
    phone: c.cliente_whatsapp || '',
    cnj: '',
    color: colorFor(c.cliente_nome),
    status: c.status === 'aberto' ? 'open' : c.status === 'escalonado' ? 'esc' : c.status === 'encerrado' ? 'done' : 'bot',
    unread: parseInt(c.nao_lidas) || 0,
    time: fmtTime(c.ultima_msg_em || c.atualizada_em),
    preview: c.ultima_msg || '',
    owner: c.advogado_id ? 'lawyer' : 'lexia',
    messages: [],
  }));

  // Agenda — montar grid semanal
  const hoje = new Date();
  const inicioSemana = new Date(hoje);
  inicioSemana.setDate(hoje.getDate() - ((hoje.getDay() + 6) % 7));

  window.EVENTS = {};
  window.AGENDA_ITEMS = Array.isArray(agenda) ? agenda : [];

  window.AGENDA_ITEMS.forEach(ev => {
    const d = new Date(ev.inicio);
    const diffDays = Math.round((d - inicioSemana) / 86400000);
    if (diffDays >= 0 && diffDays < 5) {
      const hour = d.getHours();
      if (!window.EVENTS[diffDays]) window.EVENTS[diffDays] = {};
      window.EVENTS[diffDays][hour] = {
        id: ev.id,
        title: ev.titulo,
        sub: ev.meet_link ? 'Google Meet' : 'Presencial',
        kind: ev.meet_link ? 'tel' : '',
      };
    }
  });

  window.dispatchEvent(new Event('lexia-data-loaded'));
}

window.CLIENTS = [];
window.PROCESSES = [];
window.CONVERSATIONS = [];
window.EVENTS = {};
window.AGENDA_ITEMS = [];
window.loadLEXIAData = loadLEXIAData;
window.colorFor = colorFor;
window.relativeTime = relativeTime;
window.fmtDate = fmtDate;
