import { motion } from 'framer-motion'
import { useNavigate } from 'react-router-dom'
import {
  Briefcase,
  Target,
  FileText,
  TrendingUp,
  ArrowRight,
  Sparkles,
  Link2,
  Building2,
  MapPin,
  Eye,
  X,
  Bookmark,
  BookmarkCheck,
  RefreshCw,
  CalendarDays,
  BarChart3,
  Send,
  Zap,
  CheckCircle2,
} from 'lucide-react'
import { useAuth } from '@/hooks/useAuth'
import { usePageTitle } from '@/hooks/usePageTitle'
import { InviteButton } from '@/components/InviteButton'
import { ProfileCompletionBanner } from '@/components/ProfileCompletionBanner'
import { useDashboardStats } from '@/hooks/useDashboardStats'
import { useMatches } from '@/hooks/useMatches'
import { scoreColor, formatDate, truncate, companyColor } from '@/lib/utils'
import type { Match } from '@/hooks/useMatches'
import { useState, useEffect, useCallback } from 'react'
import { supabase } from '@/lib/supabase'
import { CountUp } from '@/components/CountUp'
import { useProfile, computeCompletion } from '@/hooks/useProfile'
import { Confetti } from '@/components/Confetti'
import { TipOfTheDay } from '@/components/TipOfTheDay'
import { WeeklyDigest } from '@/components/dashboard/WeeklyDigest'
import { ActivityFeed } from '@/components/dashboard/ActivityFeed'
import { UpcomingDeadlines } from '@/components/dashboard/UpcomingDeadlines'
import { PersonalizedGreeting } from '@/components/dashboard/PersonalizedGreeting'
import { StreakCounter } from '@/components/dashboard/StreakCounter'
import { MarketInsights } from '@/components/dashboard/MarketInsights'
import { QuickActionFAB } from '@/components/dashboard/QuickActionFAB'
import { Achievements } from '@/components/dashboard/Achievements'
import { WeeklyGoals } from '@/components/dashboard/WeeklyGoals'
import { OnboardingTour } from '@/components/OnboardingTour'
import { MatchReasons } from '@/components/jobs/MatchReasons'
import { CardErrorBoundary } from '@/components/ErrorBoundary'

// ─── Smart Recommendations Hook ────────────────────────────────────

interface RecommendedJob {
  id: string
  title: string
  company: string | null
  company_logo_url: string | null
  location: string | null
  skills_required: string[]
  source_url: string | null
  matchingSkills: string[]
}

function useSmartRecommendations() {
  const { user } = useAuth()
  const { profile } = useProfile()
  const [jobs, setJobs] = useState<RecommendedJob[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!user || !profile) {
      setLoading(false)
      return
    }

    // No skills = no skill-based recommendations
    if (profile.skills.length === 0) {
      setLoading(false)
      return
    }

    async function fetchRecommendations() {
      // Use Supabase overlaps operator to find listings where skills_required overlaps with profile skills
      const { data } = await supabase
        .from('listings')
        .select('id, title, company, company_logo_url, location, skills_required, source_url')
        .overlaps('skills_required', profile!.skills)
        .order('created_at', { ascending: false })
        .limit(20)

      if (!data || data.length === 0) {
        setLoading(false)
        return
      }

      // Filter out listings user already has applications for
      const { data: existingApps } = await supabase
        .from('applications')
        .select('listing_id')
        .eq('profile_id', user!.id)

      const appliedIds = new Set((existingApps ?? []).map((a) => a.listing_id))
      const userSkillsLower = new Set(profile!.skills.map((s) => s.toLowerCase()))

      // Score by number of matching skills and filter out already-applied
      const scored = data
        .filter((listing) => !appliedIds.has(listing.id))
        .map((listing) => {
          const skills = listing.skills_required ?? []
          const matchingSkills = skills.filter((s: string) =>
            userSkillsLower.has(s.toLowerCase())
          )
          return {
            ...listing,
            skills_required: skills,
            matchingSkills,
          }
        })
        .sort((a, b) => b.matchingSkills.length - a.matchingSkills.length)
        .slice(0, 3)

      setJobs(scored)
      setLoading(false)
    }

    fetchRecommendations()
  }, [user, profile])

  return { jobs, loading, hasSkills: (profile?.skills ?? []).length > 0 }
}

// ─── Types ──────────────────────────────────────────────────────────

interface RecentApplication {
  id: string
  status: string
  created_at: string
  applied_at: string | null
  listing: {
    title: string
    company: string | null
  } | null
}

