'use client';

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

interface OfferingItem {
  id: number;
  name: string;
  image_url: string | null;
  order: number;
}

const STATIC: Record<number, { link: string; badge: string | null; badgeAlt: string; fallbackImage: string; fallbackName: string; delay: string }> = {
  1: { link: '/research',      badge: '/images/dsir.webp',              badgeAlt: 'DSIR Affiliation',  fallbackImage: '/images/hero-agricultural-research.jpg', fallbackName: 'Research',      delay: '' },
  2: { link: '/advisory',      badge: null,                             badgeAlt: '',                  fallbackImage: '/images/what-sets-us-apart-2.webp',      fallbackName: 'Advisory',      delay: 'reveal-delay-1' },
  3: { link: '/laboratory',    badge: '/images/nabl-affiliation.webp',  badgeAlt: 'NABL Affiliation',  fallbackImage: '/images/lab-1.webp',                     fallbackName: 'Laboratory',    delay: 'reveal-delay-2' },
  4: { link: '/school',        badge: null,                             badgeAlt: '',                  fallbackImage: '/images/school-background.webp',         fallbackName: 'School',        delay: 'reveal-delay-3' },
  5: { link: '/life-sciences', badge: '/images/ccsea-affiliation.webp', badgeAlt: 'CCSEA Affiliation', fallbackImage: '/images/lifescienceabout.webp',          fallbackName: 'Life Sciences', delay: 'reveal-delay-3' },
};

const TOTAL = 5;

export default function Offerings() {
  const [apiItems, setApiItems] = useState<OfferingItem[] | null>(null);
  const [current, setCurrent] = useState(0);
  const trackRef = useRef<HTMLDivElement>(null);
  const programmatic = useRef(false);

  useEffect(() => {
    const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${apiBaseUrl}/api/homepage/whatwedeliver`)
      .then((res) => res.json())
      .then((result) => {
        if (result.success && Array.isArray(result.data)) {
          setApiItems(result.data);
        }
      })
      .catch(() => {});
  }, []);

  // Scroll the wrap so the current item is centred in the viewport
  useEffect(() => {
    const track = trackRef.current;
    const wrap = track?.parentElement as HTMLElement | null;
    if (!wrap || !track) return;
    const item = track.children[current] as HTMLElement | null;
    if (!item) return;
    programmatic.current = true;
    const scrollLeft = item.offsetLeft - (wrap.offsetWidth - item.offsetWidth) / 2;
    wrap.scrollTo({ left: scrollLeft, behavior: 'smooth' });
    // Re-enable swipe sync after smooth scroll animation finishes
    const t = setTimeout(() => { programmatic.current = false; }, 500);
    return () => clearTimeout(t);
  }, [current]);

  const prev = useCallback(() => setCurrent((c) => Math.max(0, c - 1)), []);
  const next = useCallback(() => setCurrent((c) => Math.min(TOTAL - 1, c + 1)), []);

  // Sync dot indicator with native scroll position
  useEffect(() => {
    const track = trackRef.current;
    const wrap = track?.parentElement as HTMLElement | null;
    if (!wrap) return;
    const onScroll = () => {
      if (programmatic.current) return; // ignore scroll events from our own scrollTo
      const items = Array.from(track?.children ?? []) as HTMLElement[];
      const center = wrap.scrollLeft + wrap.offsetWidth / 2;
      let closest = 0;
      let minDist = Infinity;
      items.forEach((el, i) => {
        const dist = Math.abs(el.offsetLeft + el.offsetWidth / 2 - center);
        if (dist < minDist) { minDist = dist; closest = i; }
      });
      setCurrent(closest);
    };
    wrap.addEventListener('scroll', onScroll, { passive: true });
    return () => wrap.removeEventListener('scroll', onScroll);
  }, []);

  const items = ([1, 2, 3, 4, 5] as const).map((order) => {
    const s = STATIC[order];
    const api = apiItems?.find((i) => i.order === order);
    return { order, image: api?.image_url || s.fallbackImage, name: api?.name || s.fallbackName, ...s };
  });

  return (
    <section className="offerings" id="offerings">
      <div className="offerings-bg"></div>
      <div className="container">
        <div className="section-header center">
          <div className="section-eyebrow">What We Deliver</div>
          <h2 className="section-title">Our <em>Offerings</em></h2>
        </div>

        {/* Always rendered — CSS toggles grid vs carousel layout */}
        <div className="offerings-carousel-outer">
          <button className="offerings-carousel-btn prev" onClick={prev} disabled={current === 0} aria-label="Previous">&#8249;</button>
          <div className="offerings-carousel-wrap">
            <div className="offerings-row-5" ref={trackRef}>
              {items.map(({ order, image, name, link, badge, badgeAlt, delay }) => (
                <div key={order} className={`of5-item reveal ${delay}`}>
                  <div className="of5-img-wrap">
                    <Link href={link} className="of5-img-link">
                      <img src={image} alt={name} />
                    </Link>
                    {badge && (
                      <div className="of5-badge">
                        <img
                          src={badge}
                          alt={badgeAlt}
                          className="of5-affil-badge"
                          onError={e => { (e.currentTarget.parentElement as HTMLElement).style.display = 'none'; }}
                        />
                      </div>
                    )}
                  </div>
                  <Link href={link} className="of5-title-link">
                    <h3 className="of5-title">{name}</h3>
                  </Link>
                </div>
              ))}
            </div>
          </div>
          <button className="offerings-carousel-btn next" onClick={next} disabled={current === TOTAL - 1} aria-label="Next">&#8250;</button>
          <div className="offerings-dots">
            {items.map((_, i) => (
              <button key={i} className={`offerings-dot${i === current ? ' active' : ''}`} onClick={() => setCurrent(i)} aria-label={`Slide ${i + 1}`} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
