"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import Image from "next/image";
import Link from "next/link";
import { getStoredUser } from "@/lib/utils/persistAuth";
import type {
  ReadingHistoryItem,
  SavedArticle,
  FollowedTopic,
  FollowedJournalist,
  UserComment,
  Newsletter,
} from "../types/profile.types";
import type { FeedContentItem } from "@/types/api/feeds.types";

type TabId = "saved" | "feeds";

const HISTORY: ReadingHistoryItem[] = [
  { id: 1, img: "https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=600&q=80", cat: "Politics · Exclusive", title: "Inside the 96 minutes that reshuffled Maharashtra's cabinet — and rewrote the 2027 alliance map", author: "Anjali Verma", status: "read in full", when: "14 min ago", progress: 100, saved: true },
  { id: 2, img: "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?w=600&q=80", cat: "Business · Markets", title: "Rupee at six-month high — RBI seen letting it run past 82", author: "Rohan Kapoor", status: "read 78%", when: "today", progress: 78 },
  { id: 3, img: "https://images.unsplash.com/photo-1518770660439-4636190af475?w=600&q=80", cat: "Tech · Semicon", title: "How India's semiconductor mission is reshaping Gujarat's industrial belt", author: "Karthik Iyer", status: "read in full", when: "yesterday", progress: 100, saved: true },
  { id: 4, img: "https://images.unsplash.com/photo-1438449805896-28a666819a20?w=600&q=80", cat: "Climate", title: "Cyclone Remal: ground report from the Bengal coast as floodwaters recede", author: "Mira Sen", status: "read 42%", when: "yesterday", progress: 42 },
  { id: 5, img: "https://images.unsplash.com/photo-1531415074968-036ba1b575da?w=600&q=80", cat: "Sport · T20I", title: "Suryakumar's 67 off 34 clinches the series 3–1 in Ahmedabad", author: "Sanjay Iyer", status: "read in full", when: "2 days ago", progress: 100 },
  { id: 6, img: "https://images.unsplash.com/photo-1626814026160-2237a95fc5a0?w=600&q=80", cat: "Cinema", title: "'Bombay Velvet 2' first reviews are in — and they aren't kind", author: "Devika Dutt", status: "read 18%", when: "3 days ago", progress: 18 },
  { id: 7, img: "https://images.unsplash.com/photo-1517976487492-5750f3195933?w=600&q=80", cat: "Science · ISRO", title: "Inside ISRO's new launch complex at Sriharikota — a sneak peek at the Gaganyaan tower", author: "Karthik Iyer", status: "read in full", when: "last week", progress: 100, saved: true },
];

const SAVED: SavedArticle[] = [
  { id: 1, img: "https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=600&q=80", cat: "Politics", title: "Inside the 96 minutes that reshuffled Maharashtra's cabinet", author: "Anjali Verma", readTime: "14 min read", when: "14 min ago" },
  { id: 2, img: "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?w=600&q=80", cat: "Markets", title: "Nifty's quiet melt-up and why analysts are finally turning bullish", author: "Rohan Kapoor", readTime: "9 min read", when: "2 days ago" },
  { id: 3, img: "https://images.unsplash.com/photo-1518770660439-4636190af475?w=600&q=80", cat: "Technology", title: "India's semiconductor mission: inside the new fab at Dholera", author: "Karthik Iyer", readTime: "11 min read", when: "3 days ago" },
  { id: 4, img: "https://images.unsplash.com/photo-1531415074968-036ba1b575da?w=600&q=80", cat: "Sports", title: "How Rohit's successor is already redefining India's Test batting order", author: "Sanjay Iyer", readTime: "7 min read", when: "last week" },
  { id: 5, img: "https://images.unsplash.com/photo-1626814026160-2237a95fc5a0?w=600&q=80", cat: "Cinema", title: "Ten years of Anurag Kashyap's deleted scenes — finally online", author: "Devika Dutt", readTime: "5 min read", when: "last week" },
  { id: 6, img: "https://images.unsplash.com/photo-1517976487492-5750f3195933?w=600&q=80", cat: "Science", title: "Gaganyaan countdown: what the next six months look like for ISRO", author: "Karthik Iyer", readTime: "12 min read", when: "2 weeks ago" },
];

