'use client';

import Link from 'next/link';
import { motion } from 'framer-motion';
import { Star, Clock, Sparkles, ArrowRight, Trophy, Flame, Coins, Play, Target } from 'lucide-react';
import AppHeader from './AppHeader';
import BottomNav from './BottomNav';
import Mascot from '../Mascot';
import type { MascotSkin } from '@/lib/skins';
import { bn } from '@/lib/bn';

export interface SubjectCardData {
  id: string;
  name: string;
  emoji: string;
  accent: 'mango' | 'leaf' | 'sun';
  description: string;
  hasMatchGame: boolean;
  totalStars: number;
  lessonsCompleted: number;
  totalLevels: number;
  progressPct: number;
}

const ACCENT: Record<string, { bg: string; bar: string; text: string; chip: string }> = {
  mango: { bg: 'bg-mango-50', bar: 'bg-mango-500', text: 'text-mango-700', chip: 'bg-mango-100' },
  leaf: { bg: 'bg-leaf-50', bar: 'bg-leaf-500', text: 'text-leaf-700', chip: 'bg-leaf-100' },
  sun: { bg: 'bg-sun-50', bar: 'bg-sun-600', text: 'text-sun-600', chip: 'bg-sun-100' },
};

export default function HomeShell({
  subjects,
  totalStars,
  coins,
  streak,
  secondsToday,
  dailyLimitMinutes,
  skin,
}: {
  subjects: SubjectCardData[];
  totalStars: number;
  coins: number;
  streak: number;
  secondsToday: number;
  dailyLimitMinutes: number | null;
  skin?: MascotSkin;
}) {
  const limitReached = dailyLimitMinutes != null && secondsToday >= dailyLimitMinutes * 60;
  const minutesToday = Math.round(secondsToday / 60);
  const totalLevelsDone = subjects.reduce((n, s) => n + s.lessonsCompleted, 0);
  // A subject worth continuing: started but not finished (fall back to first).
  const continueSubject =
    subjects.find((s) => s.progressPct > 0 && s.progressPct < 100) ?? subjects[0];

  return (
    <div className="min-h-dvh pb-28 lg:pb-0 lg:pl-24">
      <AppHeader stars={totalStars} coins={coins} streak={streak} skin={skin} />

      <main className="mx-auto max-w-3xl space-y-10 px-4 pb-16 pt-8 sm:space-y-12 sm:px-6 sm:pb-20 sm:pt-10">
        {limitReached ? (
          <TimeUpScreen />
        ) : (
          <>
            {/* greeting */}
            <motion.div
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              className="rounded-3xl bg-gradient-to-br from-leaf-50 to-sun-50 p-7 sm:p-9"
            >
              <h1 className="font-heading text-2xl font-extrabold text-ink sm:text-3xl">
                আজ কী শিখবে?
              </h1>
              <p className="mt-2 text-sm text-ink-soft sm:text-base">
                একটা বিষয় বেছে নাও আর খেলতে খেলতে শিখে ফেলো ✨
              </p>
            </motion.div>

            {/* stats summary */}
            <section aria-label="আজকের অবস্থা">
              <div className="grid grid-cols-2 gap-4 sm:grid-cols-4 sm:gap-5">
                <StatCard icon={Clock} bg="bg-leaf-50" fg="text-leaf-600" value={`${bn(minutesToday)}`} unit="মিনিট" label="আজ পড়েছ" delay={0} />
                <StatCard icon={Flame} bg="bg-mango-50" fg="text-mango-600" value={bn(streak)} unit="দিন" label="স্ট্রিক" delay={0.05} filled />
                <StatCard icon={Coins} bg="bg-sun-50" fg="text-sun-600" value={bn(coins)} label="কয়েন" delay={0.1} />
                <StatCard icon={Star} bg="bg-mango-50" fg="text-sun-600" value={bn(totalStars)} label="স্টার" delay={0.15} filled />
              </div>
            </section>

            {/* continue + daily challenge */}
            <section className="grid gap-5 sm:grid-cols-2">
              {continueSubject && continueSubject.progressPct > 0 && continueSubject.progressPct < 100 ? (
                <ContinueCard subject={continueSubject} />
              ) : (
                <StartCard first={subjects[0]} />
              )}
              <Link
                href="/app/daily"
                className="flex items-center gap-4 rounded-3xl bg-gradient-to-br from-sun-500 to-sun-600 p-6 text-white shadow-pop transition active:scale-[0.99]"
              >
                <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-white/25">
                  <Trophy className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h3 className="font-heading text-lg font-extrabold">আজকের চ্যালেঞ্জ</h3>
                  <p className="text-sm text-sun-50">৫টা প্রশ্ন, জিতলে বোনাস কয়েন!</p>
                </div>
                <ArrowRight className="h-6 w-6" />
              </Link>
            </section>

            {/* subjects */}
            <section aria-label="বিষয়সমূহ">
              <div className="mb-4 flex items-center justify-between">
                <h2 className="font-heading text-xl font-extrabold text-ink">বিষয়সমূহ</h2>
                <span className="text-sm font-semibold text-ink-faint">
                  {bn(totalLevelsDone)} লেভেল শেষ
                </span>
              </div>
              <div className="grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
                {subjects.map((s, i) => (
                  <SubjectCard key={s.id} subject={s} index={i} />
                ))}
              </div>
            </section>

            <AiHubBanner />

            {subjects.length === 0 && (
              <p className="mt-10 text-center text-ink-soft">
                সব বিষয় এখন বন্ধ আছে। Parent Zone থেকে চালু করো।
              </p>
            )}
          </>
        )}
      </main>

      <BottomNav />
    </div>
  );
}

