"use client";

import Image from "next/image";
import { useState, useEffect, useCallback } from "react";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { addView } from "@/lib/utils/addView";

interface EpaperItem {
  id: number;
  channel_id: number;
  date: string;
  pdf: string;
  image: string;
  total_view: number;
  status: number;
  channel_name: string;
  channel_image: string;
  is_verified: number;
}

function todayStr() {
  return new Date().toISOString().slice(0, 10);
}
function isValidImg(url?: string) { return !!url && !url.includes("no_img"); }
function fmtDate(d: string) {
  try {
    return new Date(d).toLocaleDateString("en-IN", { weekday: "short", day: "numeric", month: "short" });
  } catch { return d; }
}

interface ThumbPage {
  id: string;
  sectionStart: boolean;
  img: string;
}

interface Section {
  name: string;
  pages: string;
}

const THUMB_PAGES: ThumbPage[] = [
  { id: "A1", sectionStart: true,  img: "https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=300&q=80" },
  { id: "A2", sectionStart: false, img: "https://images.unsplash.com/photo-1577563908411-5077b6dc7624?w=300&q=80" },
  { id: "A3", sectionStart: false, img: "https://images.unsplash.com/photo-1518770660439-4636190af475?w=300&q=80" },
  { id: "A4", sectionStart: false, img: "https://images.unsplash.com/photo-1554475901-4538ddfbccc2?w=300&q=80" },
  { id: "B1", sectionStart: true,  img: "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?w=300&q=80" },
  { id: "B2", sectionStart: false, img: "https://images.unsplash.com/photo-1567157577867-05ccb1388e66?w=300&q=80" },
  { id: "B3", sectionStart: false, img: "https://images.unsplash.com/photo-1551434678-e076c223a692?w=300&q=80" },
  { id: "B4", sectionStart: false, img: "https://images.unsplash.com/photo-1438449805896-28a666819a20?w=300&q=80" },
  { id: "C1", sectionStart: true,  img: "https://images.unsplash.com/photo-1531415074968-036ba1b575da?w=300&q=80" },
  { id: "C2", sectionStart: false, img: "https://images.unsplash.com/photo-1517976487492-5750f3195933?w=300&q=80" },
  { id: "C3", sectionStart: false, img: "https://images.unsplash.com/photo-1626814026160-2237a95fc5a0?w=300&q=80" },
  { id: "C4", sectionStart: false, img: "https://images.unsplash.com/photo-1587474260584-136574528ed5?w=300&q=80" },
  { id: "D1", sectionStart: true,  img: "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=300&q=80" },
  { id: "D2", sectionStart: false, img: "https://images.unsplash.com/photo-1504711434969-e33886168f5c?w=300&q=80" },
  { id: "D3", sectionStart: false, img: "https://images.unsplash.com/photo-1495020689067-958852a7765e?w=300&q=80" },
  { id: "D4", sectionStart: false, img: "https://images.unsplash.com/photo-1585829365295-ab7cd400c167?w=300&q=80" },
];

const SECTIONS: Section[] = [
  { name: "National",          pages: "A1–A6" },
  { name: "Politics",          pages: "A4–A8" },
  { name: "Business & Markets",pages: "B1–B4" },
  { name: "Opinion · Editorials",pages:"B5–B7" },
  { name: "World",             pages: "B8" },
  { name: "Sport",             pages: "C1–C4" },
  { name: "Cinema & Culture",  pages: "C5–C6" },
  { name: "Technology",        pages: "D1–D2" },
  { name: "Science · ISRO",    pages: "D3" },
  { name: "Weather · TV grid", pages: "D4" },
];

const ARCHIVE = [
  { label: "Wed · 20 May", badge: "TODAY", img: "https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=300&q=80" },
  { label: "Tue · 19 May", badge: null,    img: "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?w=300&q=80" },
  { label: "Mon · 18 May", badge: null,    img: "https://images.unsplash.com/photo-1518770660439-4636190af475?w=300&q=80" },
  { label: "Sun · 17 May", badge: null,    img: "https://images.unsplash.com/photo-1531415074968-036ba1b575da?w=300&q=80" },
  { label: "Sat · 16 May", badge: null,    img: "https://images.unsplash.com/photo-1554475901-4538ddfbccc2?w=300&q=80" },
  { label: "Fri · 15 May", badge: null,    img: "https://images.unsplash.com/photo-1577563908411-5077b6dc7624?w=300&q=80" },
];