const TOPICS: FollowedTopic[] = [
  { id: 1, label: "Markets", stories: 142, newStories: 8, icon: "₹" },
  { id: 2, label: "Maharashtra", stories: 89, newStories: 3, icon: "M" },
  { id: 3, label: "Tech & AI", stories: 203, newStories: 12, icon: "AI" },
  { id: 4, label: "Cricket", stories: 167, newStories: 5, icon: "🏏" },
  { id: 5, label: "Cinema · Hindi", stories: 78, newStories: 2, icon: "🎬" },
  { id: 6, label: "Climate", stories: 56, newStories: 4, icon: "🌿" },
  { id: 7, label: "ISRO", stories: 34, newStories: 1, icon: "🚀" },
  { id: 8, label: "Opinion", stories: 112, newStories: 6, icon: "Op" },
];

const JOURNALISTS: FollowedJournalist[] = [
  { id: 1, initials: "AV", name: "Anjali Verma", role: "Politics editor", articles: 234, readers: "12.4K", gradient: "linear-gradient(135deg,#C1272D,#7d1418)", verified: true, following: true },
  { id: 2, initials: "RK", name: "Rohan Kapoor", role: "Markets", articles: 189, readers: "8.2K", gradient: "linear-gradient(135deg,#1E3A8A,#152b69)", following: true },
  { id: 3, initials: "KI", name: "Karthik Iyer", role: "Tech & AI", articles: 312, readers: "15.8K", gradient: "linear-gradient(135deg,#0F766E,#0a4f47)", verified: true, following: true },
  { id: 4, initials: "MS", name: "Mira Sen", role: "Climate", articles: 156, readers: "6.7K", gradient: "linear-gradient(135deg,#7C2D12,#5a1f08)", following: true },
  { id: 5, initials: "DD", name: "Devika Dutt", role: "Cinema", articles: 98, readers: "4.3K", gradient: "linear-gradient(135deg,#7C3AED,#5b21b6)", following: false },
  { id: 6, initials: "SI", name: "Sanjay Iyer", role: "Sports", articles: 201, readers: "9.1K", gradient: "linear-gradient(135deg,#047857,#065f46)", following: false },
];

const COMMENTS: UserComment[] = [
  { id: 1, articleTitle: "Inside the 96 minutes that reshuffled Maharashtra's cabinet", body: "This is the most detailed breakdown I've read anywhere. The timeline of calls between the two factions is remarkable. Kudos to Anjali for the sourcing — this clearly took weeks.", likes: 47, replies: 8, when: "14 min ago" },
  { id: 2, articleTitle: "Rupee at six-month high — RBI seen letting it run past 82", body: "The RBI's stance has been fascinating this quarter. Letting the rupee appreciate while keeping rates steady signals a lot of confidence in the current account trajectory.", likes: 23, replies: 3, when: "today" },
  { id: 3, articleTitle: "Inside ISRO's new launch complex at Sriharikota", body: "Visited the new complex last year during the press day. The scale is breathtaking — nothing quite prepares you for how large the Gaganyaan tower is in person.", likes: 61, replies: 12, when: "last week" },
];

const NEWSLETTERS: Newsletter[] = [
  { id: 1, initials: "DB", name: "The Daily Briefing", schedule: "7 AM · weekdays", description: "Every morning's must-reads in five minutes. Politics, markets, and the one story you'll talk about at lunch.", gradient: "linear-gradient(135deg,#B08D2E,#7d6320)", subscribed: true },
  { id: 2, initials: "M7", name: "Markets in 7", schedule: "Closing bell", description: "Seven things moving markets today. Written by Rohan Kapoor, delivered right after the closing bell.", gradient: "linear-gradient(135deg,#047857,#065f46)", subscribed: true },
  { id: 3, initials: "AI", name: "AI This Week", schedule: "Saturday · 9 AM", description: "The week's biggest AI stories, explained without the hype. From Indian startups to Silicon Valley.", gradient: "linear-gradient(135deg,#7C3AED,#5b21b6)", subscribed: false },
];

