
// ============================================================
// JuFlow — Dashboard
// ============================================================
const { useState: useStD, useMemo: useMemoD } = React;
const UD = window.JFUtils;

// ─── Native SVG Line Chart with area gradient ─────────────
const LineAreaChart = ({ data, color = '#FF6B35', height = 200 }) => {
  const [hover, setHover] = useStD(null);
  const W = 760, H = height;
  const padL = 40, padR = 16, padT = 16, padB = 28;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;

  const values = data.map(d => d.count);
  const maxV = Math.max(1, ...values);
  const niceMax = Math.max(5, Math.ceil(maxV / 5) * 5);
  const stepX = innerW / Math.max(1, data.length - 1);
  const yScale = v => padT + innerH - (v / niceMax) * innerH;
  const points = data.map((d, i) => ({ x: padL + i * stepX, y: yScale(d.count), v: d.count, label: d.day }));
  const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
  const areaD = pathD + ` L${points[points.length-1].x.toFixed(1)},${(padT + innerH).toFixed(1)} L${points[0].x.toFixed(1)},${(padT + innerH).toFixed(1)} Z`;
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(niceMax * t));
  const xLabels = data.length > 8
    ? data.map((d, i) => i % Math.ceil(data.length / 6) === 0 || i === data.length - 1 ? d.day : null)
    : data.map(d => d.day);

  return (
    <div style={{ position:'relative' }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block' }}
        onMouseLeave={() => setHover(null)}
        onMouseMove={e => {
          const rect = e.currentTarget.getBoundingClientRect();
          const xRel = ((e.clientX - rect.left) / rect.width) * W - padL;
          const idx = Math.round(xRel / stepX);
          if (idx >= 0 && idx < data.length) setHover(idx); else setHover(null);
        }}
      >
        <defs>
          <linearGradient id="gArea" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.28" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>

        {yTicks.map(v => (
          <g key={v}>
            <line x1={padL} y1={yScale(v)} x2={W - padR} y2={yScale(v)} stroke="#F3F4F6" strokeDasharray="3 3" />
            <text x={padL - 6} y={yScale(v) + 3} fontSize="10" fill="#9CA3AF" textAnchor="end">{v}</text>
          </g>
        ))}

        <path d={areaD} fill="url(#gArea)" />
        <path d={pathD} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />

        {points.map((p, i) => (xLabels[i] ? (
          <text key={i} x={p.x} y={H - 10} fontSize="10" fill="#9CA3AF" textAnchor="middle">{xLabels[i]}</text>
        ) : null))}

        {hover !== null && (
          <g>
            <line x1={points[hover].x} y1={padT} x2={points[hover].x} y2={padT + innerH} stroke={color} strokeDasharray="3 3" opacity=".5" />
            <circle cx={points[hover].x} cy={points[hover].y} r="5" fill={color} stroke="#fff" strokeWidth="2" />
          </g>
        )}
      </svg>

      {hover !== null && (() => {
        const p = points[hover];
        const leftPct = (p.x / W) * 100;
        return (
          <div style={{
            position:'absolute', top: (p.y / H) * 100 + '%', left: `${leftPct}%`,
            transform:'translate(-50%, -130%)',
            background:'#fff', border:'1px solid #E2E8F0', borderRadius:10,
            padding:'6px 10px', fontSize:11, boxShadow:'0 6px 16px rgba(10,31,68,.12)',
            pointerEvents:'none', whiteSpace:'nowrap', zIndex:5,
          }}>
            <div style={{ color:'#6B7280', marginBottom:2 }}>{p.label}</div>
            <div style={{ color:'#0A1F44', fontWeight:700 }}>{p.v} atendimento{p.v === 1 ? '' : 's'}</div>
          </div>
        );
      })()}
    </div>
  );
};

