import { useState, useEffect, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Calendar,
  CalendarDays,
  AlertTriangle,
  Clock,
  Zap,
  RefreshCw,
  XCircle,
  FolderKanban,
  TrendingUp,
  FileText,
  Phone,
  MessageSquare,
  CreditCard,
  Coffee,
  TestTube,
  ArrowUpRight,
  Ticket,
  CheckCircle2,
  Timer,
  Sparkles,
  LayoutDashboard,
  Activity,
  Target,
} from 'lucide-react'

// Types
interface Evento {
  titulo: string
  hora: string
  data?: string
  tipo: 'personal' | 'work'
  link: string
}

interface Tarefa {
  id: number
  name: string
  projeto: string
  dias?: number
  dias_atraso?: number
}

interface Lead {
  id: number
  name: string
  company: string
  source: string
  dias: number
  dias_sem_contacto?: number
}

interface Projeto {
  id: number
  name: string
  cliente: string
  total: number
  concluidas: number
}

interface Cliente360 {
  client_name: string
  desk_project_id: number
  total_invoiced: number
  total_delivered: number
  balance: number
  status: 'credit' | 'debt' | 'ok'
}

interface DashboardData {
  data_formatada: string
  is_monday: boolean
  eventos_hoje: Evento[]
  eventos_semana: Evento[]
  monday_mood: Tarefa[]
  urgente: Tarefa[]
  alta: Tarefa[]
  vencidas: Tarefa[]
  em_testes: Tarefa[]
  esta_semana: Tarefa[]
  tickets: { ticketid: number; subject: string }[]
  proposta: Lead[]
  contactar: Lead[]
  followup: Lead[]
  projectos: Projeto[]
  billing_360: Cliente360[]
  resumo: {
    tarefas: number
    tickets: number
    projectos: number
    leads: number
    horas: number
    horas_pct: number
    pipeline_valor: number
  }
}

// Animation variants
const containerVariants = {
  hidden: { opacity: 0 },
  show: {
    opacity: 1,
    transition: { staggerChildren: 0.06 }
  }
}

const itemVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.95 },
  show: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { type: 'spring' as const, stiffness: 300, damping: 30 }
  }
}

// Sparkline Mini Chart
const Sparkline = ({ data, color }: { data: number[], color: string }) => {
  const max = Math.max(...data)
  const min = Math.min(...data)
  const range = max - min || 1
  const points = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 80}`).join(' ')

  return (
    <svg className="w-20 h-8" viewBox="0 0 100 100" preserveAspectRatio="none">
      <defs>
        <linearGradient id={`grad-${color}`} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={color} stopOpacity="0.3" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <polygon
        fill={`url(#grad-${color})`}
        points={`0,100 ${points} 100,100`}
      />
      <polyline
        fill="none"
        stroke={color}
        strokeWidth="3"
        strokeLinecap="round"
        strokeLinejoin="round"
        points={points}
      />
    </svg>
  )
}

// Hero Stat Card - Big impact numbers
const HeroStat = ({
  icon: Icon,
  label,
  value,
  sub,
  trend,
  sparkData,
  status,
  gradient,
}: {
  icon: React.ElementType
  label: string
  value: string | number
  sub: string
  trend?: string
  sparkData?: number[]
  status?: 'ok' | 'warning' | 'critical'
  gradient: string
}) => {
  const statusGlow = {
    ok: 'shadow-emerald-500/20',
    warning: 'shadow-amber-500/20',
    critical: 'shadow-red-500/20',
  }
  const trendColor = trend?.startsWith('+') ? 'text-emerald-400' : trend?.startsWith('-') ? 'text-red-400' : 'text-zinc-400'

  return (
    <motion.div
      variants={itemVariants}
      whileHover={{ scale: 1.02, y: -4 }}
      className={`relative overflow-hidden rounded-2xl bg-gradient-to-br ${gradient} p-6 border border-white/10 ${status ? statusGlow[status] : ''} shadow-2xl`}
    >
      <div className="absolute -right-8 -top-8 opacity-10">
        <Icon className="w-32 h-32" />
      </div>
      <div className="relative z-10">
        <div className="flex items-start justify-between mb-4">
          <div className="w-12 h-12 rounded-xl bg-white/10 backdrop-blur flex items-center justify-center">
            <Icon className="w-6 h-6 text-white" />
          </div>
          {sparkData && <Sparkline data={sparkData} color="#fff" />}
        </div>
        <div className="text-sm text-white/70 mb-1">{label}</div>
        <div className="flex items-baseline gap-3">
          <span className="text-4xl font-bold text-white tracking-tight">{value}</span>
          {trend && <span className={`text-sm font-medium ${trendColor}`}>{trend}</span>}
        </div>
        <div className="text-sm text-white/50 mt-2">{sub}</div>
      </div>
    </motion.div>
  )
}