const CITY_EDITIONS = [
  { city: "Mumbai",    pages: "16 pages" },
  { city: "Delhi",     pages: "20 pages" },
  { city: "Bengaluru", pages: "18 pages" },
  { city: "Chennai",   pages: "14 pages" },
  { city: "Hyderabad", pages: "12 pages" },
  { city: "Kolkata",   pages: "12 pages" },
];

export default function EPaperShell() {
  const [activePage, setActivePage] = useState(0);
  const [activeSection, setActiveSection] = useState(0);
  const [selectedDate, setSelectedDate] = useState(todayStr());
  const [epapers, setEpapers] = useState<EpaperItem[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchEpapers = useCallback(async (date: string) => {
    setLoading(true);
    try {
      const userId = getStoredUser()?.id ?? 0;
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<{ result: EpaperItem[] }>(
        API_ENDPOINTS.GET_EPAPER,
        { date, user_id: userId },
      );
      setEpapers((data.result ?? []).filter((e) => e.status === 1));
    } catch {
      setEpapers([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // When epapers load or date changes, reset selection to first item
  useEffect(() => {
    if (epapers.length > 0) setActivePage(0);
  }, [epapers]);

  // Fire add_view (type 7 = EPaper) whenever the selected edition changes
  useEffect(() => {
    const epaper = epapers[activePage];
    if (!epaper) return;
    const userId = getStoredUser()?.id ?? 0;
    addView(7, epaper.id, userId);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [epapers[activePage]?.id]);

  useEffect(() => { fetchEpapers(selectedDate); }, [selectedDate, fetchEpapers]);

  // Selected epaper from API; fall back to static page if API hasn't loaded
  const selectedEpaper = epapers[activePage] ?? null;
  const currentPage = THUMB_PAGES[activePage] ?? THUMB_PAGES[0];

  return (
    <main className="wrap ep-shell">
      <div className="ep-grid">

        {/* LEFT: edition thumbnails (API) or static page thumbnails */}
        <aside className="thumb-rail">
          <div className="h">
            {epapers.length > 0
              ? <>Editions <span className="ct">{activePage + 1} / {epapers.length}</span></>
              : <>Pages <span className="ct">{activePage + 1} / {THUMB_PAGES.length}</span></>
            }
          </div>
          <div className="thumb-list">
            {epapers.length > 0
              ? epapers.map((ep, i) => {
                  const thumb = isValidImg(ep.image) ? ep.image
                    : isValidImg(ep.channel_image) ? ep.channel_image : null;
                  return (
                    <div
                      key={ep.id}
                      className={`thumb-card${activePage === i ? " active" : ""}`}
                      onClick={() => setActivePage(i)}
                      style={{ cursor: "pointer" }}
                    >
                      {thumb ? (
                        <Image src={thumb} alt={ep.channel_name} fill style={{ objectFit: "cover" }} unoptimized />
                      ) : (
                        /* eslint-disable-next-line @next/next/no-img-element */
                        <img src={THUMB_PAGES[i % THUMB_PAGES.length]?.img ?? THUMB_PAGES[0].img} alt="" />
                      )}
                      <span className="page-no" style={{ fontSize: 9 }}>{ep.channel_name.slice(0, 6)}</span>
                    </div>
                  );
                })
              : THUMB_PAGES.map((page, i) => (
                  <div
                    key={page.id}
                    className={`thumb-card${activePage === i ? " active" : ""}${page.sectionStart ? " section-start" : ""}`}
                    onClick={() => setActivePage(i)}
                  >
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={page.img} alt="" />
                    <span className="page-no">{page.id}</span>
                  </div>
                ))
            }
          </div>
        </aside>

        {/* CENTER: page viewer */}
        <div className="ep-viewer">
          <div className="viewer-top">
            <div className="pg-info">
              {selectedEpaper ? (
                <>
                  <span className="ed" style={{ maxWidth: 70, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {selectedEpaper.channel_name}
                  </span>
                  <span><b>E-Paper</b> · {fmtDate(selectedEpaper.date)}</span>
                </>
              ) : (
                <>
                  <span className="ed">{currentPage.id}</span>
                  <span><b>Front Page</b> · Section A — National</span>
                </>
              )}
            </div>
            <div className="pg-nav">
              <button
                className={activePage === 0 ? "disabled" : ""}
                title="Previous"
                onClick={() => setActivePage(p => Math.max(0, p - 1))}
              >
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 18l-6-6 6-6" /></svg>
              </button>
              <input type="text" value={activePage + 1} readOnly maxLength={3} />
              <span className="total">/ {epapers.length || THUMB_PAGES.length}</span>
              <button
                className={activePage >= (epapers.length || THUMB_PAGES.length) - 1 ? "disabled" : ""}
                title="Next"
                onClick={() => setActivePage(p => Math.min((epapers.length || THUMB_PAGES.length) - 1, p + 1))}
              >
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6" /></svg>
              </button>
              {/* Open PDF in new tab */}
              {selectedEpaper?.pdf && (
                <a
                  href={selectedEpaper.pdf}
                  target="_blank"
                  rel="noopener noreferrer"
                  title="Open full PDF"
                  style={{ marginLeft: "0.5rem", display: "flex", alignItems: "center", gap: "0.25rem", fontSize: 11, fontFamily: "var(--mono)", color: "var(--brand)", textDecoration: "none", fontWeight: 700 }}
                >
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="9" y1="15" x2="15" y2="15" /></svg>
                  PDF
                </a>
              )}
            </div>
          </div>

          <div className="viewer-stage">
            {/* ── API epaper: show PDF or cover image ── */}
            {selectedEpaper && (
              selectedEpaper.pdf ? (
                /* PDF viewer */
                <iframe
                  key={selectedEpaper.id}
                  src={selectedEpaper.pdf}
                  title={`${selectedEpaper.channel_name} E-Paper`}
                  style={{ width: "100%", height: "100%", minHeight: 600, border: "none", display: "block" }}
                />
              ) : (
                /* Cover image or placeholder */
                <div style={{ width: "100%", minHeight: 500, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: "1rem", background: "var(--cream, #faf7f2)" }}>
                  {isValidImg(selectedEpaper.image) ? (
                    <Image
                      src={selectedEpaper.image}
                      alt={selectedEpaper.channel_name}
                      width={400}
                      height={560}
                      style={{ objectFit: "contain", maxWidth: "100%", borderRadius: 4, boxShadow: "0 4px 24px rgba(0,0,0,0.12)" }}
                      unoptimized
                    />
                  ) : (
                    <>
                      <div style={{ width: 80, height: 80, borderRadius: "50%", background: "var(--border, #e5e7eb)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="var(--text-3, #9ca3af)" strokeWidth="1.5">
                          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                          <polyline points="14 2 14 8 20 8" />
                          <line x1="12" y1="18" x2="12" y2="12" />
                          <line x1="9" y1="15" x2="15" y2="15" />
                        </svg>
                      </div>
                      <div style={{ textAlign: "center" }}>
                        <p style={{ fontWeight: 700, fontSize: "1rem", color: "var(--ink, #0e0e11)", margin: "0 0 0.25rem" }}>
                          {selectedEpaper.channel_name}
                        </p>
                        <p style={{ fontSize: "0.875rem", color: "var(--text-2, #6b7280)", margin: 0 }}>
                          PDF not available for this edition
                        </p>
                      </div>
                    </>
                  )}
                </div>
              )
            )}

            {/* ── Static demo content when no API epaper ── */}
            {!selectedEpaper && <article className="page-shell">
              <header className="mast">
                <div className="nameplate">
                  <span className="dt">DT</span>
                  <span className="news">News</span>
                </div>
                <div className="lead-line">&ldquo;News, told straight.&rdquo; — since 2014</div>
                <div className="mast-meta">
                  <span><b>VOL. XII · NO. 138</b></span>
                  <span>WEDNESDAY · 20 MAY 2026 · MUMBAI</span>
                  <span>32 PAGES · ₹6</span>
                </div>
              </header>

              <div className="columns">
                {/* Left column */}
                <div className="col">
                  <div>
                    <div className="kicker">Markets</div>
                    <h2>SENSEX surges to fresh all-time high; metals lead</h2>
                    <div className="byline">Rohan Kapoor · Mumbai</div>
                  </div>
                  <p>India&apos;s headline indices opened higher on Wednesday with the SENSEX advancing 612 points to 79,214 by mid-morning. Metals and PSU banks led the broad-based rally as foreign inflows accelerated for the fourth straight session, and the rupee strengthened to a six-month high against the dollar.</p>
                  <hr />
                  <div>
                    <div className="kicker">Science</div>
                    <h2>ISRO confirms Gaganyaan window: Aug–Sep 2026</h2>
                    <div className="byline">Karthik Iyer · Bengaluru</div>
                  </div>
                  <p>Speaking at SDSC SHAR on Tuesday, ISRO chairman confirmed the Gaganyaan crewed mission will launch in the third quarter of 2026 — a more precise window than the previously-stated &ldquo;later this year.&rdquo;</p>
                  <hr />
                  <div>
                    <div className="kicker">Climate</div>
                    <h2>Kerala monsoon onset four days ahead of schedule</h2>
                    <div className="byline">Mira Sen · Vizhinjam</div>
                  </div>
                  <p>The southwest monsoon arrived over the Kerala coast on Tuesday, four days ahead of the normal date, the India Meteorological Department said in its evening bulletin. Heavy rains are expected across the Western Ghats by Thursday.</p>
                </div>

                {/* Center column (lead) */}
                <div className="col">
                  <div>
                    <div className="kicker">Politics · Exclusive</div>
                    <h2 className="lead">Inside the 96 minutes that reshuffled Maharashtra&apos;s cabinet</h2>
                    <div className="byline">By Anjali Verma &amp; Rohan Kapoor · Mumbai</div>
                  </div>
                  <div className="photo">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src="https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=600&q=80" alt="Vidhan Bhavan, Mumbai" />
                  </div>
                  <div className="photo-cap"><b>Vidhan Bhavan, Mumbai.</b> The complex at dusk, hours before the cabinet meeting. Photo · Vipin Kumar / DTNews.</div>
                  <p>At 11:47 PM on Tuesday, the chief minister&apos;s private secretary did something he had not done in eight months: he picked up the line to the deputy CM&apos;s residence himself. By 1:23 AM the file was signed. By dawn, three portfolios had changed hands.</p>
                  <div className="text-callout">&ldquo;A regional cabinet cannot be reshuffled at midnight without a phone call from somewhere else.&rdquo;</div>
                  <p>This is the reconstruction of those 96 minutes — assembled from interviews with seven people in the room, two who took the calls, and the typed minutes a sympathetic clerk made available to DTNews. <i>Continued on page A4.</i></p>
                </div>

                {/* Right column */}
                <div className="col">
                  <div>
                    <div className="kicker">Sport · T20I</div>
                    <h2>Suryakumar&apos;s 67 off 34 clinches series 3–1</h2>
                    <div className="byline">Sanjay Iyer · Ahmedabad</div>
                  </div>
                  <div className="photo">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src="https://images.unsplash.com/photo-1531415074968-036ba1b575da?w=600&q=80" alt="T20I cricket match" />
                  </div>
                  <p>India sealed the five-match T20I series 3–1 against South Africa in Ahmedabad on Tuesday night, with Suryakumar Yadav anchoring the chase with 67 off 34 balls.</p>
                  <hr />
                  <div>
                    <div className="kicker">Cinema</div>
                    <h2>&lsquo;Bombay Velvet 2&rsquo; reviews aren&apos;t kind</h2>
                    <div className="byline">Devika Dutt · Mumbai</div>
                  </div>
                  <p>The sequel opened to muted reviews and a ₹38 crore opening weekend against a ₹120 crore budget.</p>
                  <hr />
                  <div>
                    <div className="kicker">Tech</div>
                    <h2>Bengaluru&apos;s AI startups raised $1.4B last quarter</h2>
                    <div className="byline">Karthik Iyer · Bengaluru</div>
                  </div>
                  <p>The funding number is up 41 percent on the previous quarter. Where the money actually went — agentic platforms, vertical SaaS, and a small but growing pile in Indic LLMs.</p>
                </div>
              </div>

              <footer className="footer-strip">
                <span>www.dtnews.in · @dtnews</span>
                <span>A1 · Front Page</span>
                <span>Printed at Mumbai · Delhi · Bengaluru · Chennai</span>
              </footer>
            </article>}

            <div className="zoom-fab">
              <button title="Zoom out">
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <circle cx="11" cy="11" r="7" />
                  <path d="m20 20-3-3M8 11h6" />
                </svg>
              </button>
              <span className="pct">100%</span>
              <button title="Zoom in">
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <circle cx="11" cy="11" r="7" />
                  <path d="m20 20-3-3M8 11h6M11 8v6" />
                </svg>
              </button>
              <button title="Fit width">
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="M3 9V5h4M21 9V5h-4M3 15v4h4M21 15v4h-4" />
                </svg>
              </button>
              <button title="Full screen">
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="M8 3H5a2 2 0 0 0-2 2v3M21 8V5a2 2 0 0 0-2-2h-3M3 16v3a2 2 0 0 0 2 2h3M16 21h3a2 2 0 0 0 2-2v-3" />
                </svg>
              </button>
            </div>
          </div>
        </div>

        {/* RIGHT: sections + archive */}
        <aside className="ep-right">

          <div className="ep-card">
            <div className="h">Sections in this edition <span className="ct">A–D</span></div>
            <div className="sec-list">
              {SECTIONS.map((sec, i) => (
                <button
                  key={sec.name}
                  className={`sec-row${activeSection === i ? " active" : ""}`}
                  onClick={() => setActiveSection(i)}
                >
                  <span className="lt">
                    <span className="dot" />
                    {sec.name}
                  </span>
                  <span className="pg">{sec.pages}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="ep-card">
            <div className="h">Edition stats</div>
            <div className="stat-row">
              <div className="stat"><div className="n">32</div><div className="l">Pages</div></div>
              <div className="stat"><div className="n">48</div><div className="l">Stories</div></div>
              <div className="stat"><div className="n">7</div><div className="l">Cities</div></div>
            </div>
          </div>

          {/* ── Date picker ── */}
          <div className="ep-card">
            <div className="h">Select date</div>
            <input
              type="date"
              value={selectedDate}
              max={todayStr()}
              onChange={(e) => setSelectedDate(e.target.value)}
              style={{
                width: "100%",
                padding: "0.5rem 0.625rem",
                border: "1.5px solid var(--border, #e5e7eb)",
                borderRadius: 7,
                fontSize: "0.875rem",
                color: "var(--ink)",
                background: "var(--surf, #fff)",
                outline: "none",
                cursor: "pointer",
                fontFamily: "var(--mono)",
                boxSizing: "border-box",
              }}
            />
          </div>

          {/* ── Channel editions from API ── */}
          <div className="ep-card">
            <div className="h" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span>Editions · {fmtDate(selectedDate)}</span>
              {loading && <span style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "var(--mono)" }}>Loading…</span>}
            </div>

            {epapers.length === 0 && !loading ? (
              <p style={{ fontSize: "0.8125rem", color: "var(--text-3)", margin: "0.5rem 0 0", fontFamily: "var(--mono)" }}>
                No e-papers found for this date
              </p>
            ) : (
              <div className="editions-grid">
                {epapers.map((ep) => {
                  const channelImg = isValidImg(ep.channel_image) ? ep.channel_image : null;
                  const coverImg   = isValidImg(ep.image) ? ep.image : null;
                  return (
                    <a
                      key={ep.id}
                      className="edition-card"
                      href={ep.pdf || "#"}
                      target={ep.pdf ? "_blank" : undefined}
                      rel="noopener noreferrer"
                      title={ep.pdf ? `Open ${ep.channel_name} e-paper PDF` : ep.channel_name}
                    >
                      {/* Cover or channel logo */}
                      <span className="ic" style={{ position: "relative", overflow: "hidden", borderRadius: 4 }}>
                        {coverImg ? (
                          <Image src={coverImg} alt="" fill style={{ objectFit: "cover" }} unoptimized />
                        ) : channelImg ? (
                          <Image src={channelImg} alt="" fill style={{ objectFit: "cover" }} unoptimized />
                        ) : (
                          <svg viewBox="0 0 24 24" aria-hidden="true">
                            <path d="M3 21h18M5 21V7l7-4 7 4v14" />
                          </svg>
                        )}
                      </span>
                      <div className="info">
                        <div className="nm">{ep.channel_name}</div>
                        <div className="pg" style={{ display: "flex", alignItems: "center", gap: 4 }}>
                          {ep.pdf ? (
                            <>
                              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /></svg>
                              PDF
                            </>
                          ) : (
                            <span style={{ color: "var(--text-3)" }}>No PDF</span>
                          )}
                          {ep.total_view > 0 && <span>· {ep.total_view} views</span>}
                        </div>
                      </div>
                    </a>
                  );
                })}
              </div>
            )}
          </div>

          <div className="sub-cta">
            <div className="lbl">DTNEWS+ · ₹49/mo</div>
            <h4>Get the e-paper at 6 AM, in your inbox.</h4>
            <p>Subscribers get every edition delivered to inbox, the full archive since 2014, and audio briefings of every front-page story.</p>
            <a className="btn" href="/subscribe">
              Subscribe
              <svg viewBox="0 0 24 24" aria-hidden="true">
                <path d="M5 12h14M13 6l6 6-6 6" />
              </svg>
            </a>
          </div>

        </aside>
      </div>
    </main>
  );
}
