import Image from 'next/image';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getTranslations, setRequestLocale } from 'next-intl/server';
import { routing } from '@/i18n/routing';
import ScrollReveal from '@/components/ui/ScrollReveal';
import Button from '@/components/ui/Button';
import CornerBracket from '@/components/icons/CornerBracket';

const BASE_URL = 'https://letsbe.biz';

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

interface Project {
  image: string;
  techStack: string[];
}

// ─── Slug-to-work-key mapping ─────────────────────────────────────────────────

const SLUG_TO_KEY: Record<string, string> = {
  'monaco-ocean': 'monaco',
  'port-nimara': 'portNimara',
  'port-amador': 'portAmador',
}

// ─── Data (will come from Payload CMS) ────────────────────────────────────────

const PROJECTS: Record<string, Project> = {
  'monaco-ocean': {
    image: '/images/monaco_high_res.jpg',
    techStack: ['Next.js', 'PostgreSQL', 'OpenAI API', 'Docker', 'Private Cloud'],
  },
  'port-nimara': {
    image: '/images/anguilla.png',
    techStack: ['Nuxt.js', 'Directus CMS', 'Node.js', 'Docker'],
  },
  'port-amador': {
    image: '/images/panama.png',
    techStack: ['Next.js', 'Tailwind CSS', 'Framer Motion', 'Vercel'],
  },
};

// ─── Metadata ─────────────────────────────────────────────────────────────────

type PageProps = {
  params: Promise<{ locale: string; slug: string }>;
};

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  const project = PROJECTS[slug];
  if (!project) return {};

  const workKey = SLUG_TO_KEY[slug];
  if (!workKey) return {};

  const t = await getTranslations({ locale, namespace: 'meta.work' });

  const path = locale === 'en' ? `/work/${slug}` : `/${locale}/work/${slug}`;

  return {
    title: t(`${slug}.title` as any),
    description: t(`${slug}.description` as any),
    openGraph: {
      images: [{ url: project.image }],
    },
    alternates: {
      canonical: `${BASE_URL}${path}`,
      languages: {
        'en': `${BASE_URL}/work/${slug}`,
        'fr': `${BASE_URL}/fr/work/${slug}`,
        'it': `${BASE_URL}/it/work/${slug}`,
        'es': `${BASE_URL}/es/work/${slug}`,
        'x-default': `${BASE_URL}/work/${slug}`,
      },
    },
  };
}

// ─── Static Generation ────────────────────────────────────────────────────────

