import { getPayload } from "payload";
import config from "@payload-config";
import Link from "next/link";
import { StatusTerminal } from "@/components/site/StatusTerminal";
import { GridOverlay } from "@/components/site/GridOverlay";
import { Button } from "@/components/site/Button";
import { TechChip } from "@/components/site/TechChip";
import type { Home, Project } from "@/payload-types";

export const dynamic = "force-dynamic";

const accentTextClass: Record<string, string> = {
  primary: "text-primary",
  secondary: "text-secondary",
  tertiary: "text-tertiary",
};

export default async function HomePage() {
  const payload = await getPayload({ config });
  const home: Home = await payload.findGlobal({ slug: "home", depth: 2 });

  const { hero, principles, featuredProjects, closingCta } = home;

  const resolvedProjects: Project[] = (featuredProjects ?? [])
    .map((fp) => (typeof fp.project === "object" && fp.project !== null ? fp.project : null))
    .filter((p): p is Project => p !== null)
    .slice(0, 3);

  return (
    <main>
      {/* ── Hero ────────────────────────────────────────────────────────── */}
      <section className="hero-gradient relative flex min-h-[92vh] flex-col justify-center overflow-hidden px-6 border-b border-outline-variant/10">
        <GridOverlay size={32} opacity={0.15} />

        <StatusTerminal className="absolute left-6 top-8 md:left-12" />

        <div className="mx-auto w-full max-w-7xl pt-20">
          <div className="grid grid-cols-1 items-center gap-12 lg:grid-cols-12">
            {/* Left — 60% */}
            <div className="lg:col-span-7">
              {hero?.eyebrow && (
                <span className="label-sm mb-6 block text-primary uppercase tracking-[0.4em]">
                  {hero.eyebrow}
                </span>
              )}

              {hero?.headline ? (
                <h1 className="display-lg mb-8 text-on-surface">
                  {hero.headline}
                </h1>
              ) : (
                <h1 className="display-lg mb-8 text-on-surface">
                  I WILL FIND
                  <br />
                  <span className="bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                    A WAY,
                  </span>
                  <br />
                  OR I WILL
                  <br />
                  MAKE ONE.
                </h1>
              )}

              {hero?.subheadline && (
                <p className="body-lg mb-10 max-w-2xl text-on-surface-variant">
                  {hero.subheadline}
                </p>
              )}

              {(hero?.primaryCta?.label || hero?.secondaryCta?.label) && (
                <div className="flex flex-wrap items-center gap-4">
                  {hero.primaryCta?.label && hero.primaryCta?.href && (
                    <Link href={hero.primaryCta.href}>
                      <Button variant="primary">{hero.primaryCta.label}</Button>
                    </Link>
                  )}
                  {hero.secondaryCta?.label && hero.secondaryCta?.href && (
                    <Link href={hero.secondaryCta.href}>
                      <Button variant="secondary">{hero.secondaryCta.label}</Button>
                    </Link>
                  )}
                </div>
              )}
            </div>

            {/* Right — 40% — portrait with dot-grid overlap */}
            <div className="relative hidden lg:col-span-5 lg:block">
              {hero?.heroImage && typeof hero.heroImage === "object" && (hero.heroImage as { url?: string }).url ? (
                <div className="relative">
                  {/* Dot-grid overlap element */}
                  <div
                    className="pointer-events-none absolute -left-8 -top-8 h-32 w-32 opacity-30"
                    style={{
                      backgroundImage:
                        "radial-gradient(rgba(129,236,255,0.5) 1px, transparent 1px)",
                      backgroundSize: "12px 12px",
                    }}
                  />
                  <div className="relative aspect-[3/4] overflow-hidden rounded-md bg-surface-container-highest border border-outline-variant/15">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={(hero.heroImage as { url: string }).url}
                      alt="Jason Woltje"
                      className="h-full w-full object-cover grayscale transition-all duration-700 hover:grayscale-0"
                    />
                  </div>
                  {/* Dot-grid overlap bottom-right */}
                  <div
                    className="pointer-events-none absolute -bottom-8 -right-8 h-32 w-32 opacity-20"
                    style={{
                      backgroundImage:
                        "radial-gradient(rgba(216,115,255,0.5) 1px, transparent 1px)",
                      backgroundSize: "12px 12px",
                    }}
                  />
                </div>
              ) : null}
            </div>
          </div>
        </div>

        {/* Crosshair deco */}
        <div className="absolute bottom-12 right-12 hidden opacity-20 lg:block">
          <div className="relative flex h-32 w-32 items-center justify-center rounded-full border border-primary/40">
            <div className="absolute h-px w-full bg-primary" />
            <div className="absolute h-full w-px bg-primary" />
          </div>
        </div>
      </section>

      {/* ── Silicon Ethos / Principles ──────────────────────────────────── */}
      {principles && principles.length > 0 && (
        <section className="bg-surface-container-low py-24 px-6">
          <div className="mx-auto max-w-7xl">
            <div className="mb-16">
              <span className="label-sm mb-4 block text-tertiary uppercase tracking-[0.4em]">
                02 // SILICON ETHOS
              </span>
              <h2 className="display-sm text-on-surface">OPERATING PRINCIPLES</h2>
            </div>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
              {principles.map((p) => (
                <div
                  key={p.id ?? p.title}
                  className="flex flex-col gap-4 rounded-md bg-surface-container-highest border border-outline-variant/15 p-8"
                >
                  {p.code && (
                    <span className="label-sm text-on-surface-variant tracking-[0.3em] uppercase">
                      {p.code}
                    </span>
                  )}
                  <h3 className={`title-lg font-bold tracking-tight ${accentTextClass[p.accent ?? "primary"] ?? "text-primary"}`}>
                    {p.title}
                  </h3>
                  {p.body && (
                    <p className="body-md text-on-surface-variant leading-relaxed">{p.body}</p>
                  )}
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── Featured Projects ───────────────────────────────────────────── */}
      {resolvedProjects.length > 0 && (
        <section className="py-24 px-6">
          <div className="mx-auto max-w-7xl">
            <div className="mb-16">
              <span className="label-sm mb-4 block text-secondary uppercase tracking-[0.4em]">
                03 // SELECTED WORK
              </span>
              <h2 className="display-sm text-on-surface">FEATURED PROJECTS</h2>
            </div>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
              {resolvedProjects.map((project) => (
                <Link
                  key={project.id}
                  href={`/projects/${project.slug}`}
                  className="group flex flex-col gap-5 rounded-md bg-surface-container-high border border-outline-variant/15 p-8 transition-colors hover:border-primary/30 hover:bg-surface-container-highest"
                >
                  <div className="flex items-start justify-between gap-4">
                    <h3 className="title-lg text-on-surface font-bold tracking-tight group-hover:text-primary transition-colors">
                      {project.title}
                    </h3>
                    {project.year && (
                      <span className="label-sm shrink-0 text-on-surface-variant tracking-widest">
                        {project.year}
                      </span>
                    )}
                  </div>

                  <p className="body-md text-on-surface-variant leading-relaxed line-clamp-3">
                    {project.summary}
                  </p>

                  {project.tech && project.tech.length > 0 && (
                    <div className="mt-auto flex flex-wrap gap-2 pt-2">
                      {project.tech.slice(0, 4).map((t, i) =>
                        t.label ? (
                          <TechChip key={t.id ?? i} accent="secondary">
                            {t.label}
                          </TechChip>
                        ) : null,
                      )}
                    </div>
                  )}
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── Closing CTA ─────────────────────────────────────────────────── */}
      {closingCta?.headline && (
        <section className="bg-surface-container py-24 px-6">
          <div className="mx-auto max-w-7xl">
            <div className="flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between">
              <div className="max-w-2xl">
                {closingCta.eyebrow && (
                  <span className="label-sm mb-4 block text-primary uppercase tracking-[0.4em]">
                    {closingCta.eyebrow}
                  </span>
                )}
                <h2 className="display-md text-on-surface">{closingCta.headline}</h2>
                {closingCta.body && (
                  <p className="body-lg mt-4 text-on-surface-variant">{closingCta.body}</p>
                )}
              </div>

              {closingCta.cta?.label && closingCta.cta?.href && (
                <div className="shrink-0">
                  <Link href={closingCta.cta.href}>
                    <Button variant="primary">{closingCta.cta.label}</Button>
                  </Link>
                </div>
              )}
            </div>
          </div>
        </section>
      )}
    </main>
  );
}