// ─── Status Badge Config ────────────────────────────────────────────

const STATUS_COLORS: Record<string, { bg: string; text: string }> = {
  saved: { bg: 'var(--color-bg-elevated)', text: 'var(--color-text-muted)' },
  preparing: { bg: 'var(--color-bg-elevated)', text: 'var(--color-text-muted)' },
  applied: { bg: 'var(--color-bg-elevated)', text: 'var(--color-text-secondary)' },
  interview: { bg: 'var(--color-bg-elevated)', text: 'var(--color-text-primary)' },
  offer: { bg: '#22C55E', text: 'var(--color-bg-primary)' },
  accepted: { bg: '#22C55E', text: 'var(--color-bg-primary)' },
  rejected: { bg: 'var(--color-error)', text: 'white' },
}

// ─── Score Badge Component ──────────────────────────────────────────

function ScoreBadge({ score }: { score: number }) {
  const color = scoreColor(score)
  return (
    <span
      className="badge font-bold text-xs"
      style={{
        background: `${color}18`,
        color,
        border: `1px solid ${color}30`,
      }}
    >
      {score}%
    </span>
  )
}

// ─── Status Badge Component ─────────────────────────────────────────

function StatusBadge({ status }: { status: string }) {
  const colors = STATUS_COLORS[status] ?? STATUS_COLORS.saved
  return (
    <span
      className="badge text-[10px] font-medium capitalize"
      style={{
        background: `${colors.bg}`,
        color: colors.text,
      }}
    >
      {status}
    </span>
  )
}

// ─── Match Card Component ───────────────────────────────────────────