export function generateStaticParams() {
  const slugs = Object.keys(PROJECTS);
  const allParams: { locale: string; slug: string }[] = [];

  for (const locale of routing.locales) {
    for (const slug of slugs) {
      allParams.push({ locale, slug });
    }
  }

  return allParams;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function ContentSection({
  label,
  index,
  heading,
  body,
}: {
  label: string;
  index: string;
  heading: string;
  body: string;
}) {
  return (
    <ScrollReveal variant="fadeUp" className="flex flex-col gap-4">
      <div className="flex items-center gap-3">
        <span className="label-md text-outline/50">{index}</span>
        <span className="label-md text-primary">{label}</span>
      </div>
      <h3 className="font-serif text-2xl md:text-3xl font-semibold text-on-surface leading-snug tracking-[-0.02em]">
        {heading}
      </h3>
      <p className="text-outline leading-relaxed text-base md:text-[1.0625rem]">{body}</p>
    </ScrollReveal>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

type Props = {
  params: Promise<{ locale: string; slug: string }>;
};

export default async function CaseStudyPage({ params }: Props) {
  const { locale, slug } = await params;
  setRequestLocale(locale);

  const project = PROJECTS[slug];
  if (!project) notFound();

  const workKey = SLUG_TO_KEY[slug];
  if (!workKey) notFound();

  const t = await getTranslations({ locale, namespace: 'caseStudy' });
  const tw = await getTranslations({ locale, namespace: 'work' });

  // Get translated content
  const title = tw(`projects.${workKey}.title`)
  const tags = tw.raw(`projects.${workKey}.tags`) as string[]
  const subtitle = t(`projects.${slug}.subtitle`)
  const description = t(`projects.${slug}.description`)
  const challenge = t(`projects.${slug}.challenge`)
  const approach = t(`projects.${slug}.approach`)
  const outcome = t(`projects.${slug}.outcome`)

  const caseStudyJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'CreativeWork',
    name: title,
    description: description,
    image: `${BASE_URL}${project.image}`,
    inLanguage: locale,
    creator: {
      '@type': 'Organization',
      name: 'LetsBe.',
      url: BASE_URL,
    },
  };

  return (
    <main>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(caseStudyJsonLd) }}
      />

      {/* ── Hero ── */}
      <section className="relative min-h-[420px] md:min-h-[480px] flex items-end overflow-hidden">
        {/* Background image */}
        <Image
          src={project.image}
          alt=""
          fill
          className="object-cover"
          sizes="100vw"
          priority
        />
        {/* Dark overlay for text readability */}
        <div className="absolute inset-0 bg-gradient-to-t from-[rgba(25,28,29,0.85)] via-[rgba(25,28,29,0.55)] to-[rgba(25,28,29,0.3)]" />

        <div className="relative z-10 container mx-auto px-6 pb-16 pt-32">
          <div className="max-w-3xl mx-auto flex flex-col items-center text-center gap-5">

            {/* Tags */}
            <ScrollReveal variant="fadeIn">
              <div className="flex flex-wrap items-center justify-center gap-2">
                {tags.map((tag) => (
                  <span
                    key={tag}
                    className="inline-flex items-center bg-white/15 backdrop-blur-sm text-white/90 text-[0.75rem] font-semibold px-3 py-1 rounded-full leading-none tracking-wide"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </ScrollReveal>

            {/* Title */}
            <ScrollReveal variant="fadeUp" delay={0.08}>
              <h1 className="font-serif font-semibold text-white text-4xl md:text-5xl lg:text-[3.25rem] leading-[1.1] tracking-[-0.02em]">
                {title}
              </h1>
            </ScrollReveal>

            {/* Subtitle */}
            <ScrollReveal variant="fadeUp" delay={0.16}>
              <p className="label-md text-white/70 tracking-widest">
                {subtitle}
              </p>
            </ScrollReveal>

            {/* Description */}
            <ScrollReveal variant="fadeUp" delay={0.22}>
              <p className="text-white/80 text-lg leading-relaxed max-w-2xl">
                {description}
              </p>
            </ScrollReveal>

          </div>
        </div>
      </section>

      {/* ── Case Study Content ── */}
      <section className="bg-surface py-20 md:py-28">
        <div className="container mx-auto px-6">
          <div className="max-w-3xl mx-auto">

            {/* Decorative corner brackets framing the content area */}
            <ScrollReveal variant="fadeIn" className="relative">
              <div className="absolute -top-6 -left-6 md:-left-10" aria-hidden="true">
                <CornerBracket size={36} position="top-left" color="var(--color-primary)" />
              </div>
              <div className="absolute -top-6 -right-6 md:-right-10" aria-hidden="true">
                <CornerBracket size={36} position="top-right" color="var(--color-primary)" />
              </div>
            </ScrollReveal>

            {/* Sections */}
            <div className="flex flex-col gap-16 md:gap-20">

              <ContentSection
                label={t('labels.challenge')}
                index="01"
                heading={t('labels.challengeHeading')}
                body={challenge}
              />

              {/* Divider */}
              <ScrollReveal variant="fadeIn">
                <div
                  className="w-full h-px"
                  style={{
                    background:
                      'linear-gradient(to right, transparent, var(--color-outline-variant), transparent)',
                  }}
                  aria-hidden="true"
                />
              </ScrollReveal>

              <ContentSection
                label={t('labels.approach')}
                index="02"
                heading={t('labels.approachHeading')}
                body={approach}
              />

              {/* Divider */}
              <ScrollReveal variant="fadeIn">
                <div
                  className="w-full h-px"
                  style={{
                    background:
                      'linear-gradient(to right, transparent, var(--color-outline-variant), transparent)',
                  }}
                  aria-hidden="true"
                />
              </ScrollReveal>

              <ContentSection
                label={t('labels.outcome')}
                index="03"
                heading={t('labels.outcomeHeading')}
                body={outcome}
              />

            </div>

          </div>
        </div>
      </section>

      {/* ── Tech Stack ── */}
      <section className="bg-surface-low py-12">
        <div className="container mx-auto px-6">
          <div className="max-w-3xl mx-auto">
            <ScrollReveal variant="fadeUp" className="flex flex-col gap-5">
              <p className="label-md text-outline">{t('labels.builtWith')}</p>
              <div className="flex flex-wrap gap-2">
                {project.techStack.map((tech) => (
                  <span
                    key={tech}
                    className="inline-flex items-center px-4 py-2 rounded-xl bg-surface-high text-on-surface text-sm font-medium shadow-card"
                  >
                    {tech}
                  </span>
                ))}
              </div>
            </ScrollReveal>
          </div>
        </div>
      </section>

      {/* ── CTA ── */}
      <section className="bg-surface py-20 md:py-24">
        <div className="container mx-auto px-6">
          <ScrollReveal variant="fadeUp">
            <div className="max-w-3xl mx-auto flex flex-col items-center text-center gap-8">

              {/* Decorative corner bracket */}
              <div className="relative">
                <div className="absolute -top-3 -left-3" aria-hidden="true">
                  <CornerBracket size={24} position="top-left" color="var(--color-teal)" />
                </div>
                <div className="absolute -top-3 -right-3" aria-hidden="true">
                  <CornerBracket size={24} position="top-right" color="var(--color-teal)" />
                </div>
                <p className="label-md text-primary px-4">{t('labels.yourTurn')}</p>
              </div>

              <h2 className="font-serif font-semibold text-on-surface text-3xl md:text-4xl leading-[1.1] tracking-[-0.02em]">
                {t('labels.ctaTitle')}
              </h2>

              <p className="text-outline text-lg leading-relaxed max-w-xl">
                {t('labels.ctaSubtitle')}
              </p>

              <Button variant="primary" size="lg" arrow href="/#configure">
                {t('labels.ctaButton')}
              </Button>

            </div>
          </ScrollReveal>
        </div>
      </section>

    </main>
  );
}