// Status Pill
const StatusPill = ({ children, variant }: { children: React.ReactNode; variant: string }) => {
  const styles: Record<string, string> = {
    project: 'bg-blue-500/20 text-blue-300 ring-blue-500/30',
    lead: 'bg-emerald-500/20 text-emerald-300 ring-emerald-500/30',
    followup: 'bg-violet-500/20 text-violet-300 ring-violet-500/30',
    overdue: 'bg-red-500/20 text-red-300 ring-red-500/30',
    testing: 'bg-cyan-500/20 text-cyan-300 ring-cyan-500/30',
    personal: 'bg-violet-500/20 text-violet-300 ring-violet-500/30',
    work: 'bg-amber-500/20 text-amber-300 ring-amber-500/30',
    credit: 'bg-emerald-500/20 text-emerald-300 ring-emerald-500/30',
    debt: 'bg-red-500/20 text-red-300 ring-red-500/30',
    ok: 'bg-amber-500/20 text-amber-300 ring-amber-500/30',
    days: 'bg-zinc-700/50 text-zinc-300 ring-zinc-600/30',
  }
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-semibold ring-1 ring-inset ${styles[variant] || 'bg-zinc-700/50 text-zinc-300'}`}>
      {children}
    </span>
  )
}

// Glass Card with accent
const GlassCard = ({
  title,
  icon: Icon,
  count,
  value,
  accent,
  size = 'normal',
  children,
}: {
  title: string
  icon: React.ElementType
  count?: number
  value?: string
  accent?: 'amber' | 'cyan' | 'violet' | 'emerald' | 'red' | 'blue'
  size?: 'normal' | 'tall' | 'wide'
  children: React.ReactNode
}) => {
  const accentColors = {
    amber: 'from-amber-500/10 border-amber-500/30 hover:border-amber-500/50',
    cyan: 'from-cyan-500/10 border-cyan-500/30 hover:border-cyan-500/50',
    violet: 'from-violet-500/10 border-violet-500/30 hover:border-violet-500/50',
    emerald: 'from-emerald-500/10 border-emerald-500/30 hover:border-emerald-500/50',
    red: 'from-red-500/10 border-red-500/30 hover:border-red-500/50',
    blue: 'from-blue-500/10 border-blue-500/30 hover:border-blue-500/50',
  }
  const sizeClasses = {
    normal: '',
    tall: 'md:row-span-2',
    wide: 'md:col-span-2',
  }

  return (
    <motion.div
      variants={itemVariants}
      whileHover={{ y: -2 }}
      className={`group relative overflow-hidden rounded-2xl bg-gradient-to-br ${accent ? accentColors[accent] : 'from-white/5 border-white/10 hover:border-white/20'} to-transparent backdrop-blur-xl border transition-all duration-300 ${sizeClasses[size]}`}
    >
      {/* Glow effect on hover */}
      <div className={`absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 bg-gradient-to-r ${accent ? `from-${accent}-500/5` : 'from-brand-500/5'} to-transparent`} />

      <div className="relative z-10">
        <div className="flex items-center justify-between px-5 py-4 border-b border-white/5">
          <h3 className="text-sm font-semibold text-white flex items-center gap-2">
            <Icon className={`w-4 h-4 ${accent ? `text-${accent}-400` : 'text-brand-400'}`} />
            {title}
          </h3>
          <div className="flex items-center gap-2">
            {count !== undefined && (
              <span className="px-2.5 py-0.5 rounded-full bg-white/10 text-xs font-semibold text-white/80">
                {count}
              </span>
            )}
            {value && (
              <span className="px-2.5 py-0.5 rounded-full bg-emerald-500/20 text-xs font-bold text-emerald-400">
                {value}
              </span>
            )}
          </div>
        </div>
        <div className="p-3 max-h-[320px] overflow-y-auto space-y-1.5 scrollbar-thin">
          {children}
        </div>
      </div>
    </motion.div>
  )
}

// List Item with hover effect
const ListItem = ({
  href,
  children,
  badges,
}: {
  href: string
  children: React.ReactNode
  badges?: React.ReactNode
}) => (
  <motion.a
    href={href}
    target="_blank"
    rel="noopener noreferrer"
    whileHover={{ x: 4 }}
    className="flex items-start justify-between gap-3 p-3 rounded-xl bg-white/[0.02] hover:bg-white/[0.06] border border-transparent hover:border-white/10 transition-all group cursor-pointer"
  >
    <div className="flex-1 min-w-0">
      <div className="text-sm text-zinc-200 group-hover:text-white transition-colors truncate">
        {children}
      </div>
      {badges && <div className="mt-1.5 flex flex-wrap gap-1.5">{badges}</div>}
    </div>
    <ArrowUpRight className="w-4 h-4 text-zinc-600 group-hover:text-brand-400 transition-colors flex-shrink-0 mt-0.5" />
  </motion.a>
)

// Progress Ring
const ProgressRing = ({ progress, size = 120 }: { progress: number; size?: number }) => {
  const strokeWidth = 8
  const radius = (size - strokeWidth) / 2
  const circumference = radius * 2 * Math.PI
  const offset = circumference - (progress / 100) * circumference

  return (
    <div className="relative" style={{ width: size, height: size }}>
      <svg className="transform -rotate-90" width={size} height={size}>
        <circle
          className="text-white/5"
          strokeWidth={strokeWidth}
          stroke="currentColor"
          fill="transparent"
          r={radius}
          cx={size / 2}
          cy={size / 2}
        />
        <motion.circle
          className="text-brand-500"
          strokeWidth={strokeWidth}
          strokeLinecap="round"
          stroke="currentColor"
          fill="transparent"
          r={radius}
          cx={size / 2}
          cy={size / 2}
          initial={{ strokeDashoffset: circumference }}
          animate={{ strokeDashoffset: offset }}
          transition={{ duration: 1, delay: 0.5, ease: 'easeOut' }}
          style={{ strokeDasharray: circumference }}
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className="text-3xl font-bold text-white">{progress}%</span>
        <span className="text-xs text-zinc-500">completo</span>
      </div>
    </div>
  )
}

// Summary Widget - Bento style
const SummaryWidget = ({ data }: { data: DashboardData['resumo'] }) => (
  <motion.div
    variants={itemVariants}
    className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-brand-500/10 to-violet-500/5 border border-brand-500/20 p-6 md:col-span-2"
  >
    <div className="absolute -right-20 -bottom-20 opacity-5">
      <Target className="w-64 h-64" />
    </div>
    <div className="relative z-10">
      <h3 className="text-lg font-semibold text-white flex items-center gap-2 mb-6">
        <Activity className="w-5 h-5 text-brand-400" />
        Resumo da Semana
      </h3>
      <div className="flex flex-col md:flex-row items-center gap-8">
        <ProgressRing progress={data.horas_pct} />
        <div className="flex-1 grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { label: 'Tarefas', value: data.tarefas, icon: CheckCircle2, color: 'text-brand-400' },
            { label: 'Tickets', value: data.tickets, icon: Ticket, color: 'text-amber-400' },
            { label: 'Projectos', value: data.projectos, icon: FolderKanban, color: 'text-cyan-400' },
            { label: 'Leads', value: data.leads, icon: TrendingUp, color: 'text-emerald-400' },
          ].map((item) => (
            <motion.div
              key={item.label}
              whileHover={{ scale: 1.05 }}
              className="bg-white/5 rounded-xl p-4 text-center border border-white/5"
            >
              <item.icon className={`w-5 h-5 ${item.color} mx-auto mb-2`} />
              <div className={`text-2xl font-bold ${item.color}`}>{item.value}</div>
              <div className="text-xs text-zinc-500">{item.label}</div>
            </motion.div>
          ))}
        </div>
      </div>
      <div className="mt-6 bg-white/5 rounded-xl p-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-zinc-400">Horas trabalhadas</span>
          <span className="text-sm font-medium text-white">{data.horas}h / 40h</span>
        </div>
        <div className="h-2 rounded-full bg-white/10 overflow-hidden">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${data.horas_pct}%` }}
            transition={{ duration: 1, delay: 0.5 }}
            className="h-full rounded-full bg-gradient-to-r from-brand-500 via-violet-500 to-pink-500"
          />
        </div>
      </div>
    </div>
  </motion.div>
)

