'use client';

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

interface Pub  { id: number; src: string | null; pdf: string | null; }
type PubData   = Record<string, Pub[]>;

const API = process.env.NEXT_PUBLIC_API_BASE_URL ?? '';

export default function ScientificPublicationsPage() {
  const [pubData, setPubData]   = useState<PubData>({});
  const [loading, setLoading]   = useState(true);
  const [yearIdx, setYearIdx]   = useState(0);
  const [pubIdx, setPubIdx]     = useState(0);
  const pillsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetch(`${API}/api/scientific-publications`)
      .then(r => r.json())
      .then(j => {
        if (j.success) setPubData(j.data);
      })
      .finally(() => setLoading(false));
  }, []);

  const years = Object.keys(pubData).map(Number).sort((a, b) => b - a);
  const pubs  = pubData[years[yearIdx]] ?? [];
  const pub   = pubs[pubIdx];

  function switchYear(i: number) { setYearIdx(i); setPubIdx(0); }
  function prev() { setPubIdx(i => Math.max(0, i - 1)); }
  function next() { setPubIdx(i => Math.min(pubs.length - 1, i + 1)); }
  function scrollYears(dir: -1 | 1) {
    pillsRef.current?.scrollBy({ left: dir * 120, behavior: 'smooth' });
  }

  const totalPubs = Object.values(pubData).flat().length;

  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/sciticficpub.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" 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">Scientific Publications</span>
          </nav>
          <h1>Turning Research Into <em>Published Evidence</em></h1>
        </div>
        <div className="op-hero-wave" aria-hidden="true">
          <svg viewBox="0 0 1440 60" preserveAspectRatio="none" fill="#f8fcfa">
            <path d="M0,40 C360,70 1080,10 1440,40 L1440,60 L0,60Z"/>
          </svg>
        </div>
      </div>

      {/* ── Main split ── */}
      <section className="spub-page">
        <div className="spub-page-inner">

          {/* LEFT — intro */}
          <aside className="spub-intro-col">
            <div className="spub-intro-sticky">
              <span className="section-eyebrow">Peer-Reviewed Science</span>

              <h2 className="spub-intro-title">
                Our Scientific<br /><em>Publications</em>
              </h2>

              <p className="spub-intro-text">
                This section features peer-reviewed scientific publications showcasing our
                research and findings. We share original studies, reviews, and technical
                reports, ensuring rigorous methodology and data integrity. Explore how our
                work contributes to advancing knowledge and informs evidence-based practices.
              </p>

              <div className="spub-stat-row">
                <div className="spub-stat">
                  <span className="spub-stat-num">{loading ? '—' : `${totalPubs}+`}</span>
                  <span className="spub-stat-lbl">Papers Published</span>
                </div>
                <div className="spub-stat">
                  <span className="spub-stat-num">{loading ? '—' : years.length}</span>
                  <span className="spub-stat-lbl">Years of Research</span>
                </div>
              </div>
            </div>
          </aside>

          {/* RIGHT — single-card viewer */}
          <div className="spub-gallery-col">

            {loading ? (
              <div className="spub-empty">
                <i className="fas fa-spinner fa-spin" />
                <p>Loading publications…</p>
              </div>
            ) : years.length === 0 ? (
              <div className="spub-empty">
                <i className="fas fa-file-alt" />
                <p>No publications available.</p>
              </div>
            ) : (
              <>
                {/* Year nav */}
                <div className="spub-year-nav">
                  <button
                    className="spub-year-nav-btn"
                    onClick={() => scrollYears(-1)}
                    aria-label="Scroll years left"
                  >
                    <i className="fas fa-chevron-left" />
                  </button>

                  <div className="spub-year-pills" ref={pillsRef}>
                    {years.map((y, i) => (
                      <button
                        key={y}
                        className={`spub-year-pill${i === yearIdx ? ' active' : ''}`}
                        onClick={() => switchYear(i)}
                      >
                        {y}
                      </button>
                    ))}
                  </div>

                  <button
                    className="spub-year-nav-btn"
                    onClick={() => scrollYears(1)}
                    aria-label="Scroll years right"
                  >
                    <i className="fas fa-chevron-right" />
                  </button>
                </div>

                {pubs.length === 0 ? (
                  <div className="spub-empty">
                    <i className="fas fa-file-alt" />
                    <p>No publications for this year.</p>
                  </div>
                ) : (
                  <div className="spub-viewer">
                    <button
                      className="spub-arrow spub-arrow-left"
                      onClick={prev}
                      disabled={pubIdx === 0}
                      aria-label="Previous paper"
                    >
                      <i className="fas fa-chevron-left" />
                    </button>

                    <article className="spub-card" key={`${yearIdx}-${pubIdx}`}>
                      <div className="spub-card-img-wrap">
                        {pub.src ? (
                          <img
                            src={pub.src}
                            alt={`Publication ${pubIdx + 1} of ${pubs.length}`}
                            loading="lazy"
                          />
                        ) : (
                          <div className="spub-card-no-img">
                            <i className="fas fa-file-alt" />
                          </div>
                        )}
                      </div>
                      <div className="spub-card-footer">
                        <span className="spub-card-counter">{pubIdx + 1} / {pubs.length}</span>
                        {pub.pdf ? (
                          <a
                            href={pub.pdf}
                            download
                            target="_blank"
                            rel="noreferrer"
                            className="spub-card-dl"
                          >
                            <i className="fas fa-file-arrow-down" />
                            Download Paper
                          </a>
                        ) : (
                          <span className="spub-card-soon">
                            <i className="fas fa-clock" />
                            Coming Soon
                          </span>
                        )}
                      </div>
                    </article>

                    <button
                      className="spub-arrow spub-arrow-right"
                      onClick={next}
                      disabled={pubIdx === pubs.length - 1}
                      aria-label="Next paper"
                    >
                      <i className="fas fa-chevron-right" />
                    </button>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </section>
    </>
  );
}