const SIDEBAR_TOPICS = ["Markets", "Maharashtra", "Tech & AI", "Cricket", "Cinema · Hindi", "Climate", "ISRO", "+ 35 more"];

const SIDEBAR_FOLLOWING = [
  { initials: "AV", name: "Anjali Verma", role: "Politics editor", gradient: "linear-gradient(135deg,#C1272D,#7d1418)" },
  { initials: "RK", name: "Rohan Kapoor", role: "Markets", gradient: "linear-gradient(135deg,#1E3A8A,#152b69)" },
  { initials: "KI", name: "Karthik Iyer", role: "Tech & AI", gradient: "linear-gradient(135deg,#0F766E,#0a4f47)" },
  { initials: "MS", name: "Mira Sen", role: "Climate", gradient: "linear-gradient(135deg,#7C2D12,#5a1f08)" },
];

const SIDEBAR_NEWSLETTERS = [
  { initials: "DB", name: "The Daily Briefing", schedule: "7 AM · weekdays", gradient: "linear-gradient(135deg,#B08D2E,#7d6320)", on: true },
  { initials: "M7", name: "Markets in 7", schedule: "Closing bell", gradient: "linear-gradient(135deg,#047857,#065f46)", on: true },
  { initials: "AI", name: "AI This Week", schedule: "Saturday · 9 AM", gradient: "linear-gradient(135deg,#7C3AED,#5b21b6)", on: false },
];

function isValidMediaImg(url?: string) {
  return !!url && !url.includes("no_img");
}