function MatchCard({
  match,
  index,
  onDismiss,
  onToggleSaved,
  onMarkSeen,
}: {
  match: Match
  index: number
  onDismiss: (id: string) => void
  onToggleSaved: (id: string) => void
  onMarkSeen: (id: string) => void
}) {
  const listing = match.listing

  // Mark as seen on mount (must be above early return to avoid conditional hook call)
  useEffect(() => {
    if (!match.seen) {
      onMarkSeen(match.id)
    }
    // Only run on mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  if (!listing) return null

  return (
    <motion.div
      className="flex items-center gap-3 p-3 rounded-lg hover:bg-[var(--color-bg-elevated)] transition-colors group"
      initial={{ opacity: 0, x: -10 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ delay: index * 0.06 }}
    >
      {/* Company icon */}
      <div className="w-9 h-9 rounded-lg bg-[var(--color-bg-elevated)] border border-[var(--color-border)] flex items-center justify-center shrink-0">
        {listing.company_logo_url ? (
          <img
            src={listing.company_logo_url}
            alt={listing.company ?? ''}
            className="w-full h-full object-cover rounded-lg"
            loading="lazy"
          />
        ) : (
          <Building2 size={16} className="text-[var(--color-text-muted)]" />
        )}
      </div>

      {/* Job info */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <h4 className="text-sm font-medium truncate">{truncate(listing.title, 32)}</h4>
          {!match.seen && (
            <span className="w-1.5 h-1.5 rounded-full bg-[var(--color-text-primary)] shrink-0" />
          )}
        </div>
        <div className="flex items-center gap-2 text-[10px] text-[var(--color-text-muted)] mt-0.5">
          {listing.company && <span>{listing.company}</span>}
          {listing.location && (
            <>
              <span aria-hidden="true">-</span>
              <span className="flex items-center gap-0.5">
                <MapPin size={9} />
                {truncate(listing.location, 16)}
              </span>
            </>
          )}
        </div>
      </div>

      {/* Score + actions */}
      <div className="flex items-center gap-2 shrink-0">
        <ScoreBadge score={match.score} />
        <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
          <button
            onClick={() => onToggleSaved(match.id)}
            className="p-1 rounded hover:bg-[var(--color-bg-card)] transition-colors"
            aria-label={match.saved ? 'Unsave match' : 'Save match'}
            title={match.saved ? 'Unsave' : 'Save'}
          >
            {match.saved ? (
              <BookmarkCheck size={13} className="text-[var(--color-text-primary)]" />
            ) : (
              <Bookmark size={13} className="text-[var(--color-text-muted)]" />
            )}
          </button>
          <button
            onClick={() => onDismiss(match.id)}
            className="p-1 rounded hover:bg-[var(--color-bg-card)] transition-colors"
            aria-label="Dismiss match"
            title="Dismiss"
          >
            <X size={13} className="text-[var(--color-text-muted)]" />
          </button>
        </div>
      </div>
    </motion.div>
  )
}

// ─── Weekly Activity Summary Hook ───────────────────────────────────

interface WeeklyActivity {
  jobsViewed: number
  applicationsSent: number
  aiDocsGenerated: number
  linkedinScoreChange: number
}

function useWeeklyActivity() {
  const { user } = useAuth()
  const [activity, setActivity] = useState<WeeklyActivity>({
    jobsViewed: 0,
    applicationsSent: 0,
    aiDocsGenerated: 0,
    linkedinScoreChange: 0,
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!user) {
      setLoading(false)
      return
    }

    async function fetchWeeklyActivity() {
      const now = new Date()
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      const weekAgoISO = weekAgo.toISOString()

      const [matchesRes, appsRes, genRes, profileRes] = await Promise.all([
        // Jobs viewed (matches marked as seen) this week
        supabase
          .from('matches')
          .select('id', { count: 'exact', head: true })
          .eq('profile_id', user!.id)
          .eq('seen', true)
          .gte('created_at', weekAgoISO),

        // Applications with status changes this week
        supabase
          .from('applications')
          .select('id', { count: 'exact', head: true })
          .eq('profile_id', user!.id)
          .gte('updated_at', weekAgoISO)
          .neq('status', 'saved'),

        // AI generations this week
        supabase
          .from('ai_generations')
          .select('id', { count: 'exact', head: true })
          .eq('profile_id', user!.id)
          .gte('created_at', weekAgoISO),

        // Current LinkedIn score (we compare to 0 for change display)
        supabase
          .from('profiles')
          .select('linkedin_score')
          .eq('id', user!.id)
          .maybeSingle(),
      ])

      // For LinkedIn score change, check the last two audits
      let scoreChange = 0
      const { data: audits } = await supabase
        .from('linkedin_audits')
        .select('overall_score, created_at')
        .eq('profile_id', user!.id)
        .order('created_at', { ascending: false })
        .limit(2)

      if (audits && audits.length >= 2) {
        const latest = audits[0].overall_score
        const previous = audits[1].overall_score
        const previousDate = new Date(audits[1].created_at)
        // Only count change if previous audit was within the last 14 days
        if (previousDate.getTime() > now.getTime() - 14 * 24 * 60 * 60 * 1000) {
          scoreChange = latest - previous
        }
      }

      setActivity({
        jobsViewed: matchesRes.count ?? 0,
        applicationsSent: appsRes.count ?? 0,
        aiDocsGenerated: genRes.count ?? 0,
        linkedinScoreChange: scoreChange,
      })
      setLoading(false)
    }

    fetchWeeklyActivity()
  }, [user])

  return { activity, loading }
}

// ─── Recent Applications Hook ───────────────────────────────────────

function useRecentApplications() {
  const { user } = useAuth()
  const [applications, setApplications] = useState<RecentApplication[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!user) {
      setLoading(false)
      return
    }

    async function fetchApps() {
      const { data } = await supabase
        .from('applications')
        .select(`
          id, status, created_at, applied_at,
          listing:listings (title, company)
        `)
        .eq('profile_id', user!.id)
        .order('updated_at', { ascending: false })
        .limit(5)

      setApplications((data as RecentApplication[]) ?? [])
      setLoading(false)
    }

    fetchApps()
  }, [user])

  return { applications, loading }
}

// ─── Dashboard Page ─────────────────────────────────────────────────

