"use client";

import Link from "next/link";
import Image from "next/image";
import { motion } from "framer-motion";
import { useConfigDoc } from "@/hooks/useConfigDoc";
import { useCollection } from "@/hooks/useCollection";
import { COLLECTIONS, CONFIG_DOCS } from "@/lib/firestore-paths";
import { defaultHero, defaultHome } from "@/lib/defaults";
import { resolveHeroLawImageUrl, resolveVisionLawImageUrl } from "@/lib/law-images";
import { sampleExpertise } from "@/lib/sample-expertise";
import type { ExpertiseArea, HeroContent, HomeContent } from "@/types/models";
import { ButtonLink } from "@/components/ui/ButtonLink";
import { FadeIn } from "@/components/motion/FadeIn";
import { ExpertiseIcon } from "@/components/icons/ExpertiseIcon";
import { ArrowRight, Star } from "lucide-react";
import { publicImageSrc } from "@/lib/public-image";
import { useApprovedTestimonials } from "@/hooks/useApprovedTestimonials";

function StarRow({ count }: { count: number }) {
  const n = Math.min(5, Math.max(1, Math.round(count)));
  return (
    <div className="flex gap-0.5 text-[var(--gold)]">
      {Array.from({ length: n }).map((_, i) => (
        <Star key={i} className="h-4 w-4 fill-[var(--gold)] text-[var(--gold)]" />
      ))}
    </div>
  );
}

