'use client';

import { motion, type Variants } from 'framer-motion';
import Image from 'next/image';
import { InstagramReels } from '@/components/instagram-reels';
import { normalizeEmptyArrays } from '@/lib/cms';
import { Reveal } from '@/components/reveal';

function LinkedInIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.42v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.73v20.54C0 23.22.79 24 1.77 24h20.45c.98 0 1.78-.78 1.78-1.73V1.73C24 .77 23.2 0 22.22 0z" />
    </svg>
  );
}

const logoSymbolFallback = '/assets/IMG_1765_1782804058788.jpeg';
const buhariPhotoFallback = '/assets/IMG_1935_1782806399586.png';
const founderPhotoFallback = 'https://www.unitedeconomicforum.com/assets/img/about-person.png';

type Person = { name?: string; role?: string; quote?: string; photo?: string; paragraphs?: string[] };
type Director = { name: string; role?: string | null; desc?: string | null; img?: string | null; linkedin?: string | null };

/**
 * Only `name` is required on a director in the CMS, so a newly added board
 * member can arrive with no photo. next/image throws on a null src, which
 * would take the whole About page down — initials stand in instead.
 */
function DirectorPhoto({ member }: { member: Director }) {
  if (!member.img) {
    const initials = member.name
      .replace(/^(Mr\.|Ms\.|Mrs\.|Dr\.)\s*/i, '')
      .split(/\s+/)
      .slice(0, 2)
      .map((w) => w[0])
      .join('')
      .toUpperCase();
    return (
      <div className="absolute inset-0 flex items-center justify-center bg-primary/10 text-primary font-serif text-3xl font-semibold">
        {initials}
      </div>
    );
  }
  return (
    <Image
      src={member.img}
      alt={member.name}
      fill
      sizes="(min-width: 1024px) 16vw, (min-width: 768px) 25vw, 33vw"
      className="object-cover object-top transition-transform duration-500 group-hover/img:scale-105"
    />
  );
}
type Principle = { title: string; desc: string };

export type AboutData = {
  heroEyebrow?: string;
  heroTitle?: string;
  heroSubtitle?: string;
  visionHeading?: string;
  visionText?: string;
  missionHeading?: string;
  missionItems?: string[];
  leadershipHeading?: string;
  leadershipSubtitle?: string;
  founder?: Person;
  president?: Person;
  directorsHeading?: string;
  directorsSubtitle?: string;
  directors?: Director[];
  gemHeading?: string;
  gemTagline?: string;
  gemIntro?: string;
  gemPrinciples?: Principle[];
  gemClosing?: string;
  gemReels?: string[];
  objectivesHeading?: string;
  objectives?: string[];
  logoSymbol?: string;
};

const fadeUp: Variants = {
  hidden: { opacity: 0, y: 56 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.75, ease: [0.16, 1, 0.3, 1] } }
};

