const { useState, useEffect, useMemo, useCallback } = React;
const {
  TrendingUp,
  TrendingDown,
  Search,
  ExternalLink,
  Newspaper,
  Layers,
  RefreshCw,
  Sparkles,
  X,
  BarChart2,
  PieChart,
  Moon,
  Sun,
  Flame,
  Globe,
  Radio,
  Clock,
  CheckCircle,
  AlertTriangle,
} = (function createMarketsIcons() {
  function svg(children) {
    return function Icon({ className, style }) {
      return (
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          className={className}
          style={style}
        >
          {children}
        </svg>
      );
    };
  }
  return {
    TrendingUp: svg(<><polyline points="22 7 13.5 15.5 8.5 10.5 2 17" /><polyline points="16 7 22 7 22 13" /></>),
    TrendingDown: svg(<><polyline points="22 17 13.5 8.5 8.5 13.5 2 7" /><polyline points="16 17 22 17 22 11" /></>),
    Search: svg(<><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></>),
    ExternalLink: svg(<><path d="M15 3h6v6" /><path d="M10 14 21 3" /><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" /></>),
    Newspaper: svg(<><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" /><path d="M18 14h-8" /><path d="M15 18h-5" /><path d="M10 6h8v4h-8V6Z" /></>),
    Layers: svg(<><path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z" /><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65" /><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65" /></>),
    RefreshCw: svg(<><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" /><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" /><path d="M8 16H3v5" /></>),
    Sparkles: svg(<><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z" /><path d="M5 3v4" /><path d="M19 17v4" /><path d="M3 5h4" /><path d="M17 19h4" /></>),
    X: svg(<><path d="M18 6 6 18" /><path d="m6 6 12 12" /></>),
    BarChart2: svg(<><line x1="18" x2="18" y1="20" y2="10" /><line x1="12" x2="12" y1="20" y2="4" /><line x1="6" x2="6" y1="20" y2="14" /></>),
    PieChart: svg(<><path d="M21.21 15.89A10 10 0 1 1 8 2.83" /><path d="M22 12A10 10 0 0 0 12 2v10z" /></>),
    Moon: svg(<><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" /></>),
    Sun: svg(<><circle cx="12" cy="12" r="4" /><path d="M12 2v2" /><path d="M12 20v2" /><path d="m4.93 4.93 1.41 1.41" /><path d="m17.66 17.66 1.41 1.41" /><path d="M2 12h2" /><path d="M20 12h2" /><path d="m6.34 17.66-1.41 1.41" /><path d="m19.07 4.93-1.41 1.41" /></>),
    Flame: svg(<><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z" /></>),
    Globe: svg(<><circle cx="12" cy="12" r="10" /><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" /><path d="M2 12h20" /></>),
    Radio: svg(<><path d="M4.9 19.1C1 15.2 1 8.8 4.9 4.9" /><path d="M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5" /><circle cx="12" cy="12" r="2" /><path d="M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5" /><path d="M19.1 4.9C23 8.8 23 15.1 19.1 19" /></>),
    Clock: svg(<><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></>),
    CheckCircle: svg(<><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" /><path d="m9 11 3 3L22 4" /></>),
    AlertTriangle: svg(<><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><path d="M12 9v4" /><path d="M12 17h.01" /></>),
  };
})();

// Environment placeholder — preview environments populate this key at runtime
const apiKey = '';

const GEMINI_MODEL = 'gemini-2.5-flash-preview-09-2025';

async function callGeminiStructured(query, systemPrompt, responseSchema) {
  const payload = {
    contents: [{ parts: [{ text: query }] }],
    systemInstruction: { parts: [{ text: systemPrompt }] },
    tools: [{ google_search: {} }],
    generationConfig: {
      responseMimeType: 'application/json',
      responseSchema,
    },
  };

  const response = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${apiKey}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }
  );

  if (!response.ok) {
    throw new Error(`HTTP Error Status: ${response.status}`);
  }

  const result = await response.json();
  const jsonText = result.candidates?.[0]?.content?.parts?.[0]?.text;
  if (!jsonText) {
    throw new Error('Empty response from Gemini.');
  }
  return JSON.parse(jsonText);
}

const INITIAL_STOCKS = [
  { rank: 1, symbol: 'NVDA', name: 'NVIDIA Corporation', price: 224.33, change: 4.2, marketCap: 5.11, volume: 42.1, sector: 'Information Technology', logoColor: 'bg-emerald-500', sparkline: [210, 212, 218, 215, 220, 222, 224.33] },
  { rank: 2, symbol: 'GOOGL', name: 'Alphabet Inc.', price: 376.37, change: -1.7, marketCap: 4.61, volume: 24.5, sector: 'Communication Services', logoColor: 'bg-blue-600', sparkline: [385, 382, 380, 378, 379, 377, 376.37] },
  { rank: 3, symbol: 'AAPL', name: 'Apple Inc.', price: 306.32, change: -0.8, marketCap: 4.58, volume: 28.3, sector: 'Consumer Electronics', logoColor: 'bg-slate-400', sparkline: [312, 310, 308, 311, 309, 307, 306.32] },
  { rank: 4, symbol: 'MSFT', name: 'Microsoft Corporation', price: 441.49, change: 1.15, marketCap: 3.15, volume: 22.8, sector: 'Software & Cloud', logoColor: 'bg-teal-500', sparkline: [435, 437, 436, 439, 440, 438, 441.49] },
  { rank: 5, symbol: 'AMZN', name: 'Amazon.com Inc.', price: 256.47, change: -1.9, marketCap: 2.83, volume: 19.4, sector: 'E-Commerce & Cloud', logoColor: 'bg-amber-500', sparkline: [264, 262, 260, 258, 257, 259, 256.47] },
  { rank: 6, symbol: 'TSM', name: 'Taiwan Semiconductor Manufacturing', price: 435.63, change: 7.7, marketCap: 2.17, volume: 12.6, sector: 'Semiconductors', logoColor: 'bg-orange-500', sparkline: [400, 410, 415, 422, 428, 432, 435.63] },
  { rank: 7, symbol: 'AVGO', name: 'Broadcom Inc.', price: 459.97, change: 11.1, marketCap: 2.12, volume: 10.9, sector: 'Semiconductors', logoColor: 'bg-red-500', sparkline: [410, 420, 430, 435, 442, 448, 459.97] },
  { rank: 8, symbol: 'TSLA', name: 'Tesla Inc.', price: 415.88, change: -2.4, marketCap: 1.64, volume: 31.2, sector: 'Automotive & Clean Energy', logoColor: 'bg-red-600', sparkline: [430, 425, 422, 418, 421, 417, 415.88] },
  { rank: 9, symbol: 'META', name: 'Meta Platforms Inc.', price: 600.47, change: -1.6, marketCap: 1.61, volume: 18.2, sector: 'Communication Services', logoColor: 'bg-indigo-600', sparkline: [612, 608, 605, 602, 606, 602, 600.47] },
  { rank: 10, symbol: 'BRK.B', name: 'Berkshire Hathaway Inc.', price: 469.93, change: 0.05, marketCap: 1.02, volume: 4.1, sector: 'Financial Services', logoColor: 'bg-purple-900', sparkline: [468, 469, 468.5, 469.2, 468.9, 469.5, 469.93] },
];

const INITIAL_TICKER_FEED = [
  { title: 'S&P 500 maintains robust momentum amid tech earnings reports', sentiment: 'Bullish', source: 'Wall Street Journal' },
  { title: 'Federal Reserve signals steady rate thresholds heading into Q3', sentiment: 'Neutral', source: 'Bloomberg' },
  { title: 'Global semiconductor logistics chains report improved yields', sentiment: 'Bullish', source: 'Reuters' },
];

const PRICE_SCHEMA = {
  type: 'ARRAY',
  items: {
    type: 'OBJECT',
    properties: {
      symbol: { type: 'STRING', description: 'Stock ticker symbol' },
      price: { type: 'NUMBER', description: 'Current stock price in USD' },
      change: { type: 'NUMBER', description: 'Daily percentage change' },
    },
    required: ['symbol', 'price', 'change'],
  },
};

const TICKER_NEWS_SCHEMA = {
  type: 'ARRAY',
  items: {
    type: 'OBJECT',
    properties: {
      title: { type: 'STRING' },
      sentiment: { type: 'STRING', description: 'Bullish, Bearish, or Neutral' },
      source: { type: 'STRING' },
    },
    required: ['title', 'sentiment', 'source'],
  },
};

const STOCK_NEWS_SCHEMA = {
  type: 'ARRAY',
  items: {
    type: 'OBJECT',
    properties: {
      title: { type: 'STRING' },
      summary: { type: 'STRING' },
      sentiment: { type: 'STRING' },
      source: { type: 'STRING' },
      url: { type: 'STRING' },
    },
    required: ['title', 'summary', 'sentiment', 'source', 'url'],
  },
};

function MarketsApp() {
  const [stocks, setStocks] = useState(INITIAL_STOCKS);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStock, setSelectedStock] = useState(null);
  const [theme, setTheme] = useState('dark');
  const [lastUpdated, setLastUpdated] = useState(null);
  const [isLoadingPrices, setIsLoadingPrices] = useState(false);
  const [priceError, setPriceError] = useState(null);
  const [liveTickerFeed, setLiveTickerFeed] = useState(INITIAL_TICKER_FEED);
  const [realNewsList, setRealNewsList] = useState([]);
  const [isLoadingNews, setIsLoadingNews] = useState(false);
  const [newsError, setNewsError] = useState(null);

  const fetchRealStockPrices = useCallback(async () => {
    setIsLoadingPrices(true);
    setPriceError(null);

    const maxRetries = 5;
    let delay = 1000;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        const parsedPrices = await callGeminiStructured(
          'Search the web for the absolute latest, current stock prices and daily percentage changes for: NVDA, GOOGL, AAPL, MSFT, AMZN, TSM, AVGO, TSLA, META, BRK.B. Provide authentic up-to-date numbers.',
          'You are a financial data processor. Search the live web to fetch current real-world stock prices and daily percentage changes. Return them as a precise, structured JSON array.',
          PRICE_SCHEMA
        );

        if (!Array.isArray(parsedPrices)) {
          throw new Error('Unable to contact live data pipeline.');
        }

        setStocks((prevStocks) =>
          prevStocks.map((stock) => {
            const match = parsedPrices.find((p) => p.symbol?.toUpperCase() === stock.symbol.toUpperCase());
            if (match) {
              return {
                ...stock,
                price: match.price,
                change: match.change,
                sparkline: [...stock.sparkline.slice(1), match.price],
              };
            }
            return stock;
          })
        );
        setLastUpdated(new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }));
        setIsLoadingPrices(false);
        return;
      } catch (err) {
        if (attempt === maxRetries) {
          console.error(err);
          setPriceError('Unable to load latest market quotes. Displaying last cached close.');
          setIsLoadingPrices(false);
        } else {
          await new Promise((resolve) => setTimeout(resolve, delay));
          delay *= 2;
        }
      }
    }
  }, []);

  const fetchGlobalTickerNews = useCallback(async () => {
    try {
      const parsedArray = await callGeminiStructured(
        'Find the 5 most important breaking global stock market news stories from today. Return only real current headlines.',
        'You are a news curator. Return a JSON array of the top 5 global stock market developments.',
        TICKER_NEWS_SCHEMA
      );
      if (Array.isArray(parsedArray) && parsedArray.length > 0) {
        setLiveTickerFeed(parsedArray);
      }
    } catch (err) {
      console.warn('Unable to fetch global news ticker.', err);
    }
  }, []);

  useEffect(() => {
    fetchRealStockPrices();
    fetchGlobalTickerNews();
  }, [fetchRealStockPrices, fetchGlobalTickerNews]);

  const filteredStocks = useMemo(() => {
    const q = searchQuery.toLowerCase();
    return stocks.filter(
      (stock) =>
        stock.name.toLowerCase().includes(q) ||
        stock.symbol.toLowerCase().includes(q) ||
        stock.sector.toLowerCase().includes(q)
    );
  }, [stocks, searchQuery]);

  const stats = useMemo(() => {
    const totalCap = stocks.reduce((acc, curr) => acc + curr.marketCap, 0);
    const averageChange = stocks.reduce((acc, curr) => acc + curr.change, 0) / stocks.length;
    return {
      totalCap: totalCap.toFixed(2),
      avgChange: averageChange.toFixed(2),
    };
  }, [stocks]);

  const tickerItems = useMemo(() => {
    const slice = liveTickerFeed.slice(0, 8);
    return [...slice, ...slice];
  }, [liveTickerFeed]);

  const fetchRealStockNews = async (stock) => {
    setSelectedStock(stock);
    setIsLoadingNews(true);
    setNewsError(null);
    setRealNewsList([]);

    const maxRetries = 5;
    let delay = 1000;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        const parsedNews = await callGeminiStructured(
          `Find the 3 most recent authentic news articles or market-moving developments for ${stock.name} (${stock.symbol}) in 2026. Do not generate fake stories. Return actual titles, concise summary paragraphs, publisher names, sentiment, and webpage URLs.`,
          'You are a professional financial news reporter. Search the live web to find genuine, current articles. Populate the fields with authentic URL addresses and titles matching real reports from actual news outlets.',
          STOCK_NEWS_SCHEMA
        );
        setRealNewsList(parsedNews);
        setIsLoadingNews(false);
        return;
      } catch (error) {
        if (attempt === maxRetries) {
          setNewsError(
            'Live news aggregation is momentarily cooling down. You can check 100% live updates instantly by clicking Google News or Finance Hub below.'
          );
          setIsLoadingNews(false);
        } else {
          await new Promise((resolve) => setTimeout(resolve, delay));
          delay *= 2;
        }
      }
    }
  };

  const formatMarketCap = (cap) => (cap >= 1 ? `$${cap.toFixed(2)}T` : `$${(cap * 1000).toFixed(0)}B`);
  const getGoogleNewsUrl = (symbol) =>
    `https://www.google.com/search?q=${encodeURIComponent(symbol)}+stock+latest+news&tbm=nws`;
  const getGoogleFinanceUrl = (symbol) =>
    `https://www.google.com/finance/quote/${encodeURIComponent(symbol)}:NASDAQ`;

  const isDark = theme === 'dark';
  const divideClass = isDark ? 'divide-gray-800/40' : 'divide-gray-200';

  return (
    <div className={`min-h-screen pb-12 transition-colors duration-300 ${isDark ? 'bg-[#0b0f19] text-gray-100' : 'bg-gray-50 text-gray-800'}`}>
      <div
        className={`w-full py-2.5 overflow-hidden border-b select-none text-xs ${isDark ? 'bg-gray-950 border-gray-800 text-gray-400' : 'bg-slate-100 border-gray-200 text-slate-600'}`}
      >
        <div className="flex items-center space-x-4 animate-marquee whitespace-nowrap">
          <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-indigo-600 text-white shrink-0">
            <Radio className="w-3 h-3 mr-1 animate-pulse" /> LIVE HEADLINES
          </span>
          {tickerItems.map((news, idx) => (
            <span key={`ticker-${idx}`} className="inline-flex items-center space-x-2 shrink-0">
              <span
                className={`w-1.5 h-1.5 rounded-full ${news.sentiment === 'Bullish' ? 'bg-emerald-500' : news.sentiment === 'Bearish' ? 'bg-rose-500' : 'bg-blue-500'}`}
              />
              <span className={`font-semibold ${isDark ? 'text-gray-300' : 'text-slate-700'}`}>{news.title}</span>
              <span className="text-[10px] opacity-65 font-bold text-indigo-400">({news.source})</span>
              <span className="px-3 opacity-30">|</span>
            </span>
          ))}
        </div>
      </div>

      <header
        className={`border-b ${isDark ? 'border-gray-800 bg-[#0e1424]' : 'border-gray-200 bg-white'} sticky top-0 z-30 shadow-sm backdrop-blur-md bg-opacity-95`}
      >
        <div className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between gap-3">
          <div className="flex items-center space-x-3 min-w-0">
            <div className="p-2 bg-gradient-to-tr from-indigo-600 to-blue-500 rounded-lg text-white shadow-md shrink-0">
              <Layers className="w-6 h-6" />
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-1.5 flex-wrap">
                <h1 className="text-xl font-bold tracking-tight bg-gradient-to-r from-blue-500 to-indigo-400 bg-clip-text text-transparent">
                  Market Watch AI
                </h1>
                <span className="text-[10px] px-1.5 py-0.5 font-bold rounded bg-blue-500/10 text-blue-400 border border-blue-500/20">
                  REAL-TIME
                </span>
              </div>
              <p className="text-xs text-gray-400 font-medium hidden sm:block truncate">
                Genuine Search-Grounded Client Terminal Dashboard
              </p>
            </div>
          </div>

          <div className="hidden lg:flex items-center space-x-6 text-xs">
            <div className="flex flex-col">
              <span className="text-gray-400 font-semibold uppercase tracking-wider">Top 10 Index Cap</span>
              <span className="text-sm font-bold">${stats.totalCap}T</span>
            </div>
            <div className={`h-6 w-px ${isDark ? 'bg-gray-800' : 'bg-gray-300'}`} />
            <div className="flex flex-col">
              <span className="text-gray-400 font-semibold uppercase tracking-wider">Average Daily Delta</span>
              <span
                className={`text-sm font-bold flex items-center ${Number(stats.avgChange) >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}
              >
                {Number(stats.avgChange) >= 0 ? '+' : ''}
                {stats.avgChange}%
                {Number(stats.avgChange) >= 0 ? <TrendingUp className="w-3.5 h-3.5 ml-1" /> : <TrendingDown className="w-3.5 h-3.5 ml-1" />}
              </span>
            </div>
            <div className={`h-6 w-px ${isDark ? 'bg-gray-800' : 'bg-gray-300'}`} />
            <div className="flex flex-col">
              <span className="text-gray-400 font-semibold uppercase tracking-wider">Grounded Pipeline</span>
              <span className="text-sm font-bold flex items-center gap-1.5 text-indigo-400">
                <Globe className="w-4 h-4" />
                Live Web Verified
              </span>
            </div>
          </div>

          <div className="flex items-center space-x-2 sm:space-x-3 shrink-0">
            {lastUpdated && (
              <span className="text-[11px] text-gray-400 hidden md:inline-block font-medium">
                Last Sync: <strong className="font-mono text-indigo-400">{lastUpdated}</strong>
              </span>
            )}
            <button
              type="button"
              onClick={fetchRealStockPrices}
              disabled={isLoadingPrices}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
                isLoadingPrices
                  ? 'bg-indigo-600/20 text-indigo-400 border border-indigo-500/20 cursor-wait'
                  : 'bg-indigo-600 hover:bg-indigo-500 text-white shadow-md'
              }`}
              title="Pull current real-world pricing via Google Search Grounding"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${isLoadingPrices ? 'animate-spin' : ''}`} />
              <span className="hidden sm:inline">{isLoadingPrices ? 'Syncing...' : 'Sync Real Prices'}</span>
            </button>
            <button
              type="button"
              onClick={() => setTheme(isDark ? 'light' : 'dark')}
              className={`p-2 rounded-full border transition-all ${
                isDark ? 'bg-gray-800 text-amber-400 border-gray-700' : 'bg-gray-100 text-indigo-900 border-gray-300'
              }`}
            >
              {isDark ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
            </button>
          </div>
        </div>
      </header>

      <main className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="mb-6 p-4 rounded-xl border border-emerald-500/20 bg-emerald-500/5 flex items-start gap-3">
          <CheckCircle className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />
          <div className="text-xs text-gray-400 leading-normal">
            <strong className="text-emerald-400">100% Verified Terminal:</strong> Both market prices and news feeds are
            completely grounded in reality. Price quotes, index shifts, and business news summaries are pulled live from
            active web indices on demand.
          </div>
        </div>

        {priceError && (
          <div className="mb-6 p-4 rounded-xl border border-amber-500/30 bg-amber-500/10 flex items-start gap-3">
            <AlertTriangle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
            <p className="text-xs text-amber-200/90 leading-normal m-0">{priceError}</p>
          </div>
        )}

        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 items-start">
          <div className="xl:col-span-2 space-y-6">
            <div
              className={`p-4 rounded-xl border flex flex-col md:flex-row items-center justify-between gap-4 ${
                isDark ? 'bg-[#0f1424] border-gray-800' : 'bg-white border-gray-200'
              }`}
            >
              <div className="relative w-full md:w-80">
                <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Search symbol, company or sector..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className={`w-full py-2 pl-9 pr-4 rounded-lg text-sm border focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all ${
                    isDark
                      ? 'bg-gray-950 border-gray-800 text-gray-100 placeholder-gray-500 focus:border-indigo-500'
                      : 'bg-gray-50 border-gray-300 text-gray-800 placeholder-gray-400 focus:border-indigo-400'
                  }`}
                />
              </div>
              <div className="flex items-center space-x-4 w-full md:w-auto justify-between md:justify-end text-xs">
                <span className="text-gray-400">
                  Total Index Cap: <strong className={isDark ? 'text-gray-200' : 'text-gray-800'}>${stats.totalCap}T</strong>
                </span>
                <span className={`h-4 w-px ${isDark ? 'bg-gray-800' : 'bg-gray-300'}`} />
                <span className="text-gray-400">
                  Avg Daily Delta:{' '}
                  <strong className={Number(stats.avgChange) >= 0 ? 'text-emerald-500' : 'text-rose-500'}>{stats.avgChange}%</strong>
                </span>
              </div>
            </div>

            <div
              className={`border rounded-2xl overflow-hidden shadow-lg transition-colors ${
                isDark ? 'bg-[#0f1424]/90 border-gray-800' : 'bg-white border-gray-200'
              }`}
            >
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse min-w-[700px]">
                  <thead>
                    <tr
                      className={`border-b text-xs font-bold uppercase tracking-wider ${
                        isDark ? 'bg-gray-950/80 border-gray-800 text-gray-400' : 'bg-gray-50 border-gray-200 text-gray-500'
                      }`}
                    >
                      <th className="py-4 px-3 w-16 text-center">Rank</th>
                      <th className="py-4 px-3">Asset</th>
                      <th className="py-4 px-3 text-right">Price</th>
                      <th className="py-4 px-3 text-right">24h Change</th>
                      <th className="py-4 px-3 text-right">Market Cap</th>
                      <th className="py-4 px-3 text-center">Trend (7d)</th>
                      <th className="py-4 px-3 text-center">Intelligence Actions</th>
                    </tr>
                  </thead>
                  <tbody className={divideClass}>
                    {filteredStocks.length > 0 ? (
                      filteredStocks.map((stock) => {
                        const isPositive = stock.change >= 0;
                        const minVal = Math.min(...stock.sparkline);
                        const maxVal = Math.max(...stock.sparkline);
                        const range = maxVal - minVal || 1;
                        const selected = selectedStock?.symbol === stock.symbol;

                        return (
                          <tr
                            key={stock.symbol}
                            className={`transition-colors duration-150 cursor-pointer ${
                              selected
                                ? isDark
                                  ? 'bg-indigo-950/30'
                                  : 'bg-indigo-50/70'
                                : isDark
                                  ? 'hover:bg-gray-800/20'
                                  : 'hover:bg-gray-100/40'
                            }`}
                            onClick={() => fetchRealStockNews(stock)}
                          >
                            <td className="py-4 px-3 text-center font-bold text-gray-500">#{stock.rank}</td>
                            <td className="py-4 px-3">
                              <div className="flex items-center space-x-3">
                                <div
                                  className={`w-9 h-9 rounded-lg ${stock.logoColor} flex items-center justify-center text-white font-extrabold text-xs shadow-sm`}
                                >
                                  {stock.symbol.slice(0, 3)}
                                </div>
                                <div className="flex flex-col">
                                  <div className="flex items-center gap-1.5">
                                    <span className={`font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>{stock.symbol}</span>
                                    <span
                                      className={`text-[10px] px-1.5 py-0.5 rounded ${isDark ? 'bg-gray-800 text-gray-400' : 'bg-gray-100 text-gray-500'}`}
                                    >
                                      NASDAQ
                                    </span>
                                  </div>
                                  <span className="text-xs text-gray-400 max-w-[160px] truncate">{stock.name}</span>
                                </div>
                              </div>
                            </td>
                            <td className="py-4 px-3 text-right font-mono font-bold tracking-tight">
                              ${stock.price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                            </td>
                            <td className="py-4 px-3 text-right">
                              <div
                                className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold font-mono ${
                                  isPositive ? 'bg-emerald-500/10 text-emerald-400' : 'bg-rose-500/10 text-rose-400'
                                }`}
                              >
                                {isPositive ? '+' : ''}
                                {stock.change.toFixed(2)}%
                                {isPositive ? <TrendingUp className="w-3.5 h-3.5" /> : <TrendingDown className="w-3.5 h-3.5" />}
                              </div>
                            </td>
                            <td className="py-4 px-3 text-right font-semibold">
                              {formatMarketCap(stock.marketCap)}
                              <div className="text-[10px] text-gray-500 font-normal">Vol: {stock.volume}B</div>
                            </td>
                            <td className="py-4 px-3">
                              <div className="flex justify-center items-center">
                                <svg className="w-24 h-8 overflow-visible" strokeWidth="1.5">
                                  <path
                                    d={stock.sparkline
                                      .map((val, idx) => {
                                        const x = (idx / (stock.sparkline.length - 1)) * 96;
                                        const y = 30 - ((val - minVal) / range) * 26;
                                        return `${idx === 0 ? 'M' : 'L'} ${x} ${y}`;
                                      })
                                      .join(' ')}
                                    fill="none"
                                    stroke={isPositive ? '#10b981' : '#f43f5e'}
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                  />
                                </svg>
                              </div>
                            </td>
                            <td className="py-4 px-3 text-center" onClick={(e) => e.stopPropagation()}>
                              <button
                                type="button"
                                onClick={() => fetchRealStockNews(stock)}
                                className={`flex items-center gap-1.5 text-xs font-semibold px-3.5 py-1.5 rounded-lg border transition-all mx-auto ${
                                  selected
                                    ? 'bg-indigo-600 border-indigo-500 text-white shadow-md'
                                    : isDark
                                      ? 'bg-gray-800/80 border-gray-700 text-gray-200 hover:bg-gray-700 hover:border-gray-600'
                                      : 'bg-white border-gray-300 text-slate-700 hover:bg-gray-100'
                                }`}
                              >
                                <Newspaper className="w-3.5 h-3.5" />
                                <span>View Actual News</span>
                              </button>
                            </td>
                          </tr>
                        );
                      })
                    ) : (
                      <tr>
                        <td colSpan="7" className="py-12 text-center text-gray-500">
                          <Search className="w-8 h-8 mx-auto mb-3 opacity-25" />
                          <p className="text-sm font-semibold">No stock results match your filter</p>
                          <button
                            type="button"
                            onClick={() => setSearchQuery('')}
                            className="text-indigo-400 hover:text-indigo-300 text-xs mt-2 underline"
                          >
                            Clear search filters
                          </button>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {[
                {
                  icon: Flame,
                  iconClass: 'text-amber-400',
                  title: 'Market Cycle',
                  text: 'Semiconductors & AI hardware indices lead trading liquidity currently. General energy, logistics, and traditional finance maintain structural backing support.',
                },
                {
                  icon: BarChart2,
                  iconClass: 'text-emerald-400',
                  title: 'Data Frequency',
                  text: 'Asset metrics are updated on-demand through our Google Grounding sync action. Full market values represent real-time actual values.',
                },
                {
                  icon: PieChart,
                  iconClass: 'text-blue-400',
                  title: 'Global Exposure',
                  text: 'Our index covers over 80% of global mega-cap technology exposure, encompassing US, Taiwan, and East Asian integrated manufacturing hubs.',
                },
              ].map(({ icon: CardIcon, iconClass, title, text }) => (
                <div key={title} className={`p-4 rounded-xl border ${isDark ? 'bg-[#0f1424] border-gray-800' : 'bg-white border-gray-200'}`}>
                  <div className="flex items-center gap-2 mb-2">
                    <CardIcon className={`w-4 h-4 ${iconClass}`} />
                    <span className={`text-xs font-bold uppercase tracking-wider ${isDark ? 'text-gray-400' : 'text-slate-600'}`}>
                      {title}
                    </span>
                  </div>
                  <p className="text-xs text-gray-400 leading-relaxed">{text}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="space-y-6">
            <div
              className={`border rounded-2xl overflow-hidden shadow-xl transition-all ${
                isDark ? 'bg-[#0f1424] border-gray-800' : 'bg-white border-gray-200'
              }`}
            >
              <div
                className={`p-4 border-b flex items-center justify-between ${
                  isDark ? 'bg-gray-950/50 border-gray-800' : 'bg-gray-50 border-gray-200'
                }`}
              >
                <div className="flex items-center space-x-2">
                  <Globe className="w-5 h-5 text-indigo-400 animate-pulse" />
                  <div>
                    <h3 className={`font-bold text-sm ${isDark ? 'text-white' : 'text-slate-900'}`}>Live Financial Grounding</h3>
                    <p className="text-[10px] text-gray-400">Authentic News Aggregator</p>
                  </div>
                </div>
                {selectedStock && (
                  <button type="button" onClick={() => setSelectedStock(null)} className="p-1 rounded hover:bg-gray-800 transition">
                    <X className="w-4 h-4 text-gray-400" />
                  </button>
                )}
              </div>

              {selectedStock ? (
                <div className="p-5 space-y-5">
                  <div
                    className={`p-3.5 rounded-xl border flex items-center justify-between ${
                      isDark ? 'bg-gray-950/60 border-gray-800' : 'bg-gray-50 border-gray-200'
                    }`}
                  >
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-extrabold text-base tracking-tight">{selectedStock.symbol}</span>
                        <span className="text-xs text-gray-400 font-medium truncate max-w-[130px]">{selectedStock.name}</span>
                      </div>
                      <span className="text-[10px] text-gray-500 font-mono">
                        Current: ${selectedStock.price.toFixed(2)} ({selectedStock.change >= 0 ? '+' : ''}
                        {selectedStock.change.toFixed(2)}%)
                      </span>
                    </div>
                    <div className="flex flex-col items-end">
                      <span className="text-xs font-bold text-indigo-400">Rank #{selectedStock.rank}</span>
                      <span className="text-[10px] text-gray-500">Cap: {formatMarketCap(selectedStock.marketCap)}</span>
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <span className="text-[10px] font-bold uppercase tracking-wider text-indigo-400 flex items-center gap-1">
                        <Newspaper className="w-3.5 h-3.5" /> Recent Genuine Reports
                      </span>
                      {isLoadingNews ? (
                        <span className="text-[10px] text-gray-400 flex items-center gap-1.5">
                          <Clock className="w-3 h-3 animate-spin" /> Querying Web...
                        </span>
                      ) : (
                        <span className="text-[10px] text-emerald-400 flex items-center gap-1">
                          <CheckCircle className="w-3 h-3" /> Live Feed Online
                        </span>
                      )}
                    </div>

                    <div className="space-y-3">
                      {isLoadingNews && (
                        <div className="space-y-3 animate-pulse py-2">
                          <div className={`h-16 rounded-lg w-full ${isDark ? 'bg-gray-800/50' : 'bg-gray-200'}`} />
                          <div className={`h-16 rounded-lg w-full ${isDark ? 'bg-gray-800/50' : 'bg-gray-200'}`} />
                          <div className={`h-16 rounded-lg w-full ${isDark ? 'bg-gray-800/50' : 'bg-gray-200'}`} />
                        </div>
                      )}

                      {!isLoadingNews &&
                        realNewsList.map((news, idx) => (
                          <div
                            key={idx}
                            className={`p-3 rounded-lg border text-xs leading-relaxed transition-all ${
                              isDark
                                ? 'bg-gray-950/40 border-gray-800/80 hover:border-indigo-500/30'
                                : 'bg-slate-50 border-gray-200 hover:border-indigo-400/30'
                            }`}
                          >
                            <div className="flex items-center justify-between mb-1.5">
                              <span className="text-[10px] opacity-75 font-bold text-indigo-400">{news.source}</span>
                              <span
                                className={`text-[9px] px-1.5 py-0.5 rounded font-bold uppercase tracking-wider ${
                                  news.sentiment === 'Bullish'
                                    ? 'bg-emerald-500/10 text-emerald-400'
                                    : news.sentiment === 'Bearish'
                                      ? 'bg-rose-500/10 text-rose-400'
                                      : 'bg-blue-500/10 text-blue-400'
                                }`}
                              >
                                {news.sentiment}
                              </span>
                            </div>
                            <p className={`font-bold mb-1 ${isDark ? 'text-gray-100' : 'text-slate-900'}`}>{news.title}</p>
                            <p className="text-gray-400 text-[11px] mb-2">{news.summary}</p>
                            {news.url && (
                              <a
                                href={news.url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="inline-flex items-center gap-1 text-[10px] font-bold text-blue-400 hover:underline"
                              >
                                Read Full Article <ExternalLink className="w-2.5 h-2.5" />
                              </a>
                            )}
                          </div>
                        ))}

                      {!isLoadingNews && newsError && (
                        <div className="p-3 bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-xs rounded-lg">{newsError}</div>
                      )}
                    </div>
                  </div>

                  <div className={`pt-3 border-t space-y-2 ${isDark ? 'border-gray-800/60' : 'border-gray-200'}`}>
                    <span className="text-xs font-bold uppercase tracking-wider text-gray-400 block">External Search &amp; Trade Hubs</span>
                    <div className="grid grid-cols-2 gap-2">
                      <a
                        href={getGoogleNewsUrl(selectedStock.symbol)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={`flex items-center justify-center gap-1.5 py-2 px-3 text-xs font-semibold rounded-lg border transition-all ${
                          isDark
                            ? 'bg-gray-900 border-gray-800 text-gray-200 hover:bg-gray-800'
                            : 'bg-gray-50 border-gray-200 text-slate-700 hover:bg-gray-100'
                        }`}
                      >
                        <Globe className="w-3.5 h-3.5 text-blue-500" />
                        <span>Google News</span>
                        <ExternalLink className="w-2.5 h-2.5 text-gray-500" />
                      </a>
                      <a
                        href={getGoogleFinanceUrl(selectedStock.symbol)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={`flex items-center justify-center gap-1.5 py-2 px-3 text-xs font-semibold rounded-lg border transition-all ${
                          isDark
                            ? 'bg-gray-900 border-gray-800 text-gray-200 hover:bg-gray-800'
                            : 'bg-gray-50 border-gray-200 text-slate-700 hover:bg-gray-100'
                        }`}
                      >
                        <BarChart2 className="w-3.5 h-3.5 text-emerald-500" />
                        <span>Finance Hub</span>
                        <ExternalLink className="w-2.5 h-2.5 text-gray-500" />
                      </a>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="p-8 text-center text-gray-500 space-y-4">
                  <div className="w-12 h-12 rounded-full bg-indigo-500/10 flex items-center justify-center mx-auto text-indigo-400">
                    <Sparkles className="w-6 h-6 animate-pulse" />
                  </div>
                  <div>
                    <h4 className={`text-sm font-semibold mb-1 ${isDark ? 'text-gray-300' : 'text-slate-800'}`}>Select an Asset For Brief</h4>
                    <p className="text-xs text-gray-400 leading-relaxed">
                      Click &quot;View Actual News&quot; beside any asset row. The built-in Google Grounded pipeline queries
                      real-world headlines, publisher names, and links instantly.
                    </p>
                  </div>
                </div>
              )}
            </div>

            <div className={`p-5 rounded-2xl border ${isDark ? 'bg-[#0f1424] border-gray-800' : 'bg-white border-gray-200'}`}>
              <h4 className={`text-xs font-bold uppercase tracking-wider mb-3 ${isDark ? 'text-gray-400' : 'text-slate-600'}`}>
                Stock Tracking Glossary
              </h4>
              <ul className="space-y-3 text-xs">
                <li className="flex items-start gap-2.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-blue-500 mt-1.5 shrink-0" />
                  <div>
                    <strong className={isDark ? 'text-gray-300' : 'text-slate-700'}>Live Grounding:</strong> Google Search is
                    queried securely inside the web container to discover genuine reports, entirely replacing static mock
                    templates.
                  </div>
                </li>
                <li className="flex items-start gap-2.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-indigo-500 mt-1.5 shrink-0" />
                  <div>
                    <strong className={isDark ? 'text-gray-300' : 'text-slate-700'}>Structured News Schema:</strong> Output is
                    parsed into a verified list of titles, URLs, and publisher names, allowing direct navigation to original
                    source articles.
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </main>

      <style>{`
        @keyframes marquee {
          0% { transform: translateX(0%); }
          100% { transform: translateX(-50%); }
        }
        .animate-marquee {
          display: inline-flex;
          animation: marquee 45s linear infinite;
        }
        .animate-marquee:hover {
          animation-play-state: paused;
        }
      `}</style>
    </div>
  );
}

const rootEl = document.getElementById('markets-root');
if (rootEl) {
  ReactDOM.createRoot(rootEl).render(<MarketsApp />);
}
