'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';

// ─── Types ────────────────────────────────────────────────────────────────────

interface TrackedCompany {
  id: string;
  company_name: string;
  company_website: string | null;
  site_scope: string;
  mention_count: number;
  auto_story_enabled: boolean;
  last_crawled: string | null;
  next_crawl_scheduled: string | null;
  crawl_priority: string;
  notes: string | null;
  created_at: string;
}

interface StoryQueueItem {
  id: string;
  company_name: string;
  story_type: string;
  assigned_pen_name: string;
  site_id: number;
  status: string;
  generated_title: string | null;
  generated_content: string | null;
  generated_excerpt: string | null;
  quality_confidence: number | null;
  source_title: string | null;
  rejection_reason: string | null;
  created_at: string;
}

interface CrawlLog {
  id: string;
  company_name: string;
  source_url: string | null;
  items_found: number;
  stories_queued: number;
  status: string;
  error_message: string | null;
  crawled_at: string;
}

interface Settings {
  autopilot_enabled: boolean;
  reminder_email: string;
  last_scan_at: string | null;
  last_scan_articles_processed: number;
  last_scan_companies_found: number;
}

interface TrackerSettings {
  auto_story_global_enabled: boolean;
  mention_threshold: number;
  max_stories_per_company_per_week: number;
  auto_publish_enabled: boolean;
  auto_publish_confidence_threshold: number;
}

type TabType = 'queue' | 'companies' | 'crawl-log' | 'settings';
type QueueStatus = 'generated' | 'pending' | 'approved' | 'published' | 'rejected';

const SITE_CONFIG = {
  1: { name: 'AV Beat', badge: 'BB', bgClass: 'bg-[#0ea5e9]/10', textClass: 'text-[#0ea5e9]' },
  2: { name: 'AV Beat',        badge: 'AV', bgClass: 'bg-[#f97316]/10', textClass: 'text-[#f97316]' },
};

const BB_PEN_NAMES = ['Michael Strand','David Harlow','Karen Fielding','James Mercer','Peter Calloway','Sandra Voss','Brian Kowalski','Laura Pennington','Thomas Reeves','Christine Vale','Marcus Webb','Ellen Forsythe'];
const AV_PEN_NAMES = ['Rex Chandler','Dana Flux','Derek Wainwright','Sloane Rigging','Chip Crosspoint','Blair Presenter','Jordan Lumen'];