export default function Dashboard() {
  usePageTitle('Dashboard', 'Your Launchrly dashboard — track applications, view AI matches, monitor your job search progress, and unlock achievements.')
  const { user } = useAuth()
  const navigate = useNavigate()
  const { stats, loading: statsLoading } = useDashboardStats()
  const {
    topMatches,
    loading: matchesLoading,
    computing,
    unseenCount,
    dismissMatch,
    toggleSaved,
    markSeen,
    computeMatches,
  } = useMatches()
  const { applications: recentApps, loading: appsLoading } = useRecentApplications()
  const { activity: weeklyActivity, loading: weeklyLoading } = useWeeklyActivity()
  const { jobs: recommendedJobs, loading: recsLoading, hasSkills } = useSmartRecommendations()

  const { profile: dashProfile } = useProfile()
  const profileCompletion = computeCompletion(dashProfile)
  const [showConfetti, setShowConfetti] = useState(false)

  // Confetti on first 100% profile completion
  useEffect(() => {
    if (profileCompletion >= 100) {
      const key = 'launchrly_profile_complete_celebrated'
      if (!localStorage.getItem(key)) {
        localStorage.setItem(key, '1')
        setShowConfetti(true)
      }
    }
  }, [profileCompletion])

  // "Top X% of active users" — deterministic based on stats
  const topPercent = stats.applicationCount > 20 ? 5
    : stats.applicationCount > 10 ? 15
    : stats.applicationCount > 5 ? 30
    : stats.applicationCount > 2 ? 50
    : null

  const name = user?.user_metadata?.full_name?.split(' ')[0] || 'there'

  const statCards = [
    {
      label: 'Matched Jobs',
      value: statsLoading ? '...' : String(stats.matchCount),
      icon: Target,
      color: 'var(--color-text-secondary)',
      badge: unseenCount > 0 ? `${unseenCount} new` : undefined,
    },
    {
      label: 'Applications',
      value: statsLoading ? '...' : String(stats.applicationCount),
      icon: Briefcase,
      color: 'var(--color-text-secondary)',
      badge: stats.responseRate > 0 ? `${stats.responseRate}% rate` : undefined,
    },
    {
      label: 'AI Generations',
      value: statsLoading ? '...' : String(stats.aiGenerationCount),
      icon: FileText,
      color: 'var(--color-text-secondary)',
    },
    {
      label: 'LinkedIn Score',
      value: statsLoading ? '...' : stats.linkedinScore > 0 ? `${stats.linkedinScore}` : '--',
      icon: TrendingUp,
      color: 'var(--color-text-secondary)',
      badge: stats.linkedinScore >= 80 ? 'Strong' : stats.linkedinScore >= 50 ? 'Good' : undefined,
    },
  ]

  const handleRefreshMatches = useCallback(async () => {
    await computeMatches()
  }, [computeMatches])

  // Stagger entrance animation for dashboard sections
  const sectionVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: (i: number) => ({
      opacity: 1,
      y: 0,
      transition: { delay: i * 0.08, duration: 0.4, ease: 'easeOut' },
    }),
  }

  return (
    <div className="space-y-8">
      {/* Confetti celebration for 100% profile completion */}
      {showConfetti && <Confetti onComplete={() => setShowConfetti(false)} />}

      {/* Top X% active users badge */}
      {topPercent !== null && !statsLoading && (
        <motion.div
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[var(--color-bg-secondary)] border border-[var(--color-border)]"
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <Zap size={16} className="text-[var(--color-text-secondary)]" />
          <span className="text-sm">
            You&apos;re in the <strong className="text-[var(--color-text-primary)]">top {topPercent}%</strong> of active users
          </span>
        </motion.div>
      )}

      {/* Personalized Greeting */}
      <motion.div
        custom={0}
        initial="hidden"
        animate="visible"
        variants={sectionVariants}
      >
        <CardErrorBoundary name="Greeting">
          <PersonalizedGreeting />
        </CardErrorBoundary>
      </motion.div>

      {/* Streak Counter */}
      <CardErrorBoundary name="Streak Counter">
        <StreakCounter />
      </CardErrorBoundary>

      {/* Weekly Goals */}
      <CardErrorBoundary name="Weekly Goals">
        <WeeklyGoals />
      </CardErrorBoundary>

      {/* Achievements */}
      <CardErrorBoundary name="Achievements">
        <Achievements />
      </CardErrorBoundary>

      {/* Profile Completion Banner */}
      <CardErrorBoundary name="Profile Completion">
        <ProfileCompletionBanner />
      </CardErrorBoundary>

      {/* Tip of the Day */}
      <CardErrorBoundary name="Tip of the Day">
        <TipOfTheDay />
      </CardErrorBoundary>

      {/* Skill Match Hero Badge */}
      {hasSkills && !recsLoading && recommendedJobs.length > 0 && (
        <motion.div
          className="flex items-center gap-3 px-4 py-3 rounded-xl bg-[#22C55E]/5 border border-[#22C55E]/20"
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          <div className="p-2 rounded-lg bg-[#22C55E]/10">
            <Target size={18} className="text-[#22C55E]" />
          </div>
          <span className="text-sm">
            <strong className="text-[#22C55E]">{stats.matchCount} {stats.matchCount === 1 ? 'job' : 'jobs'}</strong>
            <span className="text-[var(--color-text-secondary)]"> match your skills right now</span>
          </span>
          <button
            onClick={() => navigate('/jobs?sort_by=match_score')}
            className="ml-auto text-xs text-[#22C55E] hover:underline flex items-center gap-1 shrink-0"
          >
            View matches <ArrowRight size={12} />
          </button>
        </motion.div>
      )}

      {/* Stats Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4" aria-live="polite">
        {statCards.map((stat, i) => (
          <motion.div
            key={stat.label}
            className="card-glow p-5"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.1 }}
          >
            {statsLoading ? (
              /* Skeleton while loading */
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="w-10 h-10 rounded-lg bg-[var(--color-bg-elevated)] animate-pulse" />
                  <div className="w-14 h-5 rounded-full bg-[var(--color-bg-elevated)] animate-pulse" />
                </div>
                <div className="w-16 h-7 rounded bg-[var(--color-bg-elevated)] animate-pulse" />
                <div className="w-24 h-3 rounded bg-[var(--color-bg-elevated)] animate-pulse" />
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between mb-3">
                  <div
                    className="p-2 rounded-lg"
                    style={{ background: `${stat.color}15` }}
                  >
                    <stat.icon size={20} style={{ color: stat.color }} />
                  </div>
                  {stat.badge && (
                    <span
                      className="badge text-[10px]"
                      style={{
                        background: `${stat.color}18`,
                        color: stat.color,
                        border: `1px solid ${stat.color}25`,
                      }}
                    >
                      {stat.badge}
                    </span>
                  )}
                </div>
                <div className="text-2xl font-bold">
                  {/^\d+$/.test(stat.value)
                    ? <CountUp end={parseInt(stat.value, 10)} />
                    : stat.value}
                </div>
                <div className="text-xs text-[var(--color-text-muted)] mt-1">{stat.label}</div>
              </>
            )}
          </motion.div>
        ))}
      </div>

      {/* This Week Summary */}
      <motion.div
        className="card-glow p-5"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.35 }}
      >
        <div className="flex items-center gap-2 mb-4">
          <CalendarDays size={18} className="text-[var(--color-text-secondary)]" />
          <h2 className="text-sm font-semibold">This Week</h2>
        </div>
        {weeklyLoading ? (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="space-y-2">
                <div className="h-6 w-12 bg-[var(--color-bg-elevated)] rounded animate-pulse" />
                <div className="h-3 w-20 bg-[var(--color-bg-elevated)] rounded animate-pulse" />
              </div>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div className="flex items-center gap-3">
              <div className="p-1.5 rounded-md bg-[var(--color-bg-elevated)]">
                <Eye size={14} className="text-[var(--color-text-secondary)]" />
              </div>
              <div>
                <div className="text-lg font-bold">{weeklyActivity.jobsViewed}</div>
                <div className="text-[10px] text-[var(--color-text-muted)]">Jobs Viewed</div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-1.5 rounded-md bg-[var(--color-bg-elevated)]">
                <Send size={14} className="text-[var(--color-text-secondary)]" />
              </div>
              <div>
                <div className="text-lg font-bold">{weeklyActivity.applicationsSent}</div>
                <div className="text-[10px] text-[var(--color-text-muted)]">Apps Sent</div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-1.5 rounded-md bg-[var(--color-bg-elevated)]">
                <Zap size={14} className="text-[var(--color-text-secondary)]" />
              </div>
              <div>
                <div className="text-lg font-bold">{weeklyActivity.aiDocsGenerated}</div>
                <div className="text-[10px] text-[var(--color-text-muted)]">AI Docs</div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-1.5 rounded-md bg-[var(--color-bg-elevated)]">
                <BarChart3 size={14} className="text-[var(--color-text-secondary)]" />
              </div>
              <div>
                <div className="text-lg font-bold">
                  {weeklyActivity.linkedinScoreChange > 0
                    ? `+${weeklyActivity.linkedinScoreChange}`
                    : weeklyActivity.linkedinScoreChange === 0
                      ? '--'
                      : String(weeklyActivity.linkedinScoreChange)}
                </div>
                <div className="text-[10px] text-[var(--color-text-muted)]">LI Score</div>
              </div>
            </div>
          </div>
        )}
      </motion.div>

      {/* Recommended for You */}
      <motion.div
        className="card-glow p-6"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.38 }}
      >
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold flex items-center gap-2">
            <Sparkles size={18} className="text-[var(--color-text-secondary)]" />
            Recommended for You
            <span className="badge bg-[var(--color-bg-secondary)] text-[var(--color-text-primary)] border border-[var(--color-border)] text-[10px]">
              NEW
            </span>
          </h2>
          {recommendedJobs.length > 0 && (
            <button
              onClick={() => navigate('/jobs')}
              className="text-xs text-[var(--color-text-secondary)] hover:underline flex items-center gap-1"
            >
              View all jobs <ArrowRight size={12} />
            </button>
          )}
        </div>

        {recsLoading ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="bg-[var(--color-bg-elevated)] rounded-xl p-4 space-y-3">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-[var(--color-bg-card)] animate-pulse" />
                  <div className="flex-1 space-y-1.5">
                    <div className="h-3.5 bg-[var(--color-bg-card)] rounded animate-pulse w-3/4" />
                    <div className="h-2.5 bg-[var(--color-bg-card)] rounded animate-pulse w-1/2" />
                  </div>
                </div>
                <div className="flex gap-1">
                  <div className="h-5 w-14 bg-[var(--color-bg-card)] rounded-full animate-pulse" />
                  <div className="h-5 w-16 bg-[var(--color-bg-card)] rounded-full animate-pulse" />
                </div>
                <div className="h-8 bg-[var(--color-bg-card)] rounded-lg animate-pulse" />
              </div>
            ))}
          </div>
        ) : !hasSkills ? (
          <div className="flex flex-col items-center justify-center py-6 text-center">
            <div className="w-12 h-12 rounded-full bg-[var(--color-bg-elevated)] flex items-center justify-center mx-auto mb-3">
              <Sparkles size={24} className="text-[var(--color-text-secondary)]" />
            </div>
            <h3 className="text-sm font-semibold mb-1">Get personalized recommendations</h3>
            <p className="text-[var(--color-text-muted)] text-xs max-w-[300px] mx-auto">
              Add skills to your profile so we can match you with the best opportunities.
            </p>
            <button
              onClick={() => navigate('/profile')}
              className="btn btn-primary text-xs mt-3"
            >
              Add Skills <ArrowRight size={12} />
            </button>
          </div>
        ) : recommendedJobs.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {recommendedJobs.map((job, i) => (
              <motion.div
                key={job.id}
                className="bg-[var(--color-bg-elevated)] rounded-xl p-4 hover:bg-[var(--color-bg-card)] transition-colors cursor-pointer group"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.4 + i * 0.08 }}
                onClick={() => navigate('/jobs')}
              >
                {/* Company + Title */}
                <div className="flex items-start gap-3 mb-3">
                  <div className="w-10 h-10 rounded-lg bg-[var(--color-bg-card)] border border-[var(--color-border)] flex items-center justify-center shrink-0 overflow-hidden">
                    {job.company_logo_url ? (
                      <img
                        src={job.company_logo_url}
                        alt={job.company || ''}
                        className="w-full h-full object-cover rounded-lg"
                        loading="lazy"
                      />
                    ) : job.company ? (
                      <span
                        className="text-xs font-bold"
                        style={{ color: companyColor(job.company) }}
                      >
                        {job.company.charAt(0).toUpperCase()}
                      </span>
                    ) : (
                      <Building2 size={16} className="text-[var(--color-text-muted)]" />
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    <h4 className="text-sm font-medium leading-tight group-hover:text-[var(--color-text-primary)] transition-colors line-clamp-2">
                      {job.title}
                    </h4>
                    {job.company && (
                      <p className="text-[10px] text-[var(--color-text-muted)] mt-0.5">
                        {job.company}
                        {job.location ? ` - ${truncate(job.location, 20)}` : ''}
                      </p>
                    )}
                  </div>
                </div>

                {/* Matching skills highlighted in green */}
                <div className="flex flex-wrap gap-1 mb-3">
                  {job.matchingSkills.map((skill) => (
                    <span
                      key={skill}
                      className="inline-flex items-center gap-0.5 px-2 py-0.5 rounded-full text-[10px] font-medium"
                      style={{
                        background: 'rgba(0, 255, 170, 0.1)',
                        color: 'var(--color-success)',
                        border: '1px solid rgba(0, 255, 170, 0.2)',
                      }}
                    >
                      <CheckCircle2 size={9} />
                      {skill}
                    </span>
                  ))}
                  {job.skills_required
                    .filter((s) => !job.matchingSkills.map((m) => m.toLowerCase()).includes(s.toLowerCase()))
                    .slice(0, 2)
                    .map((skill) => (
                      <span
                        key={skill}
                        className="px-2 py-0.5 rounded-full text-[10px] text-[var(--color-text-muted)] bg-[var(--color-bg-card)]"
                      >
                        {skill}
                      </span>
                    ))}
                </div>

                {/* Match Reasons */}
                <MatchReasons
                  matchingSkills={job.matchingSkills}
                  location={job.location}
                  userLocations={dashProfile?.locations}
                  userRemoteOk={dashProfile?.remote_ok}
                  userDegreeLevel={dashProfile?.degree_level}
                />

                {/* Apply button */}
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    if (job.source_url) {
                      window.open(job.source_url, '_blank', 'noopener,noreferrer')
                    } else {
                      navigate('/jobs')
                    }
                  }}
                  className="btn btn-primary w-full text-xs py-2"
                >
                  Apply
                  <ArrowRight size={12} />
                </button>
              </motion.div>
            ))}
          </div>
        ) : (
          <div className="text-center py-6">
            <p className="text-xs text-[var(--color-text-muted)]">
              No skill-based matches found yet. New jobs are added regularly.
            </p>
          </div>
        )}
      </motion.div>

      {/* Job Market Insights */}
      <CardErrorBoundary name="Market Insights">
        <MarketInsights />
      </CardErrorBoundary>

      {/* Weekly Digest Preview */}
      <CardErrorBoundary name="Weekly Digest">
        <WeeklyDigest />
      </CardErrorBoundary>

      {/* Upcoming Deadlines */}
      <CardErrorBoundary name="Upcoming Deadlines">
        <UpcomingDeadlines />
      </CardErrorBoundary>

      {/* Activity Feed */}
      <CardErrorBoundary name="Activity Feed">
        <ActivityFeed />
      </CardErrorBoundary>

      {/* Quick Actions */}
      <motion.div
        className="flex flex-wrap gap-3"
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.4 }}
      >
        <button
          onClick={() => navigate('/jobs')}
          className="btn btn-primary text-sm"
        >
          <Target size={16} />
          Browse Jobs
        </button>
        <button
          onClick={() => navigate('/import')}
          className="btn btn-secondary text-sm"
        >
          <Link2 size={16} />
          Import URL
        </button>
        <button
          onClick={() => navigate('/assistant')}
          className="btn btn-secondary text-sm"
        >
          <Sparkles size={16} />
          AI Assistant
        </button>
        <button
          onClick={handleRefreshMatches}
          disabled={computing}
          className="btn btn-ghost text-sm"
          title="Recompute matches based on your latest profile"
        >
          <RefreshCw size={16} className={computing ? 'animate-spin' : ''} />
          {computing ? 'Computing...' : 'Refresh Matches'}
        </button>
        <InviteButton />
      </motion.div>

      {/* Main Content Grid */}
      <div className="grid lg:grid-cols-2 gap-6">
        {/* Top Matches */}
        <motion.div
          className="card-glow p-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
        >
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Target size={18} className="text-[var(--color-text-secondary)]" />
              Top Matches
            </h2>
            {topMatches.length > 0 && (
              <button
                onClick={() => navigate('/jobs?sort_by=match_score')}
                className="text-xs text-[var(--color-text-secondary)] hover:underline flex items-center gap-1"
              >
                View all <ArrowRight size={12} />
              </button>
            )}
          </div>

          {matchesLoading ? (
            <div className="space-y-3">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="flex items-center gap-3 p-3">
                  <div className="w-9 h-9 rounded-lg bg-[var(--color-bg-elevated)] animate-pulse" />
                  <div className="flex-1 space-y-1.5">
                    <div className="h-3.5 bg-[var(--color-bg-elevated)] rounded animate-pulse w-3/4" />
                    <div className="h-2.5 bg-[var(--color-bg-elevated)] rounded animate-pulse w-1/2" />
                  </div>
                  <div className="h-5 w-12 bg-[var(--color-bg-elevated)] rounded-full animate-pulse" />
                </div>
              ))}
            </div>
          ) : topMatches.length > 0 ? (
            <div className="space-y-1">
              {topMatches.map((match, i) => (
                <MatchCard
                  key={match.id}
                  match={match}
                  index={i}
                  onDismiss={dismissMatch}
                  onToggleSaved={toggleSaved}
                  onMarkSeen={markSeen}
                />
              ))}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <div className="w-14 h-14 rounded-full bg-[var(--color-bg-elevated)] flex items-center justify-center mx-auto mb-3">
                <Target size={28} className="text-[var(--color-text-secondary)]" />
              </div>
              <h3 className="text-sm font-semibold mb-1">No matches yet</h3>
              <p className="text-[var(--color-text-muted)] text-xs max-w-[260px] mx-auto">
                Complete your profile with skills and preferences so our AI can find your perfect internship match.
              </p>
              <div className="flex gap-2 mt-4">
                <button
                  onClick={() => navigate('/profile')}
                  className="btn btn-primary text-xs"
                >
                  Complete Your Profile <ArrowRight size={12} />
                </button>
                <button
                  onClick={() => navigate('/jobs')}
                  className="btn btn-ghost text-xs"
                >
                  Browse Jobs
                </button>
              </div>
            </div>
          )}
        </motion.div>

        {/* Recent Applications */}
        <motion.div
          className="card-glow p-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
        >
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Briefcase size={18} className="text-[var(--color-text-secondary)]" />
              Recent Applications
            </h2>
            {recentApps.length > 0 && (
              <button
                onClick={() => navigate('/tracker')}
                className="text-xs text-[var(--color-text-secondary)] hover:underline flex items-center gap-1"
              >
                View all <ArrowRight size={12} />
              </button>
            )}
          </div>

          {appsLoading ? (
            <div className="space-y-3">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="flex items-center gap-3 p-3">
                  <div className="flex-1 space-y-1.5">
                    <div className="h-3.5 bg-[var(--color-bg-elevated)] rounded animate-pulse w-3/4" />
                    <div className="h-2.5 bg-[var(--color-bg-elevated)] rounded animate-pulse w-1/2" />
                  </div>
                  <div className="h-5 w-16 bg-[var(--color-bg-elevated)] rounded-full animate-pulse" />
                </div>
              ))}
            </div>
          ) : recentApps.length > 0 ? (
            <div className="space-y-1">
              {recentApps.map((app, i) => (
                <motion.div
                  key={app.id}
                  className="flex items-center gap-3 p-3 rounded-lg hover:bg-[var(--color-bg-elevated)] transition-colors cursor-pointer"
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: i * 0.06 }}
                  onClick={() => navigate('/tracker')}
                >
                  <div className="flex-1 min-w-0">
                    <h4 className="text-sm font-medium truncate">
                      {app.listing?.title ?? 'Unknown position'}
                    </h4>
                    <div className="flex items-center gap-2 text-[10px] text-[var(--color-text-muted)] mt-0.5">
                      {app.listing?.company && <span>{app.listing.company}</span>}
                      <span aria-hidden="true">-</span>
                      <span>
                        {app.applied_at
                          ? `Applied ${formatDate(app.applied_at)}`
                          : formatDate(app.created_at)}
                      </span>
                    </div>
                  </div>
                  <StatusBadge status={app.status} />
                </motion.div>
              ))}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <div className="w-14 h-14 rounded-full bg-[var(--color-bg-elevated)] flex items-center justify-center mx-auto mb-3">
                <Briefcase size={28} className="text-[var(--color-text-secondary)]" />
              </div>
              <h3 className="text-sm font-semibold mb-1">No applications yet</h3>
              <p className="text-[var(--color-text-muted)] text-xs max-w-[260px] mx-auto">
                Save a job you like to start tracking your application pipeline from saved to accepted.
              </p>
              <div className="flex gap-2 mt-4">
                <button
                  onClick={() => navigate('/jobs')}
                  className="btn btn-primary text-xs"
                >
                  Browse Jobs <ArrowRight size={12} />
                </button>
                <button
                  onClick={() => navigate('/tracker')}
                  className="btn btn-ghost text-xs"
                >
                  Open Tracker
                </button>
              </div>
            </div>
          )}
        </motion.div>
      </div>

      {/* Score Legend */}
      {topMatches.length > 0 && (
        <motion.div
          className="flex items-center gap-4 text-[10px] text-[var(--color-text-muted)]"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.8 }}
        >
          <span className="flex items-center gap-1.5">
            <span
              className="w-2 h-2 rounded-full"
              style={{ background: '#22C55E' }}
            />
            80%+ Excellent
          </span>
          <span className="flex items-center gap-1.5">
            <span
              className="w-2 h-2 rounded-full"
              style={{ background: '#22C55E' }}
            />
            60-79% Good
          </span>
          <span className="flex items-center gap-1.5">
            <span
              className="w-2 h-2 rounded-full"
              style={{ background: 'var(--color-text-secondary)' }}
            />
            40-59% Fair
          </span>
          <span className="flex items-center gap-1.5">
            <span
              className="w-2 h-2 rounded-full"
              style={{ background: 'var(--color-text-muted)' }}
            />
            &lt;40% Low
          </span>
        </motion.div>
      )}

      {/* Mobile Quick Action FAB */}
      <QuickActionFAB />

      {/* Onboarding Tour (first visit only) */}
      <OnboardingTour />
    </div>
  )
}