export function HomeView() {
  const { data: hero } = useConfigDoc<HeroContent>(
    COLLECTIONS.config,
    CONFIG_DOCS.hero,
    defaultHero
  );
  const { data: home } = useConfigDoc<HomeContent>(
    COLLECTIONS.config,
    CONFIG_DOCS.home,
    defaultHome
  );
  const {
    items: approvedTestimonials,
    loading: testimonialsLoading,
    error: testimonialsError,
  } = useApprovedTestimonials(3);
  const { items: expertiseRaw } = useCollection<ExpertiseArea>(
    COLLECTIONS.expertise,
    "order",
    "asc"
  );
  const expertise =
    expertiseRaw.length > 0
      ? [...expertiseRaw].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
      : sampleExpertise;

  const visionTitle = home.visionTitle ?? defaultHome.visionTitle;
  const visionBody = home.visionBody ?? defaultHome.visionBody;
  const visionQuote = home.visionQuote ?? defaultHome.visionQuote;
  const heroBadge = hero.badge ?? defaultHero.badge;
  const heroBgSrc = publicImageSrc(resolveHeroLawImageUrl(hero.heroImageUrl));
  const visionImageSrc = publicImageSrc(resolveVisionLawImageUrl(home.visionImageUrl));

  const expertiseShow = expertise.slice(0, 5);

  return (
    <>
      {/* —— Hero —— */}
      <section className="relative min-h-[min(92vh,880px)] overflow-hidden">
        {heroBgSrc ? (
          <Image
            src={heroBgSrc}
            alt=""
            fill
            priority
            className="object-cover object-center"
            sizes="100vw"
            unoptimized={!heroBgSrc.includes("unsplash.com")}
          />
        ) : (
          <div className="absolute inset-0 bg-gradient-to-br from-[#0b1630] via-[#0f1f44] to-[#152a45]" />
        )}
        <div className="absolute inset-0 bg-gradient-to-r from-[#0a1228]/95 via-[#0f1f44]/80 to-[#0f1f44]/35" />
        <div className="absolute inset-0 bg-gradient-to-t from-[#070b14]/90 via-transparent to-[#070b14]/20" />

        <div className="relative mx-auto flex min-h-[min(92vh,880px)] max-w-6xl flex-col justify-center px-4 pb-20 pt-28 sm:px-6 lg:px-8 lg:pb-24 lg:pt-32">
          <motion.div
            initial={{ opacity: 0, y: 28 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.75, ease: [0.22, 1, 0.36, 1] }}
            className="max-w-2xl"
          >
            <span className="inline-block rounded-full border border-[var(--gold)]/50 bg-[var(--gold)]/10 px-4 py-1.5 text-[11px] font-semibold uppercase tracking-[0.22em] text-[var(--gold)] backdrop-blur-sm">
              {heroBadge}
            </span>
            <h1 className="mt-6 font-[family-name:var(--font-display)] text-[clamp(2.25rem,5vw,3.75rem)] font-semibold leading-[1.05] tracking-tight text-white">
              {hero.lawyerName}
            </h1>
            <p className="mt-4 font-[family-name:var(--font-display)] text-[clamp(1.25rem,2.5vw,1.75rem)] font-medium leading-snug text-[var(--gold)]">
              {hero.slogan}
            </p>
            <p className="mt-6 max-w-xl text-base leading-relaxed text-white/85 sm:text-lg">
              {hero.shortDescription}
            </p>
            <div className="mt-10 flex flex-wrap gap-4">
              <ButtonLink href="/iletisim" variant="navySolid">
                {hero.ctaLabel}
              </ButtonLink>
              <ButtonLink href="/uzmanlik-alanlari" variant="goldOutline">
                Uzmanlıklar
              </ButtonLink>
            </div>
          </motion.div>
        </div>
      </section>

      {/* —— İstatistikler —— */}
      <section className="border-b border-black/[0.06] bg-white py-14 sm:py-16">
        <div className="mx-auto grid max-w-6xl grid-cols-2 gap-8 px-4 sm:grid-cols-4 sm:gap-6 sm:px-6 lg:px-8">
          {home.stats.map((s, i) => (
            <FadeIn key={s.id} delay={i * 0.06}>
              <div className="text-center sm:text-left">
                <p className="font-[family-name:var(--font-display)] text-4xl font-semibold tracking-tight text-[var(--navy)] sm:text-5xl">
                  {s.value}
                </p>
                <p className="mt-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-[var(--muted)]">
                  {s.label}
                </p>
              </div>
            </FadeIn>
          ))}
        </div>
      </section>

      {/* —— Vizyon / yaklaşım —— */}
      <section className="bg-white py-16 sm:py-20 lg:py-24">
        <div className="mx-auto grid max-w-6xl items-center gap-12 px-4 sm:px-6 lg:grid-cols-2 lg:gap-16 lg:px-8">
          <FadeIn>
            <div className="relative mx-auto aspect-[4/5] max-w-md overflow-hidden rounded-2xl bg-[#0f1f44] shadow-[0_24px_60px_-20px_rgba(15,31,68,0.4)] ring-1 ring-black/[0.06] lg:mx-0">
              <Image
                src={visionImageSrc}
                alt="Hukuk ve adalet temalı görsel"
                fill
                className="object-cover object-center"
                sizes="(min-width: 1024px) 480px, 90vw"
                unoptimized={!visionImageSrc.includes("unsplash.com")}
              />
              <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-[#0a1228]/75 via-[#0f1f44]/15 to-transparent" />
              <div className="absolute bottom-5 right-5 left-5 sm:left-auto sm:max-w-[280px]">
                <div className="rounded-xl border border-white/40 bg-white/90 px-5 py-4 shadow-lg backdrop-blur-md">
                  <p className="text-sm font-medium leading-relaxed text-[var(--navy)]">{visionQuote}</p>
                </div>
              </div>
            </div>
          </FadeIn>
          <FadeIn delay={0.08}>
            <h2 className="font-[family-name:var(--font-display)] text-3xl font-semibold tracking-tight text-[var(--navy)] sm:text-4xl">
              {visionTitle}
            </h2>
            <div className="mt-6 space-y-4 text-[15px] leading-relaxed text-[var(--muted)]">
              {visionBody.split(/\n\n+/).map((para, idx) => (
                <p key={idx}>{para}</p>
              ))}
            </div>
            <Link
              href="/hakkimda"
              className="mt-8 inline-flex items-center gap-2 text-sm font-semibold text-[var(--navy)] transition hover:gap-3"
            >
              Daha fazla bilgi
              <ArrowRight className="h-4 w-4 text-[var(--gold-dark)]" />
            </Link>
          </FadeIn>
        </div>
      </section>

      {/* —— Uzmanlık alanları —— */}
      <section className="bg-[#eef0f5] py-16 sm:py-20 lg:py-24">
        <div className="mx-auto max-w-6xl px-4 sm:px-6 lg:px-8">
          <FadeIn>
            <div className="mx-auto max-w-2xl text-center">
              <p className="text-xs font-semibold uppercase tracking-[0.22em] text-[var(--gold-dark)]">
                Çalışma alanları
              </p>
              <h2 className="mt-3 font-[family-name:var(--font-display)] text-3xl font-semibold text-[var(--navy)] sm:text-4xl">
                Uzmanlık alanlarımız
              </h2>
              <p className="mt-4 text-sm leading-relaxed text-[var(--muted)] sm:text-base">
                Her alanda güncel mevzuat, sağlam dokümantasyon ve net iletişim ile ilerliyorum.
              </p>
            </div>
          </FadeIn>

          <div className="mt-12 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
            {expertiseShow.map((area, i) => (
              <FadeIn key={area.id} delay={i * 0.05}>
                <Link href="/uzmanlik-alanlari" className="group block h-full">
                  <article className="flex h-full flex-col rounded-2xl border border-black/[0.06] bg-white p-6 shadow-[0_12px_40px_-24px_rgba(15,31,68,0.35)] transition duration-300 hover:-translate-y-1 hover:shadow-[0_20px_50px_-24px_rgba(15,31,68,0.45)]">
                    <ExpertiseIcon
                      name={area.iconKey}
                      className="h-8 w-8 text-[var(--gold)]"
                    />
                    <h3 className="mt-5 font-[family-name:var(--font-display)] text-xl font-semibold text-[var(--navy)]">
                      {area.title}
                    </h3>
                    <p className="mt-2 flex-1 text-sm leading-relaxed text-[var(--muted)]">
                      {area.description}
                    </p>
                    <span className="mt-6 inline-flex items-center gap-1 text-xs font-bold uppercase tracking-wide text-[var(--gold-dark)]">
                      İncele
                      <ArrowRight className="h-3.5 w-3.5 transition group-hover:translate-x-0.5" />
                    </span>
                  </article>
                </Link>
              </FadeIn>
            ))}

            <FadeIn delay={0.2}>
              <div className="flex h-full min-h-[240px] flex-col justify-center rounded-2xl border border-[var(--navy)]/15 bg-[var(--navy)] p-8 text-center text-white shadow-[0_20px_50px_-20px_rgba(15,31,68,0.5)]">
                <p className="font-[family-name:var(--font-display)] text-xl font-semibold sm:text-2xl">
                  Diğer tüm alanlar
                </p>
                <p className="mt-2 text-sm text-white/70">
                  Tüm uzmanlık başlıkları ve detaylar için sayfayı ziyaret edin.
                </p>
                <div className="mt-8">
                  <ButtonLink
                    href="/uzmanlik-alanlari"
                    variant="secondary"
                    className="!bg-white !text-[var(--navy)] shadow-sm hover:!bg-white/90"
                  >
                    Tümünü gör
                  </ButtonLink>
                </div>
              </div>
            </FadeIn>
          </div>
        </div>
      </section>

      {/* —— Müvekkil yorumları —— */}
      <section className="bg-[var(--navy)] py-16 sm:py-20 lg:py-24">
        <div className="mx-auto max-w-6xl px-4 sm:px-6 lg:px-8">
          <FadeIn>
            <div className="mx-auto max-w-2xl text-center">
              <div className="mx-auto h-px w-12 bg-[var(--gold)]" />
              <h2 className="mt-5 font-[family-name:var(--font-display)] text-3xl font-semibold text-white sm:text-4xl">
                Müvekkil yorumları
              </h2>
              <p className="mt-3 text-sm text-white/65">
                Yayınlanan yorumlar yönetici onayından geçer. Deneyiminizi{" "}
                <Link
                  href="/bizi-degerlendirin"
                  className="font-semibold text-[var(--gold)] underline-offset-2 hover:underline"
                >
                  buradan
                </Link>{" "}
                iletebilirsiniz.
              </p>
            </div>
          </FadeIn>

          <div className="mt-12 grid gap-6 md:grid-cols-3">
            {testimonialsLoading ? (
              <p className="col-span-full text-center text-sm text-white/60">Yükleniyor…</p>
            ) : testimonialsError ? (
              <p className="col-span-full text-center text-sm text-amber-200/90">{testimonialsError}</p>
            ) : approvedTestimonials.length === 0 ? (
              <p className="col-span-full text-center text-sm text-white/60">
                Henüz yayınlanmış yorum yok. Onaylandığında burada listelenir.
              </p>
            ) : (
              approvedTestimonials.map((t, i) => (
                <FadeIn key={t.id} delay={i * 0.08}>
                  <article className="flex h-full flex-col rounded-2xl border border-white/10 bg-white/[0.08] p-6 shadow-xl backdrop-blur-md">
                    <StarRow count={t.rating ?? 5} />
                    <p className="mt-5 flex-1 text-sm leading-relaxed text-white/90">
                      &ldquo;{t.quote}&rdquo;
                    </p>
                    <div className="mt-6 flex items-center gap-3 border-t border-white/10 pt-5">
                      {t.imageUrl ? (
                        <div className="relative h-11 w-11 shrink-0 overflow-hidden rounded-full border border-white/20">
                          <Image src={publicImageSrc(t.imageUrl)} alt="" fill className="object-cover" unoptimized />
                        </div>
                      ) : (
                        <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[var(--gold)]/20 text-sm font-bold text-[var(--gold)]">
                          {t.name.charAt(0)}
                        </div>
                      )}
                      <div>
                        <p className="text-sm font-semibold text-[var(--gold)]">{t.name}</p>
                        <p className="text-xs text-white/60">{t.role}</p>
                      </div>
                    </div>
                  </article>
                </FadeIn>
              ))
            )}
          </div>
        </div>
      </section>
    </>
  );
}