// Main App
function App() {
  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const fetchData = useCallback(async () => {
    setRefreshing(true)
    try {
      const response = await fetch('/api.php')
      if (!response.ok) throw new Error('Failed to fetch')
      const json = await response.json()
      setData(json)
    } catch {
      setData(getMockData())
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  const getGreeting = () => {
    const hour = new Date().getHours()
    if (hour < 12) return 'Bom dia'
    if (hour < 19) return 'Boa tarde'
    return 'Boa noite'
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-mesh flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center"
        >
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 2, repeat: Infinity, ease: 'linear' }}
            className="w-20 h-20 rounded-2xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center mx-auto mb-6 shadow-lg shadow-brand-500/30"
          >
            <Sparkles className="w-10 h-10 text-white" />
          </motion.div>
          <p className="text-zinc-400 text-lg">A preparar o dashboard...</p>
        </motion.div>
      </div>
    )
  }

  if (!data) return null

  return (
    <div className="min-h-screen bg-mesh">
      <div className="bg-grid min-h-screen">
        {/* Header */}
        <header className="sticky top-0 z-50 border-b border-white/5 bg-[#0a0a0f]/90 backdrop-blur-2xl">
          <div className="max-w-[1800px] mx-auto px-6 lg:px-8 py-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <motion.div
                  whileHover={{ scale: 1.05, rotate: 5 }}
                  className="w-11 h-11 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shadow-lg shadow-brand-500/30"
                >
                  <Zap className="w-6 h-6 text-white" />
                </motion.div>
                <div>
                  <h1 className="text-xl font-bold text-white tracking-tight">Plan EAL</h1>
                  <p className="text-xs text-zinc-500">Descomplicar Dashboard SDK</p>
                </div>
              </div>

              <nav className="hidden md:flex items-center gap-1 bg-white/5 rounded-xl p-1">
                <a href="#" className="px-4 py-2 rounded-lg bg-brand-500 text-white text-sm font-medium flex items-center gap-2">
                  <LayoutDashboard className="w-4 h-4" />
                  Dashboard
                </a>
                <a href="/monitor" className="px-4 py-2 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 text-sm font-medium transition-all flex items-center gap-2">
                  <Activity className="w-4 h-4" />
                  Monitor
                </a>
              </nav>

              <div className="flex items-center gap-3">
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={fetchData}
                  disabled={refreshing}
                  className="p-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 transition-all"
                >
                  <RefreshCw className={`w-5 h-5 text-zinc-400 ${refreshing ? 'animate-spin' : ''}`} />
                </motion.button>
                <div className="w-10 h-10 rounded-full bg-gradient-to-br from-brand-500 to-violet-600 ring-2 ring-white/10" />
              </div>
            </div>
          </div>
        </header>

        {/* Main Content */}
        <main className="max-w-[1800px] mx-auto px-6 lg:px-8 py-8">
          <AnimatePresence mode="wait">
            <motion.div
              key="dashboard"
              variants={containerVariants}
              initial="hidden"
              animate="show"
            >
              {/* Welcome */}
              <motion.div variants={itemVariants} className="mb-8">
                <h2 className="text-3xl font-bold text-white tracking-tight">{getGreeting()}, Emanuel</h2>
                <p className="text-zinc-400 mt-1 flex items-center gap-2">
                  <Calendar className="w-4 h-4" />
                  {data.data_formatada}
                </p>
              </motion.div>

              {/* Hero Stats - Bento Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5 mb-8">
                <HeroStat
                  icon={CheckCircle2}
                  label="Tarefas Pendentes"
                  value={data.resumo.tarefas}
                  sub={`${data.vencidas.length} vencidas · ${data.urgente.length} urgentes`}
                  trend={data.vencidas.length > 0 ? `-${data.vencidas.length}` : undefined}
                  sparkData={[3, 5, 4, 7, 6, 8, data.resumo.tarefas]}
                  status={data.vencidas.length > 0 ? 'critical' : data.urgente.length > 0 ? 'warning' : 'ok'}
                  gradient="from-zinc-800 to-zinc-900"
                />
                <HeroStat
                  icon={Ticket}
                  label="Tickets Abertos"
                  value={data.tickets.length}
                  sub="Suporte pendente"
                  status={data.tickets.length > 0 ? 'warning' : 'ok'}
                  gradient="from-amber-900/30 to-zinc-900"
                />
                <HeroStat
                  icon={TrendingUp}
                  label="Pipeline"
                  value={`${data.resumo.pipeline_valor.toLocaleString('pt-PT')}€`}
                  sub={`${data.resumo.leads} leads activos`}
                  trend="+12%"
                  sparkData={[8000, 9500, 11000, 10500, 12000, 11500, data.resumo.pipeline_valor]}
                  gradient="from-emerald-900/30 to-zinc-900"
                />
                <HeroStat
                  icon={Timer}
                  label="Horas Semana"
                  value={`${data.resumo.horas}h`}
                  sub={`${data.resumo.horas_pct}% do objectivo`}
                  sparkData={[15, 18, 20, 22, 24, 21, data.resumo.horas]}
                  gradient="from-brand-900/30 to-zinc-900"
                />
              </div>

              {/* Cards Grid - Bento Layout */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                {/* Agenda Hoje */}
                {data.eventos_hoje.length > 0 && (
                  <GlassCard title="Agenda Hoje" icon={Calendar} count={data.eventos_hoje.length}>
                    {data.eventos_hoje.map((e, i) => (
                      <ListItem key={i} href={e.link} badges={<StatusPill variant={e.tipo}>{e.hora}</StatusPill>}>
                        {e.titulo}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Restante Semana */}
                {data.eventos_semana.length > 0 && (
                  <GlassCard title="Restante Semana" icon={CalendarDays} count={data.eventos_semana.length}>
                    {data.eventos_semana.map((e, i) => (
                      <ListItem key={i} href={e.link} badges={<StatusPill variant={e.tipo}>{e.data}</StatusPill>}>
                        {e.titulo}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Monday Mood */}
                {data.is_monday && data.monday_mood.length > 0 && (
                  <GlassCard title="Monday Mood" icon={Coffee} count={data.monday_mood.length} accent="amber">
                    {data.monday_mood.map((t) => (
                      <ListItem key={t.id} href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`} badges={<StatusPill variant="project">{t.projeto}</StatusPill>}>
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Vencidas */}
                {data.vencidas.length > 0 && (
                  <GlassCard title="Vencidas" icon={XCircle} count={data.vencidas.length} accent="red">
                    {data.vencidas.map((t) => (
                      <ListItem
                        key={t.id}
                        href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`}
                        badges={
                          <>
                            <StatusPill variant="overdue">-{t.dias_atraso}d</StatusPill>
                            <StatusPill variant="project">{t.projeto}</StatusPill>
                          </>
                        }
                      >
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Urgente */}
                {data.urgente.length > 0 && (
                  <GlassCard title="Urgente" icon={AlertTriangle} count={data.urgente.length} accent="red">
                    {data.urgente.map((t) => (
                      <ListItem key={t.id} href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`} badges={<StatusPill variant="project">{t.projeto}</StatusPill>}>
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Alta Prioridade */}
                {data.alta.length > 0 && (
                  <GlassCard title="Alta Prioridade" icon={ArrowUpRight} count={data.alta.length} size="tall">
                    {data.alta.map((t) => (
                      <ListItem
                        key={t.id}
                        href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`}
                        badges={
                          <>
                            <StatusPill variant="project">{t.projeto}</StatusPill>
                            {t.dias !== undefined && <StatusPill variant="days">{t.dias >= 0 ? '+' : ''}{t.dias}d</StatusPill>}
                          </>
                        }
                      >
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Em Testes */}
                {data.em_testes.length > 0 && (
                  <GlassCard title="Em Testes" icon={TestTube} count={data.em_testes.length} accent="cyan">
                    {data.em_testes.map((t) => (
                      <ListItem key={t.id} href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`} badges={<StatusPill variant="project">{t.projeto}</StatusPill>}>
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Esta Semana */}
                {data.esta_semana.length > 0 && (
                  <GlassCard title="Esta Semana" icon={Clock} count={data.esta_semana.length}>
                    {data.esta_semana.map((t) => (
                      <ListItem
                        key={t.id}
                        href={`https://desk.descomplicar.pt/admin/tasks/view/${t.id}`}
                        badges={
                          <>
                            <StatusPill variant="project">{t.projeto}</StatusPill>
                            <StatusPill variant="days">+{t.dias}d</StatusPill>
                          </>
                        }
                      >
                        {t.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Fazer Proposta */}
                {data.proposta.length > 0 && (
                  <GlassCard title="Fazer Proposta" icon={FileText} count={data.proposta.length}>
                    {data.proposta.map((l) => (
                      <ListItem
                        key={l.id}
                        href={`https://desk.descomplicar.pt/admin/leads/index/${l.id}`}
                        badges={
                          <>
                            <StatusPill variant="lead">{l.source}</StatusPill>
                            <StatusPill variant="days">{l.dias}d</StatusPill>
                          </>
                        }
                      >
                        {l.company || l.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Contactar */}
                {data.contactar.length > 0 && (
                  <GlassCard title="Contactar" icon={Phone} count={data.contactar.length} accent="emerald">
                    {data.contactar.map((l) => (
                      <ListItem
                        key={l.id}
                        href={`https://desk.descomplicar.pt/admin/leads/index/${l.id}`}
                        badges={
                          <>
                            <StatusPill variant="lead">{l.source}</StatusPill>
                            <StatusPill variant="days">{l.dias}d</StatusPill>
                          </>
                        }
                      >
                        {l.company || l.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* FollowUp */}
                {data.followup.length > 0 && (
                  <GlassCard title="FollowUp" icon={MessageSquare} count={data.followup.length} accent="violet">
                    {data.followup.map((l) => (
                      <ListItem
                        key={l.id}
                        href={`https://desk.descomplicar.pt/admin/leads/index/${l.id}`}
                        badges={
                          <>
                            <StatusPill variant="followup">{l.dias_sem_contacto}d sem contacto</StatusPill>
                            <StatusPill variant="lead">{l.source}</StatusPill>
                          </>
                        }
                      >
                        {l.company || l.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Projectos Activos */}
                {data.projectos.length > 0 && (
                  <GlassCard title="Projectos Activos" icon={FolderKanban} count={data.projectos.length} accent="blue">
                    {data.projectos.map((p) => (
                      <ListItem
                        key={p.id}
                        href={`https://desk.descomplicar.pt/admin/projects/view/${p.id}`}
                        badges={
                          <>
                            <StatusPill variant="project">{p.cliente}</StatusPill>
                            <StatusPill variant="days">{p.concluidas}/{p.total}</StatusPill>
                          </>
                        }
                      >
                        {p.name}
                      </ListItem>
                    ))}
                  </GlassCard>
                )}

                {/* Clientes 360 */}
                {data.billing_360.length > 0 && (
                  <GlassCard title="Clientes 360" icon={CreditCard} count={data.billing_360.length} accent="violet">
                    {data.billing_360.map((b) => (
                      <motion.a
                        key={b.desk_project_id}
                        href={`https://desk.descomplicar.pt/admin/projects/view/${b.desk_project_id}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        whileHover={{ x: 4 }}
                        className="block p-3 rounded-xl bg-white/[0.02] hover:bg-white/[0.06] border border-transparent hover:border-white/10 transition-all"
                      >
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-white">{b.client_name}</span>
                          <StatusPill variant={b.status}>
                            {b.balance > 0 ? '+' : ''}{b.balance}h
                          </StatusPill>
                        </div>
                        <div className="text-xs text-zinc-500 mt-1.5">
                          Fact: {b.total_invoiced}h · Entregue: {b.total_delivered}h
                        </div>
                      </motion.a>
                    ))}
                  </GlassCard>
                )}

                {/* Summary Widget */}
                <SummaryWidget data={data.resumo} />
              </div>
            </motion.div>
          </AnimatePresence>
        </main>

        {/* Footer */}
        <footer className="border-t border-white/5 mt-12">
          <div className="max-w-[1800px] mx-auto px-6 lg:px-8 py-6">
            <div className="flex items-center justify-between text-sm text-zinc-500">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span>Plan EAL v3.0</span>
                <span className="text-zinc-700">·</span>
                <span>SDK Dashboard</span>
              </div>
              <span>Actualizado: {new Date().toLocaleString('pt-PT')}</span>
            </div>
          </div>
        </footer>
      </div>
    </div>
  )
}

// Mock data
function getMockData(): DashboardData {
  return {
    data_formatada: 'Segunda-feira, 3 de Fevereiro',
    is_monday: true,
    eventos_hoje: [
      { titulo: 'Buscar Tomás', hora: '12:55', tipo: 'personal', link: '#' },
      { titulo: 'Reunião Carstuff', hora: '15:00', tipo: 'work', link: '#' },
    ],
    eventos_semana: [
      { titulo: 'Entrega projecto SolarFV', data: 'Qua 05', hora: '10:00', tipo: 'work', link: '#' },
      { titulo: 'Buscar Tomás', data: 'Sex 07', hora: '13:30', tipo: 'personal', link: '#' },
    ],
    monday_mood: [
      { id: 100, name: 'Revisão semanal de métricas', projeto: 'DES 360º' },
      { id: 101, name: 'Planeamento sprint Q1', projeto: 'DES Stack Workflow' },
    ],
    urgente: [],
    alta: [
      { id: 1, name: 'Sistema métricas - tráfego e conversões', projeto: 'CTF Carstuff 360º', dias: 2 },
      { id: 2, name: 'Sistema métricas - tráfego e conversões', projeto: 'SFV 360º', dias: 2 },
      { id: 3, name: 'SDK MCP - Biblioteca de Desenvolvimento MCP', projeto: 'DES Stack Workflow', dias: 5 },
      { id: 4, name: 'Skill /sdk - Gestão de SDKs e PDCA', projeto: 'DES Stack Workflow', dias: 5 },
      { id: 5, name: 'Sistema de Gestão de Informação Descomplicar', projeto: 'DES Stack Workflow', dias: 7 },
      { id: 6, name: 'SDK Dashboard - Biblioteca de Componentes', projeto: 'DES Stack Workflow', dias: 7 },
    ],
    vencidas: [
      { id: 7, name: 'Implementar plugin Catálogos PDF', projeto: 'CTF Carstuff 360º', dias_atraso: 3 },
    ],
    em_testes: [
      { id: 8, name: 'Decisão reCAPTCHA - reactivar ou manter honeypot', projeto: 'CTF Carstuff 360º' },
      { id: 9, name: 'MCP Gateway - HTTP Streamable Proxy', projeto: 'DES Stack Workflow' },
      { id: 10, name: 'MCP Gateway', projeto: 'DES Stack Workflow' },
    ],
    esta_semana: [
      { id: 11, name: 'Mapeamento de Dados', projeto: 'CTF Carstuff 360º', dias: 3 },
    ],
    tickets: [],
    proposta: [
      { id: 1, name: 'MegaSport', company: 'MegaSport Travel', source: 'Mail Mkt', dias: 71 },
    ],
    contactar: [
      { id: 2, name: 'DSI', company: 'DSI Credito DS Seguros', source: 'Google', dias: 6 },
      { id: 3, name: 'Century', company: 'CENTURY 21 Via', source: 'Google', dias: 6 },
      { id: 4, name: 'Rui', company: 'Rui Marques', source: 'Google', dias: 12 },
      { id: 5, name: 'Entreescolha', company: 'Entreescolha', source: 'Google', dias: 12 },
    ],
    followup: [
      { id: 7, name: 'Grupo Criativo', company: 'Grupo Criativo', source: 'Google', dias: 12, dias_sem_contacto: 1 },
      { id: 8, name: 'Casa Aleixo', company: 'Casa Aleixo Lda', source: 'Mail Mkt', dias: 15, dias_sem_contacto: 1 },
      { id: 9, name: 'Hidraulicentro', company: 'Hidraulicentro, Lda', source: 'Mail Mkt', dias: 20, dias_sem_contacto: 1 },
    ],
    projectos: [
      { id: 1, name: 'DES 360º', cliente: 'DES - Marketing', total: 115, concluidas: 99 },
      { id: 2, name: 'DES Stack Workflow', cliente: 'DES - Inovação', total: 225, concluidas: 55 },
      { id: 3, name: 'SFV 360º', cliente: 'Solar FV', total: 19, concluidas: 10 },
      { id: 4, name: 'CTF Carstuff 360º', cliente: 'CTF Carstuff', total: 21, concluidas: 5 },
    ],
    billing_360: [
      { client_name: 'Carstuff', desk_project_id: 67, total_invoiced: 150, total_delivered: 133.1, balance: 16.9, status: 'credit' },
      { client_name: 'SolarFV', desk_project_id: 68, total_invoiced: 120, total_delivered: 72.4, balance: 47.6, status: 'credit' },
    ],
    resumo: {
      tarefas: 7,
      tickets: 0,
      projectos: 4,
      leads: 8,
      horas: 22.8,
      horas_pct: 57,
      pipeline_valor: 12842,
    },
  }
}

export default App
