'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import Link from 'next/link';

interface ParticipationItem {
  year: number;
  title: string;
  location: string | null;
  date_label: string | null;
}

interface PageIntro {
  intro_eyebrow: string;
  intro_title: string;
  intro_para1: string | null;
  intro_para2: string | null;
}

const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';

const STATIC_INTRO: PageIntro = {
  intro_eyebrow: 'Our Participation',
  intro_title: 'Active Engagement Across Global Platforms',
  intro_para1:
    'Our team members consistently share their expertise and insights at leading industry events, reflecting our commitment to advancing knowledge in animal agriculture. This includes frequent participation as invited speakers at prestigious conferences like Novacon, WVPA (India) Conference, and the Adisseo Technical Summit, where our professionals, such as Dr. Sudipto Haldar, Dr. Sayantani Sihi Arora, and Dr. Anirvid Sarkar, present on critical topics.',
  intro_para2:
    'Furthermore, our team actively engages in specialized forums like the Annual Poultry Science Conference in the USA and various technical seminars, often taking on roles from lead speaker to co-organizer, ensuring our contributions directly influence the latest discussions and innovations in the field.',
};

const STATIC_DATA: Record<number, ParticipationItem[]> = {
  2025: [
    { year: 2025, date_label: 'August 2025',        title: 'Animal Agriculture in India – The Way Forward, CLFMA AGM & National Symposium 2025', location: 'Hyderabad, India' },
    { year: 2025, date_label: 'February 2025',       title: 'Disease Diagnosis In Poultry – Modern Approach, Kolkata International Poultry Fair',  location: 'Kolkata, India' },
    { year: 2025, date_label: '2025',                title: 'Technical Seminar by Novus International',                                             location: 'Thiruvananthapuram, India' },
    { year: 2025, date_label: 'February 2025',       title: 'Novacon',                                                                              location: 'Kolkata, India' },
    { year: 2025, date_label: '10–11 November 2025', title: 'Asian Agribiz Layer Quality Conference',                                               location: 'Bangkok, Thailand' },
  ],
  2024: [
    { year: 2024, date_label: '2024',          title: 'XXXII Annual Conference of Society of Animal Physiologists of India & International Symposium', location: 'Meerut, India' },
    { year: 2024, date_label: '2024',          title: 'Ingredient IQ',                                                                                 location: 'Pune, India' },
    { year: 2024, date_label: 'February 2024', title: 'Novacon',                                                                                       location: 'Kolkata, India' },
    { year: 2024, date_label: '2024',          title: 'WVPA (India) Conference',                                                                       location: 'Bengaluru, India' },
  ],
  2023: [
    { year: 2023, date_label: '2023',         title: 'World Veterinary Poultry Association Conference',                                  location: 'Jabalpur, India' },
    { year: 2023, date_label: '2023',         title: 'Novacon, West Bengal Poultry Federation',                                          location: 'Kolkata, India' },
    { year: 2023, date_label: '2023',         title: 'Novacon, West Bengal Poultry Federation',                                          location: 'Kolkata, India' },
    { year: 2023, date_label: '2023',         title: 'Adisseo Technical Summit',                                                         location: null },
    { year: 2023, date_label: '2023',         title: 'Adisseo Technical Summit',                                                         location: null },
    { year: 2023, date_label: 'October 2023', title: '12th Asia Pacific Poultry Conference (APPC 2023), October 31 – November 3, 2023', location: 'Nanjing, China' },
  ],
  2020: [
    { year: 2020, date_label: 'February 2020', title: 'World Veterinary Poultry Association Conference', location: 'Bangalore, India' },
  ],
  2019: [
    { year: 2019, date_label: 'November 2019',  title: 'Poultry Knowledge Day – Poultry India',                                                  location: 'Hyderabad, India' },
    { year: 2019, date_label: 'September 2019', title: 'World Veterinary Poultry Association Congress',                                          location: 'Bangkok, Thailand' },
    { year: 2019, date_label: 'July 2019',      title: 'PSA Annual Meeting',                                                                     location: 'Montreal, Canada' },
    { year: 2019, date_label: 'July 2019',      title: 'A Technical Symposium – "Nutrition & Gut Health Management in High Performing Animals"', location: 'Kuala Lumpur, Malaysia' },
    { year: 2019, date_label: 'March 2019',     title: 'VIV Asia 2019 – 11th International Poultry Show & Seminar',                             location: 'Bangkok, Thailand; Dhaka, Bangladesh' },
  ],
  2018: [
    { year: 2018, date_label: 'November 2018',  title: 'Poultry Knowledge Day – Poultry India',                                  location: 'Hyderabad, India' },
    { year: 2018, date_label: 'October 2018',   title: 'World Veterinary Poultry Association Asia Conference',                   location: 'Kuala Lumpur, Malaysia' },
    { year: 2018, date_label: 'September 2018', title: 'Poultry Panorama',                                                       location: 'Phuket, Thailand' },
    { year: 2018, date_label: 'July 2018',      title: 'Visit to Poultry Research Facility of North Carolina State University', location: 'Raleigh, USA' },
    { year: 2018, date_label: 'March 2018',     title: 'VICTAM Asia 2018',                                                       location: 'Bangkok, Thailand' },
  ],
  2017: [
    { year: 2017, date_label: 'November 2017',  title: 'Poultry Knowledge Day – Poultry India',                                           location: 'Hyderabad, India' },
    { year: 2017, date_label: 'September 2017', title: 'Golden Jubilee Celebration of CLAFMA of India',                                  location: 'Mumbai, India' },
    { year: 2017, date_label: 'August 2017',    title: 'Broiler Feed Quality Conference & Advanced Feed Mill Management Symposium',       location: 'Bangkok, Thailand; Kolkata, India' },
    { year: 2017, date_label: 'June 2017',      title: 'Asia Pacific Summit on Feed Enzymes in Animal Nutrition ("2017 AAFAN")',         location: 'Bangkok, Thailand; Beijing, China' },
    { year: 2017, date_label: 'March 2017',     title: 'VIV Asia 2017',                                                                  location: 'Bangkok, Thailand' },
  ],
  2016: [
    { year: 2016, date_label: 'December 2016', title: 'Seminar of Arm & Hammer',                                                                                location: 'Hyderabad, India' },
    { year: 2016, date_label: 'November 2016', title: 'Poultry Knowledge Day – Poultry India',                                                                  location: 'Hyderabad, India' },
    { year: 2016, date_label: 'August 2016',   title: "Broiler Feed Quality Conference & Best Technical Service Provider Award – Poultry CEO's Forum India",    location: 'Bangkok, Thailand; Hyderabad, India' },
    { year: 2016, date_label: 'July 2016',     title: 'PSA Annual Meeting',                                                                                     location: 'New Orleans, USA' },
    { year: 2016, date_label: 'April 2016',    title: 'Visit to "Feed Design Lab"',                                                                             location: 'Stayerhofweg, Netherlands' },
    { year: 2016, date_label: 'January 2016',  title: 'The International Production & Processing Expo',                                                         location: 'Atlanta, USA' },
  ],
  2015: [
    { year: 2015, date_label: 'November 2015',  title: 'Poultry Knowledge Day – Poultry India',                           location: 'Hyderabad, India' },
    { year: 2015, date_label: 'September 2015', title: 'Poultry Feed Quality Conference',                                 location: 'Bangkok, Thailand' },
    { year: 2015, date_label: 'August 2015',    title: 'ResCom Summit & European Symposium on Poultry Nutrition (ESPN)', location: 'Goa, India; Prague, Czech Republic' },
    { year: 2015, date_label: 'May 2015',       title: 'Alltech REBELation',                                             location: 'Lexington, USA' },
    { year: 2015, date_label: '2015',           title: 'Technical Symposium Conducted by MSD Animal Health',             location: 'Malacca, Malaysia' },
    { year: 2015, date_label: 'March 2015',     title: 'VIV Asia 2015 & Novus Feed Technology Seminar',                 location: 'Bangkok, Thailand' },
  ],
  2013: [
    { year: 2013, date_label: 'December 2013', title: 'Alltech South Asia Poultry Nutrition Summit 2013', location: 'Colombo, Sri Lanka' },
    { year: 2013, date_label: 'March 2013',    title: 'VIV Asia 2013',                                   location: 'Bangkok, Thailand' },
  ],
};

