'use client';

import { useRef, useState } from 'react';
import { motion, type Variants } from 'framer-motion';
import Image from 'next/image';
import Link from 'next/link';
import { ArrowRight, ArrowLeft, GraduationCap, Lightbulb, Rocket, Wrench, Handshake, Users } from 'lucide-react';
import { normalizeEmptyArrays } from '@/lib/cms';
import { Reveal } from '@/components/reveal';

// A Trade Summit 2025 panel discussion — knowledge exchange, which is what an
// institutions page is about, and the only summit photo not already carrying a
// hero elsewhere. Anchored to the bottom on purpose: the top third of this
// frame is a row of speaker name cards in large type, and cropping it away is
// what makes the picture usable behind a headline. Swappable via heroImage.
const heroImageFallback = '/assets/events/ts2025-panel.jpg';

const fadeUp: Variants = {
  hidden: { opacity: 0, y: 56 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.75, ease: [0.16, 1, 0.3, 1] } },
};

const stagger: Variants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.06 } },
};

export type InstitutionsData = {
  heroImage?: string;
  heroBadge?: string;
  heroTitle?: string;
  heroIntro?: string;
  introEyebrow?: string;
  introHeading?: string;
  introText?: string;
  focusAreas?: string[];
  listEyebrow?: string;
  listHeading?: string;
  institutions?: string[];
  ctaHeading?: string;
  ctaText?: string;
  ctaLabel?: string;
  ctaHref?: string;
};

// Supplied by UEF in "UEF Website changes.docx" (19 Aug 2026), section 3.
// Kept in the order given. The count shown on the page is derived from this
// array rather than hard-coded, so it cannot fall out of step with the list.
const institutionsFallback = [
  'Aalim Muhammed Salegh College of Engineering',
  'AIMAN College of Arts and Science for Women',
  'Al-Islamiya Polytechnic College',
  'Al-Ameen Engineering College',
  'Annai College of Engineering and Technology',
  "Annai Hajira Women's College",
  'Anvarul Muslimeen Industrial Training Institute',
  'As-Salam College of Engineering and Technology',
  'B. S. Abdur Rahman Crescent Institute of Science and Technology',
  'C. Abdul Hakeem College',
  'Chendu College of Engineering and Technology',
  'Dhaanish Engineering College',
  'Dr. Zakir Hussain College',
  'Hajee Karutha Rowther Howdia College',
  'Haji Sheik Ismail Engineering and Polytechnic Colleges',
  'Himayath Industrial Training Centre',
  'Institute of Safety Management',
  "Islamiah College for Men & Islamiah Women's College of Arts & Science",
  'Jamal Mohamed College',
  'Justice Basheer Ahmed Sayeed College for Women',
  'Kazi Tajudeen Industrial Training Institute',
  'Khadir Mohideen College',
  "M. M. E. S. Women's Arts & Science College",
  'M. A. R. College of Engineering and Technology',
  'MAM Group of Institutions',
  'MAM College of Engineering and Technology',
  'Mazharul Uloom College',
  'MEASI',
  'Mohamed Sathak Trust',
  'Muqayyath Sha Sirguro Wakf Board College',
  'Muslim Arts College',
  'Muslim College of Education',
  'Naina Mohamed College of Arts & Science',
  'National College of Engineering',
  'Noorul Islam College of Engineering and Technology',
  'PET Engineering College',
  'Quaid-E-Millath College',
  "Rabiammal Ahamed Maideen Women's College",
  'RDB Educational Institutions',
  'Sadakathullah Appa College',
  'Sethu Institute of Technology',
  'Syed Ammal Engineering College',
  'Syed Hameedha Arts and Science College',
  'Thassim Beevi Abdul Kader College for Women',
  "Wavoo Wajeeha Women's College",
];

const focusAreasFallback = [
  'Education',
  'Innovation',
  'Entrepreneurship',
  'Incubation',
  'Skill development',
  'Industry–institution collaboration',
];

const FOCUS_ICONS = [GraduationCap, Lightbulb, Rocket, Wrench, Users, Handshake];

