"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchCities,
  fetchArticlesByCity,
  toggleCitySelection,
  clearCitySelection,
  selectCities,
  selectSelectedCityIds,
  selectCityArticles,
  selectCitiesLoaded,
  selectCitiesLoading,
  selectArticlesLoading,
} from "@/store/slices/citySlice";
import { getStoredUser } from "@/lib/utils/persistAuth";

// ── Helpers ───────────────────────────────────────────────────────────────────
function isValidImg(url?: string) { return !!url && !url.includes("no_img"); }
function fmtViews(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
  return String(n);
}
function fmtRelTime(d: string) {
  const diff = Date.now() - new Date(d).getTime();
  const m = Math.floor(diff / 60_000);
  const h = Math.floor(m / 60);
  if (m < 60) return `${m}m ago`;
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

// ── Skeleton ──────────────────────────────────────────────────────────────────
function ArticleSkeleton() {
  return (
    <div style={{ display: "flex", gap: "0.875rem", padding: "1rem", background: "var(--surf, #fff)", border: "1px solid var(--border, #e5e7eb)", borderRadius: 10 }}>
      <div style={{ flexShrink: 0, width: 100, height: 72, borderRadius: 7, background: "#e5e7eb" }} />
      <div style={{ flex: 1 }}>
        <div style={{ height: 9, width: "30%", background: "#e5e7eb", borderRadius: 4, marginBottom: 7 }} />
        <div style={{ height: 13, background: "#e5e7eb", borderRadius: 4, marginBottom: 5 }} />
        <div style={{ height: 13, width: "65%", background: "#e5e7eb", borderRadius: 4, marginBottom: 9 }} />
        <div style={{ height: 9, width: "40%", background: "#e5e7eb", borderRadius: 4 }} />
      </div>
    </div>
  );
}

// ── Main component ────────────────────────────────────────────────────────────
export default function LocalNewsShell() {
  const dispatch = useAppDispatch();
  const fetchedRef = useRef(false);
  const [userId, setUserId] = useState(0);

  const cities           = useAppSelector(selectCities);
  const selectedIds      = useAppSelector(selectSelectedCityIds);
  const articles         = useAppSelector(selectCityArticles);
  const citiesLoaded     = useAppSelector(selectCitiesLoaded);
  const citiesLoading    = useAppSelector(selectCitiesLoading);
  const articlesLoading  = useAppSelector(selectArticlesLoading);

  useEffect(() => { setUserId(getStoredUser()?.id ?? 0); }, []);

  // Load cities on mount
  useEffect(() => {
    if (!citiesLoaded && !fetchedRef.current) {
      fetchedRef.current = true;
      dispatch(fetchCities({ userId }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Fetch articles whenever selection changes
  useEffect(() => {
    if (selectedIds.length > 0) {
      dispatch(fetchArticlesByCity({ cityIds: selectedIds, userId }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedIds.join(",")]);

  // Selected city names for the label
  const selectedNames = cities
    .filter((c) => selectedIds.includes(c.id))
    .map((c) => c.name)
    .join(", ");

  return (
    <div style={{ minHeight: "60vh", background: "var(--bg, #f8f9fb)" }}>

      {/* ── Page header ── */}
      <div style={{
        background: "var(--surf, #fff)",
        borderBottom: "1px solid var(--border, #e5e7eb)",
        paddingTop: "2rem",
        paddingBottom: 0,
      }}>
        <div className="wrap">
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: "1.25rem" }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.375rem" }}>
                {/* Location pin */}
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--brand, #C1272D)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
                  <circle cx="12" cy="10" r="3" />
                </svg>
                <h1 style={{ fontFamily: "var(--serif, Georgia, serif)", fontSize: "clamp(1.5rem, 3vw, 2rem)", fontWeight: 800, margin: 0, color: "var(--ink, #0e0e11)", letterSpacing: "-0.02em" }}>
                  Local News
                </h1>
              </div>
              <p style={{ margin: 0, fontSize: "0.875rem", color: "var(--text-2, #6b7280)" }}>
                {selectedIds.length === 0
                  ? "Select cities to see local stories"
                  : `Showing news from ${selectedIds.length} city${selectedIds.length > 1 ? "ies" : ""}`
                }
              </p>
            </div>

            {selectedIds.length > 0 && (
              <button
                onClick={() => dispatch(clearCitySelection())}
                style={{ fontSize: "0.8125rem", fontWeight: 600, color: "var(--text-2, #6b7280)", background: "none", border: "1px solid var(--border, #e5e7eb)", borderRadius: 7, padding: "0.375rem 0.75rem", cursor: "pointer" }}
              >
                Clear all
              </button>
            )}
          </div>

          {/* ── City picker — horizontal scroll ── */}
          <div style={{ position: "relative" }}>
            <div
              style={{
                display: "flex",
                gap: "0.5rem",
                overflowX: "auto",
                scrollbarWidth: "none",
                paddingBottom: "1rem",
              }}
            >
              {citiesLoading ? (
                /* City chip skeletons */
                Array.from({ length: 10 }).map((_, i) => (
                  <div key={i} style={{ flexShrink: 0, height: 34, width: 80 + (i % 3) * 20, borderRadius: 99, background: "#e5e7eb" }} />
                ))
              ) : (
                cities.map((city) => {
                  const selected = selectedIds.includes(city.id);
                  return (
                    <button
                      key={city.id}
                      onClick={() => dispatch(toggleCitySelection(city.id))}
                      style={{
                        flexShrink: 0,
                        display: "flex",
                        alignItems: "center",
                        gap: "0.375rem",
                        padding: "0.4375rem 0.875rem",
                        borderRadius: 99,
                        border: `1.5px solid ${selected ? "var(--brand, #C1272D)" : "var(--border, #e5e7eb)"}`,
                        background: selected ? "var(--brand, #C1272D)" : "var(--surf, #fff)",
                        color: selected ? "#fff" : "var(--ink, #0e0e11)",
                        fontWeight: selected ? 700 : 500,
                        fontSize: "0.8125rem",
                        cursor: "pointer",
                        transition: "all 0.15s cubic-bezier(0.22,1,0.36,1)",
                        transform: selected ? "scale(1.04)" : "scale(1)",
                        boxShadow: selected ? "0 2px 8px rgba(193,39,45,0.25)" : "none",
                        fontFamily: "var(--sans)",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {selected && (
                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round">
                          <path d="M20 6L9 17l-5-5" />
                        </svg>
                      )}
                      {city.name}
                    </button>
                  );
                })
              )}
            </div>
            {/* Fade right edge */}
            <div style={{ position: "absolute", right: 0, top: 0, bottom: "1rem", width: 48, background: "linear-gradient(to right, transparent, var(--surf, #fff))", pointerEvents: "none" }} />
          </div>
        </div>
      </div>

      {/* ── Article listing ── */}
      <div className="wrap" style={{ paddingTop: "1.5rem", paddingBottom: "3rem" }}>

        {/* No cities selected */}
        {selectedIds.length === 0 && !citiesLoading && (
          <div style={{ textAlign: "center", padding: "4rem 1rem" }}>
            <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--surf, #fff)", border: "1px solid var(--border, #e5e7eb)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 1rem" }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--text-3, #9ca3af)" strokeWidth="1.5" strokeLinecap="round">
                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
                <circle cx="12" cy="10" r="3" />
              </svg>
            </div>
            <p style={{ fontWeight: 700, fontSize: "1rem", color: "var(--ink, #0e0e11)", marginBottom: "0.375rem" }}>Choose your cities</p>
            <p style={{ fontSize: "0.875rem", color: "var(--text-2, #6b7280)" }}>Tap any city above to see news from that area</p>
          </div>
        )}

        {/* Loading articles */}
        {articlesLoading && (
          <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            {Array.from({ length: 6 }).map((_, i) => <ArticleSkeleton key={i} />)}
          </div>
        )}

        {/* Empty result */}
        {!articlesLoading && selectedIds.length > 0 && articles.length === 0 && (
          <div style={{ textAlign: "center", padding: "3rem 0", color: "var(--text-2, #6b7280)" }}>
            <p style={{ fontWeight: 600, marginBottom: "0.375rem" }}>No stories found</p>
            <p style={{ fontSize: "0.875rem" }}>Try selecting different cities</p>
          </div>
        )}

        {/* Articles */}
        {!articlesLoading && articles.length > 0 && (
          <>
            {/* Result count + selected cities */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "1rem" }}>
              <p style={{ fontSize: "0.8125rem", fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)", margin: 0 }}>
                {articles.length} stories · {selectedNames}
              </p>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
              {articles.map((a) => {
                const img = isValidImg(a.web_image) ? a.web_image
                  : isValidImg(a.landscape_img) ? a.landscape_img
                  : isValidImg(a.portrait_img) ? a.portrait_img : null;
                return (
                  <Link
                    key={a.id}
                    href={`/detail/${a.id}?type=1`}
                    style={{
                      display: "flex",
                      gap: "0.875rem",
                      alignItems: "flex-start",
                      padding: "1rem",
                      background: "var(--surf, #fff)",
                      border: "1px solid var(--border, #e5e7eb)",
                      borderRadius: 10,
                      textDecoration: "none",
                      color: "inherit",
                      transition: "box-shadow 0.15s",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.boxShadow = "0 2px 12px rgba(0,0,0,0.07)")}
                    onMouseLeave={(e) => (e.currentTarget.style.boxShadow = "none")}
                  >
                    {/* Thumbnail */}
                    <div style={{ flexShrink: 0, width: 100, height: 72, borderRadius: 7, overflow: "hidden", position: "relative", background: "#e5e7eb" }}>
                      {img
                        ? <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />
                        : (
                          <div style={{ width: "100%", height: "100%", background: "linear-gradient(135deg, #1e293b, #0f172a)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1.5">
                              <rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><path d="M21 15l-5-5L5 21" />
                            </svg>
                          </div>
                        )
                      }
                      {a.is_premium === 1 && (
                        <span style={{ position: "absolute", top: 3, right: 3, background: "#b45309", color: "#fff", fontSize: 7, fontWeight: 700, padding: "1px 4px", borderRadius: 2 }}>PRO</span>
                      )}
                    </div>

                    {/* Content */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      {/* Category + city */}
                      <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: 4, flexWrap: "wrap" }}>
                        {a.category && (
                          <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--brand, #C1272D)" }}>
                            {a.category}
                          </span>
                        )}
                        {a.city && (
                          <span style={{ display: "flex", alignItems: "center", gap: 3, fontSize: 9, fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)" }}>
                            <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
                            {a.city}
                          </span>
                        )}
                      </div>

                      <h3 style={{ fontSize: "0.9rem", fontWeight: 600, lineHeight: 1.4, margin: "0 0 6px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", color: "var(--ink, #0e0e11)" }}>
                        {a.title}
                      </h3>

                      <div style={{ display: "flex", gap: "0.5rem", fontSize: "0.688rem", fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)", flexWrap: "wrap" }}>
                        {a.channel_name && <span>{a.channel_name}</span>}
                        <span>·</span>
                        <span>{fmtRelTime(a.created_at)}</span>
                        {a.total_view > 0 && <><span>·</span><span>{fmtViews(a.total_view)}</span></>}
                      </div>
                    </div>
                  </Link>
                );
              })}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
