
// Dashboard Module

function Dashboard({ onNavigate }) {
  const [events, setEvents] = React.useState([]);
  const [budgets, setBudgets] = React.useState([]);
  const [freelancers, setFreelancers] = React.useState([]);
  const [tasks, setTasks] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [selectedEvent, setSelectedEvent] = React.useState(null);

  React.useEffect(() => {
    Promise.all([
      sb.from('events').select('*').order('event_date'),
      sb.from('budgets').select('*').order('issued_date', { ascending: false }),
      sb.from('freelancers').select('id, name, status'),
      sb.from('tasks').select('id, status'),
    ]).then(([ev, bud, fr, tsk]) => {
      setEvents(ev.data || []);
      setBudgets(bud.data || []);
      setFreelancers(fr.data || []);
      setTasks(tsk.data || []);
      setLoading(false);
    });
  }, []);

  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);

  const eventsThisMonth = events.filter(e => {
    const d = new Date(e.event_date);
    return d >= monthStart && d <= monthEnd;
  });
  const eventsInProgress = events.filter(e => e.status === 'Em andamento');
  const openBudgets = budgets.filter(b => b.status === 'Pendente' || b.status === 'Em análise');
  const openBudgetsTotal = openBudgets.reduce((s, b) => s + (parseFloat(b.total) || 0), 0);
  const escalatedFreelancers = freelancers.filter(f => f.status === 'Escalado');
  const overdueTasks = tasks.filter(t => t.status === 'done' ? false : false); // placeholder

  const CAT_COLORS = ['#3B82F6', '#8B5CF6', '#10B981', '#F59E0B', '#EF4444'];

  const revenueData = (() => {
    const result = [];
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const label = d.toLocaleDateString('pt-BR', { month: 'short' }).replace('.', '');
      const yStart = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-01';
      const last = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      const yEnd = last.getFullYear() + '-' + String(last.getMonth() + 1).padStart(2, '0') + '-' + String(last.getDate()).padStart(2, '0');
      const total = budgets
        .filter(b => b.status === 'Aprovado' && b.issued_date && b.issued_date >= yStart && b.issued_date <= yEnd)
        .reduce((s, b) => s + (parseFloat(b.total) || 0), 0);
      result.push({ label, value: total });
    }
    return result;
  })();

  const categoryData = (() => {
    const counts = {};
    events.forEach(e => {
      const t = e.event_type || e.type || 'Outros';
      counts[t] = (counts[t] || 0) + 1;
    });
    const total = Math.max(events.length, 1);
    return Object.entries(counts).map(([label, count], i) => ({
      label, color: CAT_COLORS[i % CAT_COLORS.length],
      value: Math.round((count / total) * 100),
    }));
  })();

  const approvedTotal = budgets.filter(b => b.status === 'Aprovado').reduce((s, b) => s + (parseFloat(b.total) || 0), 0);
  const nonZeroMonths = revenueData.filter(d => d.value > 0);
  const bestMonth = nonZeroMonths.length ? revenueData.reduce((a, b) => b.value > a.value ? b : a) : null;
  const avgMonthly = nonZeroMonths.length ? nonZeroMonths.reduce((s, d) => s + d.value, 0) / nonZeroMonths.length : 0;

  const alerts = [
    { icon: 'clock', color: '#F59E0B', text: 'Confira os eventos desta semana na Agenda', nav: 'events' },
    { icon: 'alert', color: '#EF4444', text: 'Verifique tarefas pendentes no Kanban', nav: 'tasks' },
    { icon: 'budget', color: '#3B82F6', text: `${openBudgets.length} orçamento(s) aguardando aprovação`, nav: 'budgets' },
    { icon: 'users', color: '#10B981', text: `${escalatedFreelancers.length} freelancer(s) escalado(s)`, nav: 'freelancers' },
  ];

  const statusVariant = { 'Em andamento': 'primary', 'Confirmado': 'success', 'Planejamento': 'purple', 'Orçamento': 'warning', 'Concluído': 'success', 'Cancelado': 'danger' };

  const fmtDate = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso + 'T00:00:00');
    return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' });
  };

  const fmtMoney = (v) => {
    const n = parseFloat(v) || 0;
    if (n >= 1000000) return `R$ ${(n / 1000000).toFixed(1)}M`;
    if (n >= 1000) return `R$ ${(n / 1000).toFixed(0)}k`;
    return `R$ ${n.toLocaleString('pt-BR')}`;
  };

  const recentEvents = events.slice(0, 5);

  const StatClickable = ({ label, value, delta, icon, color, subtitle, nav }) => {
    const [hov, setHov] = React.useState(false);
    return (
      <div onClick={() => onNavigate && onNavigate(nav)}
        onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
        style={{ cursor: 'pointer', transform: hov ? 'translateY(-2px)' : 'none', transition: 'transform 0.15s' }}>
        <StatCard label={label} value={value} delta={delta} icon={icon} color={color} subtitle={subtitle} />
      </div>
    );
  };

  if (loading) {
    return (
      <div>
        <div style={{ marginBottom: 28 }}>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Dashboard</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Carregando dados…</p>
        </div>
        <Spinner />
      </div>
    );
  }

  return (
    <div>
      {/* Page header */}
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Dashboard</h1>
        <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Bem-vindo de volta. Aqui está o resumo de hoje.</p>
      </div>

      {/* Stat cards — clickable */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        <StatClickable label="Eventos do mês" value={String(eventsThisMonth.length || events.length)} delta={8} icon="calendar" color="#3B82F6" subtitle={`${eventsInProgress.length} em andamento`} nav="events" />
        <StatClickable label="Em andamento" value={String(eventsInProgress.length)} delta={-1} icon="zap" color="#8B5CF6" subtitle="Clique para ver agenda" nav="events" />
        <StatClickable label="Orçamentos abertos" value={String(openBudgets.length)} delta={15} icon="budget" color="#F59E0B" subtitle={fmtMoney(openBudgetsTotal) + ' total'} nav="budgets" />
        <StatClickable label="Freelancers escalados" value={String(escalatedFreelancers.length)} delta={4} icon="users" color="#10B981" subtitle={`de ${freelancers.length} no total`} nav="freelancers" />
      </div>

      {/* Charts + Alerts row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 300px', gap: 16, marginBottom: 24 }}>
        {/* Revenue chart */}
        <Card style={{ padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>Faturamento</div>
              <div style={{ fontSize: 12, color: DS.colors.textSec }}>Últimos 6 meses</div>
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: DS.colors.text }}>{approvedTotal > 0 ? fmtMoney(approvedTotal) : '—'}</div>
          </div>
          <MiniBarChart data={revenueData} color="#3B82F6" height={120} />
          <div style={{ display: 'flex', gap: 16, marginTop: 16, paddingTop: 16, borderTop: `1px solid ${DS.colors.border}` }}>
            <div><div style={{ fontSize: 11, color: DS.colors.textMuted }}>Melhor mês</div><div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{bestMonth ? bestMonth.label : '—'}</div></div>
            <div><div style={{ fontSize: 11, color: DS.colors.textMuted }}>Média mensal</div><div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{avgMonthly > 0 ? fmtMoney(avgMonthly) : '—'}</div></div>
            <div><div style={{ fontSize: 11, color: DS.colors.textMuted }}>Total aprovado</div><div style={{ fontSize: 13, fontWeight: 700, color: '#10B981' }}>{approvedTotal > 0 ? fmtMoney(approvedTotal) : '—'}</div></div>
          </div>
        </Card>

        {/* Category chart */}
        <Card style={{ padding: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 4 }}>Eventos por categoria</div>
          <div style={{ fontSize: 12, color: DS.colors.textSec, marginBottom: 20 }}>Distribuição atual</div>
          {categoryData.length > 0 ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
              <DonutChart segments={categoryData} size={110} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
                {categoryData.map(c => (
                  <div key={c.label} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}
                    onClick={() => onNavigate && onNavigate('events')}>
                    <div style={{ width: 8, height: 8, borderRadius: 2, background: c.color, flexShrink: 0 }} />
                    <div style={{ flex: 1, fontSize: 12, color: DS.colors.textSec }}>{c.label}</div>
                    <div style={{ fontSize: 12, fontWeight: 700, color: DS.colors.text }}>{c.value}%</div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '24px 0', color: DS.colors.textMuted, fontSize: 13 }}>
              <Icon name="calendar" size={32} color={DS.colors.border} />
              <div style={{ marginTop: 10 }}>Crie eventos para ver a distribuição</div>
            </div>
          )}
        </Card>

        {/* Alerts — each one navigates somewhere */}
        <Card style={{ padding: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 16 }}>Alertas</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {alerts.map((a, i) => (
              <div key={i} onClick={() => onNavigate && onNavigate(a.nav)}
                style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', background: '#F8FAFC', borderRadius: DS.radius.sm, borderLeft: `3px solid ${a.color}`, cursor: 'pointer', transition: 'background 0.1s' }}
                onMouseEnter={e => e.currentTarget.style.background = '#F1F5F9'}
                onMouseLeave={e => e.currentTarget.style.background = '#F8FAFC'}>
                <Icon name={a.icon} size={14} color={a.color} />
                <span style={{ fontSize: 12, color: DS.colors.text, lineHeight: 1.4 }}>{a.text}</span>
                <Icon name="arrow" size={12} color={DS.colors.textMuted} style={{ marginLeft: 'auto', flexShrink: 0 }} />
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Recent events table — rows clickable */}
      <Card>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${DS.colors.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Últimos eventos</div>
          <Btn variant="ghost" size="sm" onClick={() => onNavigate && onNavigate('events')}>Ver todos</Btn>
        </div>
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 0.8fr 1fr 1fr 0.8fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            <span>Evento</span><span>Cliente</span><span>Data</span><span>Tipo</span><span>Status</span><span style={{ textAlign: 'right' }}>Orçamento</span>
          </div>
          {recentEvents.length === 0 && (
            <div style={{ padding: '32px 24px', textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>
              Nenhum evento cadastrado ainda.
              <span style={{ marginLeft: 8, color: DS.colors.primary, cursor: 'pointer', fontWeight: 600 }} onClick={() => onNavigate && onNavigate('events')}>Criar evento</span>
            </div>
          )}
          {recentEvents.map((ev, i) => (
            <div key={ev.id}
              onClick={() => setSelectedEvent(ev)}
              style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 0.8fr 1fr 1fr 0.8fr', padding: '14px 24px', borderBottom: i < recentEvents.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center', cursor: 'pointer', transition: 'background 0.1s' }}
              onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{ev.name}</span>
              <span style={{ fontSize: 13, color: DS.colors.textSec }}>{ev.client_name || '—'}</span>
              <span style={{ fontSize: 13, color: DS.colors.textSec }}>{fmtDate(ev.event_date)}</span>
              <span><Badge variant="default">{ev.event_type || ev.type || '—'}</Badge></span>
              <span><Badge variant={statusVariant[ev.status] || 'default'}>{ev.status}</Badge></span>
              <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, textAlign: 'right' }}>{fmtMoney(ev.budget_estimate || ev.budget || 0)}</span>
            </div>
          ))}
        </div>
      </Card>

      {/* Event detail modal */}
      {selectedEvent && (
        <Modal open={!!selectedEvent} onClose={() => setSelectedEvent(null)} title="Detalhes do Evento" width={600}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
              <div style={{ width: 52, height: 52, borderRadius: DS.radius.md, background: DS.colors.primary + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="calendar" size={24} color={DS.colors.primary} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 18, fontWeight: 800, color: DS.colors.text }}>{selectedEvent.name}</div>
                <div style={{ fontSize: 13, color: DS.colors.textSec, marginTop: 4 }}>{selectedEvent.client_name || 'Cliente não informado'}</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
                  <Badge variant={statusVariant[selectedEvent.status] || 'default'}>{selectedEvent.status}</Badge>
                  <Badge variant="default">{selectedEvent.event_type || selectedEvent.type || '—'}</Badge>
                </div>
              </div>
            </div>

            <Divider />

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
              {[
                { label: 'Data', value: fmtDate(selectedEvent.event_date) },
                { label: 'Horário', value: selectedEvent.start_time || selectedEvent.time || '—' },
                { label: 'Local', value: selectedEvent.location || '—' },
                { label: 'Orçamento', value: fmtMoney(selectedEvent.budget_estimate || selectedEvent.budget || 0) },
                { label: 'Tipo', value: selectedEvent.event_type || selectedEvent.type || '—' },
                { label: 'Convidados', value: selectedEvent.guest_count ? `${selectedEvent.guest_count} pessoas` : '—' },
              ].map(item => (
                <div key={item.label}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{item.label}</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{item.value}</div>
                </div>
              ))}
            </div>

            {selectedEvent.notes && (
              <>
                <Divider />
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8 }}>Observações</div>
                  <div style={{ fontSize: 13, color: DS.colors.textSec, lineHeight: 1.6 }}>{selectedEvent.notes}</div>
                </div>
              </>
            )}

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 4 }}>
              <Btn variant="secondary" onClick={() => setSelectedEvent(null)}>Fechar</Btn>
              <Btn icon="calendar" onClick={() => { setSelectedEvent(null); onNavigate && onNavigate('events'); }}>Ver na Agenda</Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard });
