'use client';

import { useEffect, useRef, useState, useCallback } from 'react';

interface JourneyItem {
  id: number;
  year: string;
  content: string;
  is_highlight: boolean;
  order: number;
  is_active: boolean;
}

const CARD_W = 210;

export default function Milestones() {
  const [items, setItems] = useState<JourneyItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeId, setActiveId] = useState<number | null>(null);

  // Desktop carousel refs
  const trackRef = useRef<HTMLDivElement>(null);
  const isDragging = useRef(false);
  const startX = useRef(0);
  const scrollLeftStart = useRef(0);

  // Mobile strip ref
  const stripRef = useRef<HTMLDivElement>(null);

  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const itemsRef = useRef<JourneyItem[]>([]);
  itemsRef.current = items;

  useEffect(() => {
    const base = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${base}/api/homepage/journey`)
      .then(r => r.json())
      .then(d => {
        if (d.success && Array.isArray(d.data)) {
          const data: JourneyItem[] = d.data;
          setItems(data);
          const highlighted = data.find(i => i.is_highlight);
          setActiveId(highlighted ? highlighted.id : (data[0]?.id ?? null));
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  /* ── scroll desktop track to card index ── */
  const scrollToIdx = (idx: number) => {
    trackRef.current?.scrollTo({ left: idx * CARD_W, behavior: 'smooth' });
  };

  /* ── scroll mobile strip to centre the active node ── */
  const scrollNodeIntoView = (id: number) => {
    const strip = stripRef.current;
    if (!strip) return;
    const node = strip.querySelector(`[data-id="${id}"]`) as HTMLElement | null;
    if (!node) return;
    strip.scrollTo({
      left: node.offsetLeft - strip.offsetWidth / 2 + node.offsetWidth / 2,
      behavior: 'smooth',
    });
  };

  /* ── auto-advance ── */
  const startAuto = useCallback(() => {
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setActiveId(prev => {
        const list = itemsRef.current;
        const idx = list.findIndex(i => i.id === prev);
        const nextIdx = idx >= list.length - 1 ? 0 : idx + 1;
        const next = list[nextIdx];
        scrollToIdx(nextIdx);
        if (next) scrollNodeIntoView(next.id);
        return next?.id ?? prev;
      });
    }, 3200);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const stopAuto = useCallback(() => {
    if (intervalRef.current) clearInterval(intervalRef.current);
  }, []);

  useEffect(() => {
    if (!items.length) return;
    startAuto();
    return () => stopAuto();
  }, [items, startAuto, stopAuto]);

  /* ── select a year ── */
  const select = (id: number, idx: number) => {
    stopAuto();
    setActiveId(id);
    scrollToIdx(idx);
    scrollNodeIntoView(id);
    startAuto();
  };

  /* ── desktop drag-to-scroll ── */
  const onMouseDown = (e: React.MouseEvent) => {
    isDragging.current = true;
    startX.current = e.pageX - (trackRef.current?.offsetLeft ?? 0);
    scrollLeftStart.current = trackRef.current?.scrollLeft ?? 0;
    stopAuto();
  };
  const onMouseMove = (e: React.MouseEvent) => {
    if (!isDragging.current || !trackRef.current) return;
    e.preventDefault();
    const x = e.pageX - trackRef.current.offsetLeft;
    trackRef.current.scrollLeft = scrollLeftStart.current - (x - startX.current);
  };
  const onMouseUp = () => {
    if (isDragging.current) { isDragging.current = false; startAuto(); }
  };

  if (loading) {
    return (
      <section className="ms-section" id="milestones">
        <div className="ms-bg" />
        <div className="container">
          <div className="section-header center">
            <div className="section-eyebrow">Our Journey</div>
            <h2 className="section-title">Milestones That <em>Define Us</em></h2>
          </div>
        </div>
      </section>
    );
  }

  if (!items.length) return null;

  const activeItem = items.find(i => i.id === activeId) ?? items[0];
  const activeIdx  = items.findIndex(i => i.id === activeId);
  const bullets    = activeItem.content.split(' · ').map(b => b.trim()).filter(Boolean);

  return (
    <section className="ms-section" id="milestones">
      <div className="ms-bg" />
      <div className="container">

        <div className="section-header center">
          <div className="section-eyebrow">Our Journey</div>
          <h2 className="section-title">Milestones That <em>Define Us</em></h2>
        </div>

        {/* ══ DESKTOP: original horizontal card carousel ══ */}
        <div className="jny-wrap ms-desktop-only">
          <button
            className="jny-arrow jny-arrow--prev"
            aria-label="Previous"
            onClick={() => { stopAuto(); trackRef.current?.scrollBy({ left: -CARD_W, behavior: 'smooth' }); startAuto(); }}
          >
            <i className="fas fa-chevron-left" />
          </button>

          <div className="jny-outer">
            <div
              className="jny-track"
              ref={trackRef}
              onMouseDown={onMouseDown}
              onMouseMove={onMouseMove}
              onMouseUp={onMouseUp}
              onMouseLeave={onMouseUp}
            >
              {items.map((item, idx) => {
                const isActive = item.id === activeId;
                const bulletList = item.content.split(' · ').map(b => b.trim()).filter(Boolean);
                return (
                  <div
                    key={item.id}
                    className={`jny-card${isActive ? ' jny-active' : ''}`}
                    onClick={() => select(item.id, idx)}
                  >
                    <div className="jny-year">{item.year}</div>
                    <div className="jny-body">
                      {bulletList.map((b, i) => (
                        <span key={i} className="jny-line">{b}</span>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <button
            className="jny-arrow jny-arrow--next"
            aria-label="Next"
            onClick={() => { stopAuto(); trackRef.current?.scrollBy({ left: CARD_W, behavior: 'smooth' }); startAuto(); }}
          >
            <i className="fas fa-chevron-right" />
          </button>
        </div>

        {/* ══ MOBILE: compact year-strip + content panel ══ */}
        <div className="ms-mobile-only">
          <div className="ms-strip-wrap">
            <div className="ms-strip-line" />
            <div className="ms-strip" ref={stripRef}>
              {items.map((item, idx) => (
                <button
                  key={item.id}
                  data-id={item.id}
                  className={`ms-node${activeId === item.id ? ' active' : ''}${item.is_highlight ? ' hl' : ''}`}
                  onClick={() => select(item.id, idx)}
                >
                  <div className="ms-node-dot" />
                  <span className="ms-node-label">{item.year}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="ms-panel" key={activeItem.id}>
            <div className="ms-panel-left">
              <div className={`ms-panel-year${activeItem.is_highlight ? ' hl' : ''}`}>
                {activeItem.year}
              </div>
              <div className="ms-panel-nav">
                <button
                  className="ms-nav-btn"
                  onClick={() => activeIdx > 0 && select(items[activeIdx - 1].id, activeIdx - 1)}
                  disabled={activeIdx === 0}
                  aria-label="Previous"
                >
                  <i className="fas fa-chevron-left" />
                </button>
                <span className="ms-nav-count">{activeIdx + 1}<em>/{items.length}</em></span>
                <button
                  className="ms-nav-btn"
                  onClick={() => activeIdx < items.length - 1 && select(items[activeIdx + 1].id, activeIdx + 1)}
                  disabled={activeIdx === items.length - 1}
                  aria-label="Next"
                >
                  <i className="fas fa-chevron-right" />
                </button>
              </div>
            </div>
            <div className="ms-panel-bullets">
              {bullets.map((b, i) => (
                <div key={i} className="ms-bullet">
                  <span className="ms-bullet-pip" />
                  <span>{b}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

      </div>
    </section>
  );
}