function FeedMediaGrid({ items }: { items: FeedContentItem[] }) {
  const visible = items.filter((i) => i.status === 1);
  if (!visible.length) return null;
  const count = Math.min(visible.length, 4);

  const gridTemplate =
    count === 1 ? "1fr" :
    count === 2 ? "1fr 1fr" :
    "1fr 1fr";

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: gridTemplate,
      gap: 2,
      borderRadius: 10,
      overflow: "hidden",
      marginTop: "0.75rem",
    }}>
      {visible.slice(0, 4).map((item, idx) => {
        const minH = count === 1 ? 220 : count === 3 && idx === 0 ? 180 : 130;
        return (
          <div
            key={item.id}
            style={{
              position: "relative",
              borderRadius: count === 1 ? 10 : 0,
              overflow: "hidden",
              background: "#0f172a",
              gridColumn: count === 3 && idx === 0 ? "1 / span 2" : undefined,
              minHeight: minH,
            }}
          >
            {item.content_type === 2 && item.video ? (
              <video
                src={item.video}
                controls
                playsInline
                style={{ width: "100%", height: "100%", minHeight: minH, objectFit: "cover", display: "block" }}
              />
            ) : isValidMediaImg(item.image) ? (
              <Image src={item.image} alt="" fill style={{ objectFit: "cover" }} unoptimized />
            ) : item.content_type === 2 ? (
              <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 8 }}>
                <div style={{ width: 40, height: 40, borderRadius: "50%", background: "rgba(255,255,255,0.12)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="rgba(255,255,255,0.8)"><polygon points="6 4 20 12 6 20" /></svg>
                </div>
                <span style={{ fontSize: 11, color: "rgba(255,255,255,0.4)", fontFamily: "var(--mono, monospace)" }}>Video</span>
              </div>
            ) : (
              <div style={{ position: "absolute", inset: 0, background: "linear-gradient(135deg,#1e293b,#0f172a)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <svg width="24" height="24" 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" />
                </svg>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

interface ProfileBodyProps {
  locale: string;
}

// ── Bookmarked content types ──────────────────────────────────────────────────
type BookmarkType = 1 | 2 | 4;

interface BookmarkedItem {
  id: number;
  channel_id: number;
  title: string;
  portrait_img?: string;
  video?: string;
  channel_name?: string;
  channel_image?: string;
  total_view: number;
  total_like: number;
  is_user_like?: number;
  status: number;
}

const BOOKMARK_TABS: { type: BookmarkType; label: string }[] = [
  { type: 1, label: "Articles" },
  { type: 2, label: "Clips" },
  { type: 4, label: "Shows" },
];

function isValidImg(url?: string) { return !!url && !url.includes("no_img"); }

export function ProfileBody({ locale }: ProfileBodyProps) {
  const { t } = useTranslation("profile");
  const [activeTab, setActiveTab] = useState<TabId>("feeds");

  // Legacy state for hidden tab sections (not used in active tabs)
  const [savedItems] = useState<Set<number>>(new Set());
  const [followingJournalists] = useState<Set<number>>(new Set());
  const [subscribedNewsletters] = useState<Set<number>>(new Set());

  // ── Bookmarks state ───────────────────────────────────────────────────────
  const [bookmarkType, setBookmarkType] = useState<BookmarkType>(1);
  const [bookmarkedItems, setBookmarkedItems] = useState<BookmarkedItem[]>([]);
  const [bookmarkLoading, setBookmarkLoading] = useState(false);
  const loadedTypes = useState<Set<BookmarkType>>(new Set())[0];

  const fetchBookmarks = useCallback(async (type: BookmarkType) => {
    if (loadedTypes.has(type)) return;
    const userId = getStoredUser()?.id ?? 0;
    if (!userId) return;
    setBookmarkLoading(true);
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<{ result: BookmarkedItem[] }>(
        API_ENDPOINTS.GET_BOOKMARKED_CONTENT,
        { user_id: userId, type },
      );
      setBookmarkedItems((data.result ?? []).filter((i) => i.status === 1));
      loadedTypes.add(type);
    } catch {
      setBookmarkedItems([]);
    } finally {
      setBookmarkLoading(false);
    }
  }, [loadedTypes]);

  // Fetch when saved tab becomes active or bookmark type changes
  useEffect(() => {
    if (activeTab === "saved") {
      loadedTypes.clear(); // refetch on type switch
      fetchBookmarks(bookmarkType);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, bookmarkType]);

  // ── User feeds state ──────────────────────────────────────────────────────
  const [userFeeds, setUserFeeds] = useState<import("@/types/api/feeds.types").FeedItem[]>([]);
  const [feedsLoading, setFeedsLoading] = useState(false);
  const feedsFetchedRef = useRef(false);

  useEffect(() => {
    if (activeTab === "feeds" && !feedsFetchedRef.current) {
      feedsFetchedRef.current = true;
      const userId = getStoredUser()?.id ?? 0;
      if (!userId) return;
      setFeedsLoading(true);
      (async () => {
        try {
          const { default: apiClient } = await import("@/services/api.client");
          const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
          const { data } = await apiClient.post<{ result: import("@/types/api/feeds.types").FeedItem[] }>(
            API_ENDPOINTS.GET_USER_FEED,
            { to_user_id: userId, user_id: userId },
          );
          setUserFeeds((data.result ?? []).filter((f) => f.status === 1));
        } catch {
          setUserFeeds([]);
        } finally {
          setFeedsLoading(false);
        }
      })();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  // ── Only Feeds + Saved tabs shown ────────────────────────────────────────
  const tabs: { id: TabId; label: string; count: number; icon: React.ReactNode }[] = [
    {
      id: "feeds",
      label: "Feeds",
      count: userFeeds.length,
      icon: (
        <svg viewBox="0 0 24 24">
          <path d="M4 11a9 9 0 0 1 9 9M4 4a16 16 0 0 1 16 16" />
          <circle cx="5" cy="19" r="1.6" />
        </svg>
      ),
    },
    {
      id: "saved",
      label: t("tabs.saved"),
      count: 0,
      icon: (
        <svg viewBox="0 0 24 24">
          <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
        </svg>
      ),
    },
  ];

  // Toggle functions kept as stubs (referenced by hidden tab sections below)
  function toggleSave(_id: number) { /* hidden tab */ }
  function toggleFollow(_id: number) { /* hidden tab */ }
  function toggleNewsletter(_id: number) { /* hidden tab */ }

  return (
    <>
      {/* Sticky tabs */}
      <nav className="pf-tabs">
        <div className="wrap pf-tabs-row">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              className={`pf-tab${activeTab === tab.id ? " active" : ""}`}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.icon}
              {tab.label}
              <span className="ct">
                {tab.count.toLocaleString()}
              </span>
            </button>
          ))}
        </div>
      </nav>

      {/* Body */}
      <main className="wrap pf-shell">
        <div>
          {/* ── User Feeds ── */}
          {activeTab === "feeds" && (
            <section>
              <div className="pf-sec-h">
                <h2>My Feeds</h2>
              </div>

              {feedsLoading && (
                <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                  {Array.from({ length: 3 }).map((_, i) => (
                    <div key={i} style={{ background: "var(--surf, #fff)", border: "1px solid var(--line-hi, rgba(0,0,0,0.06))", borderRadius: 10, padding: "1rem" }}>
                      <div style={{ display: "flex", gap: "0.75rem", marginBottom: "0.625rem" }}>
                        <div style={{ width: 34, height: 34, borderRadius: "50%", background: "#e5e7eb", flexShrink: 0 }} />
                        <div style={{ flex: 1 }}>
                          <div style={{ height: 11, width: "30%", background: "#e5e7eb", borderRadius: 4, marginBottom: 6 }} />
                          <div style={{ height: 13, background: "#e5e7eb", borderRadius: 4 }} />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {!feedsLoading && userFeeds.length === 0 && (
                <div style={{ textAlign: "center", padding: "3rem 0", color: "var(--text-2, #6b7280)" }}>
                  <p style={{ fontWeight: 600, marginBottom: "0.375rem" }}>No posts yet</p>
                  <p style={{ fontSize: "0.875rem" }}>
                    <Link href="/feeds" style={{ color: "var(--brand, #C1272D)", fontWeight: 600 }}>Go to Feeds</Link> to post something
                  </p>
                </div>
              )}

              {!feedsLoading && userFeeds.length > 0 && (
                <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                  {userFeeds.map((feed) => (
                    <div key={feed.id} style={{ background: "var(--surf, #fff)", border: "1px solid var(--line-hi, rgba(0,0,0,0.06))", borderRadius: 10, padding: "1rem" }}>
                      {/* Header */}
                      <div style={{ display: "flex", alignItems: "flex-start", gap: "0.75rem", marginBottom: "0.625rem" }}>
                        <div style={{ width: 34, height: 34, borderRadius: "50%", background: "var(--brand-08, rgba(193,39,45,0.08))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, overflow: "hidden", position: "relative" }}>
                          {feed.user_image && !feed.user_image.includes("no_img") ? (
                            <Image src={feed.user_image} alt="" fill style={{ objectFit: "cover" }} unoptimized />
                          ) : (
                            <span style={{ fontSize: 12, fontWeight: 800, color: "var(--brand, #C1272D)" }}>
                              {feed.user_name?.charAt(0)?.toUpperCase() ?? "U"}
                            </span>
                          )}
                        </div>
                        <div style={{ flex: 1 }}>
                          <p style={{ margin: 0, fontWeight: 700, fontSize: "0.8125rem", color: "var(--ink, #0e0e11)" }}>{feed.user_name}</p>
                          <p style={{ margin: 0, fontSize: "0.7rem", fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)" }}>
                            {new Date(feed.created_at).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}
                          </p>
                        </div>
                      </div>
                      {/* Content */}
                      {feed.title && <p style={{ margin: "0 0 0.25rem", fontWeight: 600, fontSize: "0.9rem", color: "var(--ink, #0e0e11)" }}>{feed.title}</p>}
                      {feed.description && feed.description !== feed.title && (
                        <p style={{ margin: "0 0 0.375rem", fontSize: "0.875rem", color: "var(--text-2, #6b7280)", lineHeight: 1.5 }}>{feed.description}</p>
                      )}
                      {feed.hasteg?.length > 0 && (
                        <div style={{ display: "flex", flexWrap: "wrap", gap: "0.25rem", marginTop: "0.375rem" }}>
                          {feed.hasteg.map((h) => (
                            <span key={h.id} style={{ fontSize: "0.8125rem", color: "var(--brand, #C1272D)", fontWeight: 500 }}>#{h.name.trim()}</span>
                          ))}
                        </div>
                      )}
                      {/* Media */}
                      {feed.feed_content?.length > 0 && (
                        <FeedMediaGrid items={feed.feed_content} />
                      )}
                      {/* Stats */}
                      <div style={{ display: "flex", gap: "1rem", marginTop: "0.625rem", paddingTop: "0.5rem", borderTop: "1px solid var(--line, rgba(0,0,0,0.04))", fontSize: "0.75rem", fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)" }}>
                        <span>{feed.total_like} likes</span>
                        <span>{feed.total_comment} comments</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </section>
          )}

          {/* ── Reading history (hidden) ── */}
          {(activeTab as string) === "history" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.recently_read")}</h2>
                <button type="button" className="link">
                  {t("sections.clear_history")}
                </button>
              </div>
              <div className="pf-list">
                {HISTORY.map((item) => (
                  <div key={item.id} className="pf-row">
                    <div className="thumb">
                      <Image
                        src={item.img}
                        alt={item.title}
                        width={140}
                        height={88}
                        style={{ objectFit: "cover", width: "100%", height: "100%" }}
                        unoptimized
                      />
                    </div>
                    <div className="info">
                      <div className="cat">{item.cat}</div>
                      <h4>{item.title}</h4>
                      <div className="meta">
                        <span>{item.author}</span>
                        <b>· {item.status}</b>
                        <span>· {item.when}</span>
                      </div>
                      <div className="progress">
                        <div className="bar" style={{ width: `${item.progress}%` }} />
                      </div>
                    </div>
                    <div className="actions">
                      <button
                        type="button"
                        className={savedItems.has(item.id) ? "on" : ""}
                        title={savedItems.has(item.id) ? t("actions.saved") : t("actions.save")}
                        onClick={() => toggleSave(item.id)}
                      >
                        <svg viewBox="0 0 24 24" fill={savedItems.has(item.id) ? "currentColor" : "none"}>
                          <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
                        </svg>
                      </button>
                      <button type="button" title={t("actions.hide")}>
                        <svg viewBox="0 0 24 24">
                          <path d="M6 6l12 12M18 6L6 18" />
                        </svg>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ── Saved articles ── */}
          {activeTab === "saved" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.saved_articles")}</h2>
              </div>

              {/* Content-type sub-tabs */}
              <div style={{ display: "flex", gap: 0, marginBottom: "1.25rem", borderBottom: "1px solid var(--border, #e5e7eb)" }}>
                {BOOKMARK_TABS.map((tab) => (
                  <button
                    key={tab.type}
                    onClick={() => setBookmarkType(tab.type)}
                    style={{
                      padding: "0.5rem 1rem",
                      background: "none",
                      border: "none",
                      borderBottom: bookmarkType === tab.type ? "2.5px solid var(--brand, #C1272D)" : "2.5px solid transparent",
                      color: bookmarkType === tab.type ? "var(--brand, #C1272D)" : "var(--text-2, #6b7280)",
                      fontWeight: bookmarkType === tab.type ? 700 : 500,
                      fontSize: "0.875rem",
                      cursor: "pointer",
                      transition: "all 0.15s",
                    }}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>

              {/* Skeleton */}
              {bookmarkLoading && (
                <div className="pf-saved-grid">
                  {Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="pf-saved-card" style={{ opacity: 0.6 }}>
                      <div className="ph" style={{ background: "#e5e7eb" }} />
                      <div className="body">
                        <div style={{ height: 10, width: "40%", background: "#e5e7eb", borderRadius: 4, marginBottom: 8 }} />
                        <div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, marginBottom: 5 }} />
                        <div style={{ height: 14, width: "70%", background: "#e5e7eb", borderRadius: 4 }} />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Empty state */}
              {!bookmarkLoading && bookmarkedItems.length === 0 && (
                <div style={{ textAlign: "center", padding: "3rem 0", color: "var(--text-2, #6b7280)" }}>
                  <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ marginBottom: "0.75rem", opacity: 0.35 }}>
                    <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
                  </svg>
                  <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>
                    No saved {BOOKMARK_TABS.find((b) => b.type === bookmarkType)?.label.toLowerCase()}
                  </p>
                  <p style={{ fontSize: "0.875rem" }}>Bookmark content to find it here</p>
                </div>
              )}

              {/* Results */}
              {!bookmarkLoading && bookmarkedItems.length > 0 && (
                <div className="pf-saved-grid">
                  {bookmarkedItems.map((item) => {
                    const img = isValidImg(item.portrait_img) ? item.portrait_img : null;
                    const href = `/detail/${item.id}?type=${bookmarkType}`;
                    return (
                      <Link key={item.id} href={href} style={{ textDecoration: "none", color: "inherit" }}>
                        <div className="pf-saved-card">
                          <div className="ph" style={{ position: "relative" }}>
                            {img ? (
                              <Image
                                src={img}
                                alt={item.title}
                                width={400}
                                height={225}
                                style={{ objectFit: "cover", width: "100%", height: "100%" }}
                                unoptimized
                              />
                            ) : (
                              <div style={{ width: "100%", height: "100%", background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                                {bookmarkType === 2 && (
                                  <svg width="24" height="24" viewBox="0 0 24 24" fill="rgba(255,255,255,0.2)"><polygon points="6 4 20 12 6 20" /></svg>
                                )}
                              </div>
                            )}
                            <div className="save" style={{ background: "var(--brand, #C1272D)" }}>
                              <svg viewBox="0 0 24 24" fill="currentColor">
                                <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
                              </svg>
                            </div>
                          </div>
                          <div className="body">
                            <span className="cat">{item.channel_name}</span>
                            <h4>{item.title}</h4>
                            <div className="foot">
                              <span>{item.total_view > 0 ? `${item.total_view} views` : ""}</span>
                              <span style={{ fontSize: "0.7rem", fontFamily: "var(--mono, monospace)", color: "var(--text-3, #9ca3af)", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                                {BOOKMARK_TABS.find((b) => b.type === bookmarkType)?.label.slice(0, -1)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </Link>
                    );
                  })}
                </div>
              )}
            </section>
          )}

          {/* ── Topics ── */}
          {(activeTab as string) === "topics" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.your_topics")}</h2>
              </div>
              <div className="pf-topics-grid">
                {TOPICS.map((topic) => (
                  <div key={topic.id} className="pf-topic">
                    <div className="ico">{topic.icon}</div>
                    <div className="info">
                      <div className="nm">{topic.label}</div>
                      <div className="stat">
                        {topic.stories} stories ·{" "}
                        <span className="new">{topic.newStories} new</span>
                      </div>
                    </div>
                    <button type="button" className="toggle">
                      {t("actions.following")}
                    </button>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ── Following ── */}
          {(activeTab as string) === "following" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.following")}</h2>
              </div>
              <div className="pf-follow-grid">
                {JOURNALISTS.map((j) => (
                  <div key={j.id} className="pf-follow">
                    <div className="av" style={{ background: j.gradient }}>
                      {j.initials}
                    </div>
                    <div className="info">
                      <div className="nm">
                        {j.name}
                        {j.verified && (
                          <span className="v">
                            <svg viewBox="0 0 24 24">
                              <path d="M5 12l5 5L20 7" />
                            </svg>
                          </span>
                        )}
                      </div>
                      <div className="role">{j.role}</div>
                      <div className="stat">
                        {j.articles} articles · {j.readers} readers
                      </div>
                    </div>
                    <button
                      type="button"
                      className={`btn${followingJournalists.has(j.id) ? " on" : ""}`}
                      onClick={() => toggleFollow(j.id)}
                    >
                      {followingJournalists.has(j.id)
                        ? t("actions.following")
                        : t("actions.follow")}
                    </button>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ── Comments ── */}
          {(activeTab as string) === "comments" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.your_comments")}</h2>
              </div>
              <div className="pf-comments">
                {COMMENTS.map((c) => (
                  <div key={c.id} className="pf-comment">
                    <div className="on-article">
                      On: <a href="#">{c.articleTitle}</a>
                    </div>
                    <div className="body">{c.body}</div>
                    <div className="foot">
                      <span className="item like">
                        <svg viewBox="0 0 24 24">
                          <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
                        </svg>
                        {c.likes}
                      </span>
                      <span className="item">
                        <svg viewBox="0 0 24 24">
                          <path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8z" />
                        </svg>
                        {c.replies} replies
                      </span>
                      <span className="item">{c.when}</span>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* ── Newsletters ── */}
          {(activeTab as string) === "newsletters" && (
            <section>
              <div className="pf-sec-h">
                <h2>{t("sections.your_newsletters")}</h2>
              </div>
              <div className="pf-nl-list">
                {NEWSLETTERS.map((nl) => (
                  <div
                    key={nl.id}
                    className={`pf-nl${subscribedNewsletters.has(nl.id) ? " subscribed" : ""}`}
                  >
                    <div className="cover" style={{ background: nl.gradient }}>
                      {nl.initials}
                    </div>
                    <div className="info">
                      <div className="nm">{nl.name}</div>
                      <div className="meta">{nl.schedule}</div>
                      <p>{nl.description}</p>
                    </div>
                    <div className="actions">
                      <button
                        type="button"
                        className={`toggle-pill${subscribedNewsletters.has(nl.id) ? " on" : " off"}`}
                        onClick={() => toggleNewsletter(nl.id)}
                      >
                        {subscribedNewsletters.has(nl.id)
                          ? t("actions.subscribed")
                          : t("actions.subscribe")}
                      </button>
                      <span className="preview-link">{t("actions.preview")}</span>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>

        {/* ── Sidebar ── */}
        <aside className="pf-side">
          {/* Topics */}
          <div className="pf-card accent-l">
            <div className="h">{t("sidebar.topics_you_follow")}</div>
            <div className="topic-chips">
              {SIDEBAR_TOPICS.map((topic) => (
                <a key={topic} href="#" className="on">
                  {topic}
                </a>
              ))}
            </div>
          </div>

          {/* Subscription card */}
          <div className="sub-card">
            <div className="lbl">{t("subscription.label")}</div>
            <h5>{t("subscription.title")}</h5>
            <div className="plan">
              <span className="n">₹49</span>
              <span className="l">
                {t("subscription.per_month")} · {t("subscription.renews")} 14 Jun 2026
              </span>
            </div>
            <a className="btn" href="#">
              {t("subscription.manage")}
              <svg viewBox="0 0 24 24">
                <path d="M5 12h14M13 6l6 6-6 6" />
              </svg>
            </a>
          </div>

          {/* Following */}
          <div className="pf-card">
            <div className="h">{t("sidebar.following")}</div>
            <div className="author-list">
              {SIDEBAR_FOLLOWING.map((author) => (
                <div key={author.name} className="author-row">
                  <div className="av" style={{ background: author.gradient }}>
                    {author.initials}
                  </div>
                  <div>
                    <div className="nm">{author.name}</div>
                    <div className="role">{author.role}</div>
                  </div>
                  <span className="pill on">{t("actions.following")}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Newsletters */}
          <div className="pf-card">
            <div className="h">{t("sidebar.newsletters")}</div>
            <div className="author-list">
              {SIDEBAR_NEWSLETTERS.map((nl) => (
                <div key={nl.name} className="author-row">
                  <div
                    className="av"
                    style={{
                      background: nl.gradient,
                      fontStyle: "italic",
                      fontFamily: "var(--italic)",
                    }}
                  >
                    {nl.initials}
                  </div>
                  <div>
                    <div className="nm">{nl.name}</div>
                    <div className="role">{nl.schedule}</div>
                  </div>
                  <span className={`pill${nl.on ? " on" : ""}`}>
                    {nl.on ? t("actions.on") : t("actions.off")}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </aside>
      </main>
    </>
  );
}