const STATIC_YEARS = Object.keys(STATIC_DATA).map(Number).sort((a, b) => b - a);

export default function ParticipationPage() {
  const [intro, setIntro] = useState<PageIntro>(STATIC_INTRO);
  const [byYear, setByYear] = useState<Record<number, ParticipationItem[]>>(STATIC_DATA);
  const [years, setYears] = useState<number[]>(STATIC_YEARS);
  const [yearIdx, setYearIdx] = useState(0);
  const [slide, setSlide] = useState(0);
  const [cardsPerSlide, setCardsPerSlide] = useState(2);
  const trackRef = useRef<HTMLDivElement>(null);
  const pillsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function updateCPS() { setCardsPerSlide(window.innerWidth <= 820 ? 1 : 2); }
    updateCPS();
    window.addEventListener('resize', updateCPS);
    return () => window.removeEventListener('resize', updateCPS);
  }, []);

  useEffect(() => {
    fetch(`${API_BASE}/api/participations`)
      .then(r => r.json())
      .then(data => {
        if (data.page) setIntro(data.page);
        if (data.participations) {
          const mapped: Record<number, ParticipationItem[]> = {};
          for (const yr in data.participations) {
            mapped[Number(yr)] = data.participations[yr];
          }
          setByYear(mapped);
        }
        if (data.years && data.years.length > 0) {
          setYears(data.years.map(Number));
        }
      })
      .catch(() => {});
  }, []);

  const currentYear = years[yearIdx] ?? years[0];
  const items = byYear[currentYear] ?? [];
  const totalSlides = Math.max(1, Math.ceil(items.length / cardsPerSlide));
  const clampedSlide = Math.min(slide, totalSlides - 1);
  const pageItems = items.slice(clampedSlide * cardsPerSlide, (clampedSlide + 1) * cardsPerSlide);

  const goSlide = useCallback((idx: number) => {
    setSlide(Math.max(0, Math.min(idx, totalSlides - 1)));
  }, [totalSlides]);

  function selectYear(i: number) {
    setYearIdx(i);
    setSlide(0);
  }

  function scrollYears(dir: 'left' | 'right') {
    pillsRef.current?.scrollBy({ left: dir === 'left' ? -180 : 180, behavior: 'smooth' });
  }

  return (
    <>
      {/* ── Hero ── */}
      <div
        className="op-hero"
        style={{
          background:
            "linear-gradient(135deg,rgba(6,18,10,.88) 0%,rgba(8,24,14,.65) 60%,rgba(8,24,14,.5) 100%), url('/images/presentationsbannernew.webp') center/cover no-repeat",
        }}
      >
        <div className="op-hero-deco" aria-hidden="true">
          <svg className="deco-leaf-1" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
            <path d="M100 50 C140 70 160 130 140 190 C120 250 60 260 40 200" stroke="#a9d4bc" strokeWidth="1.5" fill="none"/>
          </svg>
          <svg className="deco-leaf-2" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
          </svg>
        </div>

        <div className="container op-hero-inner">
          <nav className="op-breadcrumb op-breadcrumb--sm" aria-label="Breadcrumb">
            <Link href="/" className="op-bc-item">Home</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item">Insights &amp; Outreach</span>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">Participation</span>
          </nav>
          <h1>Our <em>Participation</em></h1>
        </div>

        <div className="op-hero-wave" aria-hidden="true">
          <svg viewBox="0 0 1440 60" preserveAspectRatio="none" fill="#ffffff">
            <path d="M0,40 C360,70 1080,10 1440,40 L1440,60 L0,60Z"/>
          </svg>
        </div>
      </div>

      {/* ── Main section ── */}
      <section className="pres2-section" aria-label="Participation">
        <div className="container pres2-wrap">

          <div className="pres2-layout">

            {/* LEFT: intro content only */}
            <aside className="pres2-intro-col">
              <div className="pres2-intro-sticky">
                <span className="section-eyebrow">{intro.intro_eyebrow}</span>
                <h2 className="pres2-intro-title">{intro.intro_title}</h2>
                {intro.intro_para1 && <p className="pres2-intro-text">{intro.intro_para1}</p>}
                {intro.intro_para2 && <p className="pres2-intro-text">{intro.intro_para2}</p>}
              </div>
            </aside>

            {/* RIGHT: year pills + carousel */}
            <div className="pres2-main-col">

              {/* Scrollable year pills with arrow buttons */}
              <div className="pres2-year-row">
                <button
                  className="pres2-year-arrow"
                  onClick={() => scrollYears('left')}
                  aria-label="Scroll years left"
                >
                  <i className="fas fa-chevron-left" />
                </button>

                <div className="pres2-year-pills" ref={pillsRef} role="group" aria-label="Filter by year">
                  {years.map((y, i) => (
                    <button
                      key={y}
                      className={`pres2-year-pill${i === yearIdx ? ' pres2-year-pill--active' : ''}`}
                      onClick={() => selectYear(i)}
                      aria-pressed={i === yearIdx}
                    >
                      {y}
                      <span className="pres2-year-pill-cnt">{byYear[y]?.length ?? 0}</span>
                    </button>
                  ))}
                </div>

                <button
                  className="pres2-year-arrow"
                  onClick={() => scrollYears('right')}
                  aria-label="Scroll years right"
                >
                  <i className="fas fa-chevron-right" />
                </button>
              </div>

              {/* Card carousel */}
              <div className="pres2-carousel-area">

                <div className="pres2-carousel-header">
                  <h3 className="pres2-carousel-year">{currentYear}</h3>
                  <span className="pres2-carousel-count">
                    {clampedSlide + 1} / {totalSlides}
                  </span>
                </div>

                {/* Cards — 2 per slide on desktop, 1 on mobile */}
                {pageItems.length > 0 && (
                  <div ref={trackRef} key={`${currentYear}-${clampedSlide}`} className="pres2-cards-track">
                    {pageItems.map((item, idx) => {
                      const globalIdx = clampedSlide * cardsPerSlide + idx;
                      const num = String(globalIdx + 1).padStart(2, '0');
                      return (
                        <article key={globalIdx} className="pres2-card">
                          <span className="pres2-card-num" aria-hidden="true">{num}</span>

                          <div className="pres2-card-top">
                            <h4 className="pres2-card-title">{item.title}</h4>
                          </div>

                          <div className="pres2-card-foot">
                            {item.location && item.location !== '—' && (
                              <span className="pres2-card-chip">
                                <i className="fas fa-map-marker-alt" aria-hidden="true" />
                                {item.location}
                              </span>
                            )}
                            {item.date_label && (
                              <span className="pres2-card-chip pres2-card-chip--date">
                                <i className="fas fa-calendar-alt" aria-hidden="true" />
                                {item.date_label}
                              </span>
                            )}
                          </div>
                        </article>
                      );
                    })}
                  </div>
                )}

                {/* Prev / dots / next */}
                <div className="pres2-carousel-nav">
                  <button
                    className="pres2-nav-btn"
                    onClick={() => goSlide(clampedSlide - 1)}
                    disabled={clampedSlide <= 0}
                    aria-label="Previous"
                  >
                    <i className="fas fa-chevron-left" />
                  </button>

                  <div className="pres2-dots" role="tablist" aria-label="Slides">
                    {Array.from({ length: totalSlides }, (_, i) => (
                      <button
                        key={i}
                        className={`pres2-dot${i === clampedSlide ? ' pres2-dot--active' : ''}`}
                        onClick={() => goSlide(i)}
                        aria-label={`Slide ${i + 1}`}
                        role="tab"
                        aria-selected={i === clampedSlide}
                      />
                    ))}
                  </div>

                  <button
                    className="pres2-nav-btn"
                    onClick={() => goSlide(clampedSlide + 1)}
                    disabled={clampedSlide >= totalSlides - 1}
                    aria-label="Next"
                  >
                    <i className="fas fa-chevron-right" />
                  </button>
                </div>

              </div>
            </div>

          </div>
        </div>
      </section>
    </>
  );
}
