import { Head, Link } from "@inertiajs/react";
import { motion } from "framer-motion";
import { Nav } from "@/components/sections/Nav";
import { Footer } from "@/components/sections/Footer";
import { fadeUp, staggerContainer, staggerItem, viewportOptions } from "@/lib/animations";

interface Post {
  id: number;
  title: string;
  slug: string;
  excerpt: string | null;
  image_url: string | null;
  category: string;
  published_at: string;
}

interface PaginatedPosts {
  data: Post[];
  links: { url: string | null; label: string; active: boolean }[];
}

function formatDate(d: string) {
  return new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
}

function PostCard({ post, accent = "text-amber" }: { post: Post; accent?: string }) {
  return (
    <Link
      href={`/news/${post.slug}`}
      className="group flex flex-col overflow-hidden rounded-2xl border border-border bg-white shadow-sm transition-shadow hover:shadow-md"
    >
      {post.image_url ? (
        <img
          src={post.image_url}
          alt={post.title}
          className="h-48 w-full object-cover transition-transform duration-300 group-hover:scale-105"
        />
      ) : (
        <div className="flex h-48 w-full items-center justify-center bg-surface">
          <span className="text-4xl">
            {post.category === "Success Story" ? "⭐" : post.category === "Opportunity" ? "💼" : "📰"}
          </span>
        </div>
      )}
      <div className="flex flex-1 flex-col p-5">
        <span className={`mb-2 text-xs font-bold uppercase tracking-widest ${accent}`}>
          {post.category}
        </span>
        <h3 className="mb-2 font-serif text-lg leading-snug text-navy transition-colors group-hover:text-amber">
          {post.title}
        </h3>
        {post.excerpt && (
          <p className="mb-4 flex-1 text-sm text-secondary line-clamp-3">{post.excerpt}</p>
        )}
        <p className="mt-auto text-xs text-muted">{formatDate(post.published_at)}</p>
      </div>
    </Link>
  );
}

function StoryCard({ post }: { post: Post }) {
  return (
    <Link
      href={`/news/${post.slug}`}
      className="group flex gap-5 rounded-2xl border border-border bg-white p-5 shadow-sm transition-shadow hover:shadow-md"
    >
      {post.image_url ? (
        <img
          src={post.image_url}
          alt={post.title}
          className="h-24 w-24 shrink-0 rounded-xl object-cover"
        />
      ) : (
        <div className="flex h-24 w-24 shrink-0 items-center justify-center rounded-xl bg-amber-tint text-3xl">
          ⭐
        </div>
      )}
      <div className="flex flex-col justify-center">
        <span className="mb-1 text-xs font-bold uppercase tracking-widest text-amber">Success Story</span>
        <h3 className="mb-1 font-serif text-base leading-snug text-navy transition-colors group-hover:text-amber">
          {post.title}
        </h3>
        {post.excerpt && (
          <p className="text-xs text-secondary line-clamp-2">{post.excerpt}</p>
        )}
        <p className="mt-2 text-xs text-muted">{formatDate(post.published_at)}</p>
      </div>
    </Link>
  );
}

function OpportunityCard({ post }: { post: Post }) {
  return (
    <Link
      href={`/news/${post.slug}`}
      className="group flex flex-col justify-between rounded-2xl border border-border bg-white p-6 shadow-sm transition-shadow hover:shadow-md"
    >
      <div>
        <span className="mb-4 inline-block rounded-full bg-teal px-3 py-1 text-xs font-bold text-white">
          Opportunity
        </span>
        <h3 className="mb-2 font-serif text-lg leading-snug text-navy transition-colors group-hover:text-teal">
          {post.title}
        </h3>
        {post.excerpt && (
          <p className="text-sm text-secondary line-clamp-3">{post.excerpt}</p>
        )}
      </div>
      <div className="mt-5 flex items-center justify-between border-t border-border pt-4 text-xs text-muted">
        <span>{formatDate(post.published_at)}</span>
        <span className="font-semibold text-teal group-hover:underline">Read more →</span>
      </div>
    </Link>
  );
}

export default function NewsletterPage({
  news,
  stories,
  opportunities,
}: {
  news: PaginatedPosts;
  stories: Post[];
  opportunities: Post[];
}) {
  return (
    <>
      <Head title="News & Updates" />
      <Nav />

      <main className="pt-18">
        {/* Hero */}
        <div className="bg-navy px-16 py-20 text-center max-md:px-8">
          <motion.div variants={fadeUp} initial="hidden" animate="visible">
            <p className="mb-3 font-mono text-[11px] font-bold tracking-[0.18em] text-amber uppercase">
              Stay Informed
            </p>
            <h1 className="mb-4 text-[clamp(32px,4.5vw,58px)] font-bold leading-[1.05] tracking-tight text-white">
              News, Stories &amp; Opportunities
            </h1>
            <p className="mx-auto max-w-xl text-[17px] leading-[1.7] text-white/70">
              Updates from our programmes, success stories from the young people we serve, and opportunities to get involved.
            </p>
          </motion.div>
        </div>

        {/* ── Success Stories ── */}
        {stories.length > 0 && (
          <section className="border-b border-border bg-amber-tint px-16 py-20 max-md:px-8">
            <div className="mx-auto max-w-[1140px]">
              <motion.div
                variants={fadeUp}
                initial="hidden"
                whileInView="visible"
                viewport={viewportOptions}
                className="mb-10"
              >
                <p className="mb-2 font-mono text-[11px] font-bold tracking-[0.18em] text-amber uppercase">
                  Real People. Real Change.
                </p>
                <h2 className="text-[clamp(24px,3vw,38px)] font-bold leading-tight text-navy">
                  Success Stories
                </h2>
              </motion.div>

              <motion.div
                className="grid gap-5 md:grid-cols-2"
                variants={staggerContainer}
                initial="hidden"
                whileInView="visible"
                viewport={viewportOptions}
              >
                {stories.map((post) => (
                  <motion.div key={post.id} variants={staggerItem}>
                    <StoryCard post={post} />
                  </motion.div>
                ))}
              </motion.div>
            </div>
          </section>
        )}

        {/* ── Opportunities ── */}
        {opportunities.length > 0 && (
          <section id="opportunities" className="border-b border-border bg-teal-tint px-16 py-20 max-md:px-8">
            <div className="mx-auto max-w-[1140px]">
              <motion.div
                variants={fadeUp}
                initial="hidden"
                whileInView="visible"
                viewport={viewportOptions}
                className="mb-10"
              >
                <p className="mb-2 font-mono text-[11px] font-bold tracking-[0.18em] text-teal uppercase">
                  Get Involved
                </p>
                <h2 className="text-[clamp(24px,3vw,38px)] font-bold leading-tight text-navy">
                  Opportunities
                </h2>
              </motion.div>

              <motion.div
                className="grid gap-5 md:grid-cols-2 lg:grid-cols-3"
                variants={staggerContainer}
                initial="hidden"
                whileInView="visible"
                viewport={viewportOptions}
              >
                {opportunities.map((post) => (
                  <motion.div key={post.id} variants={staggerItem}>
                    <OpportunityCard post={post} />
                  </motion.div>
                ))}
              </motion.div>
            </div>
          </section>
        )}

        {/* ── News & Updates ── */}
        <section className="px-16 py-20 max-md:px-8">
          <div className="mx-auto max-w-[1140px]">
            <motion.div
              variants={fadeUp}
              initial="hidden"
              whileInView="visible"
              viewport={viewportOptions}
              className="mb-10"
            >
              <p className="mb-2 font-mono text-[11px] font-bold tracking-[0.18em] text-amber uppercase">
                Latest
              </p>
              <h2 className="text-[clamp(24px,3vw,38px)] font-bold leading-tight text-navy">
                News &amp; Updates
              </h2>
            </motion.div>

            {news.data.length === 0 ? (
              <div className="py-24 text-center text-secondary">
                <p className="text-lg">No news posts yet. Check back soon.</p>
              </div>
            ) : (
              <>
                <motion.div
                  className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3"
                  variants={staggerContainer}
                  initial="hidden"
                  whileInView="visible"
                  viewport={viewportOptions}
                >
                  {news.data.map((post) => (
                    <motion.div key={post.id} variants={staggerItem}>
                      <PostCard post={post} />
                    </motion.div>
                  ))}
                </motion.div>

                {news.links.length > 3 && (
                  <div className="mt-12 flex justify-center gap-2">
                    {news.links.map((link, i) => (
                      <Link
                        key={i}
                        href={link.url ?? "#"}
                        className={`rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
                          link.active
                            ? "bg-navy text-white"
                            : link.url
                            ? "border border-border text-secondary hover:border-navy hover:text-navy"
                            : "cursor-default text-muted"
                        }`}
                        dangerouslySetInnerHTML={{ __html: link.label }}
                      />
                    ))}
                  </div>
                )}
              </>
            )}
          </div>
        </section>
      </main>

      <Footer />
    </>
  );
}
