import { Link } from '@inertiajs/react';
import { SeoHead } from '@/components/seo-head';
import { ArrowRight, ChevronRight, Lightbulb } from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import { motion } from 'framer-motion';
import { useEffect, useRef, useState } from 'react';

interface FeaturedTheme { id: number; title: string; summary: string | null; cover_url: string | null; icon: string | null; sort_order: number }

function resolveIcon(name: string | null): React.ElementType {
    if (name && name in LucideIcons) return (LucideIcons as any)[name];
    return Lightbulb;
}

function useInView(threshold = 0.15) {
    const ref = useRef<HTMLDivElement>(null);
    const [inView, setInView] = useState(false);
    useEffect(() => {
        const observer = new IntersectionObserver(
            ([e]) => {
                if (e.isIntersecting) {
                    setInView(true);
                    observer.disconnect();
                }
            },
            { threshold },
        );
        if (ref.current) observer.observe(ref.current);
        return () => observer.disconnect();
    }, [threshold]);
    return { ref, inView };
}

const stats = [
    { value: '19', label: 'Member Universities' },
    { value: '9', label: 'African Countries' },
    { value: '10', label: 'Summer Schools' },
    { value: '2012', label: 'Year Founded' },
];

const memberCountries = [
    { name: 'Uganda', count: 6 },
    { name: 'South Africa', count: 3 },
    { name: 'Ethiopia', count: 4 },
    { name: 'Kenya', count: 3 },
    { name: 'Tanzania', count: 2 },
    { name: 'Nigeria', count: 2 },
    { name: 'Malawi', count: 2 },
    { name: 'Egypt', count: 1 },
    { name: 'Zambia', count: 1 },
];

const publications = [
    {
        year: 2020,
        title: 'Nurturing next-generation biomedical engineers in Africa',
        journal: 'Global Health',
    },
    {
        year: 2017,
        title: 'Building needs-based healthcare technology competencies across Africa',
        journal: 'South African Journal of Science',
    },
    {
        year: 2015,
        title: 'Open biomedical engineering education in Africa',
        journal: 'IEEE EMBC',
    },
];

function ThemeCard({ theme, index }: { theme: FeaturedTheme; index: number }) {
    const Icon = resolveIcon(theme.icon);
    return (
        <Link href="/programs" className="group relative flex flex-col overflow-hidden h-80 lg:h-96">
            {theme.cover_url && (
                <img
                    src={theme.cover_url}
                    alt={theme.title}
                    className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
                />
            )}
            {/* Brand-blue overlay — navy base, teal on hover */}
            <div className="absolute inset-0 bg-gradient-to-t from-[#0A2647] via-[#0A2647]/85 via-40% to-[#1B6B7D]/30 transition-all duration-500 group-hover:to-[#1B6B7D]/60" />

            <div className="absolute inset-0 flex flex-col justify-end p-7">
                <div className="flex items-center justify-between mb-4">
                    <span className="text-white/15 text-5xl font-black leading-none">0{index + 1}</span>
                    <div className="w-9 h-9 bg-white/10 group-hover:bg-[#df2548] flex items-center justify-center transition-colors duration-300">
                        <Icon size={16} className="text-white" />
                    </div>
                </div>
                <h3 className="text-white font-bold text-2xl leading-snug mb-3 tracking-tight">{theme.title}</h3>
                {theme.summary && <p className="text-white/80 text-base leading-relaxed">{theme.summary}</p>}
                <div className="mt-4 flex items-center gap-1.5 text-[#d0d4ec] text-xs font-semibold tracking-wider uppercase opacity-0 group-hover:opacity-100 transition-opacity">
                    Explore <ArrowRight size={10} className="group-hover:translate-x-1 transition-transform" />
                </div>
            </div>
        </Link>
    );
}

interface HomeProps {
    stats: { members: number; institutions: number; countries: number };
    featured_events: any[];
    latest_news: any[];
    featured_themes: FeaturedTheme[];
}