export function InstitutionsContent({ data: rawData }: { data?: InstitutionsData | null }) {
  // Empty arrays from the CMS must fall back like missing ones do.
  const data = normalizeEmptyArrays(rawData);
  const institutions = data?.institutions?.length ? data.institutions : institutionsFallback;
  const focusAreas = data?.focusAreas?.length ? data.focusAreas : focusAreasFallback;
  const count = institutions.length;

  // Ten at a time: the full list of 45 read as a spreadsheet rather than a
  // network worth joining.
  const PER_PAGE = 10;
  const [page, setPage] = useState(0);
  const pageCount = Math.ceil(count / PER_PAGE);
  const shown = institutions.slice(page * PER_PAGE, page * PER_PAGE + PER_PAGE);
  const listTop = useRef<HTMLDivElement>(null);

  // Paging from the controls at the bottom otherwise leaves the reader looking
  // at the end of a list that has already changed under them.
  const goTo = (next: number) => {
    setPage(next);
    listTop.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="flex flex-col min-h-screen bg-background">
      {/* HERO */}
      <section className="relative bg-slate-950 pt-40 pb-20 overflow-hidden">
        <Image
          src={data?.heroImage ?? heroImageFallback}
          alt=""
          fill
          priority
          sizes="100vw"
          className="object-cover object-bottom opacity-80"
        />
        {/* Same three layers as the UEF Angels and Youth Wing heroes, so the
            three section fronts read as one family. */}
        <div className="absolute inset-0 bg-slate-950/35" />
        <div className="absolute inset-0 bg-gradient-to-r from-slate-950/90 via-slate-950/50 to-transparent" />
        <div aria-hidden="true" className="absolute inset-0 pointer-events-none">
          <div className="absolute -top-1/3 right-0 w-[55vw] h-[55vw] rounded-full bg-primary/15 blur-[130px]" />
        </div>
        <div className="container mx-auto px-6 md:px-12 relative z-10 max-w-4xl">
          <motion.p
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            className="inline-flex items-center gap-2.5 px-4 py-2 rounded-full bg-white/[0.07] border border-white/15 text-white/90 text-[11px] font-semibold uppercase tracking-[0.18em] mb-8"
          >
            <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
            {data?.heroBadge ?? 'ESIIA'}
          </motion.p>
          <motion.h1
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 }}
            className="font-serif font-semibold text-white text-[clamp(2.1rem,4.4vw,3.4rem)] leading-[1.1] tracking-[-0.015em] text-balance mb-6"
          >
            {data?.heroTitle ?? `${count} institutions. One ecosystem.`}
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="text-lg text-white/70 leading-relaxed max-w-2xl"
          >
            {data?.heroIntro ??
              'Our partnerships promote education, innovation, entrepreneurship, incubation, skill development, and industry–institution collaboration, creating opportunities for students, startups, and young entrepreneurs.'}
          </motion.p>
        </div>
      </section>

      {/* FOCUS AREAS */}
      <section className="py-20 md:py-24 bg-white border-b border-border">
        <div className="container mx-auto px-6 md:px-12">
        <Reveal>
          <p className="text-xs font-bold tracking-widest uppercase text-primary mb-4">
            {data?.introEyebrow ?? 'What the partnerships do'}
          </p>
          <h2 className="text-3xl md:text-4xl font-serif font-semibold mb-6 max-w-3xl text-balance">
            {data?.introHeading ?? 'Where the network turns into opportunity.'}
          </h2>
          <p className="text-foreground/70 leading-relaxed max-w-2xl mb-12">
            {data?.introText ??
              'Each association is a route for students, startups and young entrepreneurs into the wider UEF ecosystem — its members, its mentors and its capital.'}
          </p>
        </Reveal>
                <motion.div
            variants={stagger}
            initial="hidden"
            whileInView="visible"
            viewport={{ margin: '-80px' }}
            className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4"
          >
            {focusAreas.map((area, i) => {
              const Icon = FOCUS_ICONS[i % FOCUS_ICONS.length];
              return (
                <motion.div
                  key={area}
                  variants={fadeUp}
                  className="flex items-center gap-4 bg-muted border border-border rounded-lg px-5 py-4"
                >
                  <Icon className="w-5 h-5 text-primary shrink-0" aria-hidden="true" />
                  <span className="font-medium">{area}</span>
                </motion.div>
              );
            })}
          </motion.div>
        </div>
      </section>

      {/* THE LIST */}
      <section className="py-20 md:py-24 bg-muted">
        <div className="container mx-auto px-6 md:px-12">
          <div ref={listTop} className="flex flex-wrap items-baseline justify-between gap-4 mb-12 scroll-mt-32">
            <div>
              <p className="text-xs font-bold tracking-widest uppercase text-primary mb-3">
                {data?.listEyebrow ?? 'The network'}
              </p>
              <h2 className="text-3xl md:text-4xl font-serif font-semibold text-balance">
                {data?.listHeading ?? 'Associated Educational Institutions'}
              </h2>
            </div>
            <p className="text-sm font-semibold uppercase tracking-widest text-foreground/40 tabular-nums">
              {count} institutions
            </p>
          </div>

          {/* key={page} restarts the stagger on every page, so a new set reads
              as arriving rather than silently swapping in place. */}
          <motion.ol
            key={page}
            variants={stagger}
            initial="hidden"
            animate="visible"
            className="grid sm:grid-cols-2 gap-5"
          >
            {shown.map((name, i) => {
              const number = page * PER_PAGE + i + 1;
              // An odd number on the final page would otherwise strand one card.
              const orphan = shown.length % 2 === 1 && i === shown.length - 1;
              return (
                <motion.li
                  key={name}
                  variants={fadeUp}
                  whileHover={{ y: -8, transition: { duration: 0.25, ease: 'easeOut' } }}
                  className={`uef-card group flex items-baseline gap-4 rounded-2xl border border-border bg-white p-6 shadow-sm${
                    orphan ? ' sm:col-span-2 sm:mx-auto sm:w-[calc(50%-0.625rem)]' : ''
                  }`}
                >
                  <span className="text-xs font-semibold text-primary/60 tabular-nums shrink-0 w-6 transition-colors duration-300 group-hover:text-primary">
                    {String(number).padStart(2, '0')}
                  </span>
                  <span className="leading-snug transition-colors duration-300 group-hover:text-primary">{name}</span>
                </motion.li>
              );
            })}
          </motion.ol>

          <nav className="mt-10 flex flex-wrap items-center justify-center gap-3" aria-label="Institutions pages">
            <button
              type="button"
              onClick={() => goTo(page - 1)}
              disabled={page === 0}
              className="flex items-center gap-2 rounded-full border border-border px-5 py-2.5 text-sm font-medium transition-colors hover:border-primary hover:text-primary disabled:pointer-events-none disabled:opacity-40"
            >
              <ArrowLeft className="h-4 w-4" aria-hidden /> Previous
            </button>

            <div className="flex items-center gap-1.5">
              {Array.from({ length: pageCount }, (_, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => goTo(i)}
                  aria-label={`Page ${i + 1}`}
                  aria-current={i === page ? 'page' : undefined}
                  className={`h-9 w-9 rounded-full text-sm font-semibold tabular-nums transition-colors ${
                    i === page
                      ? 'bg-primary text-primary-foreground'
                      : 'border border-border hover:border-primary hover:text-primary'
                  }`}
                >
                  {i + 1}
                </button>
              ))}
            </div>

            <button
              type="button"
              onClick={() => goTo(page + 1)}
              disabled={page >= pageCount - 1}
              className="flex items-center gap-2 rounded-full border border-border px-5 py-2.5 text-sm font-medium transition-colors hover:border-primary hover:text-primary disabled:pointer-events-none disabled:opacity-40"
            >
              Next <ArrowRight className="h-4 w-4" aria-hidden />
            </button>
          </nav>
        </div>
      </section>

      {/* CTA */}
      <section className="py-20 md:py-24 bg-white">
        <div className="container mx-auto px-6 md:px-12 max-w-3xl text-center">
        <Reveal>
          <h2 className="text-3xl md:text-4xl font-serif font-semibold mb-5 text-balance">
            {data?.ctaHeading ?? 'Partner your institution with UEF.'}
          </h2>
          <p className="text-foreground/70 leading-relaxed mb-9">
            {data?.ctaText ??
              'If your college or training institute wants to join the network, the Secretariat will take you through what an association involves.'}
          </p>
          <Link
            href={data?.ctaHref ?? '/contact'}
            className="bg-primary text-white h-14 px-9 rounded-md font-semibold inline-flex items-center gap-2.5 transition-all hover:bg-primary/90 hover:-translate-y-0.5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-primary"
          >
            {data?.ctaLabel ?? 'Talk to the Secretariat'}
            <ArrowRight className="w-4 h-4" />
          </Link>
        </Reveal>
        </div>
      </section>
    </div>
  );
}
