'use client';

import { motion } from 'framer-motion';
import Link from 'next/link';
import { Calendar, MapPin, ArrowRight, ExternalLink } from 'lucide-react';
import { normalizeEmptyArrays } from '@/lib/cms';

// Every field here is optional because Sanity returns null for anything an
// editor has not filled in. A half-created entry must degrade quietly, not
// take the whole page down — an empty item in the CMS crashed this page on
// `highlights.length` before these guards existed.
type EventItem = {
  title?: string | null;
  date?: string | null;
  location?: string | null;
  type?: string | null;
  desc?: string | null;
  highlights?: string[] | null;
  status?: string | null;
  link?: string | null;
  images?: string[] | null;
  video?: string | null;
  videoPoster?: string | null;
};

export type EventsData = {
  heroEyebrow?: string;
  heroTitle?: string;
  heroSubtitle?: string;
  events?: EventItem[];
};

export function EventsContent({ data: rawData }: { data?: EventsData | null }) {
  // Empty arrays from the CMS must fall back like missing ones do.
  const data = normalizeEmptyArrays(rawData);
  const fallbackEvents: EventItem[] = [
    {
      title: "UEF Trade Summit 2025",
      date: "December 12, 13 & 14, 2025",
      location: "Chennai Trade Centre, Nandambakkam",
      type: "Flagship Trade Summit",
      desc: "A landmark international summit that brought together 12,000 participants from 20 countries, featuring 200 exhibitors, 100 distinguished speakers, and key stakeholders including government ministers, global investors, industry leaders, entrepreneurs, policymakers, and innovators to foster strategic partnerships, drive investment, and shape the future of sustainable economic growth.",
      highlights: ["20+ Nations", "200+ Stalls", "4 Pavilions", "Government Ministers"],
      status: "Past",
      link: "https://www.unitedeconomicforum.com/uef2025/",
      images: [
        "/assets/events/ts2025-curtain-raiser.jpg",
        "/assets/events/ts2025-journey-wall.jpg",
        "/assets/events/ts2025-inauguration.jpg",
        "/assets/events/ts2025-panel.jpg",
        "/assets/events/ts2025-4tn-for-tn.jpg",
        "/assets/events/ts2025-success-meet.jpg",
      ],
      video: "/assets/events/ts2025-video.mp4",
    },
    {
      title: "UEF World Summit 2020",
      date: "December 2020",
      location: "Chennai, India",
      type: "Flagship Summit",
      desc: "UEF conducted a World Summit on a virtual platform with over 16,000 registered delegates, more than 100 speakers, and participants from 30 countries. It was the first international event of its kind organised in Tamil Nadu.",
      highlights: [],
      status: "Past",
      link: null,
      images: []
    },
    {
      title: "UEF–WIEF Round Table 2018",
      date: "2018",
      location: "Chennai, India",
      type: "Global Conference",
      desc: "UEF conducted a Round Table Conference in association with the World Islamic Economic Forum (WIEF), Malaysia, on \"Innovative and Alternative Finance for Business and Infrastructure Development in India.\" The event witnessed participation from 600 delegates and 20 speakers representing 6 overseas countries.",
      highlights: [],
      status: "Past",
      link: null,
      images: [
        "https://www.unitedeconomicforum.com/assets/img/18-1-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/18-2-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/18-3-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/18-4-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/18-5-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/18-6-min.PNG",
      ]
    },
    {
      title: "UEF Trade Summit 2017",
      date: "18 & 19 November 2017",
      location: "Chennai, India",
      type: "Trade Summit",
      desc: "The second UEF Trade Summit, convened on 18th & 19th November 2017, was inaugurated by the Hon'ble Finance Minister of Jammu & Kashmir and attended by the Hon'ble Deputy Chief Minister of Tamil Nadu, State Ministers, 900 delegates, and 50 renowned speakers from 10 overseas countries. MoUs were signed for Economic Enhancement worth INR 2,651 Crore (USD 360 Million).",
      highlights: [],
      status: "Past",
      link: null,
      images: [
        "https://www.unitedeconomicforum.com/assets/img/17-1-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/17-2-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/17-3-min.JPG",
        "https://www.unitedeconomicforum.com/assets/img/17-4-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/17-5-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/17-6-min.PNG",
      ]
    },
    {
      title: "UEF Trade Summit 2015",
      date: "14 & 15 November 2015",
      location: "Chennai, India",
      type: "Trade Summit",
      desc: "The first UEF Trade Summit, conducted on 14th & 15th November 2015, was inaugurated by Late Janab Mufti Mohammad Sayeed, Former Chief Minister of Jammu & Kashmir. The summit was attended by over 700 delegates and 35 renowned speakers from 7 overseas countries. UEF entered into MoUs for Economic Enhancement worth INR 2,440 Crore (USD 340 Million).",
      highlights: [],
      status: "Past",
      link: null,
      images: [
        "https://www.unitedeconomicforum.com/assets/img/15-1-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/15-2-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/15-3-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/15-4-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/15-5-min.PNG",
        "https://www.unitedeconomicforum.com/assets/img/15-6-min.PNG",
      ]
    }
  ];

  // Upcoming events first, whatever order they sit in inside the CMS. Sanity
  // appends new array items to the bottom and reordering there means dragging,
  // so without this an event added today lands below the 2015 summit. Array
  // sort is stable, so past events keep their existing reverse-chronological
  // order relative to each other.
  const events = [...(data?.events ?? fallbackEvents)].sort(
    (a, b) => Number(b.status === 'Upcoming') - Number(a.status === 'Upcoming'),
  );

  return (
    <div className="flex flex-col min-h-screen pt-32 bg-background">
      {/* Same treatment as the About header: tinted band, two soft washes, an
          eyebrow pill and a divider that draws itself. */}
      <section className="py-20 md:py-28 bg-gradient-to-b from-primary/[0.09] via-muted to-background border-b border-border relative overflow-hidden">
        {/* Placed away from the copy, so nothing sits behind text it could
            reduce the contrast of. */}
        <div aria-hidden className="pointer-events-none absolute -top-24 -left-24 w-[460px] h-[460px] rounded-full bg-primary/25 blur-3xl" />
        <div aria-hidden className="pointer-events-none absolute -bottom-32 right-0 w-[420px] h-[420px] rounded-full bg-primary/[0.18] blur-3xl" />

        <div className="container mx-auto px-6 md:px-12 relative z-10 text-center">
          <motion.p
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            className="inline-flex items-center gap-2 rounded-full border border-primary/40 bg-primary/15 px-5 py-2 shadow-sm
                       text-primary text-xs md:text-sm font-semibold uppercase tracking-[0.18em] mb-6"
          >
            <span className="w-2 h-2 rounded-full bg-primary" />
            {data?.heroEyebrow ?? 'Since 1979 · Chennai'}
          </motion.p>

          <motion.h1 initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="text-5xl md:text-6xl font-serif font-semibold">{data?.heroTitle ?? 'Events & Summits'}</motion.h1>

          <motion.div
            initial={{ scaleX: 0 }} animate={{ scaleX: 1 }} transition={{ duration: 0.6, delay: 0.2, ease: [0.4, 0, 0.2, 1] }}
            className="mx-auto my-6 h-1 w-32 origin-center rounded-full bg-gradient-to-r from-primary/30 via-primary to-primary/30"
          />

          <motion.p initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="text-xl text-foreground/70 max-w-3xl mx-auto leading-relaxed">
            {data?.heroSubtitle ?? 'Where ideas meet opportunity. Showcasing decades of impactful dialogue and networking.'}
          </motion.p>
        </div>
      </section>

      <section className="py-24">
        <div className="container mx-auto px-6 md:px-12 max-w-5xl">
          <div className="space-y-12">
            {events.map((evt, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ margin: '-100px' }}
                whileHover={{ y: -8, transition: { duration: 0.25, ease: 'easeOut' } }}
                className="uef-card group bg-white border border-border p-8 md:p-12 rounded-2xl shadow-sm"
              >
                {evt.status === "Upcoming" && (
                  <div className="absolute top-0 right-0 bg-primary text-white text-xs font-bold px-4 py-2 uppercase tracking-wider rounded-bl-lg">
                    Upcoming Event
                  </div>
                )}

                <div className="flex flex-col md:flex-row gap-8 items-start">
                  <div className="shrink-0 w-full md:w-64 border-r border-border md:pr-8">
                    <p className="text-primary font-semibold mb-2">{evt.type}</p>
                    {evt.date && (
                      <div className="flex items-center gap-2 text-foreground/60 mb-2">
                        <Calendar className="w-4 h-4" />
                        <span className="text-lg">{evt.date}</span>
                      </div>
                    )}
                    {evt.location && (
                      <div className="flex items-center gap-2 text-foreground/50 text-sm">
                        <MapPin className="w-3.5 h-3.5 shrink-0" />
                        <span>{evt.location}</span>
                      </div>
                    )}
                    {(evt.highlights?.length ?? 0) > 0 && (
                      <div className="flex flex-wrap gap-2 mt-4">
                        {evt.highlights?.map((h, j) => (
                          <span key={j} className="text-xs bg-primary/10 text-primary font-medium px-2 py-1 rounded-full">{h}</span>
                        ))}
                      </div>
                    )}
                  </div>

                  <div className="flex-1 min-w-0">
                    <h3 className="text-3xl font-serif font-semibold mb-4 text-foreground group-hover:text-primary transition-colors">{evt.title}</h3>
                    <p className="text-lg text-foreground/70 leading-relaxed mb-6">{evt.desc}</p>
                    {evt.link ? (
                      <a href={evt.link} target="_blank" rel="noopener noreferrer" className="text-primary font-medium flex items-center gap-2 hover:gap-3 transition-all">
                        Visit Event Website <ExternalLink className="w-4 h-4" />
                      </a>
                    ) : evt.status === "Upcoming" ? (
                      /* Without this branch an upcoming event with no website
                         would be labelled "Past Event" directly beneath its own
                         "Upcoming Event" badge. */
                      <Link href="/contact" className="text-primary font-medium flex items-center gap-2 hover:gap-3 transition-all">
                        Contact the Secretariat to attend <ArrowRight className="w-4 h-4" />
                      </Link>
                    ) : (
                      <span className="text-foreground/40 font-medium flex items-center gap-2 text-sm">
                        Past Event <ArrowRight className="w-4 h-4" />
                      </span>
                    )}
                  </div>
                </div>

                {(evt.images?.length ?? 0) > 0 && (
                  <div className="mt-8 pt-8 border-t border-border">
                    <div className="grid grid-cols-3 md:grid-cols-6 gap-2">
                      {evt.images?.map((src, j) => (
                        <div key={j} className="aspect-square rounded-lg overflow-hidden bg-muted">
                          <img
                            src={src}
                            alt={`${evt.title} photo ${j + 1}`}
                            className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {evt.video && (
                  <div className={`${(evt.images?.length ?? 0) > 0 ? 'mt-4' : 'mt-8 pt-8 border-t border-border'}`}>
                    <div className="rounded-xl overflow-hidden bg-black shadow-md">
                      <video
                        src={evt.video}
                        poster={evt.videoPoster ?? "/assets/events/ts2025-video-poster.jpg"}
                        controls
                        preload="metadata"
                        playsInline
                        className="w-full h-auto max-h-[560px] mx-auto"
                      />
                    </div>
                  </div>
                )}
              </motion.div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