export default function Home({ featured_themes }: HomeProps) {
    const themesSection = useInView(0.05);
    const pubSection = useInView();
    const ctaSection = useInView();

    const homeJsonLd = {
        '@context': 'https://schema.org',
        '@type': 'WebPage',
        '@id': 'https://abecafrica.org/#webpage',
        url: 'https://abecafrica.org',
        name: 'ABEC Africa — African Biomedical Engineering Consortium',
        description: 'Pan-African membership body promoting excellence in biomedical engineering across 19+ institutions in 10+ African countries.',
        isPartOf: { '@id': 'https://abecafrica.org/#website' },
        about: { '@id': 'https://abecafrica.org/#organization' },
        inLanguage: 'en-GB',
    };

    return (
        <div>
            <SeoHead
                title="ABEC Africa — African Biomedical Engineering Consortium"
                description="Pan-African membership body promoting excellence in biomedical engineering across 19+ institutions in 10+ African countries. Join, collaborate, and advance healthcare technology in Africa."
                image="/images/lab-researcher-flask-microscope.jpg"
                keywords="African Biomedical Engineering, ABEC Africa, biomedical engineering Africa, biomedical research Africa, healthcare technology Africa, biomedical engineering consortium"
                jsonLd={homeJsonLd}
            />
            {/* ── HERO ─────────────────────────────────────────── */}
            <section className="relative min-h-screen flex items-end overflow-hidden">
                <div className="absolute inset-0">
                    <img
                        src="/images/scientist-microscope-warmlight.jpg"
                        alt="African scientist at microscope"
                        className="w-full h-full object-cover object-center"
                    />
                    <div
                        className="absolute inset-0"
                        style={{
                            background:
                                'linear-gradient(105deg, rgba(17,17,19,0.97) 0%, rgba(27,38,92,0.88) 35%, rgba(27,38,92,0.55) 60%, rgba(27,38,92,0.15) 85%, transparent 100%)',
                        }}
                    />
                    <div
                        className="absolute bottom-0 left-0 right-0 h-48"
                        style={{
                            background: 'linear-gradient(to top, rgba(17,17,19,0.7) 0%, transparent 100%)',
                        }}
                    />
                </div>

                <div className="absolute inset-0 pointer-events-none overflow-hidden">
                    <div className="absolute top-1/3 left-0 right-0 h-px bg-white/5" />
                    <div className="absolute top-2/3 left-0 right-0 h-px bg-white/5" />
                </div>

                <div className="relative w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 pt-40">
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        transition={{ duration: 1 }}
                        className="max-w-3xl"
                    >
                        <motion.div
                            initial={{ opacity: 0, x: -24 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ duration: 0.7, delay: 0.2 }}
                            className="flex items-center gap-3 mb-8"
                        >
                            <div className="w-10 h-px bg-[#df2548]" />
                            <span className="text-[#d0d4ec] text-xs font-semibold tracking-[0.22em] uppercase">
                                Pan-African Platform · Est. 2012
                            </span>
                        </motion.div>

                        <motion.h1
                            initial={{ opacity: 0, y: 40 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ duration: 0.9, delay: 0.35, ease: [0.16, 1, 0.3, 1] }}
                            className="text-5xl lg:text-7xl xl:text-8xl font-black text-white leading-[1.0] tracking-[-0.03em] mb-8"
                        >
                            Engineering
                            <br />
                            <span className="text-[#df2548]">Africa's</span>
                            <br />
                            Health Future
                        </motion.h1>

                        <motion.p
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ duration: 0.7, delay: 0.6 }}
                            className="text-white/75 text-lg leading-[1.85] max-w-xl mb-10 font-light"
                        >
                            Promoting and Sharing Excellence in Biomedical Engineering to Improve the Health and
                            Wealth of Africa. Building people, systems, and partnerships across 9 countries.
                        </motion.p>

                        <motion.div
                            initial={{ opacity: 0, y: 16 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ duration: 0.6, delay: 0.8 }}
                            className="flex flex-wrap gap-4"
                        >
                            <Link
                                href="/join"
                                className="inline-flex items-center gap-2 h-12 px-8 bg-[#d0d4ec] text-[#1b265c] text-sm font-semibold tracking-wider uppercase hover:bg-[#D4BC96] transition-colors"
                            >
                                Join the Movement
                                <ArrowRight size={16} />
                            </Link>
                            <Link
                                href="/about"
                                className="inline-flex items-center h-12 px-8 border border-white/30 bg-transparent text-white text-sm font-semibold tracking-wider uppercase hover:bg-white hover:text-[#1b265c] transition-colors"
                            >
                                Our Story
                            </Link>
                        </motion.div>
                    </motion.div>

                    {/* Stats row */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.7, delay: 1.1 }}
                        className="mt-16 pt-8 border-t border-white/15 grid grid-cols-2 lg:grid-cols-4 gap-6"
                    >
                        {stats.map((s) => (
                            <div key={s.label}>
                                <div className="text-3xl lg:text-4xl font-black text-white">{s.value}</div>
                                <div className="flex items-center gap-1.5 mt-1">
                                    <div className="w-3 h-px bg-[#df2548]" />
                                    <span className="text-white/45 text-xs tracking-[0.14em] uppercase">{s.label}</span>
                                </div>
                            </div>
                        ))}
                    </motion.div>
                </div>
            </section>

            {/* ── INTRO BAND ───────────────────────────────────── */}
            <section className="bg-[#d0d4ec] py-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex flex-col md:flex-row items-center justify-between gap-6">
                        <p className="text-[#1b265c] font-bold text-sm tracking-[0.06em] max-w-2xl leading-relaxed">
                            "ABEC is more than a network — it is a movement. For over a decade, we have built the
                            infrastructure, relationships, and platforms that make African healthcare transformation
                            possible."
                        </p>
                        <Link
                            href="/about"
                            className="flex-shrink-0 inline-flex items-center gap-1 h-8 px-4 bg-[#1b265c] text-white text-xs font-semibold tracking-wider uppercase hover:bg-[#df2548] transition-colors"
                        >
                            About ABEC
                            <ChevronRight size={12} />
                        </Link>
                    </div>
                </div>
            </section>

            {/* ── STRATEGIC THEMES ─────────────────────────────── */}
            <section ref={themesSection.ref} className="py-24 bg-white">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex items-end justify-between mb-16">
                        <div>
                            <div className="section-rule" />
                            <span className="label-caps block mb-3">What We Do</span>
                            <h2 className="text-4xl lg:text-5xl font-black text-[#1b265c] tracking-tight leading-tight">
                                Five Strategic Themes
                            </h2>
                        </div>
                        <Link
                            href="/programs"
                            className="hidden md:inline-flex items-center gap-1 h-8 px-4 border border-[#1b265c] text-[#1b265c] text-xs font-semibold tracking-wider uppercase hover:bg-[#1b265c] hover:text-white transition-colors"
                        >
                            All Programs
                            <ChevronRight size={12} />
                        </Link>
                    </div>

                    {/* Row 1 — two cards */}
                    <div className="grid md:grid-cols-2 gap-1">
                        {featured_themes.slice(0, 2).map((theme, i) => (
                            <motion.div
                                key={theme.id}
                                initial={{ opacity: 0, y: 24 }}
                                animate={themesSection.inView ? { opacity: 1, y: 0 } : {}}
                                transition={{ duration: 0.55, delay: i * 0.09 }}
                            >
                                <ThemeCard theme={theme} index={i} />
                            </motion.div>
                        ))}
                    </div>

                    {/* Row 2 — three cards */}
                    <div className="grid md:grid-cols-3 gap-1 mt-1">
                        {featured_themes.slice(2).map((theme, i) => (
                            <motion.div
                                key={theme.id}
                                initial={{ opacity: 0, y: 24 }}
                                animate={themesSection.inView ? { opacity: 1, y: 0 } : {}}
                                transition={{ duration: 0.55, delay: (i + 2) * 0.09 }}
                            >
                                <ThemeCard theme={theme} index={i + 2} />
                            </motion.div>
                        ))}
                    </div>
                </div>
            </section>

            {/* ── CONTINENTAL REACH ────────────────────────────── */}
            <section className="py-20 bg-[#F8F2E6]">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="grid lg:grid-cols-2 gap-16 items-center">
                        <div>
                            <div className="section-rule" />
                            <span className="label-caps block mb-4">Continental Reach</span>
                            <h2 className="text-4xl lg:text-5xl font-black text-[#1b265c] tracking-tight leading-tight mb-6">
                                9 Countries,
                                <br />
                                One Vision
                            </h2>
                            <p className="text-[#3a2020]/70 leading-relaxed mb-8 max-w-md text-sm">
                                ABEC members span East, West, North, and Southern Africa — with a European partner
                                in Italy and strategic backing from the United Nations Economic Commission for Africa.
                            </p>
                            <Link
                                href="/members"
                                className="inline-flex items-center gap-1 h-10 px-6 border border-[#1b265c] text-[#1b265c] text-xs font-semibold tracking-wider uppercase hover:bg-[#1b265c] hover:text-white transition-colors"
                            >
                                View All Members
                                <ChevronRight size={14} />
                            </Link>
                        </div>
                        <div className="grid grid-cols-3 gap-3">
                            {memberCountries.map((c, i) => (
                                <Link
                                    key={c.name}
                                    href={`/members?country=${encodeURIComponent(c.name)}`}
                                    className={`group p-4 border border-[#D4BC96] bg-white hover:border-[#1b265c] hover:bg-[#1b265c] transition-all duration-200${i === 0 ? ' col-span-2' : ''}`}
                                >
                                    <div className="text-2xl font-black text-[#1b265c] group-hover:text-white transition-colors">
                                        {c.count}
                                    </div>
                                    <div className="text-xs font-semibold text-[#1b265c] group-hover:text-white/80 transition-colors tracking-wide mt-1">
                                        {c.name}
                                    </div>
                                </Link>
                            ))}
                        </div>
                    </div>
                </div>
            </section>

            {/* ── GRADUATES + PUBLICATIONS ─────────────────────── */}
            <section ref={pubSection.ref} className="bg-white">
                <div className="grid lg:grid-cols-2">
                    <div className="relative h-80 lg:h-auto min-h-[400px] overflow-hidden">
                        <img
                            src="/images/african-graduates-caps-gowns.jpg"
                            alt="African graduates"
                            className="w-full h-full object-cover object-top"
                        />
                        <div
                            className="absolute inset-0"
                            style={{
                                background: 'linear-gradient(to right, transparent 50%, white 100%)',
                            }}
                        />
                    </div>

                    <div className="py-16 px-8 lg:px-12 flex flex-col justify-center">
                        <div className="section-rule" />
                        <span className="label-caps block mb-4">Research Output</span>
                        <h2 className="text-3xl font-black text-[#1b265c] tracking-tight mb-8">
                            Recent Publications
                        </h2>

                        <div className="space-y-6 mb-8">
                            {publications.map((pub, i) => (
                                <motion.div
                                    key={pub.title}
                                    initial={{ opacity: 0, x: 16 }}
                                    animate={pubSection.inView ? { opacity: 1, x: 0 } : {}}
                                    transition={{ duration: 0.5, delay: i * 0.1 }}
                                    className="border-l-2 border-[#df2548] pl-4"
                                >
                                    <div className="text-[#df2548] text-xs font-bold mb-1">{pub.year}</div>
                                    <p className="text-[#1b265c] font-bold text-sm leading-snug mb-1">
                                        {pub.title}
                                    </p>
                                    <p className="text-[#555e8a] text-xs italic">{pub.journal}</p>
                                </motion.div>
                            ))}
                        </div>

                        <Link
                            href="/research"
                            className="inline-flex items-center gap-2 h-8 px-4 border border-[#1b265c] text-[#1b265c] text-xs font-semibold tracking-wider uppercase hover:bg-[#1b265c] hover:text-white transition-colors self-start"
                        >
                            View All Publications
                            <ArrowRight size={12} />
                        </Link>
                    </div>
                </div>
            </section>

            {/* ── CTA BAND ────────────────────────────────── */}
            <section ref={ctaSection.ref} className="relative overflow-hidden">
                <div className="absolute inset-0">
                    <img
                        src="/images/african-university-convocation.jpg"
                        alt="African university convocation"
                        className="w-full h-full object-cover"
                    />
                    <div
                        className="absolute inset-0"
                        style={{ background: 'linear-gradient(to right, rgba(10,38,71,0.97) 0%, rgba(10,38,71,0.92) 40%, rgba(10,38,71,0.35) 65%, transparent 100%)' }}
                    />
                </div>

                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-24">
                    <div className="max-w-lg">
                        <motion.div
                            initial={{ opacity: 0, y: 20 }}
                            animate={ctaSection.inView ? { opacity: 1, y: 0 } : {}}
                            transition={{ duration: 0.6 }}
                            className="space-y-10"
                        >
                            <div className="border-l-2 border-[#d0d4ec]/30 pl-8">
                                <span className="text-[#d0d4ec]/60 text-xs tracking-[0.2em] uppercase font-semibold block mb-3">
                                    For Individuals &amp; Institutions
                                </span>
                                <h3 className="text-3xl font-black text-white tracking-tight mb-4">
                                    Join the Movement
                                </h3>
                                <p className="text-white/60 leading-relaxed mb-6 text-sm">
                                    Students join free. Institutions from $100/year. Open to universities, industries,
                                    researchers, and innovators across Africa and beyond.
                                </p>
                                <Link
                                    href="/join"
                                    className="inline-flex items-center gap-2 h-12 px-8 bg-[#d0d4ec] text-[#1b265c] text-sm font-semibold tracking-wider uppercase hover:bg-white transition-colors"
                                >
                                    Apply for Membership
                                    <ArrowRight size={16} />
                                </Link>
                            </div>

                            <div className="border-l-2 border-[#df2548]/50 pl-8">
                                <span className="text-[#d0d4ec]/60 text-xs tracking-[0.2em] uppercase font-semibold block mb-3">
                                    For Funders &amp; Partners
                                </span>
                                <h3 className="text-3xl font-black text-white tracking-tight mb-4">
                                    Partner With ABEC
                                </h3>
                                <p className="text-white/60 leading-relaxed mb-6 text-sm">
                                    Invest in Africa's biomedical engineering future. Support Summer Schools, establish
                                    BME programs, and contribute to continental health security.
                                </p>
                                <Link
                                    href="/contact"
                                    className="inline-flex items-center gap-2 h-12 px-8 bg-[#df2548] text-white text-sm font-semibold tracking-wider uppercase hover:bg-[#c41e3d] transition-colors"
                                >
                                    Get in Touch
                                    <ArrowRight size={16} />
                                </Link>
                            </div>
                        </motion.div>
                    </div>
                </div>
            </section>
        </div>
    );
}
