import React, { useState, useEffect, useCallback } from 'react';
import { useSource, useAppState, useAction } from './sdk';
import { Badge, Metric, Glass, Icon } from './components';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, BarChart, Bar, Cell } from 'recharts';
import { TrendingUp, DollarSign, Users, AlertTriangle, CheckCircle, RefreshCw, Settings, Bell, Clock, History, BarChart3, Search, Shield, Zap, AlertCircle } from 'lucide-react';

// Mock data for competitors
const MOCK_COMPETITORS = [
  {
    id: 'comp-1',
    name: 'Competitor A',
    url: 'https://competitor-a.com/pricing',
    status: 'connected',
    lastScrape: '2026-04-10T18:30:00Z',
    health: 'healthy',
    plans: [
      { name: 'Starter', price: 29, cycle: 'month', features: ['5 users', '10GB storage', 'Email support'] },
      { name: 'Professional', price: 79, cycle: 'month', features: ['25 users', '100GB storage', 'Priority support'] },
      { name: 'Enterprise', price: 199, cycle: 'month', features: ['Unlimited users', '1TB storage', '24/7 support'] }
    ]
  },
  {
    id: 'comp-2',
    name: 'Competitor B',
    url: 'https://competitor-b.com/pricing',
    status: 'connected',
    lastScrape: '2026-04-10T17:45:00Z',
    health: 'healthy',
    plans: [
      { name: 'Basic', price: 25, cycle: 'month', features: ['3 users', '5GB storage', 'Community support'] },
      { name: 'Pro', price: 69, cycle: 'month', features: ['20 users', '50GB storage', 'Email support'] },
      { name: 'Business', price: 149, cycle: 'month', features: ['Unlimited users', '500GB storage', 'Phone support'] }
    ]
  },
  {
    id: 'comp-3',
    name: 'Competitor C',
    url: 'https://competitor-c.com/pricing',
    status: 'connected',
    lastScrape: '2026-04-10T19:00:00Z',
    health: 'warning',
    plans: [
      { name: 'Starter', price: 35, cycle: 'month', features: ['10 users', '20GB storage', 'Email support'] },
      { name: 'Growth', price: 89, cycle: 'month', features: ['50 users', '200GB storage', 'Priority support'] },
      { name: 'Scale', price: 249, cycle: 'month', features: ['Unlimited users', '2TB storage', 'Dedicated support'] }
    ]
  }
];

const MOCK_CHANGES = [
  { id: 1, competitor: 'Competitor A', type: 'price_change', description: 'Professional plan increased from $69 to $79', change: '+14.5%', timestamp: '2026-04-10T18:30:00Z', severity: 'medium' },
  { id: 2, competitor: 'Competitor B', type: 'new_plan', description: 'Added new "Team" plan at $99/month', change: 'new', timestamp: '2026-04-09T14:20:00Z', severity: 'high' },
  { id: 3, competitor: 'Competitor C', type: 'feature_change', description: 'Starter plan now includes 10 users (was 5)', change: 'feature', timestamp: '2026-04-08T10:15:00Z', severity: 'low' },
  { id: 4, competitor: 'Competitor A', type: 'price_change', description: 'Enterprise plan decreased from $249 to $199', change: '-20%', timestamp: '2026-04-07T16:45:00Z', severity: 'high' },
  { id: 5, competitor: 'Competitor B', type: 'discount', description: 'Annual billing now offers 20% discount (was 15%)', change: 'discount', timestamp: '2026-04-06T09:30:00Z', severity: 'medium' }
];

const MOCK_PRICE_HISTORY = [
  { date: '2026-04-01', compA: 69, compB: 65, compC: 85 },
  { date: '2026-04-03', compA: 69, compB: 65, compC: 85 },
  { date: '2026-04-05', compA: 79, compB: 65, compC: 85 },
  { date: '2026-04-07', compA: 79, compB: 69, compC: 89 },
  { date: '2026-04-09', compA: 79, compB: 69, compC: 89 },
  { date: '2026-04-10', compA: 79, compB: 69, compC: 89 }
];