export function AboutContent({ data: rawData }: { data?: AboutData | null }) {
  // Empty arrays from the CMS must fall back like missing ones do.
  const data = normalizeEmptyArrays(rawData);
  const logoSymbol = data?.logoSymbol ?? logoSymbolFallback;

  const missionItems = data?.missionItems ?? [
    "Become a Catalyst for Economic and Social Development",
    "Contribute towards Viksit Bharat and Unnata Tamizhagam (உன்னத தமிழகம்-Inspirational Tamil Nadu) and a US $4 Trillion Economy for Tamil Nadu by 2047",
    "Bring together 1,500 like minded businessmen, technocrats, professionals, Educational Institutions (EI's) Chambers, Associations, NGOs etc. and provide entrepreneurial support.",
    "Encourage 10x growth for members",
    "Provide Strategic and Financial Advisory Services to Member Organisations.",
  ];

  const founder = data?.founder;
  const president = data?.president;

  const founderParagraphs = founder?.paragraphs ?? [
    "Alhaj Late Dr. B.S. Abdur Rahman, a distinguished descendant of the legendary philanthropist Seethakkathi, was born in Keelakarai, Tamil Nadu in 1927. A visionary industrialist, eminent educationist, philanthropist, and social reformer, renowned for his remarkable contributions to education, business, infrastructure, and social development.",
    "His lifelong dedication to education and social welfare led to the establishment of a vast network of educational and charitable institutions across Tamil Nadu including B.S. Abdur Rahman Crescent Institute of Science and Technology, Crescent School, Thassim Beevi Abdul Kader College for Women etc. These institutions educate over 18,000 students today.",
    "Dr. B. S. Abdur Rahman was also a pioneering entrepreneur and industrialist. He established several companies including ECCI, ETA Ascon, Star Insurance, etc, which became major contributors to the economic development of the Middle East & India generating employment opportunities for thousands of people.",
    "His companies were associated with the development of several landmark infrastructure projects in India and overseas, including Burj Khalifa in Dubai, Anna Flyover and Valluvar Kottam in Chennai, Delhi Metro etc.",
    "His legacy continues to inspire generations, and his vision of empowering society through education, entrepreneurship, and philanthropy remains a lasting testament to a life dedicated to the betterment of humanity.",
  ];

  const presidentParagraphs = president?.paragraphs ?? [
    "Ahmed Buhari is the son of the founder of UEF and has been serving as its President since 2011. A dynamic entrepreneur, visionary leader, and philanthropist, he has played a pivotal role in shaping UEF into a prominent platform for economic empowerment, entrepreneurship, and community development.",
    "He is the Founder of the C&O Group of Companies, which commissioned a 1,200 MW power plant in Tuticorin, Tamil Nadu, supplying approximately 5% of Tamil Nadu's power requirements. His entrepreneurial journey reflects his commitment to strengthening India's infrastructure and contributing to the nation's economic growth.",
    "Ahmed Buhari serves as a Board Member of B. S. Abdur Rahman Crescent Institute of Science and Technology, Director of Buhari Holdings, Trustee of Seethakkathi Trust, Founder of Tuticorin Development Board and Keelakarai Town Development Trust, through which he has contributed towards Nation building.",
    "He holds a Master's degree in Shipping, Trading and Finance from City St George's, University of London, and a degree in Marketing from Bentley University, Boston.",
    "Ahmed Buhari is committed to positioning UEF as a premier Economic and Social forum fostering a strong, united, and progressive community that can emerge as a Formidable Contributor to the nation and beyond.",
  ];

  const directors: Director[] = data?.directors ?? [
    { name: "Mr. Ahmed Buhari", role: "President, UEF", desc: "Trustee-BSA Crescent Institute", img: "/assets/IMG_2061_1782910005791.webp", linkedin: "https://www.linkedin.com/in/ahmedbuhari?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. Sajid Sathak", role: "Director General, UEF", desc: "MD, Inno Advisory P Ltd", img: "/assets/IMG_2071_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/sajid-sathak-99b850b?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. A. Mohamed Ali", role: "Director, UEF", desc: "Chairman & MD – South India Shelters", img: "/assets/IMG_2062_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/mohamed-ali-5a6740238?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Fathima Bathool Maluk", role: "Director – UEF · Secretary & CEO", desc: "MASTer Group of Institutions", img: "/assets/IMG_2063_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/fathima-bathool-maluk-52095b91?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. S. Yoosuf Mohamed", role: "Director, UEF", desc: "CEO – FAMY Consulting", img: "/assets/IMG_2064_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/yoosufmohamed?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. Tariq Akbar", role: "Director, UEF", desc: "Co-CEO, LegalEase Solutions · Venture Partner, Dallas Venture", img: "/assets/IMG_2065_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/tariq?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. Naveed Khan", role: "Director, UEF", desc: "Global Service Director – Project Management, Aracdis", img: "/assets/IMG_2066_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/naveed-khan-818aa82a2?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Dr. KM Abul Hasan", role: "Director, UEF", desc: "MD, City Hospital, Erode", img: "/assets/IMG_2067_1782910005791.jpeg", linkedin: "https://www.linkedin.com/in/drkmabulhasan?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. S.K.M. Abdul Cader", role: "Director, UEF", desc: "CEO – Kitchen House", img: "/assets/IMG_2023_1782910005791.jpeg", linkedin: null },
    { name: "Mr. Faizel Abdul Cader", role: "Director, UEF", desc: "Director, Mohammed Sathak Trust & Group", img: "/assets/IMG_2024_1782910005791.jpeg", linkedin: null },
    { name: "Ms. Zainab Millwala", role: "Director, UEF", desc: "CEO – Fermier Engineers · Co-Founder, Maheela Power", img: "/assets/IMG_2022_1782910005791.png", linkedin: "https://www.linkedin.com/in/zainabmillwalamaster?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
    { name: "Mr. Jubran Siddique", role: "Youth Director, UEF", desc: "Co-Founder, Edge Up", img: "/assets/104cd594-2fa7-417c-a563-6fb7aa57d5f8_1782910729313.jpeg", linkedin: "https://www.linkedin.com/in/jubransiddique?utm_source=share_via&utm_content=profile&utm_medium=member_ios" },
  ];

  const gemPrinciples: Principle[] = data?.gemPrinciples ?? [
    { title: "Integrity", desc: "over shortcuts" },
    { title: "Trust", desc: "over tactics" },
    { title: "Shared Success", desc: "over solo wins" },
  ];

  const gemReels = data?.gemReels ?? [
    'https://www.instagram.com/p/DaR6xT3TSum/',
    'https://www.instagram.com/p/DXjXrSzk-58/',
    'https://www.instagram.com/p/DWn59stk50S/',
    'https://www.instagram.com/p/DXhMCink_4y/',
    'https://www.instagram.com/p/DZmKvWATl3-/',
  ];

  const objectives = data?.objectives ?? [
    "To function as a Chamber of Commerce for promoting Trade, Commerce and Industry.",
    "To provide entrepreneurial support for existing members as also to encourage and mentor aspiring and budding ones.",
    "To actively promote networking among members as well as other trade organisations.",
    "To hold dialogue with government by providing feedback from the industry on policy matters.",
    "To conduct market surveys and carry out economic research.",
    "To organize Trade and Investment missions for members to explore investment and business development potential in India and globally.",
    "To setup an Advisory & Investment Facilitation Cell for Facilitating Private Equity Finance including Shariah Compliant Funds.",
  ];

  return (
    <div className="flex flex-col min-h-screen pt-32 bg-background">
      {/* Header */}
      <section className="py-20 md:py-28 bg-gradient-to-b from-primary/[0.09] via-muted to-background relative overflow-hidden">
        <img src={logoSymbol} className="absolute right-0 top-0 w-[500px] opacity-[0.07] object-contain translate-x-1/3 -translate-y-1/4" alt="" aria-hidden="true" />
        {/* Two soft primary washes give the flat muted band some depth without
            putting anything behind the text that would hurt contrast. */}
        <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="hidden" animate="visible" variants={fadeUp}
            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 ?? 'A platform · A purpose · A promise'}
          </motion.p>

          <motion.h1 initial="hidden" animate="visible" variants={fadeUp} className="text-5xl md:text-6xl font-serif font-semibold">{data?.heroTitle ?? 'About UEF'}</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="hidden" animate="visible" variants={fadeUp} className="text-xl text-foreground/70 max-w-3xl mx-auto leading-relaxed">
            {data?.heroSubtitle ?? 'A premier Chamber of Commerce dedicated to the economic, educational, and social transformation of the community since 1979.'}
          </motion.p>
        </div>
      </section>

      {/* Vision & Mission */}
      <section className="py-24 bg-white border-b border-border">
        <div className="container mx-auto px-6 md:px-12">
          <div className="grid md:grid-cols-2 gap-16">
            <motion.div initial="hidden" whileInView="visible" viewport={{ margin: '-100px' }} variants={fadeUp}>
              <h2 className="text-xl font-semibold tracking-widest text-primary uppercase mb-4">{data?.visionHeading ?? 'Our Vision'}</h2>
              <p className="text-lg text-foreground/80 leading-relaxed">
                {data?.visionText ?? 'To emerge as a ‘Premier Forum’ for enabling the Backward Community and Society at Large to become ‘Inspirational & Formidable Contributors to the Nation and Beyond’ through Economic Enhancement, Education and Social Development.'}
              </p>
            </motion.div>

            <motion.div initial="hidden" whileInView="visible" viewport={{ margin: '-100px' }} variants={fadeUp}>
              <h2 className="text-xl font-semibold tracking-widest text-primary uppercase mb-4">{data?.missionHeading ?? 'Our Mission'}</h2>
              <ul className="space-y-4 text-lg text-foreground/80">
                {missionItems.map((item, i) => (
                  <li key={i} className="flex items-start gap-3">
                    <div className="w-2 h-2 rounded-full bg-primary mt-2 shrink-0" />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </motion.div>
          </div>
        </div>
      </section>

      {/* Leadership */}
      <section className="py-24 bg-muted">
        <div className="container mx-auto px-6 md:px-12">
          <Reveal className="text-center max-w-3xl mx-auto mb-16">
            <h2 className="text-4xl font-serif font-semibold mb-4">{data?.leadershipHeading ?? 'Leadership'}</h2>
            <p className="text-foreground/70 text-lg">{data?.leadershipSubtitle ?? 'Guided by visionaries committed to nation-building.'}</p>
          </Reveal>

          <div className="space-y-24">
            {/* Founder */}
            <div className="grid md:grid-cols-12 gap-12 items-center">
              <div className="md:col-span-5 relative">
                <div className="uef-card uef-card-lift group aspect-[4/5] rounded-xl shadow-lg border border-border">
                  <img src={founder?.photo ?? founderPhotoFallback} alt={founder?.name ?? 'Alhaj Late Dr. B.S. Abdur Rahman'} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
                </div>
              </div>
              <div className="md:col-span-7">
                <h3 className="text-3xl font-serif font-semibold mb-2">{founder?.name ?? 'Alhaj Late Dr. B.S. Abdur Rahman'}</h3>
                <p className="text-primary font-medium text-lg mb-6">{founder?.role ?? 'Founder, UEF'}</p>
                <div className="space-y-4 text-foreground/80 leading-relaxed text-lg">
                  {founderParagraphs.map((p, i) => <p key={i}>{p}</p>)}
                </div>
              </div>
            </div>

            {/* President */}
            <div className="grid md:grid-cols-12 gap-12 items-center">
              <div className="md:col-span-5 md:order-last relative">
                <div className="uef-card uef-card-lift group aspect-[4/5] rounded-xl shadow-lg border border-border">
                  <Image src={president?.photo ?? buhariPhotoFallback} alt={president?.name ?? 'Ahmed A.R. Buhari'} fill sizes="(min-width: 768px) 40vw, 100vw" className="object-cover object-top transition-transform duration-500 group-hover:scale-105" />
                </div>
              </div>
              <div className="md:col-span-7 md:order-first">
                <h3 className="text-3xl font-serif font-semibold mb-2">{president?.name ?? 'Mr. Ahmed A.R. Buhari'}</h3>
                <p className="text-primary font-medium text-lg mb-6">{president?.role ?? 'President, UEF & Trustee-BSA Crescent Institute'}</p>
                <blockquote className="text-2xl font-serif italic text-foreground border-l-4 border-primary pl-6 py-2 mb-8">
                  {president?.quote ?? '"Integrity, Humility and purpose driven mindset should be built on for the betterment of the Society, Nation and Beyond."'}
                </blockquote>
                <div className="space-y-4 text-foreground/80 leading-relaxed text-lg">
                  {presidentParagraphs.map((p, i) => <p key={i}>{p}</p>)}
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Board of Directors */}
      <section className="py-24 bg-white">
        <div className="container mx-auto px-6 md:px-12">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-serif font-semibold mb-3">{data?.directorsHeading ?? 'Board of Directors'}</h2>
            <p className="text-foreground/60 text-lg">{data?.directorsSubtitle ?? '12 leaders across industry, technology, and civil society.'}</p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
            {directors.map((member, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, scale: 0.95 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ margin: '-100px' }}
                transition={{ delay: i * 0.05 }}
                whileHover={{ y: -8, transition: { duration: 0.25, ease: 'easeOut' } }}
                className="group"
              >
                {member.linkedin ? (
                  <a
                    href={member.linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    aria-label={`Open ${member.name}'s LinkedIn profile`}
                    className="uef-card group/img block aspect-square bg-muted rounded-xl mb-3 border border-border shadow-sm"
                  >
                    <DirectorPhoto member={member} />
                    <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-primary/85 text-white opacity-0 group-hover/img:opacity-100 transition-opacity duration-300">
                      <LinkedInIcon className="w-6 h-6" />
                      <span className="text-[11px] font-semibold text-center px-2 leading-tight">Open LinkedIn profile</span>
                    </div>
                  </a>
                ) : (
                  <div className="uef-card aspect-square bg-muted rounded-xl mb-3 border border-border shadow-sm">
                    <DirectorPhoto member={member} />
                  </div>
                )}
                <h4 className="font-serif font-semibold text-[13px] leading-tight">{member.name}</h4>
                <p className="text-[11px] text-primary font-semibold mt-1 leading-snug">{member.role}</p>
                <p className="text-[11px] text-foreground/55 mt-0.5 leading-snug">{member.desc}</p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Good Economy Movement */}
      <section className="py-24 bg-white border-t border-border">
        <div className="container mx-auto px-6 md:px-12 max-w-3xl text-center">
          <motion.div initial="hidden" whileInView="visible" viewport={{ margin: '-100px' }} variants={fadeUp}>
            <h2 className="text-3xl md:text-4xl font-semibold tracking-widest uppercase mb-8 text-primary">
              {data?.gemHeading ?? 'Good Economy Movement'}
            </h2>

            <p className="text-lg md:text-xl font-serif font-semibold text-foreground leading-snug mb-10 whitespace-pre-line">
              {data?.gemTagline ?? 'Trade is not just about finance.\nBusiness is not just about transactions.'}
            </p>

            <p className="text-lg text-foreground/70 leading-relaxed mb-10 whitespace-pre-line">
              {data?.gemIntro ?? 'Good Economy is a shift.\nFrom deals to dignity, from growth at any cost to growth with values.'}
            </p>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-10">
              {gemPrinciples.map((principle, i) => (
                <div key={i} className="uef-card uef-card-lift group bg-muted rounded-xl p-5 border border-border">
                  <p className="text-xl md:text-2xl font-serif font-semibold text-foreground">{principle.title}</p>
                  <p className="text-sm text-foreground/60">{principle.desc}</p>
                </div>
              ))}
            </div>

            <p className="text-lg text-foreground/70 leading-relaxed">
              {data?.gemClosing ?? 'At UEF, we believe good business uplifts people, strengthens communities, and creates lasting progress. This is the future we are shaping.'}
            </p>
          </motion.div>
        </div>

        <div className="container mx-auto px-6 md:px-12 mt-16">
          <InstagramReels urls={gemReels} />
        </div>
      </section>

      {/* Objectives */}
      <section className="py-24 bg-primary text-primary-foreground relative overflow-hidden">
        <img src={logoSymbol} className="absolute left-0 bottom-0 w-full opacity-5 object-cover translate-y-1/2" alt="" aria-hidden="true" />
        <div className="container mx-auto px-6 md:px-12 relative z-10">
          <Reveal>
            <h2 className="text-4xl font-serif font-semibold mb-12 text-center">{data?.objectivesHeading ?? 'Chamber of Commerce Objectives'}</h2>
          </Reveal>
          <div className="grid md:grid-cols-2 gap-8 max-w-5xl mx-auto">
            {objectives.map((obj, i) => {
              // The first objective — being a Chamber of Commerce — is the one the
              // other six qualify, so it leads at full width. That also fixes the
              // parity: 1 featured + 6 leaves a clean 2x3 grid with nothing
              // stranded. The orphan guard stays for a CMS edit that changes the
              // count, since 1 + an odd remainder would strand one again.
              const featured = i === 0;
              const orphan = !featured && objectives.length % 2 === 0 && i === objectives.length - 1;
              return (
              <div
                key={i}
                className={`uef-card uef-card-lift uef-card-on-primary group flex gap-4 items-start bg-primary-foreground/10 rounded-lg backdrop-blur-sm border border-white/15${
                  featured
                    ? ' md:col-span-2 p-7 md:p-8 gap-5 border-white/30 bg-primary-foreground/[0.16]'
                    : ' p-6'
                }${orphan ? ' md:col-span-2 md:mx-auto md:w-[calc(50%-1rem)]' : ''}`}
              >
                <div
                  className={`rounded-full bg-white/20 flex items-center justify-center shrink-0 font-serif transition-colors duration-300 group-hover:bg-white/35 ${
                    featured ? 'w-11 h-11 text-lg' : 'w-8 h-8 text-sm'
                  }`}
                >
                  {i + 1}
                </div>
                <p className={`leading-relaxed ${featured ? 'text-xl md:text-2xl font-serif' : 'text-lg'}`}>{obj}</p>
              </div>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}
