import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { prisma } from "@/lib/prisma";
import { AnimatedSection } from "@/components/animated-section";
import { SiteHeader } from "@/components/site-header";
import { BackToTop } from "@/components/back-to-top";
import { HomeHero } from "@/components/home-hero";
import { HomeHeroSparkles } from "@/components/home-hero-sparkles";
import { SiteFooter } from "@/components/site-footer";
import { JsonLd } from "@/components/json-ld";
import { getHomeEnergySettings } from "@/lib/home-energy";
import { getHomeFortunesSettings } from "@/lib/home-fortunes";
import { absoluteUrl, SITE_DESCRIPTION, SITE_NAME } from "@/lib/site";
import {
  formatFortunePeriod,
  fortunePublicPath,
  getLatestDailyFortune,
  getLatestMonthlyFortune,
} from "@/lib/fortunes";

function maskPhone(phone: string): string {
  if (phone.length < 7) return "کاربر";
  return `${phone.slice(0, 4)}***${phone.slice(-3)}`;
}

export default async function HomePage() {
  const [latestPosts, readingTestimonials, homeEnergy, homeFortunes, dailyFortune, monthlyFortune] =
    await Promise.all([
      prisma.blogPost.findMany({
        where: { status: "PUBLISHED" },
        orderBy: { publishedAt: "desc" },
        take: 4,
        include: { category: { select: { nameFa: true } } },
      }),
      prisma.comment.findMany({
        where: { status: "APPROVED", readingId: { not: null } },
        orderBy: { createdAt: "desc" },
        take: 6,
        include: { user: { select: { phone: true } } },
      }),
      getHomeEnergySettings(),
      getHomeFortunesSettings(),
      getLatestDailyFortune(),
      getLatestMonthlyFortune(),
    ]);

  return (
    <div className="min-h-screen flex flex-col">
      <JsonLd
        data={{
          "@context": "https://schema.org",
          "@graph": [
            {
              "@type": "WebSite",
              name: SITE_NAME,
              description: SITE_DESCRIPTION,
              url: absoluteUrl("/"),
              inLanguage: "fa-IR",
            },
            {
              "@type": "Organization",
              name: SITE_NAME,
              url: absoluteUrl("/"),
              logo: absoluteUrl("/logo.PNG"),
            },
          ],
        }}
      />
      <section
        id="home-hero"
        className="relative min-h-screen bg-[url('/bg.png')] bg-cover bg-top bg-no-repeat"
      >
        <HomeHeroSparkles />
        <SiteHeader homeSticky />
        <HomeHero energy={homeEnergy} />
      </section>

      <main className="flex-1 bg-background">
        {/* How it works */}
        <AnimatedSection delay={0.15}>
          <section className="py-20 section-alt">
            <div className="container mx-auto px-4">
              <h2 className="text-2xl md:text-3xl font-bold text-center mb-4 text-foreground">
                نحوه کار
              </h2>
              <p className="text-muted-foreground text-center mb-14 max-w-lg mx-auto">
                سه گام ساده تا دریافت تفسیر فال شما
              </p>
              <div className="grid md:grid-cols-3 gap-8 max-w-4xl mx-auto">
                <Card className="card-hover border-primary/10 hover:border-primary/20">
                  <CardContent className="pt-8 pb-8 text-center">
                    <span className="inline-flex size-14 items-center justify-center rounded-full bg-primary/10 text-primary text-2xl font-bold">
                      ۱
                    </span>
                    <h3 className="font-semibold mt-5 text-lg">انتخاب نوع فال</h3>
                    <p className="text-sm text-muted-foreground mt-2 leading-relaxed">
                      فال ۷ کارته (تک نیت)، ۱۸ کارته (احساسی) یا ۴۸ کارته (کلی) را انتخاب کنید.
                    </p>
                  </CardContent>
                </Card>
                <Card className="card-hover border-primary/10 hover:border-primary/20">
                  <CardContent className="pt-8 pb-8 text-center">
                    <span className="inline-flex size-14 items-center justify-center rounded-full bg-primary/10 text-primary text-2xl font-bold">
                      ۲
                    </span>
                    <h3 className="font-semibold mt-5 text-lg">برگزیدن کارت‌ها</h3>
                    <p className="text-sm text-muted-foreground mt-2 leading-relaxed">
                      از میان کارت‌های تاروت، کارت‌های خود را برگزینید.
                    </p>
                  </CardContent>
                </Card>
                <Card className="card-hover border-primary/10 hover:border-primary/20">
                  <CardContent className="pt-8 pb-8 text-center">
                    <span className="inline-flex size-14 items-center justify-center rounded-full bg-primary/10 text-primary text-2xl font-bold">
                      ۳
                    </span>
                    <h3 className="font-semibold mt-5 text-lg">دریافت نتیجه</h3>
                    <p className="text-sm text-muted-foreground mt-2 leading-relaxed">
                      پس از پرداخت، تفسیر و راهنمایی را ببینید.
                    </p>
                  </CardContent>
                </Card>
              </div>
            </div>
          </section>
        </AnimatedSection>

        {/* Testimonials */}
        <AnimatedSection delay={0.25}>
          <section className="py-20 border-t border-border/60">
            <div className="container mx-auto px-4">
              <h2 className="text-2xl md:text-3xl font-bold text-center mb-4 text-foreground">
                نظرات کاربران
              </h2>
              <p className="text-muted-foreground text-center mb-14 max-w-lg mx-auto">
                تجربه کاربران از فال‌های خود
              </p>
              {readingTestimonials.length === 0 ? (
                <p className="text-center text-muted-foreground max-w-md mx-auto py-8">
                  نظرات تأییدشده کاربران درباره فال‌هایشان اینجا نمایش داده می‌شود.
                </p>
              ) : (
                <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-5xl mx-auto">
                  {readingTestimonials.map((comment) => (
                    <Card key={comment.id} className="card-hover">
                      <CardContent className="pt-6 pb-6">
                        <p className="text-foreground/90 italic whitespace-pre-wrap line-clamp-4 leading-relaxed border-r-4 border-primary/30 pr-3">
                          {comment.content}
                        </p>
                        <p className="text-sm mt-4 font-medium text-muted-foreground">
                          —{" "}
                          {comment.user.phone ? (
                            <bdi dir="ltr" className="tabular-nums">
                              {maskPhone(comment.user.phone)}
                            </bdi>
                          ) : (
                            "کاربر"
                          )}
                        </p>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          </section>
        </AnimatedSection>

        {/* Daily & monthly fortunes */}
        <AnimatedSection delay={0.3}>
          <section className="py-20 border-t border-border/60">
            <div className="container mx-auto px-4">
              <h2 className="text-2xl md:text-3xl font-bold text-center mb-4 text-foreground">
                {homeFortunes.sectionTitle}
              </h2>
              <p className="text-muted-foreground text-center mb-14 max-w-lg mx-auto">
                {homeFortunes.sectionSubtitle}
              </p>
              {!dailyFortune && !monthlyFortune ? (
                <p className="text-center text-muted-foreground py-8">
                  هنوز فال روزانه یا ماهانه‌ای منتشر نشده است.
                </p>
              ) : (
                <div className="grid md:grid-cols-2 gap-8 max-w-4xl mx-auto">
                  {dailyFortune ? (
                    <Link
                      href={fortunePublicPath(dailyFortune)}
                      className="group block"
                    >
                      <Card className="h-full card-hover border-primary/10 group-hover:border-primary/25">
                        <CardContent className="p-6">
                          <p className="text-xs text-primary font-medium mb-2">فال روزانه</p>
                          <p className="text-sm text-muted-foreground mb-3">
                            {formatFortunePeriod(dailyFortune)}
                          </p>
                          <h3 className="font-semibold text-lg text-foreground group-hover:text-primary transition-colors">
                            {dailyFortune.titleFa}
                          </h3>
                          <p className="text-sm text-muted-foreground line-clamp-3 mt-3 leading-relaxed">
                            {dailyFortune.excerptFa}
                          </p>
                        </CardContent>
                      </Card>
                    </Link>
                  ) : (
                    <Card className="h-full border-dashed">
                      <CardContent className="p-6 text-center text-muted-foreground">
                        هنوز فال روزانه‌ای منتشر نشده است.
                      </CardContent>
                    </Card>
                  )}
                  {monthlyFortune ? (
                    <Link
                      href={fortunePublicPath(monthlyFortune)}
                      className="group block"
                    >
                      <Card className="h-full card-hover border-primary/10 group-hover:border-primary/25">
                        <CardContent className="p-6">
                          <p className="text-xs text-primary font-medium mb-2">فال ماهانه</p>
                          <p className="text-sm text-muted-foreground mb-3">
                            {formatFortunePeriod(monthlyFortune)}
                          </p>
                          <h3 className="font-semibold text-lg text-foreground group-hover:text-primary transition-colors">
                            {monthlyFortune.titleFa}
                          </h3>
                          <p className="text-sm text-muted-foreground line-clamp-3 mt-3 leading-relaxed">
                            {monthlyFortune.excerptFa}
                          </p>
                        </CardContent>
                      </Card>
                    </Link>
                  ) : (
                    <Card className="h-full border-dashed">
                      <CardContent className="p-6 text-center text-muted-foreground">
                        هنوز فال ماهانه‌ای منتشر نشده است.
                      </CardContent>
                    </Card>
                  )}
                </div>
              )}
              <div className="flex justify-center gap-6 mt-10 text-sm">
                <Link
                  href="/fortune/daily"
                  className="text-primary font-medium hover:underline underline-offset-4"
                >
                  آرشیو فال روزانه
                </Link>
                <Link
                  href="/fortune/monthly"
                  className="text-primary font-medium hover:underline underline-offset-4"
                >
                  آرشیو فال ماهانه
                </Link>
              </div>
            </div>
          </section>
        </AnimatedSection>

        {/* Latest blog */}
        <AnimatedSection delay={0.35}>
          <section className="py-20 section-alt">
            <div className="container mx-auto px-4">
              <h2 className="text-2xl md:text-3xl font-bold text-center mb-4 text-foreground">
                آخرین مطالب وبلاگ
              </h2>
              <p className="text-muted-foreground text-center mb-14 max-w-lg mx-auto">
                مقالات و مطالب مرتبط با فال و تاروت
              </p>
              {latestPosts.length === 0 ? (
                <p className="text-center text-muted-foreground py-8">
                  هنوز مطلبی منتشر نشده است.
                </p>
              ) : (
                <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-5xl mx-auto">
                  {latestPosts.map((post) => (
                    <Link key={post.id} href={`/blog/${post.slug}`} className="group block">
                      <Card className="h-full card-hover border-primary/5 group-hover:border-primary/20">
                        <CardContent className="p-5">
                          <p className="text-xs text-primary font-medium mb-2">
                            {post.category.nameFa}
                          </p>
                          <h3 className="font-semibold text-foreground group-hover:text-primary transition-colors">
                            {post.titleFa}
                          </h3>
                          <p className="text-sm text-muted-foreground line-clamp-2 mt-2 leading-relaxed">
                            {post.excerptFa}
                          </p>
                        </CardContent>
                      </Card>
                    </Link>
                  ))}
                </div>
              )}
              {latestPosts.length > 0 && (
                <p className="text-center mt-10">
                  <Link
                    href="/blog"
                    className="text-primary font-medium hover:underline underline-offset-4"
                  >
                    همه مطالب
                  </Link>
                </p>
              )}
            </div>
          </section>
        </AnimatedSection>
      </main>

      <BackToTop />
      <SiteFooter />
    </div>
  );
}
