import { useState, useMemo, useRef, useEffect } from "react";
import { Breadcrumb } from "@/components/Breadcrumb";
import { useKeyboardNav, keyboardNavItemClass } from "@/hooks/useKeyboardNav";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/_core/hooks/useAuth";
import { Link } from "wouter";
import { Card, CardContent } from "@/components/ui/card";
import { NewsCard } from "@/components/TexturedCard";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Newspaper, ArrowLeft, TrendingUp, Briefcase, Star, Calendar, Info, Globe, ExternalLink, BarChart3, Sparkles, ChevronRight } from "lucide-react";
import { LazyStreamdown as Streamdown } from "@/components/LazyStreamdown";
import { SEOHead, pageSEO } from "@/components/SEOHead";
import { PageTransition } from "@/components/PageTransition";
import { mergeAndDedup, getSourceLabel, getSourceColor, type UnifiedNewsItem } from "@/lib/newsDedup";
import { SentimentBadge } from "@/components/SentimentBadge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { QUERY_CACHE } from "@/lib/queryConfig";
import { EmptyState } from "@/components/EmptyState";
import { ElevenLabsListenButton } from "@/components/ElevenLabsListenButton";
import { ScrollReveal } from "@/components/ScrollReveal";
import { NewsSkeletonGrid } from "@/components/NewsCardSkeleton";
import { CitedMacroBriefing } from "@/components/features/CitedMacroBriefing";