function StatCard({
  icon: Icon,
  bg,
  fg,
  value,
  unit,
  label,
  delay,
  filled,
}: {
  icon: typeof Clock;
  bg: string;
  fg: string;
  value: string;
  unit?: string;
  label: string;
  delay: number;
  filled?: boolean;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay }}
      className={`rounded-3xl ${bg} p-5 shadow-card`}
    >
      <Icon className={`h-6 w-6 ${fg} ${filled ? 'fill-current' : ''}`} />
      <p className="mt-3 font-heading text-2xl font-extrabold leading-none text-ink">
        {value}
        {unit && <span className="ml-1 text-sm font-bold text-ink-soft">{unit}</span>}
      </p>
      <p className="mt-1.5 text-xs text-ink-soft">{label}</p>
    </motion.div>
  );
}

function ContinueCard({ subject }: { subject: SubjectCardData }) {
  const a = ACCENT[subject.accent];
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
      <Link
        href={`/app/subject/${subject.id}`}
        className="flex items-center gap-4 rounded-3xl bg-white p-6 shadow-card transition active:scale-[0.99]"
      >
        <div className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl ${a.chip} text-2xl`}>
          {subject.emoji}
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-xs font-semibold text-ink-faint">চালিয়ে যাও</p>
          <h3 className="truncate font-heading text-lg font-bold text-ink">{subject.name}</h3>
          <div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-cream-200">
            <div className={`h-full rounded-full ${a.bar}`} style={{ width: `${subject.progressPct}%` }} />
          </div>
        </div>
        <span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full ${a.bar} text-white`}>
          <Play className="h-5 w-5 fill-white" />
        </span>
      </Link>
    </motion.div>
  );
}

function StartCard({ first }: { first?: SubjectCardData }) {
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
      <Link
        href={first ? `/app/subject/${first.id}` : '/app'}
        className="flex items-center gap-4 rounded-3xl bg-white p-6 shadow-card transition active:scale-[0.99]"
      >
        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-leaf-100 text-leaf-600">
          <Target className="h-6 w-6" />
        </div>
        <div className="flex-1">
          <p className="text-xs font-semibold text-ink-faint">শুরু করো</p>
          <h3 className="font-heading text-lg font-bold text-ink">প্রথম লেসন খেলো</h3>
        </div>
        <ArrowRight className="h-5 w-5 text-ink-soft" />
      </Link>
    </motion.div>
  );
}

function SubjectCard({ subject, index }: { subject: SubjectCardData; index: number }) {
  const a = ACCENT[subject.accent];
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.92 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ delay: index * 0.05 }}
      whileHover={{ scale: 1.03 }}
      whileTap={{ scale: 0.97 }}
    >
      <Link
        href={`/app/subject/${subject.id}`}
        className={`block h-full rounded-3xl ${a.bg} p-6 shadow-card transition`}
      >
        <div
          className={`mb-4 flex h-14 w-14 items-center justify-center rounded-2xl ${a.chip} text-3xl`}
          aria-hidden
        >
          {subject.emoji}
        </div>
        <h3 className="font-heading text-lg font-bold text-ink">{subject.name}</h3>
        <p className="mt-1 line-clamp-2 text-xs text-ink-soft">{subject.description}</p>

        <div className="mt-5">
          <div className="mb-1.5 flex items-center justify-between text-xs font-semibold">
            <span className="text-ink-soft">
              {bn(subject.lessonsCompleted)}/{bn(subject.totalLevels)} লেভেল
            </span>
            <span className="flex items-center gap-0.5 text-sun-600">
              <Star className="h-3.5 w-3.5 fill-sun-500 text-sun-500" />
              {bn(subject.totalStars)}
            </span>
          </div>
          <div className="h-2.5 w-full overflow-hidden rounded-full bg-white/70">
            <motion.div
              className={`h-full rounded-full ${a.bar}`}
              initial={{ width: 0 }}
              animate={{ width: `${subject.progressPct}%` }}
              transition={{ duration: 0.6, delay: 0.1 + index * 0.05 }}
            />
          </div>
          <p className={`mt-1.5 text-xs font-bold ${a.text}`}>{bn(subject.progressPct)}% শেষ</p>
        </div>
      </Link>
    </motion.div>
  );
}

function AiHubBanner() {
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
      <Link
        href="/app/ai"
        className="flex items-center gap-4 rounded-3xl bg-gradient-to-br from-mango-500 to-mango-600 p-7 text-white shadow-pop transition active:scale-[0.99]"
      >
        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-white/20">
          <Sparkles className="h-6 w-6" />
        </div>
        <div className="flex-1">
          <h3 className="font-heading text-lg font-extrabold">AI বন্ধু তারা</h3>
          <p className="text-sm text-mango-50">গল্প শোনো, প্রশ্ন করো, প্র্যাকটিস করো</p>
        </div>
        <ArrowRight className="h-6 w-6" />
      </Link>
    </motion.div>
  );
}

function TimeUpScreen() {
  return (
    <div className="flex flex-col items-center justify-center rounded-3xl bg-mango-50 px-6 py-14 text-center">
      <Mascot mood="idle" size={120} />
      <div className="mt-4 flex items-center gap-2 rounded-full bg-mango-100 px-4 py-1.5 text-sm font-semibold text-mango-700">
        <Clock className="h-4 w-4" />
        আজকের সময় শেষ
      </div>
      <h2 className="mt-4 font-heading text-2xl font-extrabold text-ink">
        আজকের জন্য সময় শেষ, কাল আবার এসো!
      </h2>
      <p className="mt-2 max-w-sm text-sm text-ink-soft">
        তুমি আজ অনেক শিখেছ। এখন একটু বিশ্রাম নাও, চোখকেও বিশ্রাম দাও। কালকে আবার নতুন
        মজার লেসন অপেক্ষা করছে! 🌙
      </p>
    </div>
  );
}