// ─── Native SVG Donut Chart ───────────────────────────────
const DonutChart = ({ data, colors, size = 170 }) => {
  const [hover, setHover] = useStD(null);
  const total = data.reduce((s, d) => s + d.value, 0);
  const cx = size/2, cy = size/2, r = size/2 - 6, ir = r - 22;
  let acc = -Math.PI / 2;
  const arcs = data.map((d, i) => {
    const angle = total > 0 ? (d.value / total) * Math.PI * 2 : 0;
    const a0 = acc, a1 = acc + angle; acc = a1;
    const isHover = hover === i;
    const rOut = isHover ? r + 3 : r;
    const x0 = cx + rOut * Math.cos(a0), y0 = cy + rOut * Math.sin(a0);
    const x1 = cx + rOut * Math.cos(a1), y1 = cy + rOut * Math.sin(a1);
    const xi1 = cx + ir * Math.cos(a1), yi1 = cy + ir * Math.sin(a1);
    const xi0 = cx + ir * Math.cos(a0), yi0 = cy + ir * Math.sin(a0);
    const large = angle > Math.PI ? 1 : 0;
    const path = `M${x0.toFixed(2)},${y0.toFixed(2)} A${rOut},${rOut} 0 ${large} 1 ${x1.toFixed(2)},${y1.toFixed(2)} L${xi1.toFixed(2)},${yi1.toFixed(2)} A${ir},${ir} 0 ${large} 0 ${xi0.toFixed(2)},${yi0.toFixed(2)} Z`;
    return { path, color: colors[i % colors.length], i, name: d.name, value: d.value, pct: total ? Math.round(d.value/total*100) : 0 };
  });
  return (
    <div style={{ display:'flex', alignItems:'center', gap:14 }}>
      <div style={{ position:'relative', width:size, height:size, flexShrink:0 }}>
        <svg width={size} height={size}>
          {arcs.map(a => (
            <path key={a.i} d={a.path} fill={a.color}
              onMouseEnter={() => setHover(a.i)}
              onMouseLeave={() => setHover(null)}
              style={{ cursor:'pointer', transition:'opacity .15s', opacity: hover === null || hover === a.i ? 1 : .55 }} />
          ))}
        </svg>
        <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', pointerEvents:'none' }}>
          <div style={{ fontSize:11, color:'#9CA3AF', fontWeight:600 }}>{hover !== null ? arcs[hover].pct + '%' : 'Total'}</div>
          <div style={{ fontSize:24, fontWeight:800, color:'#0A1F44', lineHeight:1 }}>{hover !== null ? arcs[hover].value : total}</div>
          <div style={{ fontSize:10, color:'#9CA3AF', marginTop:2 }}>{hover !== null ? 'sessões' : 'sessões'}</div>
        </div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:6, flex:1, minWidth:0 }}>
        {arcs.map(a => (
          <div key={a.i}
            onMouseEnter={() => setHover(a.i)}
            onMouseLeave={() => setHover(null)}
            style={{ display:'flex', alignItems:'center', gap:7, fontSize:11, padding:'3px 6px', borderRadius:6, cursor:'pointer', background: hover === a.i ? '#F9FAFB' : 'transparent', transition:'background .15s' }}>
            <div style={{ width:8, height:8, borderRadius:2, background:a.color, flexShrink:0 }} />
            <span style={{ color:'#374151', flex:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{a.name}</span>
            <span style={{ fontWeight:700, color:'#0A1F44' }}>{a.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const Dashboard = ({ appointments, onNavigate, addToast, onNewAppointment }) => {
  // ── Metrics ────────────────────────────────────────────
  const todayAppts    = UD.todayAppointments(appointments);
  const weekAppts     = UD.weekAppointments(appointments);
  const monthRevenue  = UD.monthRevenue(appointments);
  const occupancy     = UD.occupancyRate(appointments);

  // ── Today summary (next, completed, pending revenue) ──
  const now = window.JF.TODAY;
  const nextAppt = useMemoD(() =>
    appointments
      .filter(a => ['confirmed','pending'].includes(a.status))
      .sort((a,b) => new Date(a.datetime) - new Date(b.datetime))
      .find(a => new Date(a.datetime) >= now)
  , [appointments]);
  const completedToday = todayAppts.filter(a => a.status === 'completed').length;
  const todayRevenue   = todayAppts.filter(a => a.status === 'completed').reduce((s,a)=>s+a.price,0);

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return 'Bom dia';
    if (h < 18) return 'Boa tarde';
    return 'Boa noite';
  })();

  // ── Line chart: last 30 days ───────────────────────────
  const lineData = useMemoD(() => {
    const today = window.JF.TODAY;
    return Array.from({ length: 30 }, (_, i) => {
      const d = UD.addDays(today, i - 29);
      const count = appointments.filter(a => UD.isSameDay(a.datetime, d) && a.status === 'completed').length;
      return { day: UD.formatDate(d,'dd/MM'), count };
    });
  }, [appointments]);
  const lineTotal = lineData.reduce((s,d)=>s+d.count,0);
  const lineFirstHalf = lineData.slice(0,15).reduce((s,d)=>s+d.count,0);
  const lineSecondHalf = lineData.slice(15).reduce((s,d)=>s+d.count,0);
  const lineTrend = lineFirstHalf > 0 ? ((lineSecondHalf - lineFirstHalf) / lineFirstHalf) * 100 : 0;

  // ── Pie chart: top services ────────────────────────────
  const pieData = useMemoD(() => {
    const today = window.JF.TODAY;
    const map = {};
    appointments
      .filter(a => {
        const d = new Date(a.datetime);
        return d.getMonth() === today.getMonth() && a.status === 'completed';
      })
      .forEach(a => {
        const svc = UD.getService(a.serviceId);
        if (!svc) return;
        map[svc.name] = (map[svc.name] || 0) + 1;
      });
    return Object.entries(map)
      .sort((a,b) => b[1]-a[1])
      .slice(0, 5)
      .map(([name, value]) => ({ name, value }));
  }, [appointments]);

  const PIE_COLORS = ['#FF6B35','#7C3AED','#0891B2','#059669','#D97706'];

  // ── Upcoming appointments ──────────────────────────────
  const upcoming = useMemoD(() =>
    appointments
      .filter(a => ['confirmed','pending'].includes(a.status) && new Date(a.datetime) >= window.JF.TODAY)
      .sort((a,b) => new Date(a.datetime) - new Date(b.datetime))
      .slice(0, 6)
  , [appointments]);

  // ── Top professional this month ────────────────────────
  const topProf = useMemoD(() => {
    const today = window.JF.TODAY;
    const map = {};
    appointments
      .filter(a => a.status === 'completed' && new Date(a.datetime).getMonth() === today.getMonth())
      .forEach(a => { map[a.professionalId] = (map[a.professionalId] || 0) + 1; });
    const top = Object.entries(map).sort((a,b) => b[1]-a[1])[0];
    if (!top) return null;
    return { prof: UD.getProfessional(Number(top[0])), sessions: top[1] };
  }, [appointments]);

  // ── Birthday clients this month ────────────────────────
  const birthdays = window.JF.CLIENTS.filter(c => UD.isBirthdayThisMonth(c.birthdate));

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Hero greeting */}
      <div style={{
        background:'linear-gradient(135deg, #0A1F44 0%, #1E3A5F 60%, #FF6B35 200%)',
        borderRadius:16, padding:'22px 26px', color:'#fff',
        display:'flex', alignItems:'center', justifyContent:'space-between', gap:16, flexWrap:'wrap',
        boxShadow:'0 8px 24px rgba(10,31,68,.18)',
      }}>
        <div style={{ flex:1, minWidth:240 }}>
          <div style={{ fontSize:13, color:'rgba(255,255,255,.7)', fontWeight:500, marginBottom:4 }}>
            {UD.formatDateLong(window.JF.TODAY)}
          </div>
          <h2 style={{ margin:0, fontSize:22, fontWeight:800, letterSpacing:'-.5px' }}>
            {greeting}, Admin! <span style={{ marginLeft:4 }}>👋</span>
          </h2>
          <p style={{ margin:'6px 0 0', fontSize:13, color:'rgba(255,255,255,.85)', lineHeight:1.5 }}>
            {todayAppts.length === 0
              ? 'Nenhum atendimento agendado para hoje. Aproveite para revisar a agenda da semana.'
              : <>Você tem <strong style={{ color:'#FFB89A' }}>{todayAppts.length}</strong> atendimento{todayAppts.length === 1 ? '' : 's'} hoje.{nextAppt && (() => {
                  const c = UD.getClient(nextAppt.clientId);
                  const p = UD.getProfessional(nextAppt.professionalId);
                  const dStr = UD.isSameDay(nextAppt.datetime, window.JF.TODAY) ? 'hoje' : UD.formatDate(nextAppt.datetime, 'dd/MM');
                  return <> Próximo: <strong style={{ color:'#fff' }}>{c?.name}</strong> {dStr} às <strong>{UD.formatTime(nextAppt.datetime)}</strong> com {p?.name}.</>;
                })()}
              </>}
          </p>
        </div>
        <div style={{ display:'flex', gap:8, flexShrink:0 }}>
          <button onClick={() => onNewAppointment && onNewAppointment()} style={{
            padding:'10px 16px', borderRadius:10, border:'none', cursor:'pointer',
            background:'#FF6B35', color:'#fff', fontSize:13, fontWeight:700,
            display:'flex', alignItems:'center', gap:7, boxShadow:'0 4px 12px rgba(255,107,53,.4)',
            transition:'transform .15s',
          }}
            onMouseEnter={e => e.currentTarget.style.transform='translateY(-1px)'}
            onMouseLeave={e => e.currentTarget.style.transform='translateY(0)'}
          >
            <Icon name="Plus" size={15} color="#fff" />
            Novo Agendamento
          </button>
          <button onClick={() => onNavigate('agenda')} style={{
            padding:'10px 16px', borderRadius:10, border:'1px solid rgba(255,255,255,.25)', cursor:'pointer',
            background:'rgba(255,255,255,.08)', color:'#fff', fontSize:13, fontWeight:600,
            display:'flex', alignItems:'center', gap:7,
          }}>
            <Icon name="Calendar" size={15} color="#fff" />
            Ver agenda
          </button>
        </div>
      </div>

      {/* Metric cards with mini-context */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        {[
          { title:'Atendimentos Hoje',  value: todayAppts.length, icon:'Calendar', color:'#FF6B35', trend:12, trendLabel:'vs. ontem', sub: completedToday + ' realizados' },
          { title:'Faturado Hoje',      value: UD.formatCurrency(todayRevenue), icon:'DollarSign', color:'#059669', trend:9, trendLabel:'vs. ontem', sub: completedToday > 0 ? 'média ' + UD.formatCurrency(Math.round(todayRevenue/completedToday)) : 'sem fechamentos' },
          { title:'Agendamentos da Semana', value: weekAppts.length, icon:'CalendarDays', color:'#7C3AED', trend:8, trendLabel:'vs. semana passada', sub:'sessões previstas' },
          { title:'Receita do Mês',     value: UD.formatCurrency(monthRevenue), icon:'TrendingUp', color:'#0891B2', trend:15, trendLabel:'vs. mês anterior', sub: occupancy + '% de ocupação' },
        ].map(m => (
          <div key={m.title} style={{ background:'#fff', borderRadius:14, padding:'18px 20px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', border:'1px solid #F0F4F8', transition:'all .2s' }}
            onMouseEnter={e => { e.currentTarget.style.boxShadow='0 8px 20px rgba(10,31,68,.10)'; e.currentTarget.style.transform='translateY(-2px)'; }}
            onMouseLeave={e => { e.currentTarget.style.boxShadow='0 2px 8px rgba(10,31,68,.06)'; e.currentTarget.style.transform='translateY(0)'; }}
          >
            <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:12 }}>
              <span style={{ fontSize:12, fontWeight:600, color:'#6B7280' }}>{m.title}</span>
              <div style={{ width:34, height:34, borderRadius:9, background: UD.hexToRgba(m.color,.12), display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={m.icon} size={16} color={m.color} />
              </div>
            </div>
            <div style={{ fontSize:24, fontWeight:800, color:'#0A1F44', letterSpacing:'-.4px', lineHeight:1.1 }}>{m.value}</div>
            <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:6, flexWrap:'wrap' }}>
              <span style={{ display:'inline-flex', alignItems:'center', gap:2, fontSize:11, fontWeight:700, color: m.trend >= 0 ? '#15803D' : '#B91C1C', background: m.trend >= 0 ? '#F0FDF4' : '#FEF2F2', padding:'2px 7px', borderRadius:20 }}>
                <Icon name={m.trend >= 0 ? 'TrendingUp' : 'TrendingDown'} size={11} />
                {m.trend >= 0 ? '+' : ''}{m.trend}%
              </span>
              <span style={{ fontSize:11, color:'#9CA3AF' }}>{m.trendLabel}</span>
            </div>
            <div style={{ fontSize:11, color:'#9CA3AF', marginTop:6, paddingTop:8, borderTop:'1px dashed #F0F4F8' }}>{m.sub}</div>
          </div>
        ))}
      </div>

      {/* Charts Row */}
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:20 }}>
        {/* Line chart */}
        <div style={{ background:'#fff', borderRadius:16, padding:'22px 24px', boxShadow:'0 2px 8px rgba(10,31,68,.06)' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, gap:14, flexWrap:'wrap' }}>
            <div>
              <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'#0A1F44' }}>Atendimentos — Últimos 30 dias</h3>
              <p style={{ margin:'3px 0 0', fontSize:12, color:'#9CA3AF' }}>Sessões realizadas por dia</p>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
              <div>
                <div style={{ fontSize:11, color:'#9CA3AF', fontWeight:600 }}>Total no período</div>
                <div style={{ fontSize:18, fontWeight:800, color:'#0A1F44' }}>{lineTotal} sessões</div>
              </div>
              <span style={{ display:'inline-flex', alignItems:'center', gap:3, padding:'4px 10px', borderRadius:20, fontSize:11, fontWeight:700, background: lineTrend>=0 ? '#F0FDF4' : '#FEF2F2', color: lineTrend>=0 ? '#15803D' : '#B91C1C' }}>
                <Icon name={lineTrend>=0 ? 'TrendingUp' : 'TrendingDown'} size={11} />
                {lineTrend>=0?'+':''}{lineTrend.toFixed(0)}% vs primeira quinzena
              </span>
            </div>
          </div>
          <LineAreaChart data={lineData} color="#FF6B35" height={220} />
        </div>

        {/* Pie chart */}
        <div style={{ background:'#fff', borderRadius:16, padding:'22px 24px', boxShadow:'0 2px 8px rgba(10,31,68,.06)' }}>
          <h3 style={{ margin:'0 0 4px', fontSize:15, fontWeight:700, color:'#0A1F44' }}>Serviços do Mês</h3>
          <p style={{ margin:'0 0 16px', fontSize:12, color:'#9CA3AF' }}>Top 5 mais realizados</p>
          {pieData.length > 0 ? (
            <DonutChart data={pieData} colors={PIE_COLORS} size={150} />
          ) : (
            <EmptyState icon="PieChart" title="Sem dados" message="Nenhum atendimento este mês" />
          )}
        </div>
      </div>

      {/* Bottom Row */}
      <div style={{ display:'grid', gridTemplateColumns:'3fr 2fr', gap:20 }}>
        {/* Upcoming appointments */}
        <div style={{ background:'#fff', borderRadius:16, padding:'22px 24px', boxShadow:'0 2px 8px rgba(10,31,68,.06)' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18 }}>
            <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'#0A1F44' }}>Próximos Atendimentos</h3>
            <Button variant="ghost" size="sm" icon="ArrowRight" onClick={() => onNavigate('agenda')}>Ver agenda</Button>
          </div>
          {upcoming.length === 0 ? (
            <EmptyState icon="CalendarX" title="Nenhum agendamento" message="Sem atendimentos futuros" />
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {upcoming.map(a => {
                const client = UD.getClient(a.clientId);
                const service = UD.getService(a.serviceId);
                const prof = UD.getProfessional(a.professionalId);
                return (
                  <div key={a.id} style={{
                    display:'flex', alignItems:'center', gap:12,
                    padding:'10px 12px', borderRadius:10, background:'#F9FAFB',
                    border:'1px solid #F0F4F8',
                    transition:'background .15s',
                  }}
                    onMouseEnter={e => e.currentTarget.style.background='#F0F4F8'}
                    onMouseLeave={e => e.currentTarget.style.background='#F9FAFB'}
                  >
                    <div style={{
                      width:42, textAlign:'center', flexShrink:0,
                      borderRight:'1px solid #E2E8F0', paddingRight:12,
                    }}>
                      <div style={{ fontSize:16, fontWeight:800, color:'#0A1F44' }}>
                        {UD.formatTime(a.datetime).split(':')[0]}
                      </div>
                      <div style={{ fontSize:11, color:'#9CA3AF' }}>
                        {UD.formatTime(a.datetime).split(':')[1]}
                      </div>
                    </div>
                    <div style={{
                      width:3, height:36, borderRadius:99, flexShrink:0,
                      background: prof?.color || '#FF6B35',
                    }} />
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                        {client?.name}
                      </div>
                      <div style={{ fontSize:11, color:'#6B7280', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                        {service?.name} · {prof?.name}
                      </div>
                    </div>
                    <div style={{ display:'flex', alignItems:'center', gap:8, flexShrink:0 }}>
                      <Badge status={a.status} />
                      <span style={{ fontSize:12, color:'#9CA3AF' }}>
                        {UD.formatDate(a.datetime, 'dd/MM')}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* Top professional ribbon */}
          {topProf && (
            <div style={{ marginTop:14, padding:'12px 14px', borderRadius:10, background:'linear-gradient(90deg, #FFF7ED, #fff)', border:'1px solid #FED7AA', display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:32, height:32, borderRadius:8, background:'#FF6B35', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name="Award" size={16} color="#fff" />
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:11, fontWeight:700, color:'#C2410C', textTransform:'uppercase', letterSpacing:.5 }}>Destaque do mês</div>
                <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{topProf.prof?.name} <span style={{ color:'#9CA3AF', fontWeight:500 }}>· {topProf.sessions} atendimentos</span></div>
              </div>
              <Button variant="ghost" size="sm" icon="ArrowRight" onClick={() => onNavigate('profissionais')}>Ver</Button>
            </div>
          )}
        </div>

        {/* Birthdays */}
        <div style={{ background:'linear-gradient(135deg, #FDF4FF, #fff)', borderRadius:16, padding:'22px 24px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', border:'1px solid #F3E8FF' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:18 }}>
            <div style={{ fontSize:20 }}>🎂</div>
            <div style={{ flex:1 }}>
              <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'#0A1F44' }}>Aniversariantes</h3>
              <p style={{ margin:0, fontSize:11, color:'#9CA3AF' }}>Este mês · {birthdays.length} {birthdays.length === 1 ? 'cliente' : 'clientes'}</p>
            </div>
            {birthdays.length > 0 && (
              <button onClick={() => onNavigate('marketing')} style={{
                padding:'4px 10px', borderRadius:6, border:'1px solid #E9D5FF', background:'#fff',
                fontSize:11, fontWeight:600, color:'#7C3AED', cursor:'pointer',
              }}>Marketing</button>
            )}
          </div>
          {birthdays.length === 0 ? (
            <p style={{ fontSize:13, color:'#9CA3AF', textAlign:'center', padding:'20px 0' }}>Nenhum aniversariante este mês</p>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {birthdays.slice(0,4).map(c => (
                <div key={c.id} style={{
                  display:'flex', alignItems:'center', gap:10,
                  padding:'8px 10px', borderRadius:10, background:'rgba(255,255,255,.7)',
                  border:'1px solid #F3E8FF',
                }}>
                  <Avatar name={c.name} color="#7C3AED" size={32} />
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.name}</div>
                    <div style={{ fontSize:11, color:'#9CA3AF' }}>
                      {UD.formatDate(c.birthdate, 'dd/MM')} · {UD.age(c.birthdate)} anos
                    </div>
                  </div>
                  <button
                    onClick={() => addToast && addToast(`Mensagem de parabéns enviada para ${c.name}! 🎂`, 'success')}
                    style={{
                      padding:'4px 10px', borderRadius:20, fontSize:11, fontWeight:600,
                      background:'#7C3AED', color:'#fff', border:'none', cursor:'pointer',
                      transition:'transform .15s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.transform='scale(1.05)'}
                    onMouseLeave={e => e.currentTarget.style.transform='scale(1)'}
                  >
                    Parabenizar
                  </button>
                </div>
              ))}
              {birthdays.length > 4 && (
                <div style={{ fontSize:11, color:'#7C3AED', textAlign:'center', padding:'4px 0', fontWeight:600 }}>
                  +{birthdays.length - 4} aniversariantes
                </div>
              )}
            </div>
          )}

          {/* Quick stats */}
          <div style={{ marginTop:20, paddingTop:16, borderTop:'1px solid #F3E8FF' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'#7E22CE', marginBottom:10, textTransform:'uppercase', letterSpacing:.5 }}>Destaques do mês</div>
            {[
              { label:'Clientes inativos', value: window.JF.CLIENTS.filter(c => c.lastVisit && UD.daysBetween(c.lastVisit, window.JF.TODAY) > 60).length, color:'#EF4444' },
              { label:'Novos clientes', value: 4, color:'#22C55E' },
              { label:'Taxa de retorno', value: '78%', color:'#0891B2' },
              { label:'Avaliação média', value: '4.8 ★', color:'#D97706' },
            ].map(item => (
              <div key={item.label} style={{ display:'flex', justifyContent:'space-between', padding:'5px 0', fontSize:12 }}>
                <span style={{ color:'#6B7280' }}>{item.label}</span>
                <span style={{ fontWeight:700, color:item.color }}>{item.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Dashboard });