export default function NewsFeed() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<"portfolio" | "watchlist" | "trending" | "market" | "briefings">("trending");

  // Fetch macro briefings
  const { data: briefings, isLoading: isLoadingBriefings } = trpc.macroBriefing.list.useQuery(
    { limit: 10 },
    { staleTime: 5 * 60 * 1000 }
  );
  const [visibleCount, setVisibleCount] = useState(15);
  const loadMoreRef = useRef<HTMLDivElement>(null);

  // Fetch portfolio holdings
  const { data: holdings } = trpc.realPortfolio.getHoldings.useQuery(undefined, {
    ...QUERY_CACHE.USER_DATA,
    enabled: !!user,
  });

  // Fetch watchlist
  const { data: watchlist } = trpc.watchlist.list.useQuery(undefined, {
    ...QUERY_CACHE.USER_DATA,
    enabled: !!user,
  });

  // Get symbols from portfolio
  const portfolioSymbols = useMemo(() => {
    if (!holdings) return [];
    return holdings.map((h) => h.ticker);
  }, [holdings]);

  // Get symbols from watchlist
  const watchlistSymbols = useMemo(() => {
    if (!watchlist) return [];
    return watchlist.map((w) => w.ticker);
  }, [watchlist]);

  // Trending stocks for non-authenticated users
  const trendingSymbols = useMemo(
    () => ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "JPM", "V", "UNH"],
    []
  );

  // Polygon market news (for Market Wire tab)
  const { data: polygonMarketNews, isLoading: isLoadingPolygon } = trpc.polygonNews.marketNews.useQuery(
    { limit: 30 },
    { enabled: activeTab === "market", staleTime: 5 * 60 * 1000 }
  );
  // Benzinga news via Massive API (enriches Market Wire)
  const { data: benzingaNews } = trpc.massive.benzingaNews.useQuery(
    { limit: 20 },
    { enabled: activeTab === "market", staleTime: 5 * 60 * 1000 }
  );

  // Get active symbols based on tab
  const activeSymbols = useMemo(() => {
    switch (activeTab) {
      case "portfolio":
        return portfolioSymbols;
      case "watchlist":
        return watchlistSymbols;
      case "trending":
      default:
        return trendingSymbols;
    }
  }, [activeTab, portfolioSymbols, watchlistSymbols, trendingSymbols]);

  // ── Fetch from all 4 sources ──────────────────────────────────

  // Yahoo Finance news
  const { data: yahooNews, isLoading: isLoadingYahoo } = trpc.yahooFinance.newsFeed.useQuery(
    { symbols: activeSymbols, limit: 30 },
    { enabled: activeSymbols.length > 0 && activeTab !== "market", staleTime: 5 * 60 * 1000 }
  );

  // Polygon ticker news (for cross-source dedup)
  const { data: polygonTickerNews, isLoading: isLoadingPolygonTicker } = trpc.polygonNews.forTickers.useQuery(
    { tickers: activeSymbols, limit: 30 },
    { enabled: activeSymbols.length > 0 && activeTab !== "market", staleTime: 5 * 60 * 1000 }
  );

  // Newsdata.io finance news
  const { data: newsdataNews, isLoading: isLoadingNewsdata } = trpc.newsdata.finance.useQuery(
    { size: 25 },
    { enabled: activeTab === "trending" || activeTab === "market", staleTime: 5 * 60 * 1000 }
  );

  // APITUBE finance news
  const { data: apitubeNews, isLoading: isLoadingApitube } = trpc.apitube.finance.useQuery(
    { limit: 25 },
    { enabled: activeTab === "trending" || activeTab === "market", staleTime: 5 * 60 * 1000 }
  );

  // ── Merge and deduplicate from all sources ────────────────────
  const mergedNews = useMemo(() => {
    if (activeTab === "market") {
      // Market Wire: merge Polygon + Benzinga + Newsdata + APITUBE
      const benzingaAsPolygon = (benzingaNews || []).map((a: any) => ({
        id: a.benzinga_id || `bz-${(a.title || "").slice(0, 20)}`,
        title: a.title,
        author: a.author,
        publishedUtc: a.published,
        articleUrl: a.url,
        imageUrl: a.images?.[0]?.url || null,
        description: a.teaser || (a.body || "").slice(0, 200),
        keywords: a.tags || [],
        tickers: a.tickers || [],
        publisher: { name: "Benzinga", homepageUrl: "https://benzinga.com", logoUrl: "", faviconUrl: "" },
      }));
      const combinedPolygon = [...(polygonMarketNews || []), ...benzingaAsPolygon];
      return mergeAndDedup(
        undefined,
        combinedPolygon.length > 0 ? combinedPolygon : undefined,
        newsdataNews ?? undefined,
        apitubeNews ?? undefined,
        50
      );
    }
    if (activeTab === "trending") {
      // Trending: all 4 sources
      return mergeAndDedup(
        yahooNews ?? undefined,
        polygonTickerNews ?? undefined,
        newsdataNews ?? undefined,
        apitubeNews ?? undefined,
        50
      );
    }
    // Portfolio/Watchlist: Yahoo + Polygon for specific symbols
    return mergeAndDedup(
      yahooNews ?? undefined,
      polygonTickerNews ?? undefined,
      undefined,
      undefined,
      40
    );
  }, [activeTab, yahooNews, polygonTickerNews, polygonMarketNews, newsdataNews, apitubeNews]);

  // P206-PERF3: Progressive rendering — show first 15 items, load more on scroll
  useEffect(() => {
    const el = loadMoreRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisibleCount((prev) => Math.min(prev + 15, 100));
        }
      },
      { rootMargin: '200px' }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [mergedNews.length]);

  // Reset visible count when tab changes
  useEffect(() => { setVisibleCount(15); }, [activeTab]);

  // Progressive loading: only show spinner when NO data has arrived yet
  const hasAnyData = mergedNews.length > 0;
  const allSourcesLoading =
    isLoadingYahoo &&
    isLoadingPolygonTicker &&
    (activeTab === "trending" ? (isLoadingNewsdata && isLoadingApitube) : true) &&
    (activeTab === "market" ? isLoadingPolygon : true);
  const isLoading = !hasAnyData && allSourcesLoading;
  const isPartiallyLoading = hasAnyData && (isLoadingYahoo || isLoadingPolygonTicker || isLoadingNewsdata || isLoadingApitube || isLoadingPolygon);

  // Keyboard navigation
  const newsRef = useRef<HTMLDivElement>(null);
  const { focusedIndex, isFocused } = useKeyboardNav({
    itemCount: mergedNews.length,
    onSelect: (index) => {
      const item = mergedNews[index];
      if (item?.articleUrl) {
        window.open(item.articleUrl, "_blank");
      } else if (item?.symbol) {
        window.location.href = `/research/${item.symbol}`;
      }
    },
    containerRef: newsRef as any,
  });

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    if (diffDays === 1) return "Yesterday";
    if (diffDays < 7) return `${diffDays}d ago`;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  };

  // Count active sources
  const activeSources = useMemo(() => {
    const sources = new Set(mergedNews.map((n) => n.source));
    return sources.size;
  }, [mergedNews]);

  SEOHead(pageSEO.news);

  return (
    <PageTransition>
      <div className="min-h-screen bg-background text-foreground pb-20">
        {/* Header */}
        <header className="fixed top-0 left-0 right-0 z-50 glass-strong border-b border-border/30">
          <div className="flex items-center h-14 px-4">
            <Link href="/">
              <Button variant="ghost" size="icon" aria-label="Back" className="-ml-2">
                <ArrowLeft className="w-5 h-5" />
              </Button>
            </Link>
            <div className="flex-1 text-center">
              <ScrollReveal delay={0.0}>
                <h1 className="text-lg font-editorial font-semibold flex items-center justify-center gap-2">
                  <Newspaper className="w-5 h-5 text-muted-foreground" />
                  News Feed
                  {activeSources > 1 && (
                    <span className="text-[10px] font-mono text-primary bg-primary/10 px-1.5 py-0.5 rounded-full">
                      {activeSources} sources
                    </span>
                  )}
                </h1>
              </ScrollReveal>
            </div>
            <div className="w-10" />
          </div>
        </header>

        <main role="main" className="container pt-20 pb-8">
          <div className="mb-4">
            <Breadcrumb items={[{ label: "News" }]} />
          </div>

          <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as typeof activeTab)} className="space-y-6">
            <TabsList>
              <TabsTrigger value="trending" className="flex items-center gap-2">
                <TrendingUp className="w-4 h-4" />
                Trending
              </TabsTrigger>
              <TabsTrigger value="briefings" className="flex items-center gap-2">
                <BarChart3 className="w-4 h-4" />
                Macro Briefings
              </TabsTrigger>
              <TabsTrigger value="portfolio" className="flex items-center gap-2" disabled={!user}>
                <Briefcase className="w-4 h-4" />
                Portfolio {portfolioSymbols.length > 0 && `(${portfolioSymbols.length})`}
              </TabsTrigger>
              <TabsTrigger value="watchlist" className="flex items-center gap-2" disabled={!user}>
                <Star className="w-4 h-4" />
                Watchlist {watchlistSymbols.length > 0 && `(${watchlistSymbols.length})`}
              </TabsTrigger>
              <TabsTrigger value="market" className="flex items-center gap-2">
                <Globe className="w-4 h-4" />
                Market Wire
              </TabsTrigger>
            </TabsList>

            {/* Macro Briefings Tab Content */}
            <TabsContent value="briefings" className="space-y-4">
              {isLoadingBriefings ? (
                <div className="space-y-3">
                  {[...Array(3)].map((_, i) => (
                    <div key={i} className="p-5 rounded-xl bg-card/60 border border-border/30 animate-pulse">
                      <div className="h-5 w-64 bg-muted rounded mb-3" />
                      <div className="h-3 w-full bg-muted rounded mb-2" />
                      <div className="h-3 w-3/4 bg-muted rounded" />
                    </div>
                  ))}
                </div>
              ) : briefings && briefings.length > 0 ? (
                <div className="space-y-4">
                  <div className="p-3 rounded-lg bg-primary/5 border border-primary/20 flex items-center gap-2">
                    <Sparkles className="w-4 h-4 text-primary" />
                    <span className="text-xs text-primary font-medium">Weekly educational summaries of economic indicator movements</span>
                  </div>
                  {/* Cited Macro Briefing — on-demand Mycroft analysis */}
                  <CitedMacroBriefing />
                  {briefings.map((briefing) => (
                    <BriefingCard key={briefing.id} briefing={briefing} />
                  ))}
                </div>
              ) : (
                <ScrollReveal delay={0.05}>
                  <Card>
                    <CardContent className="p-12 text-center">
                      <BarChart3 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                      <h3 className="font-semibold mb-2">No Briefings Yet</h3>
                      <p className="text-muted-foreground">
                        Weekly macro briefings are generated every Sunday. Check back soon for an educational summary of the week's economic indicator movements.
                      </p>
                    </CardContent>
                  </Card>
                </ScrollReveal>
              )}
            </TabsContent>

            {/* Unified news content for all tabs */}
            <TabsContent value={activeTab} className="space-y-4">
              {isLoading ? (
                <div className="space-y-2">
                  <div className="flex flex-col items-center gap-2 py-3">
                    <p className="text-xs text-muted-foreground animate-pulse">
                      Loading sources: {[!isLoadingYahoo && 'Yahoo', !isLoadingPolygonTicker && 'Polygon', !isLoadingNewsdata && 'Newsdata', !isLoadingApitube && 'ApiTube'].filter(Boolean).length} / 4 resolved
                    </p>
                    <div className="w-48 h-1 bg-muted rounded-full overflow-hidden">
                      <div
                        className="h-full bg-primary/60 rounded-full transition-[width] duration-500 ease-out"
                        style={{ width: `${([!isLoadingYahoo, !isLoadingPolygonTicker, !isLoadingNewsdata, !isLoadingApitube].filter(Boolean).length / 4) * 100}%` }}
                      />
                    </div>
                  </div>
                  <NewsSkeletonGrid count={6} />
                </div>
              ) : mergedNews.length > 0 ? (
                <div className="space-y-4" ref={newsRef}>
                  {mergedNews.slice(0, visibleCount).map((item, index) => (
                    <NewsCard
                      key={item.id}
                      data-keyboard-nav-item
                      className={`hover:border-primary/30 transition-[colors,opacity,transform,shadow] duration-300 float-card hover-lift ${keyboardNavItemClass(isFocused(index))}`}
                    >
                      <div className="flex items-start gap-4">
                        {/* Article image */}
                        {item.imageUrl && (
                          <img
                            src={item.imageUrl}
                            alt=""
                            className="w-20 h-14 object-cover rounded-md flex-shrink-0 bg-muted hidden sm:block"
                            onError={(e) => {
                              (e.target as HTMLImageElement).style.display = "none";
                            }}
                          />
                        )}
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                            {/* Ticker badges */}
                            {item.tickers && item.tickers.length > 0
                              ? item.tickers.slice(0, 4).map((ticker) => (
                                  <Link key={ticker} href={`/research/${ticker}`}>
                                    <Badge
                                      variant="outline"
                                      className="font-mono text-xs hover:bg-primary/10 cursor-pointer"
                                    >
                                      {ticker}
                                    </Badge>
                                  </Link>
                                ))
                              : item.symbol ? (
                                  <Link href={`/research/${item.symbol}`}>
                                    <Badge
                                      variant="outline"
                                      className="font-mono text-xs hover:bg-primary/10 cursor-pointer"
                                    >
                                      {item.symbol}
                                    </Badge>
                                  </Link>
                                ) : null}
                            {item.tickers && item.tickers.length > 4 && (
                              <Badge variant="secondary" className="text-xs">
                                +{item.tickers.length - 4}
                              </Badge>
                            )}
                            {item.companyName && (
                              <span className="text-xs text-muted-foreground">{item.companyName}</span>
                            )}

                            {/* Source badge */}
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <span
                                  className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${getSourceColor(item.source)}`}
                                >
                                  {item.source === "merged" ? "✓ Verified" : getSourceLabel(item.source)}
                                </span>
                              </TooltipTrigger>
                              <TooltipContent>
                                {item.source === "merged"
                                  ? "Confirmed by multiple sources"
                                  : `Source: ${getSourceLabel(item.source)}`}
                              </TooltipContent>
                            </Tooltip>

                            {/* Sentiment badge */}
                            {item.sentiment && (
                              <SentimentBadge
                                sentiment={item.sentiment}
                                score={item.sentimentScore}
                              />
                            )}
                          </div>

                          {/* Headline */}
                          {item.articleUrl ? (
                            <a
                              href={item.articleUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="font-medium hover:text-primary transition-colors inline-flex items-center gap-1.5 group"
                            >
                              {item.headline}
                              <ExternalLink className="w-3.5 h-3.5 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
                            </a>
                          ) : (
                            <p className="font-medium">{item.headline}</p>
                          )}

                          {/* Description */}
                          {item.description && (
                            <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                              {item.description}
                            </p>
                          )}

                          {/* Listen button */}
                          <div className="mt-1">
                            <ElevenLabsListenButton
                              text={`${item.headline}. ${item.description || ""}`}
                              compact
                              tooltip="Listen to headline"
                              showPlayer={false}
                            />
                          </div>

                          {/* Metadata row */}
                          <div className="flex items-center gap-3 mt-1.5 text-xs text-muted-foreground">
                            {item.publisher?.name && (
                              <span className="flex items-center gap-1">
                                {item.publisher.faviconUrl && (
                                  <img
                                    src={item.publisher.faviconUrl}
                                    alt=""
                                    className="w-3 h-3 rounded-sm"
                                    onError={(e) => {
                                      (e.target as HTMLImageElement).style.display = "none";
                                    }}
                                  />
                                )}
                                {item.publisher.name}
                              </span>
                            )}
                            <span className="flex items-center gap-1">
                              <Calendar className="w-3 h-3" />
                              {formatDate(item.date)}
                            </span>
                            {item.author && item.author !== "Unknown" && (
                              <span>by {item.author}</span>
                            )}
                            {/* Category tags */}
                            {item.categories && item.categories.length > 0 && (
                              <span className="hidden md:inline text-[10px] text-muted-foreground/70">
                                {item.categories.slice(0, 2).join(" · ")}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </NewsCard>
                  ))}
                  {/* Progressive load sentinel */}
                  {visibleCount < mergedNews.length && (
                    <div ref={loadMoreRef} className="flex items-center justify-center py-4 text-xs text-muted-foreground">
                      Showing {visibleCount} of {mergedNews.length} articles — scroll for more
                    </div>
                  )}
                  {/* Partial loading indicator — more sources still resolving */}
                  {isPartiallyLoading && (
                    <div className="flex items-center justify-center py-3 text-xs text-muted-foreground gap-2">
                      <div className="skeleton-shimmer h-3 w-3 rounded-full" aria-hidden="true" />
                      Loading more sources...
                    </div>
                  )}
                </div>
              ) : activeSymbols.length === 0 && activeTab !== "market" ? (
                <ScrollReveal delay={0.05}>
                  <Card>
                    <CardContent className="p-12 text-center">
                      <Info className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                      <h3 className="font-semibold mb-2">No Stocks to Track</h3>
                      <p className="text-muted-foreground mb-4">
                        {activeTab === "portfolio"
                          ? "Add stocks to your portfolio to see relevant news."
                          : activeTab === "watchlist"
                          ? "Add stocks to your watchlist to see relevant news."
                          : "No trending stocks available."}
                      </p>
                      {activeTab === "portfolio" && (
                        <Link href="/portfolio">
                          <Button>Go to Portfolio</Button>
                        </Link>
                      )}
                      {activeTab === "watchlist" && (
                        <Link href="/watchlist">
                          <Button>Go to Watchlist</Button>
                        </Link>
                      )}
                    </CardContent>
                  </Card>
                </ScrollReveal>
              ) : (
                <ScrollReveal delay={0.1}>
                  <Card>
                    <CardContent className="p-16 text-center">
                      <div className="relative w-20 h-20 mx-auto mb-6">
                        <div className="absolute inset-0 rounded-full bg-primary/5 animate-pulse" />
                        <Newspaper className="w-12 h-12 text-muted-foreground absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2" />
                      </div>
                      <h3 className="font-display text-lg font-semibold mb-2">No Recent News</h3>
                      <p className="text-muted-foreground max-w-sm mx-auto mb-6">
                        No significant developments found for your current selection. News sources are checked every few minutes.
                      </p>
                      <div className="flex items-center justify-center gap-3 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />Polygon</span>
                        <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-sky-400" />Yahoo</span>
                        <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-violet-400" />Newsdata</span>
                        <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-amber-400" />APITUBE</span>
                      </div>
                    </CardContent>
                  </Card>
                </ScrollReveal>
              )}
            </TabsContent>
          </Tabs>

          {/* Educational Note */}
          {activeTab !== "briefings" && (
          <ScrollReveal delay={0.2}>
            <Card className="mt-8 bg-card/60 backdrop-blur-md">
              <CardContent className="p-6">
                <h3 className="font-display font-semibold mb-3 flex items-center gap-2">
                  <Info className="w-5 h-5 text-muted-foreground" />
                  About Market News
                </h3>
                <div className="content-stagger grid md:grid-cols-2 gap-6 text-sm text-muted-foreground">
                  <div>
                    <h4 className="font-medium text-foreground mb-2">Multi-Source Aggregation</h4>
                    <p>
                      This feed aggregates news from Yahoo Finance, Polygon.io, Newsdata.io, and APITUBE.
                      Articles confirmed by multiple sources are marked with a{" "}
                      <span className="text-emerald-400 font-medium">✓ Verified</span> badge.
                      Sentiment analysis (bullish/bearish/neutral) is provided where available.
                    </p>
                  </div>
                  <div>
                    <h4 className="font-medium text-foreground mb-2">Using News in Your Research</h4>
                    <ul className="space-y-1">
                      <li>
                        <strong>Context matters:</strong> Consider news alongside financial metrics and
                        technical analysis.
                      </li>
                      <li>
                        <strong>Timing:</strong> Markets often react before news is public — be cautious of
                        "buying the news."
                      </li>
                      <li>
                        <strong>Sentiment:</strong> AI-powered sentiment badges indicate market tone but
                        should not be used as sole trading signals.
                      </li>
                    </ul>
                  </div>
                </div>
              </CardContent>
            </Card>
          </ScrollReveal>
          )}
        </main>
      </div>
    </PageTransition>
  );
}

// ─── Briefing Card Component ─────────────────────────────────────────────────

function BriefingCard({ briefing }: { briefing: any }) {
  const [expanded, setExpanded] = useState(false);

  const formatBriefingDate = (date: Date | string | null) => {
    if (!date) return "";
    return new Date(date).toLocaleDateString("en-US", {
      weekday: "long",
      month: "long",
      day: "numeric",
      year: "numeric",
    });
  };

  const indicators = briefing.indicators as Array<{
    name: string;
    previousValue: number;
    currentValue: number;
    change: number;
    changePercent: number;
    significance: string;
  }> | null;

  return (
    <div
      className={`p-5 rounded-xl bg-card/60 border border-border/30 transition-all cursor-pointer hover:border-primary/30 ${
        expanded ? "ring-1 ring-primary/20" : ""
      }`}
      onClick={() => setExpanded(!expanded)}
    >
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <span className="text-[10px] font-mono uppercase tracking-wider text-primary">
              Weekly Briefing
            </span>
            <span className="text-[10px] text-muted-foreground">
              {formatBriefingDate(briefing.publishedAt)}
            </span>
          </div>
          <h3 className="font-editorial text-lg font-semibold mb-1">{briefing.title}</h3>
          <p className="text-sm text-muted-foreground line-clamp-2">{briefing.summary}</p>
        </div>
        <ChevronRight
          className={`w-5 h-5 text-muted-foreground transition-transform flex-shrink-0 ${
            expanded ? "rotate-90" : ""
          }`}
        />
      </div>

      {/* Expanded Content */}
      {expanded && (
        <div className="mt-4 pt-4 border-t border-border/30 space-y-4">
          {/* Indicator Changes */}
          {indicators && indicators.length > 0 && (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
              {indicators.map((ind) => (
                <div key={ind.name} className="p-3 rounded-lg bg-secondary/30 border border-border/20">
                  <span className="text-[10px] font-mono uppercase tracking-wider text-muted-foreground block mb-1">
                    {ind.name}
                  </span>
                  <div className="flex items-center gap-2">
                    <span className="font-mono font-medium text-sm">{ind.currentValue.toFixed(1)}</span>
                    <span
                      className={`text-xs font-mono ${
                        ind.change > 0
                          ? "text-[oklch(0.72_0.19_142)]"
                          : ind.change < 0
                          ? "text-[oklch(0.65_0.2_30)]"
                          : "text-muted-foreground"
                      }`}
                    >
                      {ind.change > 0 ? "+" : ""}{ind.changePercent.toFixed(1)}%
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Full Content */}
          <div className="prose prose-sm prose-invert max-w-none">
            <Streamdown>{briefing.content}</Streamdown>
          </div>
        </div>
      )}
    </div>
  );
}
