'use client';

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

interface Presentation {
  year: number;
  title: string | null;
  event: string | null;
  speaker: string | null;
  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 Presentations',
  intro_title: 'Deep Dives into Specialised Knowledge',
  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.',
  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, Presentation[]> = {
  2025: [
    { year: 2025, date_label: 'August 2025',   location: '',                   event: '',                                                      title: 'How to recognise when intestinal challenges are likely to occur and what influences them?', speaker: 'Dr. Sudipto Haldar' },
    { year: 2025, date_label: '2025',           location: 'Mahabalipuram, India', event: '',                                                    title: 'Antibiotic-Free Poultry Production in the Era of AMR: Debunking Myths and Advancing Science', speaker: 'Dr. Sudipto Haldar' },
    { year: 2025, date_label: 'February 2025', location: 'Kolkata, India',     event: 'Kolkata International Poultry Fair',                    title: 'Disease Diagnosis In Poultry – Modern Approach', speaker: 'Dr. Amrita Kumar Dhara' },
    { year: 2025, date_label: '2025',           location: 'Thiruvananthapuram', event: 'Technical Seminar by Novus International',             title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2025, date_label: 'February 2025', location: 'Kolkata, India',     event: 'Novacon',                                              title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2025, date_label: 'February 2025', location: 'Bangkok, Thailand',  event: 'Starch function and its impact on digestive function',  title: null, speaker: 'Dr. Sudipto Haldar' },
  ],
  2024: [
    { year: 2024, date_label: '2024',          location: 'Meerut, India',    event: 'XXXII Annual Conference of Society of Animal Physiologists of India & International Symposium', title: null, speaker: 'Dr. Sayantani Sihi Arora' },
    { year: 2024, date_label: '2024',          location: 'Pune, India',      event: 'Ingredient IQ',        title: null, speaker: 'Dr. Anirvid Sarkar' },
    { year: 2024, date_label: 'February 2024', location: 'Kolkata, India',   event: 'Novacon',              title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2024, date_label: '2024',          location: 'Bengaluru, India', event: 'WVPA (India) Conference', title: null, speaker: 'Dr. Sayantani Sihi Arora' },
  ],
  2023: [
    { year: 2023, date_label: '2023', location: 'Jabalpur, India', event: 'World Veterinary Poultry Association Conference', title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2023, date_label: '2023', location: 'Kolkata, India',  event: 'Novacon, West Bengal Poultry Federation',        title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2023, date_label: '2023', location: 'Kolkata, India',  event: 'Novacon, West Bengal Poultry Federation',        title: null, speaker: 'Dr. Anirvid Sarkar' },
    { year: 2023, date_label: '2023', location: null,              event: 'Adisseo Technical Summit',                       title: null, speaker: 'Dr. Sudipto Haldar' },
    { year: 2023, date_label: '2023', location: null,              event: 'Adisseo Technical Summit',                       title: null, speaker: 'Dr. Amrita Kumar Dhara' },
  ],
  2020: [
    { year: 2020, date_label: 'November 2020', location: 'Bengaluru, India',   event: 'National webinar on Entrepreneurial Opportunities in Rural Poultry at ICAR', title: 'Business plan, Economics and Marketing opportunities in Rural Poultry', speaker: 'Dr. Anirvid Sarkar' },
    { year: 2020, date_label: 'October 2020',  location: 'West Bengal, India', event: 'National webinar on Backyard Poultry at Uttar Banga Krishi Viswavidyalaya', title: 'Trends & Opportunities for Marketing and Business economy for Backyard Poultry', speaker: 'Dr. Anirvid Sarkar' },
    { year: 2020, date_label: 'January 2020',  location: 'Bengaluru, India',   event: 'Interactive session with Marketing Frontrunners: Natural remedies', title: 'Trouble shooting in poultry nutrition', speaker: 'Dr. Sudipto Haldar' },
  ],
  2019: [
    { year: 2019, date_label: 'December 2019',  location: 'Kolkata, India',                       event: 'International Conference on Animal Nutrition, ANSI',            title: 'Removing antibiotics from poultry diets for a better future: implications and strategies', speaker: 'Dr. Sudipto Haldar' },
    { year: 2019, date_label: 'September 2019', location: 'Kolkata, India',                       event: 'Winter School by ICAR and University of Animal and Fishery Sciences', title: 'Basics of Poultry Feed Formulation', speaker: 'Dr. Sudipto Haldar' },
    { year: 2019, date_label: 'August 2019',    location: 'Bangkok, Thailand / Jakarta, Indonesia', event: 'Broiler Feed Quality Conference', title: 'Practical solutions for water quality issues', speaker: 'Dr. Sudipto Haldar' },
    { year: 2019, date_label: 'August 2019',    location: 'Dhaka, Bangladesh',                    event: 'Technical Seminar by AB Vista South Asia', title: 'Recent Trends in Poultry Nutrition', speaker: 'Dr. Sudipto Haldar' },
    { year: 2019, date_label: 'February 2019',  location: 'Bhubaneswar, India',                   event: 'Indian Poultry Review Annual Conclave', title: 'Unconventional raw materials in broiler diets… Do they really reduce costs?', speaker: 'Dr. Sudipto Haldar' },
    { year: 2019, date_label: 'June 2019',      location: 'Biratnagar & Kathmandu, Nepal',        event: 'Technical seminar by Ravioza Biotech', title: 'Role of management in producing antibiotic free chicken', speaker: 'Dr. Sudipto Haldar; Dr. Amrita Kumar Dhara' },
    { year: 2019, date_label: 'April 2019',     location: 'Kolkata, India',                       event: 'Directorate of Research, Extension & Farms, WBUAFS', title: 'Viral diseases of poultry with special emphasis on gross pathology', speaker: 'Dr. Amrita Kumar Dhara' },
  ],
  2018: [
    { year: 2018, date_label: 'July 2018',      location: 'San Antonio, Texas, USA', event: 'Poultry Science Association Annual Meeting 2018', title: 'Evaluation of a new generation intrinsically heat stable phytase at different levels of inclusion', speaker: 'Dr. Sudipto Haldar' },
    { year: 2018, date_label: 'October 2018',   location: 'Kuala Lumpur, Malaysia',  event: 'Distributor Training Program by Natural Remedies', title: 'Understanding the chicken gut microbiota – an insight into the factors leading to a healthy gut', speaker: 'Dr. Sudipto Haldar' },
    { year: 2018, date_label: 'November 2018',  location: 'Chitwan, Nepal',          event: 'Technical training by Nepal Veterinary Organization', title: 'A good quality protein meal pays dividend; Trace mineral nutrition of Poultry', speaker: 'Dr. Sudipto Haldar; Dr. Aivan Priyadarshi' },
    { year: 2018, date_label: 'May 2018',       location: 'Kathmandu, Nepal',        event: 'Poultry Nutrition and Feed Formulation Workshop, US Soybean Export Council', title: 'Basics of Poultry Feed Formulation; Critical look at protein meals', speaker: 'Dr. Sudipto Haldar' },
    { year: 2018, date_label: 'September 2018', location: 'Chandigarh, India',       event: 'Technical Seminar by Rossari Biotech Ltd', title: 'Gut health drives performance in poultry… An insight into the factors leading to a healthy gut', speaker: 'Dr. Sudipto Haldar' },
  ],
  2017: [
    { year: 2017, date_label: 'March 2017',     location: 'Bangkok, Thailand',                     event: 'Poultry Innovation Summit Asia 2017 by CevaSanteAnimale',    title: 'Surfactant technology for efficient feed production', speaker: 'Dr. Sudipto Haldar' },
    { year: 2017, date_label: 'May 2017',       location: 'Dhaka, Bangladesh',                     event: 'Technical Seminar by Guybro Chemicals',                     title: 'Organic Trace minerals – the key to extract the most from your flock', speaker: 'Dr. Sudipto Haldar' },
    { year: 2017, date_label: 'September 2017', location: 'Jakarta, Indonesia / Hyderabad, India', event: 'Technical Seminar by Novus International',                  title: 'How to use enzymes and their matrix values in poultry feed formulations', speaker: 'Dr. Sudipto Haldar' },
    { year: 2017, date_label: 'October 2017',   location: 'New Delhi, India',                      event: 'Biomin Asia Nutrition Forum',                               title: 'Feed converter – the gift from a Healthy gut', speaker: 'Dr. Sudipto Haldar' },
    { year: 2017, date_label: 'August 2017',    location: 'Bangkok, Thailand',                     event: 'Broiler Feed Quality Conference',                           title: 'Raising broiler chickens in an antibiotic free era… the myths and the myth busters', speaker: 'Dr. Sudipto Haldar' },
  ],
  2016: [
    { year: 2016, date_label: 'July 2016',     location: 'Pune, India',              event: 'Technical Symposium by Indian Herbs',     title: 'Gut health drives performance in poultry… An insight into the factors leading to a healthy gut', speaker: 'Dr. Sudipto Haldar' },
    { year: 2016, date_label: 'July 2016',     location: 'Biratnagar, Nepal',        event: 'Technical seminar by Asian Feeds',        title: 'Broiler management in tropical climate', speaker: 'Dr. Amrita Kumar Dhara' },
    { year: 2016, date_label: 'November 2016', location: 'Agartala, Tripura, India', event: 'Technical seminar by Mountt Agro',        title: 'Broiler management & disease in tropical climate', speaker: 'Dr. Amrita Kumar Dhara' },
  ],
  2015: [
    { year: 2015, date_label: 'September 2015', location: 'Bangkok, Thailand', event: 'Broiler Nutrition Symposium',                title: 'Applied Nutrition: Enzymes application in broiler diets', speaker: 'Dr. Sudipto Haldar' },
    { year: 2015, date_label: 'April 2015',     location: 'Biratnagar, Nepal', event: 'Technical seminar by Asian Feeds',           title: 'Common broiler problems encounter in tropical climate', speaker: 'Dr. Amrita Kumar Dhara' },
  ],
  2014: [
    { year: 2014, date_label: 'April 2014', location: 'Vienna, Austria', event: 'BOKU – University of Natural Resources and Life Sciences', title: 'Effects of a phytogenic feed additive on growth performance, nutrient digestibility, caecal microflora composition and intestinal histomorphology of broilers', speaker: 'Dr. Sudipto Haldar' },
  ],
};

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

export default function PresentationsPage() {
  const [intro, setIntro] = useState<PageIntro>(STATIC_INTRO);
  const [byYear, setByYear] = useState<Record<number, Presentation[]>>(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/presentations`)
      .then(r => r.json())
      .then(data => {
        if (data.page) setIntro(data.page);
        if (data.presentations) {
          const mapped: Record<number, Presentation[]> = {};
          for (const yr in data.presentations) {
            mapped[Number(yr)] = data.presentations[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">Presentations</span>
          </nav>
          <h1>Our <em>Presentations</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="Presentations">
        <div className="container pres2-wrap">

          {/* ── Two-column grid: left intro + right carousel ── */}
          <div className="pres2-layout">

            {/* LEFT: 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 row + carousel */}
            <div className="pres2-main-col">

              {/* Year row: arrows + scrollable pills — top of right column */}
              <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>

              <div className="pres2-carousel-area">

                {/* Header */}
                <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');
                      const displayTitle = item.title?.trim() || item.event?.trim() || 'Presentation';
                      const displayEvent = item.title?.trim() && item.event?.trim() ? item.event : null;
                      const initials = item.speaker
                        ? item.speaker.split(' ').filter(w => w.match(/^[A-Z]/)).slice(0, 2).map(w => w[0]).join('')
                        : null;
                      return (
                        <article key={globalIdx} className="pres2-card">
                          <span className="pres2-card-num" aria-hidden="true">{num}</span>

                          <div className="pres2-card-top">
                            {item.speaker && (
                              <span className="pres2-card-speaker">
                                {initials && <span className="pres2-card-init">{initials}</span>}
                                {item.speaker}
                              </span>
                            )}
                            <h4 className="pres2-card-title">{displayTitle}</h4>
                            {displayEvent && (
                              <p className="pres2-card-event">
                                <i className="fas fa-chalkboard-teacher" aria-hidden="true" />
                                {displayEvent}
                              </p>
                            )}
                          </div>

                          <div className="pres2-card-foot">
                            {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>
                )}

                {/* Nav: arrows + dots */}
                <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>{/* end pres2-layout */}
        </div>
      </section>
    </>
  );
}
