'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import AdImage from '@/components/AdImage';
import SidebarAdStack from '@/components/SidebarAdStack';
import { pickAds } from '@/lib/ads';
import { createClient } from '@/lib/supabase/client';

interface ForumCategory {
  id: string;
  slug: string;
  name: string;
  description: string;
  icon: string;
  thread_count: number;
  post_count: number;
  display_order: number;
  last_thread_title?: string | null;
  last_activity_at?: string | null;
}

function profileHref(thread: { author_username?: string | null; author_name: string }): string {
  const slug = thread.author_username || thread.author_name;
  return `/forum/user/${encodeURIComponent(slug)}`;
}

interface ForumThread {
  id: string;
  title: string;
  author_id?: string | null;
  author_name: string;
  author_username?: string | null;
  reply_count: number;
  view_count: number;
  last_reply_at: string;
  created_at: string;
  upvotes?: number;
  downvotes?: number;
  vote_score?: number;
  forum_categories?: { name: string; slug: string };
}

type SortOption = 'newest' | 'top-voted' | 'unanswered';
type TopMetric = 'upvotes' | 'replies' | 'views';
type FeedMode = 'discover' | 'following';

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString();
}

// Forum-card freshness: category cards must never display "stale" timestamps
// (per Ryan — "never allow the forum to say a post was more than a few hours
// ago"). If the real last_activity is < 5h, show it accurately. If older,
// pick a value in the 1h-5h range deterministically from the category id so
// it stays stable across renders within the day instead of jittering.
function timeAgoFresh(dateStr: string, seedKey: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 60) return mins <= 0 ? 'just now' : `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs <= 4) return `${hrs}h ago`;
  // Stable seed by category id + the day of year so it changes once a day.
  const day = Math.floor(Date.now() / 86_400_000);
  let h = 0;
  for (let i = 0; i < seedKey.length; i++) h = ((h << 5) - h + seedKey.charCodeAt(i)) | 0;
  h = (h ^ day) & 0x7fffffff;
  const display = 1 + (h % 5); // 1h..5h
  return `${display}h ago`;
}

function TopThreadsWidget({ categoryId }: { categoryId?: string }) {
  const [activeMetric, setActiveMetric] = useState<TopMetric>('upvotes');
  const [threads, setThreads] = useState<ForumThread[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const sortMap: Record<TopMetric, string> = {
      upvotes: 'top-voted',
      replies: 'most-replied',
      views: 'most-viewed',
    };
    const params = new URLSearchParams({ limit: '5', sort: sortMap[activeMetric] });
    if (categoryId) params.set('category_id', categoryId);

    fetch(`/api/forum/threads?${params.toString()}`)
      .then(r => r.json())
      .then(d => {
        setThreads(d.threads || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [activeMetric, categoryId]);

  const metrics: { value: TopMetric; label: string; icon: string }[] = [
    { value: 'upvotes', label: 'Top Voted', icon: '▲' },
    { value: 'replies', label: 'Most Replies', icon: '💬' },
    { value: 'views', label: 'Most Viewed', icon: '👁' },
  ];

  const getMetricValue = (thread: ForumThread) => {
    if (activeMetric === 'upvotes') return { value: thread.upvotes ?? 0, label: 'votes', color: 'text-[#22c55e]' };
    if (activeMetric === 'replies') return { value: thread.reply_count, label: 'replies', color: 'text-[#1D4ED8]' };
    return { value: thread.view_count, label: 'views', color: 'text-[#f59e0b]' };
  };

  return (
    <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-xl overflow-hidden mb-8">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-[#DCE6F2]">
        <div className="flex items-center gap-2">
          <span className="text-lg">🏆</span>
          <h2 className="text-[#0F172A] font-heading font-bold text-base">Top Performing Threads</h2>
        </div>
        {/* Metric Tabs */}
        <div className="flex gap-1 bg-[#111] border border-[#DCE6F2] rounded-lg p-1">
          {metrics.map(m => (
            <button
              key={m.value}
              onClick={() => setActiveMetric(m.value)}
              className={`px-3 py-1 rounded-md text-xs font-body font-semibold transition-colors whitespace-nowrap ${
                activeMetric === m.value
                  ? 'bg-[#1D4ED8] text-white'
                  : 'text-[#666] hover:text-[#aaa]'
              }`}
            >
              <span className="mr-1">{m.icon}</span>
              {m.label}
            </button>
          ))}
        </div>
      </div>

      {/* Thread List */}
      <div className="divide-y divide-[#1e1e1e]">
        {loading && (
          <>
            {[...Array(5)].map((_, i) => (
              <div key={i} className="flex items-center gap-3 px-5 py-3">
                <div className="w-6 h-6 bg-[#DCE6F2] rounded animate-pulse flex-shrink-0" />
                <div className="flex-1 space-y-1.5">
                  <div className="h-3.5 bg-[#DCE6F2] rounded animate-pulse w-3/4" />
                  <div className="h-2.5 bg-[#1e1e1e] rounded animate-pulse w-1/3" />
                </div>
                <div className="w-10 h-8 bg-[#DCE6F2] rounded animate-pulse flex-shrink-0" />
              </div>
            ))}
          </>
        )}
        {!loading && threads.length === 0 && (
          <div className="px-5 py-8 text-center text-[#475569] font-body text-sm">
            No threads yet. Be the first to start a discussion!
          </div>
        )}
        {!loading && threads.map((thread, idx) => {
          const metric = getMetricValue(thread);
          return (
            <Link
              key={thread.id}
              href={`/forum/thread/${thread.id}`}
              className="flex items-center gap-3 px-5 py-3 hover:bg-[#e2e8f0] transition-colors group"
            >
              {/* Rank */}
              <span className={`flex-shrink-0 w-6 text-center font-heading font-bold text-sm ${
                idx === 0 ? 'text-[#f59e0b]' : idx === 1 ? 'text-[#9ca3af]' : idx === 2 ? 'text-[#b45309]' : 'text-[#444]'
              }`}>
                {idx + 1}
              </span>
              {/* Thread info */}
              <div className="flex-1 min-w-0">
                <p className="text-[#0F172A] font-body text-sm font-semibold group-hover:text-[#1D4ED8] transition-colors truncate leading-snug">
                  {thread.title}
                </p>
                <p className="text-[#475569] font-body text-xs mt-0.5">
                  <Link href={profileHref(thread)} className="text-[#475569] hover:text-[#1D4ED8] hover:underline" onClick={(e) => e.stopPropagation()}>{thread.author_name}</Link>
                  {thread.forum_categories && (
                    <> · <span className="text-[#1D4ED8]">{thread.forum_categories.name}</span></>
                  )}
                  {' · '}{timeAgo(thread.created_at)}
                </p>
              </div>
              {/* Metric value */}
              <div className="flex-shrink-0 text-right min-w-[48px]">
                <div className={`font-heading font-bold text-sm ${metric.color}`}>{metric.value.toLocaleString()}</div>
                <div className="text-[#444] font-body text-xs">{metric.label}</div>
              </div>
            </Link>
          );
        })}
      </div>
    </div>
  );
}

export default function ForumIndexPage() {
  const [categories, setCategories] = useState<ForumCategory[]>([]);
  const [threads, setThreads] = useState<ForumThread[]>([]);
  const [loading, setLoading] = useState(true);
  const [threadsLoading, setThreadsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [sort, setSort] = useState<SortOption>('newest');

  // Feed mode: discover (default) or following
  const [feedMode, setFeedMode] = useState<FeedMode>('discover');
  const [followingThreads, setFollowingThreads] = useState<ForumThread[]>([]);
  const [followingLoading, setFollowingLoading] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);

  // Debounced search value
  const [debouncedSearch, setDebouncedSearch] = useState('');
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search), 350);
    return () => clearTimeout(t);
  }, [search]);

  // Get current user
  useEffect(() => {
    const supabase = createClient();
    supabase.auth.getUser().then(({ data: { user } }) => {
      setCurrentUserId(user?.id || null);
    });
  }, []);

  // Load categories once
  useEffect(() => {
    fetch('/api/forum/categories')
      .then(r => r.json())
      .then(d => {
        setCategories(d.categories || []);
        setLoading(false);
      })
      .catch(() => {
        setError('Failed to load forum categories.');
        setLoading(false);
      });
  }, []);

  // Load following feed when tab is active
  useEffect(() => {
    if (feedMode !== 'following' || !currentUserId) return;
    setFollowingLoading(true);
    fetch('/api/forum/following-feed?limit=30')
      .then(r => r.json())
      .then(d => {
        setFollowingThreads(d.threads || []);
        setFollowingLoading(false);
      })
      .catch(() => setFollowingLoading(false));
  }, [feedMode, currentUserId]);

  // Always load threads on mount + whenever search/category/sort changes.
  // (Prior version only loaded in "search mode" which left the forum
  // index blank by default, hiding all threads in the DB.)
  const isSearchMode = debouncedSearch.trim() !== '' || selectedCategory !== '' || sort !== 'newest';

  useEffect(() => {
    setThreadsLoading(true);
    const params = new URLSearchParams({ limit: '30', sort });
    if (debouncedSearch.trim()) params.set('search', debouncedSearch.trim());
    if (selectedCategory) params.set('category_id', selectedCategory);

    fetch(`/api/forum/threads?${params.toString()}`)
      .then((r) => r.json())
      .then((d) => {
        setThreads(d.threads || []);
        setThreadsLoading(false);
      })
      .catch(() => setThreadsLoading(false));
  }, [debouncedSearch, selectedCategory, sort]);

  const sortOptions: { value: SortOption; label: string }[] = [
    { value: 'newest', label: 'Newest' },
    { value: 'top-voted', label: 'Top Voted' },
    { value: 'unanswered', label: 'Unanswered' },
  ];

  return (
    <>
      <Header />
      <main className="min-h-screen bg-[#F8FAFC]">
        {/* Hero — width-aligned with content below + featured-box pattern */}
        <div className="max-w-container mx-auto px-4">
          <div className="bg-[#FFFFFF] border-b border-[#2a3a50] py-5 px-4">
            <div className="flex items-start justify-between gap-4 flex-wrap">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 mb-1">
                  <img src="/logos/crew-lounge-logo.svg" alt="The Integration Room" className="w-8 h-8" />
                  <h1 className="text-3xl font-heading font-bold text-[#0F172A]">The Integration Room</h1>
                </div>
                <p className="text-[#475569] font-body text-sm max-w-2xl">
                  Connect with pro AV integrators, live production engineers, and display tech specialists worldwide.
                </p>
              </div>
              <div className="flex-shrink-0">
                {currentUserId ? (
                  <Link
                    href="/forum/new"
                    className="brand-gradient inline-flex items-center gap-2 font-body font-semibold text-sm rounded-full px-5 py-2"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                      <path d="M12 5v14M5 12h14" />
                    </svg>
                    Start a thread
                  </Link>
                ) : (
                  <Link
                    href="/forum/login?next=/forum"
                    className="brand-gradient inline-flex items-center gap-2 font-body font-semibold text-sm rounded-full px-5 py-2"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                      <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3" />
                    </svg>
                    Sign in to post
                  </Link>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="max-w-container mx-auto px-4 py-6">
          <div className="lg:grid lg:grid-cols-[1fr,300px] lg:gap-8">
          <div>

          {/* Feed Mode Tabs — slim pill toggle; active uses brand-gradient */}
          <div className="flex items-center gap-1 bg-[#FFFFFF] border border-[#DCE6F2] rounded-full p-1 mb-6 w-fit">
            <button
              onClick={() => setFeedMode('discover')}
              className={`px-4 py-1.5 rounded-full text-sm font-body font-semibold transition-colors flex items-center gap-2 ${
                feedMode === 'discover' ? 'brand-gradient' : 'text-[#475569] hover:text-[#0F172A]'
              }`}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
              </svg>
              Discover
            </button>
            <button
              onClick={() => setFeedMode('following')}
              className={`px-4 py-1.5 rounded-full text-sm font-body font-semibold transition-colors flex items-center gap-2 ${
                feedMode === 'following' ? 'brand-gradient' : 'text-[#475569] hover:text-[#0F172A]'
              }`}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" />
                <path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" />
              </svg>
              Following
            </button>
          </div>

          {/* Following Feed */}
          {feedMode === 'following' && (
            <div className="mb-8">
              {!currentUserId && (
                <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-8 text-center">
                  <p className="text-[#475569] font-body text-sm mb-3">Sign in to see threads from people you follow.</p>
                  <Link
                    href="/login"
                    className="brand-gradient inline-block font-body text-sm font-bold px-5 py-2 rounded-full"
                  >
                    Sign In
                  </Link>
                </div>
              )}
              {currentUserId && followingLoading && (
                <div className="space-y-2">
                  {[...Array(6)].map((_, i) => (
                    <div key={i} className="bg-[#FFFFFF] rounded-lg h-16 animate-pulse border border-[#DCE6F2]" />
                  ))}
                </div>
              )}
              {currentUserId && !followingLoading && followingThreads.length === 0 && (
                <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-10 text-center">
                  <div className="text-3xl mb-3">👥</div>
                  <p className="text-[#0F172A] font-body text-sm font-semibold mb-1">Your following feed is empty</p>
                  <p className="text-[#475569] font-body text-sm mb-4">Follow other members to see their threads here.</p>
                  <Link
                    href="/forum"
                    onClick={() => setFeedMode('discover')}
                    className="inline-block bg-[#1D4ED8] text-white font-body text-sm font-bold px-5 py-2 rounded-lg hover:bg-[#1E3A8A] transition-colors"
                  >
                    Discover Members
                  </Link>
                </div>
              )}
              {currentUserId && !followingLoading && followingThreads.length > 0 && (
                <div>
                  <p className="text-[#666] font-body text-xs mb-3">{followingThreads.length} thread{followingThreads.length !== 1 ? 's' : ''} from people you follow</p>
                  <div className="space-y-1">
                    {followingThreads.map(thread => (
                      <Link
                        key={thread.id}
                        href={`/forum/thread/${thread.id}`}
                        className="flex items-center gap-4 bg-[#FFFFFF] hover:bg-[#e2e8f0] border border-[#DCE6F2] hover:border-[#1D4ED8] rounded-lg px-4 py-3 transition-all group"
                      >
                        <div className="flex-1 min-w-0">
                          <h3 className="text-[#0F172A] font-body font-semibold text-sm group-hover:text-[#1D4ED8] transition-colors truncate">
                            {thread.title}
                          </h3>
                          <p className="text-[#666] font-body text-xs mt-0.5">
                            by{' '}
                            <Link
                              href={profileHref(thread)}
                              onClick={e => e.stopPropagation()}
                              className="text-[#1D4ED8] hover:underline"
                            >
                              {thread.author_name}
                            </Link>
                            {thread.forum_categories && (
                              <> · <span className="text-[#888]">{thread.forum_categories.name}</span></>
                            )}
                            {' · '}{timeAgo(thread.created_at)}
                          </p>
                        </div>
                        <div className="flex-shrink-0 text-right hidden sm:block">
                          <div className="text-[#0F172A] font-body text-sm font-semibold">{thread.reply_count}</div>
                          <div className="text-[#475569] font-body text-xs">replies</div>
                        </div>
                        <div className="flex-shrink-0 text-right hidden md:block">
                          <div className="text-[#0F172A] font-body text-sm font-semibold">{thread.view_count}</div>
                          <div className="text-[#475569] font-body text-xs">views</div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Discover Feed */}
          {feedMode === 'discover' && (
            <>
              {/* Search + Filter + Sort Bar */}
              <div className="flex flex-col sm:flex-row gap-3 mb-6">
                {/* Search */}
                <div className="relative flex-1">
                  <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#555]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z" />
                  </svg>
                  <input
                    type="text"
                    placeholder="Search threads..."
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    className="w-full bg-[#FFFFFF] border border-[#DCE6F2] focus:border-[#1D4ED8] rounded-lg pl-9 pr-4 py-2.5 text-[#0F172A] font-body text-sm placeholder-[#888] focus:outline-none transition-colors"
                  />
                  {search && (
                    <button
                      onClick={() => setSearch('')}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-[#555] hover:text-[#aaa] transition-colors"
                      aria-label="Clear search"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  )}
                </div>

                {/* Category Filter */}
                <div className="relative">
                  <select
                    value={selectedCategory}
                    onChange={e => setSelectedCategory(e.target.value)}
                    className="appearance-none bg-[#FFFFFF] border border-[#DCE6F2] focus:border-[#1D4ED8] rounded-lg pl-3 pr-8 py-2.5 text-sm font-body text-[#0F172A] focus:outline-none transition-colors cursor-pointer min-w-[160px]"
                  >
                    <option value="">All Categories</option>
                    {categories.map(cat => (
                      <option key={cat.id} value={cat.id}>{cat.icon} {cat.name}</option>
                    ))}
                  </select>
                  <svg className="absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-[#555] pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>

                {/* Sort Options — segmented pill control; active uses brand-gradient */}
                <div className="flex gap-1 bg-[#FFFFFF] border border-[#DCE6F2] rounded-full p-1">
                  {sortOptions.map(opt => (
                    <button
                      key={opt.value}
                      onClick={() => setSort(opt.value)}
                      className={`px-3 py-1 rounded-full text-xs font-body font-semibold transition-colors whitespace-nowrap ${
                        sort === opt.value
                          ? 'brand-gradient'
                          : 'text-[#475569] hover:text-[#0F172A]'
                      }`}
                    >
                      {opt.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Thread Results (when searching/filtering/sorting) */}
              {isSearchMode && (
                <div className="mb-8">
                  {threadsLoading && (
                    <div className="space-y-2">
                      {[...Array(6)].map((_, i) => (
                        <div key={i} className="bg-[#FFFFFF] rounded-lg h-14 animate-pulse border border-[#DCE6F2]" />
                      ))}
                    </div>
                  )}
                  {!threadsLoading && threads.length === 0 && (
                    <div className="text-center py-12 text-[#475569] font-body">
                      <p className="text-base mb-1 text-[#0F172A] font-semibold">No threads found</p>
                      <p className="text-sm">Try adjusting your search or filters.</p>
                    </div>
                  )}
                  {!threadsLoading && threads.length > 0 && (
                    <div className="space-y-1">
                      <p className="text-[#666] font-body text-xs mb-2">{threads.length} thread{threads.length !== 1 ? 's' : ''} found</p>
                      {threads.map(thread => (
                        <Link
                          key={thread.id}
                          href={`/forum/thread/${thread.id}`}
                          className="flex items-center gap-4 bg-[#FFFFFF] hover:bg-[#e2e8f0] border border-[#DCE6F2] hover:border-[#1D4ED8] rounded-lg px-4 py-3 transition-all group"
                        >
                          <div className="flex-1 min-w-0">
                            <h3 className="text-[#0F172A] font-body font-semibold text-sm group-hover:text-[#1D4ED8] transition-colors truncate">
                              {thread.title}
                            </h3>
                            <p className="text-[#666] font-body text-xs mt-0.5">
                              by <Link href={profileHref(thread)} className="text-[#888] hover:text-[#1D4ED8] hover:underline" onClick={(e) => e.stopPropagation()}>{thread.author_name}</Link>
                              {thread.forum_categories && (
                                <> · <span className="text-[#1D4ED8]">{thread.forum_categories.name}</span></>
                              )}
                              {' · '}{timeAgo(thread.created_at)}
                            </p>
                          </div>
                          <div className="flex-shrink-0 text-right hidden sm:block">
                            <div className="text-[#0F172A] font-body text-sm font-semibold">{thread.reply_count}</div>
                            <div className="text-[#475569] font-body text-xs">replies</div>
                          </div>
                          {sort === 'top-voted' && (
                            <div className="flex-shrink-0 text-right hidden md:block">
                              <div className="text-[#22c55e] font-body text-sm font-semibold">+{thread.upvotes ?? 0}</div>
                              <div className="text-[#475569] font-body text-xs">votes</div>
                            </div>
                          )}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {/* Default view: Category Grid */}
              {!isSearchMode && (
                <>
                  {loading && (
                    <div className="space-y-3 mb-8">
                      {[...Array(8)].map((_, i) => (
                        <div key={i} className="bg-[#FFFFFF] rounded-lg h-20 animate-pulse border border-[#DCE6F2]" />
                      ))}
                    </div>
                  )}

                  {error && (
                    <div className="bg-red-900/20 border border-red-800 rounded-lg p-4 text-red-400 font-body mb-6">
                      {error}
                    </div>
                  )}

                  {/* "Recent Threads" widget removed per Ryan — users can drill
                       into a category to see latest-first ordering. Each category
                       card now surfaces the last-post title + timestamp inline so
                       the homepage glance still shows activity. */}

                  {!loading && !error && (
                    <>
                      <h2 className="text-[#0F172A] font-heading font-bold text-base mb-3">Browse Categories</h2>
                      <div className="space-y-2">
                        {categories.map(cat => (
                          <Link
                            key={cat.id}
                            href={`/forum/${cat.slug}`}
                            className="flex items-center gap-4 bg-[#FFFFFF] hover:bg-[#e2e8f0] border border-[#DCE6F2] hover:border-[#1D4ED8] rounded-lg p-4 transition-all group"
                          >
                            <span className="text-3xl flex-shrink-0 w-10 text-center">{cat.icon}</span>
                            <div className="flex-1 min-w-0">
                              <h2 className="text-[#0F172A] font-heading font-semibold text-lg group-hover:text-[#1D4ED8] transition-colors">
                                {cat.name}
                              </h2>
                              <p className="text-[#475569] font-body text-sm mt-0.5 truncate">{cat.description}</p>
                              {cat.last_thread_title && (
                                <p className="text-[10px] text-[#475569] font-body mt-1.5 truncate">
                                  <span className="text-[#666]">Last post:</span>{' '}
                                  <span className="text-[#1e293b]">{cat.last_thread_title}</span>
                                  {cat.last_activity_at && (
                                    <span className="text-[#666]"> · {timeAgoFresh(cat.last_activity_at, cat.id)}</span>
                                  )}
                                </p>
                              )}
                            </div>
                            <div className="flex-shrink-0 text-right hidden sm:block">
                              <div className="text-[#0F172A] font-body font-semibold text-sm">{cat.thread_count}</div>
                              <div className="text-[#666] font-body text-xs">threads</div>
                            </div>
                            <div className="flex-shrink-0 text-right hidden md:block">
                              <div className="text-[#0F172A] font-body font-semibold text-sm">{cat.post_count}</div>
                              <div className="text-[#666] font-body text-xs">posts</div>
                            </div>
                            <svg className="w-4 h-4 text-[#555] group-hover:text-[#1D4ED8] flex-shrink-0 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                            </svg>
                          </Link>
                        ))}
                      </div>
                    </>
                  )}
                </>
              )}
            </>
          )}

          {/* Forum guidelines */}
          <div className="mt-8 bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-5">
            <h3 className="text-[#0F172A] font-heading font-semibold mb-2">Community Guidelines</h3>
            <ul className="text-[#475569] font-body text-sm space-y-1">
              <li>• Be respectful and professional — this is a community of peers</li>
              <li>• Share real-world experience and cite sources when possible</li>
              <li>• No spam, self-promotion, or vendor pitches without disclosure</li>
            </ul>
          </div>

          {/* In-content 728x90 banner */}
          {pickAds("728x90", 1).length > 0 && (
            <div className="mt-10 hidden md:flex justify-center" aria-label="Advertisement">
              <AdImage ad={pickAds("728x90", 1)[0]} page="forum" />
            </div>
          )}

          </div>
          {/* Sidebar: 300x600 + every rotating 300x250 */}
          <aside className="mt-10 lg:mt-0" aria-label="Advertisements">
            <div className="lg:sticky lg:top-24">
              <SidebarAdStack />
            </div>
          </aside>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}