const COLORS = {
  violet: '#8b5cf6',
  cyan: '#06b6d4',
  emerald: '#10b981',
  amber: '#f59e0b',
  red: '#ef4444',
  slate: '#64748b'
};

export default function App() {
  const [activeTab, setActiveTab] = useState<'overview' | 'pricing' | 'changes' | 'settings'>('overview');
  const [selectedCompetitor, setSelectedCompetitor] = useState<any>(null);
  const [isScraping, setIsScraping] = useState(false);
  const [alertConfig, setAlertConfig] = useAppState('alertConfig', {
    emailEnabled: true,
    emailThreshold: 5,
    notifyOnPriceChange: true,
    notifyOnNewPlan: true,
    notifyOnFeatureChange: false
  });
  const [showSettings, setShowSettings] = useState(false);
  const dispatch = useAction();

  // Simulate scraping status
  const [scrapeStatus, setScrapeStatus] = useState({
    lastRun: '2026-04-10T19:00:00Z',
    nextRun: '2026-04-11T01:00:00Z',
    status: 'healthy',
    totalScrapes: 142,
    successRate: 98.5
  });

  const handleManualScrape = useCallback(async () => {
    setIsScraping(true);
    // Simulate scrape operation
    setTimeout(() => {
      setIsScraping(false);
      dispatch('toast', { message: 'Scrape completed successfully', type: 'success' });
      setScrapeStatus(prev => ({
        ...prev,
        lastRun: new Date().toISOString(),
        totalScrapes: prev.totalScrapes + 1
      }));
    }, 2000);
  }, [dispatch]);

  const handleSaveSettings = useCallback(() => {
    dispatch('toast', { message: 'Alert settings saved', type: 'success' });
    setShowSettings(false);
  }, [dispatch]);

  const formatDate = (isoString: string) => {
    const date = new Date(isoString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'high': return 'negative';
      case 'medium': return 'neutral';
      case 'low': return 'positive';
      default: return 'neutral';
    }
  };

  const renderOverview = () => (
    <div className="space-y-6">
      {/* Status Banner */}
      <Glass className="p-5 border-l-4 border-emerald-500">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-emerald-500/20 rounded-lg">
              <CheckCircle className="w-6 h-6 text-emerald-400" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-white">Monitoring Active</h3>
              <p className="text-sm text-slate-400">All {MOCK_COMPETITORS.length} competitors being tracked successfully</p>
            </div>
          </div>
          <button
            onClick={handleManualScrape}
            disabled={isScraping}
            className="flex items-center gap-2 px-4 py-2 bg-violet-600 hover:bg-violet-700 disabled:bg-slate-600 rounded-lg text-white font-medium transition-colors"
          >
            <RefreshCw className={`w-4 h-4 ${isScraping ? 'animate-spin' : ''}`} />
            {isScraping ? 'Scraping...' : 'Scrape Now'}
          </button>
        </div>
      </Glass>

      {/* Metrics Row */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Metric
          label="Competitors Tracked"
          value={MOCK_COMPETITORS.length.toString()}
          trend="stable"
          trendLabel="All active"
        />
        <Metric
          label="Changes Detected"
          value={MOCK_CHANGES.length.toString()}
          trend="up"
          trendLabel="+2 this week"
        />
        <Metric
          label="Success Rate"
          value={`${scrapeStatus.successRate}%`}
          trend="up"
          trendLabel="Last 30 days"
        />
        <Metric
          label="Total Scrapes"
          value={scrapeStatus.totalScrapes.toLocaleString()}
          trend="up"
          trendLabel="All time"
        />
      </div>

      {/* Price History Chart */}
      <Glass className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="w-5 h-5 text-violet-400" />
          <h2 className="text-lg font-semibold text-white">Price History Trend</h2>
        </div>
        <div className="h-72">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={MOCK_PRICE_HISTORY}>
              <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
              <XAxis dataKey="date" stroke="#94a3b8" fontSize={12} />
              <YAxis stroke="#94a3b8" fontSize={12} />
              <Tooltip
                contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
                labelStyle={{ color: '#f1f5f9' }}
              />
              <Legend />
              <Line type="monotone" dataKey="compA" stroke={COLORS.violet} strokeWidth={2} name="Competitor A" />
              <Line type="monotone" dataKey="compB" stroke={COLORS.cyan} strokeWidth={2} name="Competitor B" />
              <Line type="monotone" dataKey="compC" stroke={COLORS.emerald} strokeWidth={2} name="Competitor C" />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </Glass>

      {/* Recent Changes */}
      <Glass className="p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <History className="w-5 h-5 text-amber-400" />
            <h2 className="text-lg font-semibold text-white">Recent Changes</h2>
          </div>
          <button
            onClick={() => setActiveTab('changes')}
            className="text-sm text-violet-400 hover:text-violet-300"
          >
            View all →
          </button>
        </div>
        <div className="space-y-3">
          {MOCK_CHANGES.slice(0, 3).map((change) => (
            <div key={change.id} className="flex items-start gap-3 p-3 bg-slate-800/50 rounded-lg border border-slate-700/50">
              <div className={`mt-1 w-2 h-2 rounded-full ${
                change.severity === 'high' ? 'bg-red-500' :
                change.severity === 'medium' ? 'bg-amber-500' : 'bg-emerald-500'
              }`} />
              <div className="flex-1">
                <p className="text-sm text-slate-200">{change.description}</p>
                <div className="flex items-center gap-2 mt-1">
                  <span className="text-xs text-slate-400">{change.competitor}</span>
                  <span className="text-xs text-slate-500">•</span>
                  <span className="text-xs text-slate-400">{formatDate(change.timestamp)}</span>
                  <Badge label={change.type.replace('_', ' ')} variant={getSeverityColor(change.severity)} />
                </div>
              </div>
              <span className={`text-sm font-semibold ${
                change.change.startsWith('+') ? 'text-red-400' :
                change.change.startsWith('-') ? 'text-emerald-400' : 'text-violet-400'
              }`}>
                {change.change}
              </span>
            </div>
          ))}
        </div>
      </Glass>
    </div>
  );

  const renderPricing = () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {MOCK_COMPETITORS.map((competitor) => (
          <Glass
            key={competitor.id}
            className={`p-5 cursor-pointer transition-all hover:border-violet-500/50 ${
              selectedCompetitor?.id === competitor.id ? 'border-violet-500' : 'border-slate-700/50'
            }`}
          >
            <div onClick={() => setSelectedCompetitor(competitor)}>
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <Globe className="w-5 h-5 text-violet-400" />
                  <h3 className="text-lg font-semibold text-white">{competitor.name}</h3>
                </div>
                <Badge
                  label={competitor.health}
                  variant={competitor.health === 'healthy' ? 'positive' : 'neutral'}
                />
              </div>
              
              <div className="space-y-3 mb-4">
                {competitor.plans.map((plan, idx) => (
                  <div key={idx} className="p-3 bg-slate-800/50 rounded-lg">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-slate-200">{plan.name}</span>
                      <span className="text-lg font-bold text-emerald-400">${plan.price}</span>
                    </div>
                    <p className="text-xs text-slate-400">/{plan.cycle}</p>
                    <div className="flex flex-wrap gap-1 mt-2">
                      {plan.features.slice(0, 2).map((feature, fIdx) => (
                        <span key={fIdx} className="text-xs text-slate-400 bg-slate-700/50 px-2 py-0.5 rounded">
                          {feature}
                        </span>
                      ))}
                      {plan.features.length > 2 && (
                        <span className="text-xs text-slate-500">+{plan.features.length - 2} more</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              <div className="flex items-center justify-between text-xs text-slate-400">
                <span className="flex items-center gap-1">
                  <Clock className="w-3 h-3" />
                  Last: {formatDate(competitor.lastScrape)}
                </span>
                <a
                  href={competitor.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-violet-400 hover:text-violet-300 flex items-center gap-1"
                  onClick={(e) => e.stopPropagation()}
                >
                  Visit site <Icon name="external-link" size={12} />
                </a>
              </div>
            </div>
          </Glass>
        ))}
      </div>

      {/* Comparison Table */}
      <Glass className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="w-5 h-5 text-cyan-400" />
          <h2 className="text-lg font-semibold text-white">Price Comparison</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-700">
                <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">Plan</th>
                {MOCK_COMPETITORS.map((c) => (
                  <th key={c.id} className="text-center py-3 px-4 text-sm font-medium text-slate-400">{c.name}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {['Starter', 'Basic', 'Professional', 'Pro', 'Growth', 'Enterprise', 'Business', 'Scale'].map((planName, idx) => {
                const prices = MOCK_COMPETITORS.map(c => {
                  const plan = c.plans.find(p => p.name.toLowerCase().includes(planName.toLowerCase()));
                  return plan ? plan.price : null;
                });
                if (prices.every(p => p === null)) return null;
                return (
                  <tr key={idx} className="border-b border-slate-700/50">
                    <td className="py-3 px-4 text-sm text-slate-200">{planName}</td>
                    {prices.map((price, cIdx) => (
                      <td key={cIdx} className="text-center py-3 px-4">
                        {price !== null ? (
                          <span className="text-sm font-semibold text-emerald-400">${price}</span>
                        ) : (
                          <span className="text-sm text-slate-600">—</span>
                        )}
                      </td>
                    ))}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Glass>
    </div>
  );

  const renderChanges = () => (
    <div className="space-y-6">
      <Glass className="p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <History className="w-5 h-5 text-amber-400" />
            <h2 className="text-lg font-semibold text-white">Change History</h2>
          </div>
          <div className="flex items-center gap-2">
            <Badge label={`${MOCK_CHANGES.length} changes`} variant="neutral" />
            <button className="p-2 hover:bg-slate-800 rounded-lg transition-colors">
              <Icon name="download" size={16} className="text-slate-400" />
            </button>
          </div>
        </div>
        <div className="space-y-3">
          {MOCK_CHANGES.map((change) => (
            <div key={change.id} className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-lg border border-slate-700/50 hover:border-slate-600 transition-colors">
              <div className={`mt-1 p-2 rounded-lg ${
                change.severity === 'high' ? 'bg-red-500/20' :
                change.severity === 'medium' ? 'bg-amber-500/20' : 'bg-emerald-500/20'
              }`}>
                {change.type === 'price_change' ? <DollarSign className="w-4 h-4 text-slate-300" /> :
                 change.type === 'new_plan' ? <TrendingUp className="w-4 h-4 text-slate-300" /> :
                 <Settings className="w-4 h-4 text-slate-300" />}
              </div>
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-sm font-medium text-slate-200">{change.competitor}</span>
                  <Badge label={change.type.replace('_', ' ')} variant={getSeverityColor(change.severity)} />
                </div>
                <p className="text-sm text-slate-300 mb-2">{change.description}</p>
                <div className="flex items-center gap-3 text-xs text-slate-400">
                  <span className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {formatDate(change.timestamp)}
                  </span>
                  <span className={`font-semibold ${
                    change.change.startsWith('+') ? 'text-red-400' :
                    change.change.startsWith('-') ? 'text-emerald-400' : 'text-violet-400'
                  }`}>
                    {change.change}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Glass>
    </div>
  );

  const renderSettings = () => (
    <div className="space-y-6">
      <Glass className="p-6">
        <div className="flex items-center gap-2 mb-6">
          <Settings className="w-5 h-5 text-violet-400" />
          <h2 className="text-lg font-semibold text-white">Alert Configuration</h2>
        </div>
        
        <div className="space-y-6">
          <div className="flex items-center justify-between p-4 bg-slate-800/50 rounded-lg">
            <div>
              <h3 className="text-sm font-medium text-slate-200">Email Notifications</h3>
              <p className="text-xs text-slate-400 mt-1">Receive email alerts for significant changes</p>
            </div>
            <button
              onClick={() => setAlertConfig({ ...alertConfig, emailEnabled: !alertConfig.emailEnabled })}
              className={`relative w-12 h-6 rounded-full transition-colors ${
                alertConfig.emailEnabled ? 'bg-violet-600' : 'bg-slate-600'
              }`}
            >
              <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                alertConfig.emailEnabled ? 'left-7' : 'left-1'
              }`} />
            </button>
          </div>

          <div className="p-4 bg-slate-800/50 rounded-lg">
            <h3 className="text-sm font-medium text-slate-200 mb-3">Notification Triggers</h3>
            <div className="space-y-3">
              {[
                { key: 'notifyOnPriceChange', label: 'Price changes', desc: 'Any price increase or decrease' },
                { key: 'notifyOnNewPlan', label: 'New plans', desc: 'When competitors add new pricing tiers' },
                { key: 'notifyOnFeatureChange', label: 'Feature changes', desc: 'Updates to plan features or limits' }
              ].map((item) => (
                <div key={item.key} className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-slate-200">{item.label}</p>
                    <p className="text-xs text-slate-400">{item.desc}</p>
                  </div>
                  <button
                    onClick={() => setAlertConfig({ ...alertConfig, [item.key]: !alertConfig[item.key as keyof typeof alertConfig] })}
                    className={`relative w-10 h-5 rounded-full transition-colors ${
                      alertConfig[item.key as keyof typeof alertConfig] ? 'bg-violet-600' : 'bg-slate-600'
                    }`}
                  >
                    <div className={`absolute top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
                      alertConfig[item.key as keyof typeof alertConfig] ? 'left-5' : 'left-0.5'
                    }`} />
                  </button>
                </div>
              ))}
            </div>
          </div>

          <div className="p-4 bg-slate-800/50 rounded-lg">
            <h3 className="text-sm font-medium text-slate-200 mb-3">Sensitivity Threshold</h3>
            <div className="flex items-center gap-4">
              <input
                type="range"
                min="0"
                max="20"
                value={alertConfig.emailThreshold}
                onChange={(e) => setAlertConfig({ ...alertConfig, emailThreshold: parseInt(e.target.value) })}
                className="flex-1 h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer"
              />
              <span className="text-sm font-medium text-violet-400 w-16 text-right">
                {alertConfig.emailThreshold}%
              </span>
            </div>
            <p className="text-xs text-slate-400 mt-2">
              Only alert on price changes greater than {alertConfig.emailThreshold}%
            </p>
          </div>

          <button
            onClick={handleSaveSettings}
            className="w-full py-3 bg-violet-600 hover:bg-violet-700 rounded-lg text-white font-medium transition-colors"
          >
            Save Settings
          </button>
        </div>
      </Glass>

      <Glass className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Zap className="w-5 h-5 text-amber-400" />
          <h2 className="text-lg font-semibold text-white">Scraping Schedule</h2>
        </div>
        <div className="space-y-4">
          <div className="flex items-center justify-between p-4 bg-slate-800/50 rounded-lg">
            <div>
              <h3 className="text-sm font-medium text-slate-200">Scrape Interval</h3>
              <p className="text-xs text-slate-400 mt-1">How often to check competitor pricing pages</p>
            </div>
            <select className="bg-slate-700 text-slate-200 text-sm px-3 py-2 rounded-lg border border-slate-600">
              <option>Every 6 hours</option>
              <option>Every 12 hours</option>
              <option>Daily</option>
              <option>Every 3 hours</option>
            </select>
          </div>
          <div className="p-4 bg-slate-800/50 rounded-lg">
            <h3 className="text-sm font-medium text-slate-200 mb-2">Next Scheduled Run</h3>
            <p className="text-lg font-semibold text-violet-400">{formatDate(scrapeStatus.nextRun)}</p>
          </div>
        </div>
      </Glass>
    </div>
  );

  return (
    <div className="min-h-screen bg-[#0a0e1a] text-white p-6">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-violet-600/20 rounded-xl">
              <Search className="w-8 h-8 text-violet-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">Competitive Intelligence Monitor</h1>
              <p className="text-sm text-slate-400">Track competitor pricing changes in real-time</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={() => setShowSettings(!showSettings)}
              className="p-2 hover:bg-slate-800 rounded-lg transition-colors relative"
            >
              <Bell className="w-5 h-5 text-slate-400" />
              <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full" />
            </button>
            <button
              onClick={() => setActiveTab('settings')}
              className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
            >
              <Settings className="w-5 h-5 text-slate-400" />
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex items-center gap-2 border-b border-slate-700">
          {[
            { id: 'overview', label: 'Overview', icon: BarChart3 },
            { id: 'pricing', label: 'Pricing', icon: DollarSign },
            { id: 'changes', label: 'Changes', icon: History },
            { id: 'settings', label: 'Settings', icon: Settings }
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-violet-500 text-violet-400'
                  : 'border-transparent text-slate-400 hover:text-slate-200'
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      {activeTab === 'overview' && renderOverview()}
      {activeTab === 'pricing' && renderPricing()}
      {activeTab === 'changes' && renderChanges()}
      {activeTab === 'settings' && renderSettings()}

      {/* Competitor Detail Modal */}
      {selectedCompetitor && (
        <div
          className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
          onClick={() => setSelectedCompetitor(null)}
        >
          <div
            className="bg-slate-900 rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto"
            onClick={e => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold text-white">{selectedCompetitor.name}</h2>
              <button
                onClick={() => setSelectedCompetitor(null)}
                className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
              >
                <Icon name="x" size={20} className="text-slate-400" />
              </button>
            </div>
            
            <div className="space-y-4">
              <div className="p-4 bg-slate-800/50 rounded-lg">
                <h3 className="text-sm font-medium text-slate-400 mb-2">Website</h3>
                <a
                  href={selectedCompetitor.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-violet-400 hover:text-violet-300 flex items-center gap-2"
                >
                  {selectedCompetitor.url}
                  <Icon name="external-link" size={14} />
                </a>
              </div>

              <div>
                <h3 className="text-sm font-medium text-slate-400 mb-3">Pricing Plans</h3>
                <div className="space-y-3">
                  {selectedCompetitor.plans.map((plan, idx) => (
                    <div key={idx} className="p-4 bg-slate-800/50 rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-lg font-semibold text-white">{plan.name}</span>
                        <span className="text-2xl font-bold text-emerald-400">${plan.price}</span>
                      </div>
                      <p className="text-sm text-slate-400 mb-3">Billed {plan.cycle}</p>
                      <ul className="space-y-2">
                        {plan.features.map((feature, fIdx) => (
                          <li key={fIdx} className="flex items-center gap-2 text-sm text-slate-300">
                            <CheckCircle className="w-4 h-4 text-emerald-400" />
                            {feature}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>

              <div className="p-4 bg-slate-800/50 rounded-lg">
                <h3 className="text-sm font-medium text-slate-400 mb-2">Monitoring Status</h3>
                <div className="flex items-center gap-4">
                  <Badge
                    label={selectedCompetitor.health}
                    variant={selectedCompetitor.health === 'healthy' ? 'positive' : 'neutral'}
                  />
                  <span className="text-sm text-slate-400">
                    Last scraped: {formatDate(selectedCompetitor.lastScrape)}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Helper component for external link icon
function Globe({ className }: { className?: string }) {
  return <Icon name="globe" size={20} className={className} />;
}