function SiteBadge({ siteId }: { siteId: number }) {
  const cfg = SITE_CONFIG[siteId as 1 | 2] || SITE_CONFIG[1];
  return <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-bold ${cfg.bgClass} ${cfg.textClass}`}>{cfg.badge}</span>;
}

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

export default function CompanyTrackerPage() {
  const { user, loading } = useAuth();
  const router = useRouter();

  const [activeTab, setActiveTab] = useState<TabType>('queue');
  const [queueStatus, setQueueStatus] = useState<QueueStatus>('generated');
  const [queueSiteFilter, setQueueSiteFilter] = useState('');

  const [queue, setQueue] = useState<StoryQueueItem[]>([]);
  const [companies, setCompanies] = useState<TrackedCompany[]>([]);
  const [crawlLogs, setCrawlLogs] = useState<CrawlLog[]>([]);
  const [settings, setSettings] = useState<Settings>({ autopilot_enabled: false, reminder_email: 'ryan.salazar@relevantmediaproperties.com', last_scan_at: null, last_scan_articles_processed: 0, last_scan_companies_found: 0 });
  const [trackerSettings, setTrackerSettings] = useState<TrackerSettings>({ auto_story_global_enabled: true, mention_threshold: 2, max_stories_per_company_per_week: 3, auto_publish_enabled: false, auto_publish_confidence_threshold: 0.85 });

  const [loadingData, setLoadingData] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [expandedItem, setExpandedItem] = useState<string | null>(null);
  const [showAddCompany, setShowAddCompany] = useState(false);
  const [addCompanyForm, setAddCompanyForm] = useState({ company_name: '', company_website: '', site_scope: 'both', auto_story_enabled: true, crawl_priority: 'standard', notes: '' });
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 4000);
  };

  const fetchData = useCallback(async () => {
    setLoadingData(true);
    try {
      const params = new URLSearchParams({ tab: activeTab });
      if (activeTab === 'queue') {
        params.set('status', queueStatus);
        if (queueSiteFilter) params.set('site', queueSiteFilter);
      }
      const [mainRes, settingsRes] = await Promise.all([
        fetch(`/api/admin/company-coverage?${params}`),
        fetch('/api/admin/company-coverage?action=settings'),
      ]);
      const mainData = await mainRes.json();
      const settingsData = await settingsRes.json();

      if (activeTab === 'queue') setQueue(mainData.queue || []);
      else if (activeTab === 'companies') setCompanies(mainData.companies || []);
      else if (activeTab === 'crawl-log') setCrawlLogs(mainData.logs || []);

      if (settingsData.settings) setSettings(settingsData.settings);
      if (settingsData.trackerSettings) setTrackerSettings(settingsData.trackerSettings);
    } catch { showToast('Failed to load data', 'error'); }
    finally { setLoadingData(false); }
  }, [activeTab, queueStatus, queueSiteFilter]);

  useEffect(() => {
    if (!loading && !user) router.push('/login?next=' + encodeURIComponent(window.location.pathname));
  }, [user, loading, router]);

  useEffect(() => {
    if (user) fetchData();
  }, [user, fetchData]);

  const handleScan = async () => {
    setScanning(true);
    try {
      const res = await fetch('/api/admin/company-coverage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'scan' }) });
      const data = await res.json();
      if (data.success) {
        showToast(`Scan complete: ${data.newCompaniesFound} new companies found across ${data.articlesScanned} articles`);
        fetchData();
      } else showToast(data.error || 'Scan failed', 'error');
    } catch { showToast('Scan failed', 'error'); }
    finally { setScanning(false); }
  };

  const handleQueueAction = async (id: string, action: string, extra?: any) => {
    setActionLoading(id + action);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, action, ...extra }),
      });
      const data = await res.json();
      if (data.success) { showToast(action === 'approve' ? 'Story published' : action === 'reject' ? 'Story rejected' : 'Updated'); fetchData(); }
      else showToast(data.error || 'Action failed', 'error');
    } catch { showToast('Action failed', 'error'); }
    finally { setActionLoading(null); }
  };

  const handleToggleCompanyAutoStory = async (companyId: string, enabled: boolean) => {
    setActionLoading(companyId);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'toggle_company_auto_story', company_id: companyId, enabled }),
      });
      if ((await res.json()).success) { showToast(enabled ? 'Auto-stories enabled' : 'Auto-stories disabled'); fetchData(); }
    } catch { showToast('Failed', 'error'); }
    finally { setActionLoading(null); }
  };

  const handleDeleteCompany = async (companyId: string) => {
    if (!confirm('Remove this company from tracking?')) return;
    setActionLoading(companyId);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'delete_company', company_id: companyId }),
      });
      if ((await res.json()).success) { showToast('Company removed'); fetchData(); }
    } catch { showToast('Failed', 'error'); }
    finally { setActionLoading(null); }
  };

  const handleAddCompany = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'add_company', ...addCompanyForm }),
      });
      const data = await res.json();
      if (data.company) { showToast('Company added'); setShowAddCompany(false); setAddCompanyForm({ company_name: '', company_website: '', site_scope: 'both', auto_story_enabled: true, crawl_priority: 'standard', notes: '' }); fetchData(); }
      else showToast(data.error || 'Failed', 'error');
    } catch { showToast('Failed', 'error'); }
  };

  const handleSaveSettings = async () => {
    setSavingSettings(true);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'update_settings',
          autopilot_enabled: settings.autopilot_enabled,
          reminder_email: settings.reminder_email,
          auto_story_global_enabled: trackerSettings.auto_story_global_enabled,
          mention_threshold: trackerSettings.mention_threshold,
          max_stories_per_company_per_week: trackerSettings.max_stories_per_company_per_week,
          auto_publish_enabled: trackerSettings.auto_publish_enabled,
        }),
      });
      if ((await res.json()).success) showToast('Settings saved');
      else showToast('Failed to save', 'error');
    } catch { showToast('Failed', 'error'); }
    finally { setSavingSettings(false); }
  };

  if (loading || loadingData) {
    return (
      <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  const tabs: { id: TabType; label: string }[] = [
    { id: 'queue', label: 'Story Queue' },
    { id: 'companies', label: 'Tracked Companies' },
    { id: 'crawl-log', label: 'Crawl Log' },
    { id: 'settings', label: 'Settings' },
  ];

  return (
    <div className="min-h-screen bg-[#0a0a0a]">
      {toast && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg text-sm font-body shadow-lg ${
          toast.type === 'success' ? 'bg-green-500/20 border border-green-500/40 text-green-300' : 'bg-red-500/20 border border-red-500/40 text-red-300'
        }`}>{toast.message}</div>
      )}

      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <Link href="/admin" className="text-[#555] hover:text-white text-sm font-body transition-colors">Admin</Link>
              <svg className="w-3.5 h-3.5 text-[#333]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" /></svg>
              <span className="text-[#888] text-sm font-body">Company Tracker</span>
            </div>
            <h1 className="text-2xl font-display font-bold text-white">Company Story Engine</h1>
            <p className="text-[#555] text-sm font-body mt-1">Automated story generation from company mentions across AV Beat & AV Beat</p>
          </div>
          <div className="flex items-center gap-3">
            {/* Auto-Pilot toggle */}
            <div className="flex items-center gap-3 bg-[#111] border border-[#DCE6F2] rounded-lg px-4 py-2.5">
              <div>
                <div className="text-xs font-body font-bold text-white">Auto-Pilot</div>
                <div className="text-xs text-[#555] font-body">{settings.autopilot_enabled ? 'Stories auto-publish' : 'Manual review'}</div>
              </div>
              <button
                onClick={async () => {
                  const newVal = !settings.autopilot_enabled;
                  setSettings(s => ({ ...s, autopilot_enabled: newVal }));
                  await fetch('/api/admin/company-coverage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'update_settings', autopilot_enabled: newVal, reminder_email: settings.reminder_email }) });
                  showToast(newVal ? '🚀 Auto-Pilot enabled' : '⏸ Auto-Pilot disabled');
                }}
                className={`relative w-11 h-6 rounded-full transition-colors ${settings.autopilot_enabled ? 'bg-[#1D4ED8]' : 'bg-[#333]'}`}
              >
                <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${settings.autopilot_enabled ? 'translate-x-5' : 'translate-x-0'}`} />
              </button>
            </div>
            <button onClick={handleScan} disabled={scanning}
              className="flex items-center gap-2 px-4 py-2 bg-[#1D4ED8] hover:bg-blue-500 disabled:opacity-50 text-white text-sm font-body font-semibold rounded-lg transition-colors">
              {scanning ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>}
              {scanning ? 'Scanning…' : 'Scan Articles Now'}
            </button>
          </div>
        </div>

        {/* Stats row */}
        {settings.last_scan_at && (
          <div className="mb-6 flex flex-wrap gap-4">
            {[
              { label: 'Last Scan', value: timeAgo(settings.last_scan_at) },
              { label: 'Articles Processed', value: settings.last_scan_articles_processed },
              { label: 'Companies Found', value: settings.last_scan_companies_found },
              { label: 'Tracked Companies', value: companies.length || '—' },
            ].map(stat => (
              <div key={stat.label} className="bg-[#111] border border-[#DCE6F2] rounded-lg px-4 py-3">
                <div className="text-lg font-display font-bold text-white">{stat.value}</div>
                <div className="text-xs text-[#555] font-body">{stat.label}</div>
              </div>
            ))}
          </div>
        )}

        {/* Tabs */}
        <div className="flex gap-1 mb-6 bg-[#111] border border-[#DCE6F2] rounded-lg p-1 w-fit">
          {tabs.map(tab => (
            <button key={tab.id} onClick={() => setActiveTab(tab.id)}
              className={`px-4 py-2 rounded-md text-sm font-body font-medium transition-colors ${activeTab === tab.id ? 'bg-[#FFFFFF] text-white' : 'text-[#555] hover:text-[#888]'}`}>
              {tab.label}
            </button>
          ))}
        </div>

        {/* ── Story Queue Tab ── */}
        {activeTab === 'queue' && (
          <div>
            <div className="flex flex-wrap gap-3 mb-4">
              {(['generated','pending','approved','published','rejected'] as QueueStatus[]).map(s => (
                <button key={s} onClick={() => setQueueStatus(s)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-body font-medium transition-colors capitalize ${queueStatus === s ? 'bg-[#1D4ED8] text-white' : 'bg-[#111] border border-[#DCE6F2] text-[#555] hover:text-white'}`}>
                  {s === 'generated' ? 'Pending Review' : s}
                </button>
              ))}
              <select value={queueSiteFilter} onChange={e => setQueueSiteFilter(e.target.value)}
                className="bg-[#111] border border-[#DCE6F2] rounded-lg px-3 py-1.5 text-[#555] text-xs font-body focus:outline-none">
                <option value="">All Sites</option>
                <option value="1">AV Beat</option>
                <option value="2">AV Beat</option>
              </select>
            </div>

            {queue.length === 0 ? (
              <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-12 text-center">
                <p className="text-[#555] text-sm font-body">No stories in this queue. Run a scan to generate new story suggestions.</p>
              </div>
            ) : (
              <div className="space-y-3">
                {queue.map(item => (
                  <div key={item.id} className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
                    <div className="px-5 py-4 flex items-start gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <SiteBadge siteId={item.site_id} />
                          <span className="text-xs px-2 py-0.5 rounded bg-[#FFFFFF] text-[#888] font-body capitalize">{item.story_type.replace(/_/g, ' ')}</span>
                          {item.quality_confidence && (
                            <span className={`text-xs px-2 py-0.5 rounded font-body ${item.quality_confidence >= 0.85 ? 'bg-green-500/10 text-green-400' : 'bg-yellow-500/10 text-yellow-400'}`}>
                              {Math.round(item.quality_confidence * 100)}% confidence
                            </span>
                          )}
                        </div>
                        <h3 className="text-white font-medium text-sm">{item.generated_title || `Story about ${item.company_name}`}</h3>
                        <div className="flex items-center gap-3 mt-1 flex-wrap">
                          <span className="text-xs text-[#555] font-body">Company: <span className="text-[#888]">{item.company_name}</span></span>
                          <span className="text-xs text-[#555] font-body">By: <span className="text-[#888]">{item.assigned_pen_name}</span></span>
                          {item.source_title && <span className="text-xs text-[#555] font-body truncate max-w-xs">Source: {item.source_title}</span>}
                        </div>
                        {item.generated_excerpt && <p className="text-xs text-[#555] font-body mt-2 line-clamp-2">{item.generated_excerpt}</p>}
                        {item.rejection_reason && <p className="text-xs text-red-400 font-body mt-1">Rejected: {item.rejection_reason}</p>}
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        <button onClick={() => setExpandedItem(expandedItem === item.id ? null : item.id)}
                          className="text-xs text-[#555] hover:text-white font-body transition-colors">
                          {expandedItem === item.id ? 'Hide' : 'Preview'}
                        </button>
                        {(item.status === 'generated' || item.status === 'pending') && (
                          <>
                            <button onClick={() => handleQueueAction(item.id, 'approve')} disabled={actionLoading === item.id + 'approve'}
                              className="px-3 py-1.5 bg-green-500/10 hover:bg-green-500/20 text-green-400 text-xs font-body font-semibold rounded-lg transition-colors disabled:opacity-50">
                              Approve & Publish
                            </button>
                            <button onClick={() => { const reason = prompt('Rejection reason (optional):'); handleQueueAction(item.id, 'reject', { rejection_reason: reason }); }} disabled={actionLoading === item.id + 'reject'}
                              className="px-3 py-1.5 bg-red-500/10 hover:bg-red-500/20 text-red-400 text-xs font-body font-semibold rounded-lg transition-colors disabled:opacity-50">
                              Reject
                            </button>
                          </>
                        )}
                        <span className="text-xs text-[#444] font-body">{timeAgo(item.created_at)}</span>
                      </div>
                    </div>
                    {expandedItem === item.id && item.generated_content && (
                      <div className="px-5 pb-5 border-t border-[#FFFFFF]">
                        <div className="mt-4 bg-[#0a0a0a] rounded-lg p-4 text-sm text-[#aaa] font-body leading-relaxed max-h-64 overflow-y-auto"
                          dangerouslySetInnerHTML={{ __html: item.generated_content }} />
                        <div className="mt-3 flex items-center gap-3">
                          <span className="text-xs text-[#555] font-body">Reassign pen name:</span>
                          <select onChange={e => handleQueueAction(item.id, 'reassign_pen_name', { pen_name: e.target.value })}
                            defaultValue={item.assigned_pen_name}
                            className="bg-[#111] border border-[#333] rounded px-2 py-1 text-xs text-white font-body focus:outline-none">
                            {(item.site_id === 2 ? AV_PEN_NAMES : BB_PEN_NAMES).map(n => <option key={n} value={n}>{n}</option>)}
                          </select>
                          <span className="text-xs text-[#555] font-body">Reassign site:</span>
                          <select onChange={e => handleQueueAction(item.id, 'reassign_site', { site_id: parseInt(e.target.value) })}
                            defaultValue={item.site_id}
                            className="bg-[#111] border border-[#333] rounded px-2 py-1 text-xs text-white font-body focus:outline-none">
                            <option value={1}>AV Beat</option>
                            <option value={2}>AV Beat</option>
                          </select>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ── Tracked Companies Tab ── */}
        {activeTab === 'companies' && (
          <div>
            <div className="flex items-center justify-between mb-4">
              <p className="text-sm text-[#555] font-body">{companies.length} companies tracked</p>
              <button onClick={() => setShowAddCompany(true)} className="flex items-center gap-2 px-4 py-2 bg-[#1D4ED8] hover:bg-blue-500 text-white text-sm font-body font-semibold rounded-lg transition-colors">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" /></svg>
                Add Company
              </button>
            </div>

            {showAddCompany && (
              <div className="mb-4 bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
                <h3 className="text-sm font-display font-bold text-white mb-4">Add Company Manually</h3>
                <form onSubmit={handleAddCompany} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-body text-[#888] mb-1.5">Company Name *</label>
                    <input type="text" value={addCompanyForm.company_name} onChange={e => setAddCompanyForm(f => ({ ...f, company_name: e.target.value }))} required
                      className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" />
                  </div>
                  <div>
                    <label className="block text-xs font-body text-[#888] mb-1.5">Website URL</label>
                    <input type="text" value={addCompanyForm.company_website} onChange={e => setAddCompanyForm(f => ({ ...f, company_website: e.target.value }))} placeholder="example.com"
                      className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" />
                  </div>
                  <div>
                    <label className="block text-xs font-body text-[#888] mb-1.5">Site Scope</label>
                    <select value={addCompanyForm.site_scope} onChange={e => setAddCompanyForm(f => ({ ...f, site_scope: e.target.value }))}
                      className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
                      <option value="both">Both Sites</option>
                      <option value="avbeat">AV Beat only</option>
                      <option value="avbeat">AV Beat only</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-body text-[#888] mb-1.5">Crawl Priority</label>
                    <select value={addCompanyForm.crawl_priority} onChange={e => setAddCompanyForm(f => ({ ...f, crawl_priority: e.target.value }))}
                      className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
                      <option value="standard">Standard (weekly)</option>
                      <option value="high">High (every 3 days)</option>
                      <option value="critical">Critical (daily)</option>
                    </select>
                  </div>
                  <div className="md:col-span-2 flex gap-3">
                    <button type="submit" className="px-5 py-2 bg-[#1D4ED8] hover:bg-blue-500 text-white text-sm font-body font-semibold rounded-lg transition-colors">Add Company</button>
                    <button type="button" onClick={() => setShowAddCompany(false)} className="px-4 py-2 bg-[#FFFFFF] border border-[#333] text-[#888] hover:text-white text-sm font-body rounded-lg transition-colors">Cancel</button>
                  </div>
                </form>
              </div>
            )}

            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-[#FFFFFF]">
                      {['Company', 'Website', 'Mentions', 'Sites', 'Auto-Stories', 'Priority', 'Last Crawl', 'Actions'].map(h => (
                        <th key={h} className="px-4 py-3 text-left text-xs font-body font-bold text-[#555] uppercase tracking-wider">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[#FFFFFF]">
                    {companies.length === 0 ? (
                      <tr><td colSpan={8} className="px-4 py-12 text-center text-[#555] text-sm font-body">No companies tracked yet. Run a scan to auto-detect companies from published articles.</td></tr>
                    ) : companies.map(company => (
                      <tr key={company.id} className="hover:bg-[#F8FAFC] transition-colors">
                        <td className="px-4 py-3 text-sm font-body font-semibold text-white">{company.company_name}</td>
                        <td className="px-4 py-3 text-xs text-[#555] font-body">{company.company_website ? <a href={`https://${company.company_website}`} target="_blank" rel="noopener noreferrer" className="text-[#1D4ED8] hover:underline">{company.company_website}</a> : '—'}</td>
                        <td className="px-4 py-3 text-sm font-body text-white font-bold">{company.mention_count}</td>
                        <td className="px-4 py-3 text-xs text-[#888] font-body capitalize">{company.site_scope === 'both' ? 'Both' : company.site_scope === 'avbeat' ? 'BB' : 'AV'}</td>
                        <td className="px-4 py-3">
                          <button onClick={() => handleToggleCompanyAutoStory(company.id, !company.auto_story_enabled)} disabled={actionLoading === company.id}
                            className={`relative w-9 h-5 rounded-full transition-colors ${company.auto_story_enabled ? 'bg-[#1D4ED8]' : 'bg-[#333]'}`}>
                            <span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${company.auto_story_enabled ? 'translate-x-4' : 'translate-x-0'}`} />
                          </button>
                        </td>
                        <td className="px-4 py-3"><span className={`text-xs px-2 py-0.5 rounded font-body capitalize ${company.crawl_priority === 'critical' ? 'bg-red-500/10 text-red-400' : company.crawl_priority === 'high' ? 'bg-yellow-500/10 text-yellow-400' : 'bg-[#FFFFFF] text-[#555]'}`}>{company.crawl_priority}</span></td>
                        <td className="px-4 py-3 text-xs text-[#555] font-body">{company.last_crawled ? timeAgo(company.last_crawled) : 'Never'}</td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <button onClick={async () => { await fetch('/api/admin/company-coverage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'force_crawl', company_id: company.id }) }); showToast('Crawl scheduled'); }}
                              className="text-xs text-[#1D4ED8] hover:text-blue-300 font-body transition-colors">Force Crawl</button>
                            <button onClick={() => handleDeleteCompany(company.id)} disabled={actionLoading === company.id}
                              className="text-xs text-red-500 hover:text-red-400 font-body transition-colors disabled:opacity-50">Remove</button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ── Crawl Log Tab ── */}
        {activeTab === 'crawl-log' && (
          <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-[#FFFFFF]">
                    {['Date', 'Company', 'Source URL', 'Items Found', 'Stories Queued', 'Status'].map(h => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-body font-bold text-[#555] uppercase tracking-wider">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#FFFFFF]">
                  {crawlLogs.length === 0 ? (
                    <tr><td colSpan={6} className="px-4 py-12 text-center text-[#555] text-sm font-body">No crawl history yet.</td></tr>
                  ) : crawlLogs.map(log => (
                    <tr key={log.id} className="hover:bg-[#F8FAFC] transition-colors">
                      <td className="px-4 py-3 text-xs text-[#555] font-body">{new Date(log.crawled_at).toLocaleString()}</td>
                      <td className="px-4 py-3 text-sm text-white font-body">{log.company_name}</td>
                      <td className="px-4 py-3 text-xs text-[#555] font-body truncate max-w-xs">{log.source_url || '—'}</td>
                      <td className="px-4 py-3 text-sm text-white font-body">{log.items_found}</td>
                      <td className="px-4 py-3 text-sm text-white font-body">{log.stories_queued}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded font-body ${log.status === 'success' ? 'bg-green-500/10 text-green-400' : log.status === 'failed' ? 'bg-red-500/10 text-red-400' : 'bg-yellow-500/10 text-yellow-400'}`}>
                          {log.status}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ── Settings Tab ── */}
        {activeTab === 'settings' && (
          <div className="max-w-2xl space-y-6">
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-6">
              <h3 className="text-sm font-display font-bold text-white mb-4">Auto-Pilot & Reminders</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="text-sm font-body text-white">Auto-Pilot Mode</div>
                    <div className="text-xs text-[#555] font-body mt-0.5">When enabled, high-confidence stories publish automatically without review</div>
                  </div>
                  <button onClick={() => setSettings(s => ({ ...s, autopilot_enabled: !s.autopilot_enabled }))}
                    className={`relative w-11 h-6 rounded-full transition-colors ${settings.autopilot_enabled ? 'bg-[#1D4ED8]' : 'bg-[#333]'}`}>
                    <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${settings.autopilot_enabled ? 'translate-x-5' : 'translate-x-0'}`} />
                  </button>
                </div>
                <div>
                  <label className="block text-xs font-body text-[#888] mb-1.5">Reminder Email</label>
                  <input type="email" value={settings.reminder_email} onChange={e => setSettings(s => ({ ...s, reminder_email: e.target.value }))}
                    className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" />
                </div>
              </div>
            </div>

            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-6">
              <h3 className="text-sm font-display font-bold text-white mb-4">Story Generation Settings</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="text-sm font-body text-white">Global Auto-Story Engine</div>
                    <div className="text-xs text-[#555] font-body mt-0.5">Master switch for all automated story generation</div>
                  </div>
                  <button onClick={() => setTrackerSettings(s => ({ ...s, auto_story_global_enabled: !s.auto_story_global_enabled }))}
                    className={`relative w-11 h-6 rounded-full transition-colors ${trackerSettings.auto_story_global_enabled ? 'bg-[#1D4ED8]' : 'bg-[#333]'}`}>
                    <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${trackerSettings.auto_story_global_enabled ? 'translate-x-5' : 'translate-x-0'}`} />
                  </button>
                </div>
                <div className="flex items-center justify-between">
                  <div>
                    <div className="text-sm font-body text-white">Auto-Publish Mode</div>
                    <div className="text-xs text-[#555] font-body mt-0.5">Publish stories with confidence ≥ {Math.round(trackerSettings.auto_publish_confidence_threshold * 100)}% automatically</div>
                  </div>
                  <button onClick={() => setTrackerSettings(s => ({ ...s, auto_publish_enabled: !s.auto_publish_enabled }))}
                    className={`relative w-11 h-6 rounded-full transition-colors ${trackerSettings.auto_publish_enabled ? 'bg-[#1D4ED8]' : 'bg-[#333]'}`}>
                    <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${trackerSettings.auto_publish_enabled ? 'translate-x-5' : 'translate-x-0'}`} />
                  </button>
                </div>
                <div>
                  <label className="block text-xs font-body text-[#888] mb-1.5">Mention Threshold (min mentions to qualify for auto-stories)</label>
                  <input type="number" min={1} max={20} value={trackerSettings.mention_threshold} onChange={e => setTrackerSettings(s => ({ ...s, mention_threshold: parseInt(e.target.value) }))}
                    className="w-32 bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" />
                </div>
                <div>
                  <label className="block text-xs font-body text-[#888] mb-1.5">Max Stories Per Company Per Week</label>
                  <input type="number" min={1} max={20} value={trackerSettings.max_stories_per_company_per_week} onChange={e => setTrackerSettings(s => ({ ...s, max_stories_per_company_per_week: parseInt(e.target.value) }))}
                    className="w-32 bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" />
                </div>
              </div>
            </div>

            <button onClick={handleSaveSettings} disabled={savingSettings}
              className="px-6 py-2.5 bg-[#1D4ED8] hover:bg-blue-500 text-white text-sm font-body font-semibold rounded-lg transition-colors disabled:opacity-50">
              {savingSettings ? 'Saving...' : 'Save Settings'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
