'use client';

import React, { useState, useEffect } from 'react';
import {
  Play,
  RefreshCw,
  Plus,
  Trash2,
  Settings,
  Clock,
  CheckCircle2,
  XCircle,
  Loader2,
  Globe,
  Copy,
  Check,
  AlertTriangle,
  Info,
  Newspaper,
  Search,
  Send,
  MapPin,
  ExternalLink,
  Lock,
  LogOut,
  ChevronDown,
  ChevronUp,
  Zap,
  Save
} from 'lucide-react';

// Van İlçeleri için önerilen kaynak siteleri
const DISTRICT_SOURCES = [
  { name: 'Erciş Haber', url: 'https://www.ercishaber.com/rss', district: 'Erciş' },
  { name: 'Erciş Gazetesi', url: 'https://www.ercisgazetesi.com/rss', district: 'Erciş' },
  { name: 'Özalp Haber', url: 'https://www.ozalphaber.com/rss', district: 'Özalp' },
  { name: 'Muradiye Haber', url: 'https://www.muradiyehaber.com/rss', district: 'Muradiye' },
  { name: 'Gevaş Haber', url: 'https://www.gevashaber.com/rss', district: 'Gevaş' },
  { name: 'Başkale Haber', url: 'https://www.baskalehaber.com/rss', district: 'Başkale' },
];

// Kategori grupları (timeout sorunu için parçalı çalışma)
const CATEGORY_GROUPS = [
  { id: 0, name: 'Yerel & Gündem', cats: ['yerel', 'gundem'] },
  { id: 1, name: 'Spor & Ekonomi', cats: ['spor', 'ekonomi'] },
  { id: 2, name: 'Siyaset & Yaşam', cats: ['siyaset', 'yasam'] },
  { id: 3, name: 'Sağlık & Eğitim', cats: ['saglik', 'egitim'] },
  { id: 4, name: 'Teknoloji & Kültür', cats: ['teknoloji', 'kultur'] },
  { id: 5, name: 'Dünya & Adliye', cats: ['dunya', 'adliye'] },
];

// Site kategorileri (haber düzenleme için)
const SITE_CATEGORIES = ['Gündem', 'Yerel', 'Spor', 'Ekonomi', 'Siyaset', 'Yaşam', 'Sağlık', 'Eğitim', 'Teknoloji', 'Kültür & Sanat', 'Dünya', 'Adliye & Güvenlik'];

interface RSSSource {
  name: string;
  url: string;
  isLocal?: boolean;
}

interface Category {
  id: string;
  name: string;
  icon: string;
  color: string;
  sources: RSSSource[];
  enabled: boolean;
}

interface BotResult {
  success: boolean;
  message: string;
  stats?: {
    totalFound: number;
    processed: number;
    added: number;
    skipped: number;
    errors: number;
    aiSuccess: number;
    aiFailed: number;
    categories: string[];
  };
  duration?: string;
  timestamp?: string;
}

// Admin şifresi (hash olarak saklanabilir ama basit tutuyoruz)
const ADMIN_PASSWORD = 'Sgb3297282++';

export default function BotAdminPage() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [password, setPassword] = useState('');
  const [loginError, setLoginError] = useState('');

  const [categories, setCategories] = useState<Category[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [result, setResult] = useState<BotResult | null>(null);
  const [copied, setCopied] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'categories' | 'run' | 'cron' | 'index' | 'districts' | 'articles' | 'ads' | 'backlinks'>('categories');
  const [indexResult, setIndexResult] = useState<{ success: boolean; message: string; urlCount?: number } | null>(null);
  const [isIndexing, setIsIndexing] = useState(false);
  const [expandedCategory, setExpandedCategory] = useState<string | null>(null);

  // Index istatistikleri
  const [indexStats, setIndexStats] = useState<{
    site: { totalArticles: number; todayArticles: number; weekArticles: number; sitemapCount: number };
    google: { indexed: number; error?: string };
    bing: { indexed: number; error?: string };
    yandex: { indexed: number; error?: string };
  } | null>(null);
  const [isLoadingStats, setIsLoadingStats] = useState(false);

  // Reklam yönetimi
  const [adSettings, setAdSettings] = useState<Record<string, {
    name: string;
    description: string;
    size: string;
    enabled: boolean;
    code: string;
  }>>({});
  const [isLoadingAds, setIsLoadingAds] = useState(false);
  const [adSaveStatus, setAdSaveStatus] = useState<string | null>(null);

  // Backlink yönetimi
  interface Backlink {
    id: string;
    title: string;
    url: string;
    placement: 'footer' | 'article' | 'category' | 'sidebar' | 'all';
    dofollow: boolean;
    enabled: boolean;
    order: number;
    description?: string;
  }
  const [backlinks, setBacklinks] = useState<Backlink[]>([]);
  const [isLoadingBacklinks, setIsLoadingBacklinks] = useState(false);
  const [backlinkSaveStatus, setBacklinkSaveStatus] = useState<string | null>(null);

  // Haber yönetimi
  const [articles, setArticles] = useState<Array<{
    id: string;
    title: string;
    category: string;
    source: string;
    createdAt: string;
    slug: string;
    imageUrl: string | null;
  }>>([]);
  const [articleSearch, setArticleSearch] = useState('');
  const [isLoadingArticles, setIsLoadingArticles] = useState(false);
  const [articlePage, setArticlePage] = useState(1);
  const [totalArticles, setTotalArticles] = useState(0);
  const [editingArticle, setEditingArticle] = useState<{
    id: string;
    title: string;
    category: string;
  } | null>(null);


  // Oturum kontrolü - localStorage'dan
  useEffect(() => {
    const savedAuth = sessionStorage.getItem('vsd_admin_auth');
    if (savedAuth === 'true') {
      setIsAuthenticated(true);
    }
  }, []);

  // Giriş yap
  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (password === ADMIN_PASSWORD) {
      setIsAuthenticated(true);
      sessionStorage.setItem('vsd_admin_auth', 'true');
      setLoginError('');
    } else {
      setLoginError('Hatalı şifre!');
    }
  };

  // Çıkış yap
  const handleLogout = () => {
    setIsAuthenticated(false);
    sessionStorage.removeItem('vsd_admin_auth');
  };

  // Veritabanından kategorileri yükle
  const [categoriesLoading, setCategoriesLoading] = useState(true);
  const [categoriesFromDb, setCategoriesFromDb] = useState(false);

  useEffect(() => {
    async function loadCategories() {
      try {
        const response = await fetch('/api/bot-sources');
        const data = await response.json();
        if (data.categories) {
          setCategories(data.categories);
          setCategoriesFromDb(data.fromDb);
        }
      } catch (error) {
        console.error('Kategori yükleme hatası:', error);
      } finally {
        setCategoriesLoading(false);
      }
    }
    loadCategories();
  }, []);

  // Kategorileri veritabanına kaydet
  const saveCategories = async (newCategories: Category[]) => {
    setCategories(newCategories);
    try {
      await fetch('/api/bot-sources', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ categories: newCategories }),
      });
      setCategoriesFromDb(true);
    } catch (error) {
      console.error('Kategori kaydetme hatası:', error);
    }
  };

  // Kategori toggle (aktif/pasif)
  const toggleCategory = async (categoryId: string) => {
    const updated = categories.map(cat =>
      cat.id === categoryId ? { ...cat, enabled: !cat.enabled } : cat
    );
    await saveCategories(updated);
  };

  // Kategoriye kaynak ekle
  const addSourceToCategory = async (categoryId: string, source: RSSSource) => {
    const updated = categories.map(cat =>
      cat.id === categoryId
        ? { ...cat, sources: [...cat.sources, source] }
        : cat
    );
    await saveCategories(updated);
  };

  // Kategoriden kaynak sil
  const removeSourceFromCategory = async (categoryId: string, sourceIndex: number) => {
    if (confirm('Bu kaynağı silmek istediğinizden emin misiniz?')) {
      const updated = categories.map(cat =>
        cat.id === categoryId
          ? { ...cat, sources: cat.sources.filter((_, i) => i !== sourceIndex) }
          : cat
      );
      await saveCategories(updated);
    }
  };

  // Yeni kaynak state (her kategori için ayrı)
  const [newSourceForCategory, setNewSourceForCategory] = useState<Record<string, { name: string; url: string; isLocal: boolean }>>({});

  // Botu çalıştır (grup parametresi opsiyonel)
  const runBot = async (groupId?: number) => {
    setIsRunning(true);
    setResult(null);

    try {
      // Grup veya kategori parametresi ile URL oluştur
      let url = '/api/fetch-news';
      if (groupId !== undefined) {
        url = `/api/fetch-news?group=${groupId}`;
      }

      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });

      // Timeout veya hata kontrolü
      if (!response.ok) {
        if (response.status === 504) {
          setResult({
            success: false,
            message: 'Zaman aşımı! İşlem çok uzun sürdü. Lütfen grup bazlı çalıştırmayı deneyin.',
          });
          return;
        }
        throw new Error(`HTTP ${response.status}`);
      }

      const text = await response.text();

      // JSON parse kontrolü
      try {
        const data = JSON.parse(text);
        setResult(data);
      } catch {
        setResult({
          success: false,
          message: 'Sunucu geçersiz yanıt döndürdü. Lütfen tekrar deneyin.',
        });
      }
    } catch (error) {
      setResult({
        success: false,
        message: `Bağlantı hatası: ${error}`,
      });
    } finally {
      setIsRunning(false);
    }
  };

  // Tek kategori çalıştır
  const runCategory = async (categoryId: string) => {
    setIsRunning(true);
    setResult(null);

    try {
      const response = await fetch(`/api/fetch-news?cat=${categoryId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });

      if (!response.ok) {
        if (response.status === 504) {
          setResult({ success: false, message: 'Zaman aşımı!' });
          return;
        }
        throw new Error(`HTTP ${response.status}`);
      }

      const data = await response.json();
      setResult(data);
    } catch (error) {
      setResult({ success: false, message: `Hata: ${error}` });
    } finally {
      setIsRunning(false);
    }
  };

  // Kopyala
  const copyToClipboard = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopied(id);
    setTimeout(() => setCopied(null), 2000);
  };

  // Reklam ayarlarını yükle
  const loadAdSettings = async () => {
    setIsLoadingAds(true);
    try {
      const response = await fetch('/api/ads');
      const data = await response.json();
      if (data.success && data.ads) {
        setAdSettings(data.ads);
      }
    } catch (error) {
      console.error('Reklam ayarları yüklenemedi:', error);
    } finally {
      setIsLoadingAds(false);
    }
  };

  // Reklam ayarlarını kaydet
  const saveAdSettings = async () => {
    setAdSaveStatus('saving');
    try {
      const response = await fetch('/api/ads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ads: adSettings }),
      });
      const data = await response.json();
      if (data.success) {
        setAdSaveStatus('saved');
        setTimeout(() => setAdSaveStatus(null), 2000);
      } else {
        setAdSaveStatus('error');
      }
    } catch (error) {
      setAdSaveStatus('error');
    }
  };

  // Reklam tab açıldığında yükle
  useEffect(() => {
    if (activeTab === 'ads' && isAuthenticated) {
      loadAdSettings();
    }
  }, [activeTab, isAuthenticated]);

  // Backlink yükleme
  const loadBacklinks = async () => {
    setIsLoadingBacklinks(true);
    try {
      const response = await fetch('/api/backlinks');
      const data = await response.json();
      if (data.success && data.allBacklinks) {
        setBacklinks(data.allBacklinks);
      }
    } catch (error) {
      console.error('Backlink yüklenemedi:', error);
    } finally {
      setIsLoadingBacklinks(false);
    }
  };

  // Backlink kaydetme
  const saveBacklinks = async () => {
    setBacklinkSaveStatus('saving');
    try {
      const response = await fetch('/api/backlinks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ backlinks }),
      });
      const data = await response.json();
      if (data.success) {
        setBacklinkSaveStatus('saved');
        setTimeout(() => setBacklinkSaveStatus(null), 2000);
      } else {
        setBacklinkSaveStatus('error');
      }
    } catch (error) {
      setBacklinkSaveStatus('error');
    }
  };

  // Yeni backlink ekleme
  const addBacklink = () => {
    const newBacklink: Backlink = {
      id: `bl_${Date.now()}`,
      title: '',
      url: '',
      placement: 'footer',
      dofollow: true,
      enabled: true,
      order: backlinks.length,
    };
    setBacklinks([...backlinks, newBacklink]);
  };

  // Backlink silme
  const removeBacklink = (id: string) => {
    setBacklinks(backlinks.filter(bl => bl.id !== id));
  };

  // Backlink güncelleme
  const updateBacklink = (id: string, field: keyof Backlink, value: any) => {
    setBacklinks(backlinks.map(bl => 
      bl.id === id ? { ...bl, [field]: value } : bl
    ));
  };

  // Backlink tab açıldığında yükle
  useEffect(() => {
    if (activeTab === 'backlinks' && isAuthenticated && backlinks.length === 0) {
      loadBacklinks();
    }
  }, [activeTab, isAuthenticated]);

  // Index istatistiklerini yükle
  const loadIndexStats = async () => {
    setIsLoadingStats(true);
    try {
      const response = await fetch('/api/index-stats');
      const data = await response.json();
      if (data.success) {
        setIndexStats(data.stats);
      }
    } catch (error) {
      console.error('Index stats yüklenemedi:', error);
    } finally {
      setIsLoadingStats(false);
    }
  };

  // Index tab açıldığında istatistikleri yükle
  useEffect(() => {
    if (activeTab === 'index' && isAuthenticated) {
      loadIndexStats();
    }
  }, [activeTab, isAuthenticated]);

  // Google/Bing indexleme
  const runGooglePing = async (hours: number = 24) => {
    setIsIndexing(true);
    setIndexResult(null);

    try {
      const response = await fetch('/api/google-ping', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ hours }),
      });

      const data = await response.json();
      setIndexResult({
        success: data.success,
        message: data.message,
        urlCount: data.urlCount,
      });
    } catch (error) {
      setIndexResult({
        success: false,
        message: `Hata: ${error}`,
      });
    } finally {
      setIsIndexing(false);
    }
  };

  // Haberleri getir
  const fetchArticles = async (search: string = '', page: number = 1) => {
    setIsLoadingArticles(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: '20',
        admin: 'true',
      });
      if (search) params.set('search', search);

      const response = await fetch(`/api/articles?${params}`);
      const data = await response.json();

      setArticles(data.articles || []);
      setTotalArticles(data.total || 0);
      setArticlePage(page);
    } catch (error) {
      console.error('Haber getirme hatası:', error);
    } finally {
      setIsLoadingArticles(false);
    }
  };

  // Haber sil
  const deleteArticle = async (id: string, title: string) => {
    if (!confirm(`"${title.substring(0, 50)}..." haberini silmek istediğinizden emin misiniz?`)) {
      return;
    }

    try {
      const response = await fetch(`/api/articles?id=${id}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        setArticles(prev => prev.filter(a => a.id !== id));
        setTotalArticles(prev => prev - 1);
      } else {
        alert('Silme işlemi başarısız!');
      }
    } catch (error) {
      alert(`Hata: ${error}`);
    }
  };

  // Haber düzenle
  const updateArticle = async () => {
    if (!editingArticle) return;

    try {
      const response = await fetch('/api/articles', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: editingArticle.id,
          title: editingArticle.title,
          category: editingArticle.category,
        }),
      });

      if (response.ok) {
        setArticles(prev => prev.map(a =>
          a.id === editingArticle.id
            ? { ...a, title: editingArticle.title, category: editingArticle.category }
            : a
        ));
        setEditingArticle(null);
      } else {
        alert('Güncelleme başarısız!');
      }
    } catch (error) {
      alert(`Hata: ${error}`);
    }
  };

  // Haberler sekmesi açıldığında yükle
  useEffect(() => {
    if (activeTab === 'articles' && articles.length === 0) {
      fetchArticles();
    }
  }, [activeTab]);

  // Cron URL'leri
  const siteUrl = typeof window !== 'undefined' ? window.location.origin : 'https://vansondakika.com.tr';
  const cronUrlSequential = `${siteUrl}/api/fetch-news?seq=1`; // SIRALI MOD - Her çağrıda 1 kategori
  const cronUrl = `${siteUrl}/api/fetch-news`; // Tüm kategoriler

  // Giriş ekranı
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4">
        <div className="w-full max-w-md">
          <div className="bg-white rounded-2xl shadow-xl p-8">
            <div className="text-center mb-8">
              <div className="w-16 h-16 bg-red-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <Lock className="w-8 h-8 text-red-600" />
              </div>
              <h1 className="text-2xl font-bold text-gray-900">Admin Girişi</h1>
              <p className="text-gray-500 text-sm mt-2">Bot yönetim paneline erişmek için şifre girin</p>
            </div>

            <form onSubmit={handleLogin} className="space-y-4">
              {loginError && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm flex items-center gap-2">
                  <XCircle className="w-4 h-4" />
                  {loginError}
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Şifre</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent outline-none"
                  placeholder="••••••••"
                  autoFocus
                />
              </div>

              <button
                type="submit"
                className="w-full py-3 bg-red-600 text-white rounded-lg font-bold hover:bg-red-700 transition-colors flex items-center justify-center gap-2"
              >
                <Lock className="w-4 h-4" />
                Giriş Yap
              </button>
            </form>

            <div className="mt-6 text-center">
              <a href="/" className="text-sm text-gray-500 hover:text-red-600">
                ← Ana Sayfaya Dön
              </a>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-6xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-red-100 rounded-xl">
                <Settings className="w-6 h-6 text-red-600" />
              </div>
              <div>
                <h1 className="text-xl font-bold text-gray-900">Haber Botu Yönetimi</h1>
                <p className="text-sm text-gray-500">RSS kaynakları ve otomatik haber çekme</p>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <a href="/" className="text-sm text-gray-500 hover:text-red-600">
                ← Ana Sayfa
              </a>
              <button
                onClick={handleLogout}
                className="flex items-center gap-2 px-3 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm hover:bg-red-100 hover:text-red-600 transition-colors"
              >
                <LogOut className="w-4 h-4" />
                Çıkış
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-4 py-8">
        {/* Tabs */}
        <div className="flex flex-wrap gap-2 mb-6">
          <button
            onClick={() => setActiveTab('categories')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'categories'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <Globe className="w-4 h-4 inline mr-2" />
            Kategoriler & Kaynaklar
          </button>
          <button
            onClick={() => setActiveTab('run')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'run'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <Play className="w-4 h-4 inline mr-2" />
            Botu Çalıştır
          </button>
          <button
            onClick={() => setActiveTab('cron')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'cron'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <Clock className="w-4 h-4 inline mr-2" />
            Cron Ayarları
          </button>
          <button
            onClick={() => setActiveTab('index')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'index'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <Search className="w-4 h-4 inline mr-2" />
            Google Index
          </button>
          <button
            onClick={() => setActiveTab('districts')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'districts'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <MapPin className="w-4 h-4 inline mr-2" />
            İlçeler
          </button>
          <button
            onClick={() => setActiveTab('articles')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'articles'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            <Newspaper className="w-4 h-4 inline mr-2" />
            Haberler
          </button>
          <button
            onClick={() => setActiveTab('ads')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'ads'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            📢 Reklamlar
          </button>
          <button
            onClick={() => setActiveTab('backlinks')}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              activeTab === 'backlinks'
                ? 'bg-red-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            🔗 Backlinks
          </button>
        </div>

        {/* KATEGORİLER TAB */}
        {activeTab === 'categories' && (
          <div className="space-y-6">
            {/* Durum */}
            <div className={`rounded-2xl p-4 border ${categoriesFromDb ? 'bg-green-50 border-green-200' : 'bg-yellow-50 border-yellow-200'}`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  {categoriesLoading ? (
                    <Loader2 className="w-5 h-5 animate-spin text-gray-500" />
                  ) : categoriesFromDb ? (
                    <CheckCircle2 className="w-5 h-5 text-green-600" />
                  ) : (
                    <AlertTriangle className="w-5 h-5 text-yellow-600" />
                  )}
                  <span className={`font-medium ${categoriesFromDb ? 'text-green-800' : 'text-yellow-800'}`}>
                    {categoriesLoading ? 'Kategoriler yükleniyor...' : categoriesFromDb ? 'Kategoriler veritabanından yüklendi ✓' : 'Varsayılan kategoriler (Kaydet butonuna basın)'}
                  </span>
                </div>
                {!categoriesFromDb && !categoriesLoading && (
                  <button
                    onClick={() => saveCategories(categories)}
                    className="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700"
                  >
                    Kaydet
                  </button>
                )}
              </div>
            </div>

            {/* İstatistikler */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="bg-blue-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-blue-600">{categories.length}</div>
                <div className="text-xs text-gray-600">Toplam Kategori</div>
              </div>
              <div className="bg-green-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-green-600">{categories.filter(c => c.enabled).length}</div>
                <div className="text-xs text-gray-600">Aktif Kategori</div>
              </div>
              <div className="bg-purple-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-purple-600">{categories.reduce((sum, c) => sum + c.sources.length, 0)}</div>
                <div className="text-xs text-gray-600">Toplam Kaynak</div>
              </div>
              <div className="bg-amber-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-amber-600">{categories.filter(c => c.sources.some(s => s.isLocal)).length}</div>
                <div className="text-xs text-gray-600">Yerel Kaynaklı</div>
              </div>
            </div>

            {/* Kategori Listesi */}
            <div className="space-y-4">
              {categories.map(category => (
                <div key={category.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                  {/* Kategori Başlık */}
                  <div
                    className={`p-4 flex items-center justify-between cursor-pointer transition-colors ${
                      category.enabled ? 'bg-gradient-to-r from-green-50 to-white' : 'bg-gray-50'
                    }`}
                    onClick={() => setExpandedCategory(expandedCategory === category.id ? null : category.id)}
                  >
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">{category.icon}</span>
                      <div>
                        <h3 className="font-bold text-gray-900">{category.name}</h3>
                        <p className="text-xs text-gray-500">{category.sources.length} kaynak</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      {/* Çalıştır butonu */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          runCategory(category.id);
                        }}
                        disabled={isRunning || !category.enabled}
                        className="px-3 py-1.5 bg-blue-600 text-white text-xs font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-1"
                      >
                        <Zap className="w-3 h-3" />
                        Çalıştır
                      </button>
                      {/* Toggle */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleCategory(category.id);
                        }}
                        className={`w-12 h-6 rounded-full transition-colors relative ${
                          category.enabled ? 'bg-green-500' : 'bg-gray-300'
                        }`}
                      >
                        <span
                          className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-all ${
                            category.enabled ? 'right-1' : 'left-1'
                          }`}
                        />
                      </button>
                      {/* Expand/Collapse */}
                      {expandedCategory === category.id ? (
                        <ChevronUp className="w-5 h-5 text-gray-400" />
                      ) : (
                        <ChevronDown className="w-5 h-5 text-gray-400" />
                      )}
                    </div>
                  </div>

                  {/* Kategori İçeriği (Genişletilmiş) */}
                  {expandedCategory === category.id && (
                    <div className="border-t border-gray-100 p-4">
                      {/* Kaynak Listesi */}
                      <div className="space-y-2 mb-4">
                        {category.sources.map((source, idx) => (
                          <div
                            key={idx}
                            className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                          >
                            <div>
                              <div className="flex items-center gap-2">
                                <span className="font-medium text-gray-800">{source.name}</span>
                                {source.isLocal && (
                                  <span className="text-[10px] px-2 py-0.5 bg-green-100 text-green-700 rounded-full font-bold">YEREL</span>
                                )}
                              </div>
                              <span className="text-xs text-gray-500">{source.url}</span>
                            </div>
                            <button
                              onClick={() => removeSourceFromCategory(category.id, idx)}
                              className="p-2 text-red-500 hover:bg-red-100 rounded-lg"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        ))}
                      </div>

                      {/* Yeni Kaynak Ekle */}
                      <div className="flex gap-2">
                        <input
                          type="text"
                          placeholder="Kaynak Adı"
                          value={newSourceForCategory[category.id]?.name || ''}
                          onChange={(e) => setNewSourceForCategory({
                            ...newSourceForCategory,
                            [category.id]: { ...newSourceForCategory[category.id], name: e.target.value }
                          })}
                          className="flex-1 px-3 py-2 text-sm border border-gray-200 rounded-lg"
                        />
                        <input
                          type="url"
                          placeholder="RSS URL"
                          value={newSourceForCategory[category.id]?.url || ''}
                          onChange={(e) => setNewSourceForCategory({
                            ...newSourceForCategory,
                            [category.id]: { ...newSourceForCategory[category.id], url: e.target.value }
                          })}
                          className="flex-[2] px-3 py-2 text-sm border border-gray-200 rounded-lg"
                        />
                        <label className="flex items-center gap-1 text-xs text-gray-600">
                          <input
                            type="checkbox"
                            checked={newSourceForCategory[category.id]?.isLocal || false}
                            onChange={(e) => setNewSourceForCategory({
                              ...newSourceForCategory,
                              [category.id]: { ...newSourceForCategory[category.id], isLocal: e.target.checked }
                            })}
                            className="rounded"
                          />
                          Yerel
                        </label>
                        <button
                          onClick={() => {
                            const src = newSourceForCategory[category.id];
                            if (src?.name && src?.url) {
                              addSourceToCategory(category.id, {
                                name: src.name,
                                url: src.url,
                                isLocal: src.isLocal || false,
                              });
                              setNewSourceForCategory({
                                ...newSourceForCategory,
                                [category.id]: { name: '', url: '', isLocal: false }
                              });
                            }
                          }}
                          className="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700"
                        >
                          <Plus className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* BOTU ÇALIŞTIR TAB */}
        {activeTab === 'run' && (
          <div className="space-y-6">
            {/* Durum */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Play className="w-5 h-5 text-green-600" />
                Haber Botu
              </h2>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div className="p-4 bg-blue-50 rounded-xl">
                  <div className="text-2xl font-bold text-blue-600">{categories.filter(c => c.enabled).length}</div>
                  <div className="text-sm text-gray-600">Aktif Kategori</div>
                </div>
                <div className="p-4 bg-green-50 rounded-xl">
                  <div className="text-2xl font-bold text-green-600">{categories.reduce((sum, c) => sum + c.sources.length, 0)}</div>
                  <div className="text-sm text-gray-600">Toplam Kaynak</div>
                </div>
                <div className="p-4 bg-purple-50 rounded-xl">
                  <div className="text-2xl font-bold text-purple-600">{categories.filter(c => c.sources.some(s => s.isLocal)).length}</div>
                  <div className="text-sm text-gray-600">Yerel Kaynaklı Kategori</div>
                </div>
              </div>

              {/* Grup bazlı butonlar (timeout sorunu için) */}
              <div className="mb-4">
                <h3 className="text-sm font-medium text-gray-500 mb-3">⚡ Hızlı Çalıştır (Timeout Sorunu Varsa)</h3>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {CATEGORY_GROUPS.map(group => (
                    <button
                      key={group.id}
                      onClick={() => runBot(group.id)}
                      disabled={isRunning}
                      className={`py-3 px-4 rounded-lg font-medium text-sm transition-all ${
                        isRunning
                          ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                          : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                      }`}
                    >
                      {group.name}
                    </button>
                  ))}
                </div>
              </div>

              <div className="text-center text-sm text-gray-500 mb-2">veya</div>

              <button
                onClick={() => runBot()}
                disabled={isRunning}
                className={`w-full py-4 rounded-xl font-bold text-lg transition-all flex items-center justify-center gap-3 ${
                  isRunning
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    : 'bg-gradient-to-r from-red-600 to-red-700 text-white hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl'
                }`}
              >
                {isRunning ? (
                  <>
                    <Loader2 className="w-6 h-6 animate-spin" />
                    Haberler Çekiliyor...
                  </>
                ) : (
                  <>
                    <Play className="w-6 h-6" />
                    Tümünü Çalıştır (8 Kategori)
                  </>
                )}
              </button>
            </div>

            {/* Sonuç */}
            {result && (
              <div className={`bg-white rounded-2xl p-6 shadow-sm border ${
                result.success ? 'border-green-200' : 'border-red-200'
              }`}>
                <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                  {result.success ? (
                    <CheckCircle2 className="w-5 h-5 text-green-600" />
                  ) : (
                    <XCircle className="w-5 h-5 text-red-600" />
                  )}
                  Sonuç
                </h2>

                <p className={`mb-4 ${result.success ? 'text-green-600' : 'text-red-600'}`}>
                  {result.message}
                </p>

                {result.stats && (
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                    <div className="p-3 bg-blue-50 rounded-lg text-center">
                      <div className="text-xl font-bold text-blue-600">{result.stats.totalFound}</div>
                      <div className="text-xs text-gray-600">Toplam Bulundu</div>
                    </div>
                    <div className="p-3 bg-green-50 rounded-lg text-center">
                      <div className="text-xl font-bold text-green-600">{result.stats.added}</div>
                      <div className="text-xs text-gray-600">Eklendi</div>
                    </div>
                    <div className="p-3 bg-yellow-50 rounded-lg text-center">
                      <div className="text-xl font-bold text-yellow-600">{result.stats.skipped}</div>
                      <div className="text-xs text-gray-600">Atlandı (Mevcut)</div>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg text-center">
                      <div className="text-xl font-bold text-purple-600">{result.stats.aiSuccess}</div>
                      <div className="text-xs text-gray-600">AI Başarılı</div>
                    </div>
                  </div>
                )}

                {result.stats?.categories && result.stats.categories.length > 0 && (
                  <div className="mt-4 p-4 bg-gray-50 rounded-lg">
                    <h4 className="font-medium text-gray-700 mb-2">Eklenen Kategoriler:</h4>
                    <div className="flex flex-wrap gap-2">
                      {result.stats.categories.map(cat => (
                        <span key={cat} className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm">
                          {cat}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {result.duration && (
                  <p className="text-sm text-gray-500 mt-4">
                    İşlem süresi: {result.duration}
                  </p>
                )}
              </div>
            )}
          </div>
        )}

        {/* CRON AYARLARI TAB */}
        {activeTab === 'cron' && (
          <div className="space-y-6">
            {/* Bilgi */}
            <div className="bg-green-50 rounded-2xl p-6 border border-green-100">
              <div className="flex items-start gap-3">
                <Zap className="w-6 h-6 text-green-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="font-bold text-green-900 mb-2">🔄 Sıralı Çalışma Modu (Önerilen)</h3>
                  <p className="text-green-800 text-sm">
                    Bot her çalıştığında sıradaki <strong>1 kategoriden 1 haber</strong> ekler.
                    Örneğin {categories.filter(c => c.enabled).length} aktif kategori varsa ve cron her 2 saatte çalışırsa,
                    günde {Math.floor(24/2)} çalışma = tüm kategoriler {Math.floor(Math.floor(24/2) / categories.filter(c => c.enabled).length)} kez güncellenir.
                  </p>
                </div>
              </div>
            </div>

            {/* SIRALI MOD URL */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-green-200">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Globe className="w-5 h-5 text-green-600" />
                ⭐ Sıralı Mod URL (Önerilen)
              </h2>
              <p className="text-sm text-gray-600 mb-3">
                Her çağrıda sıradaki kategoriden 1 haber ekler. Timeout sorunu olmaz!
              </p>
              <div className="flex items-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200">
                <code className="flex-1 text-sm text-gray-700 overflow-x-auto">{cronUrlSequential}</code>
                <button
                  onClick={() => copyToClipboard(cronUrlSequential, 'seq')}
                  className="p-2 hover:bg-green-100 rounded-lg transition-colors"
                >
                  {copied === 'seq' ? <Check className="w-4 h-4 text-green-600" /> : <Copy className="w-4 h-4 text-gray-600" />}
                </button>
              </div>
            </div>

            {/* Plesk Cron Ayarı */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Clock className="w-5 h-5 text-purple-600" />
                Plesk'te Cron Job Ekleme
              </h2>

              <div className="space-y-4">
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium text-gray-900 mb-2">1. Plesk Paneli Açın</h4>
                  <p className="text-sm text-gray-600">
                    Plesk Panel → Web Sitesi → vansondakika.com.tr → Zamanlanan Görevler (Scheduled Tasks)
                  </p>
                </div>

                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <h4 className="font-medium text-green-900 mb-2">2. ⭐ Sıralı Mod Komutu (Önerilen)</h4>
                  <p className="text-sm text-green-800 mb-3">
                    Her 2 saatte bir çalışsın - günde tüm kategoriler güncellenir:
                  </p>
                  <div className="flex items-center gap-2 p-3 bg-gray-900 rounded-lg">
                    <code className="flex-1 text-sm text-green-400 overflow-x-auto">
                      curl -s "{cronUrlSequential}" &gt; /dev/null 2&gt;&amp;1
                    </code>
                    <button
                      onClick={() => copyToClipboard(`curl -s "${cronUrlSequential}" > /dev/null 2>&1`, 'cmd')}
                      className="p-2 hover:bg-gray-700 rounded-lg transition-colors"
                    >
                      {copied === 'cmd' ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4 text-gray-400" />}
                    </button>
                  </div>
                </div>

                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium text-gray-900 mb-2">3. Zamanlama (Önerilen: Her 2 Saatte)</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-3">
                    <div className="p-3 border-2 border-green-500 rounded-lg bg-green-50">
                      <div className="font-medium text-green-900">✅ Her 2 Saatte (Önerilen)</div>
                      <code className="text-xs text-green-700 block mt-1">0 */2 * * *</code>
                      <p className="text-xs text-green-600 mt-1">Günde 12 çalışma = Her kategori güncellenir</p>
                    </div>
                    <div className="p-3 border border-gray-200 rounded-lg">
                      <div className="font-medium text-gray-900">Her Saat</div>
                      <code className="text-xs text-gray-500 block mt-1">0 * * * *</code>
                      <p className="text-xs text-gray-400 mt-1">Günde 24 çalışma = Daha sık güncelleme</p>
                    </div>
                    <div className="p-3 border border-gray-200 rounded-lg">
                      <div className="font-medium text-gray-900">Her 3 Saatte</div>
                      <code className="text-xs text-gray-500 block mt-1">0 */3 * * *</code>
                    </div>
                    <div className="p-3 border border-gray-200 rounded-lg">
                      <div className="font-medium text-gray-900">Her 4 Saatte</div>
                      <code className="text-xs text-gray-500 block mt-1">0 */4 * * *</code>
                    </div>
                  </div>
                </div>

                {/* Nasıl çalışıyor */}
                <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                  <h4 className="font-medium text-blue-900 mb-2">📊 Sıralı Mod Nasıl Çalışıyor?</h4>
                  <div className="text-sm text-blue-800 space-y-1">
                    <p>1. Çalışma → Gündem kategorisinden 1 haber</p>
                    <p>2. Çalışma → Ekonomi kategorisinden 1 haber</p>
                    <p>3. Çalışma → Yerel kategorisinden 1 haber</p>
                    <p>... ve devam eder</p>
                    <p className="font-medium mt-2">Son kategoriye gelince başa döner!</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Alternatif */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <RefreshCw className="w-5 h-5 text-orange-600" />
                Alternatif: wget
              </h2>
              <div className="flex items-center gap-2 p-3 bg-gray-900 rounded-lg">
                <code className="flex-1 text-sm text-green-400 overflow-x-auto">
                  wget -q -O /dev/null "{cronUrlSequential}"
                </code>
                <button
                  onClick={() => copyToClipboard(`wget -q -O /dev/null "${cronUrlSequential}"`, 'wget')}
                  className="p-2 hover:bg-gray-700 rounded-lg transition-colors"
                >
                  {copied === 'wget' ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4 text-gray-400" />}
                </button>
              </div>
            </div>

            {/* Bilgi */}
            <div className="bg-blue-50 rounded-2xl p-6 border border-blue-100">
              <div className="flex items-start gap-3">
                <Info className="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="font-bold text-blue-900 mb-2">Önemli Notlar</h3>
                  <ul className="text-blue-800 text-sm space-y-1 list-disc list-inside">
                    <li>Sıralı mod her çalışmada sadece 1 kategoriden 1 haber ekler</li>
                    <li>Timeout sorunu yaşamazsınız çünkü işlem çok kısa sürer</li>
                    <li>Günde {categories.filter(c => c.enabled).length} kategori = her 2 saatte bir çalışırsa günde ~{Math.floor(24/2)} haber</li>
                    <li>Duplicate haberler otomatik atlanır</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* GOOGLE INDEX TAB */}
        {activeTab === 'index' && (
          <div className="space-y-6">
            {/* Index İstatistikleri */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                  <Globe className="w-5 h-5 text-blue-600" />
                  Index İstatistikleri
                </h2>
                <button
                  onClick={loadIndexStats}
                  disabled={isLoadingStats}
                  className="px-3 py-1.5 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg flex items-center gap-2"
                >
                  {isLoadingStats ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                  Yenile
                </button>
              </div>

              {isLoadingStats ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
                </div>
              ) : indexStats ? (
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  {/* Site İstatistikleri */}
                  <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-4 text-white">
                    <div className="text-3xl font-black">{indexStats.site.totalArticles}</div>
                    <div className="text-blue-100 text-sm">Toplam Haber</div>
                  </div>

                  {/* Google */}
                  <div className="bg-gradient-to-br from-red-500 to-red-600 rounded-xl p-4 text-white">
                    <div className="text-3xl font-black">{indexStats.google.indexed || 0}</div>
                    <div className="text-red-100 text-sm">Google Index</div>
                    {indexStats.google.error && (
                      <div className="text-xs text-red-200 mt-1 truncate" title={indexStats.google.error}>
                        {indexStats.google.error.length > 20 ? '⚠️' : indexStats.google.error}
                      </div>
                    )}
                  </div>

                  {/* Bing */}
                  <div className="bg-gradient-to-br from-cyan-500 to-cyan-600 rounded-xl p-4 text-white">
                    <div className="text-3xl font-black">{indexStats.bing.indexed || 0}</div>
                    <div className="text-cyan-100 text-sm">Bing Index</div>
                    {indexStats.bing.error && (
                      <div className="text-xs text-cyan-200 mt-1 truncate">{indexStats.bing.error}</div>
                    )}
                  </div>

                  {/* Yandex */}
                  <div className="bg-gradient-to-br from-yellow-500 to-orange-500 rounded-xl p-4 text-white">
                    <div className="text-3xl font-black">{indexStats.yandex.indexed || 0}</div>
                    <div className="text-yellow-100 text-sm">Yandex Index</div>
                    {indexStats.yandex.error && (
                      <div className="text-xs text-yellow-200 mt-1 truncate">{indexStats.yandex.error}</div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  İstatistikler yüklenemedi
                </div>
              )}

              {indexStats && (
                <div className="mt-4 pt-4 border-t border-gray-100 grid grid-cols-3 gap-4 text-center">
                  <div>
                    <div className="text-2xl font-bold text-green-600">{indexStats.site.todayArticles}</div>
                    <div className="text-xs text-gray-500">Bugün Eklenen</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold text-blue-600">{indexStats.site.weekArticles}</div>
                    <div className="text-xs text-gray-500">Bu Hafta</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold text-purple-600">{indexStats.site.sitemapCount || '-'}</div>
                    <div className="text-xs text-gray-500">Sitemap&apos;te</div>
                  </div>
                </div>
              )}
            </div>

            {/* Bilgi */}
            <div className="bg-green-50 rounded-2xl p-6 border border-green-100">
              <div className="flex items-start gap-3">
                <Search className="w-6 h-6 text-green-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="font-bold text-green-900 mb-2">Google & Bing Indexleme</h3>
                  <p className="text-green-800 text-sm">
                    Yeni eklenen haberler otomatik olarak Google, Bing ve Yandex&apos;e bildirilir.
                    Google Indexing API, IndexNow ve WebSub protokolleri kullanılıyor.
                  </p>
                </div>
              </div>
            </div>

            {/* Otomatik Indexleme Durumu */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <CheckCircle2 className="w-5 h-5 text-green-600" />
                Otomatik Indexleme
              </h2>
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <div className="flex items-center gap-3">
                  <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse" />
                  <span className="font-medium text-green-800">Aktif</span>
                </div>
                <p className="text-sm text-green-700 mt-2">
                  Her haber eklendiğinde Google ve Bing&apos;e otomatik ping atılır.
                  IndexNow API ile URL&apos;ler hızlıca bildirilir.
                </p>
              </div>
            </div>

            {/* Manuel Indexleme */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Send className="w-5 h-5 text-blue-600" />
                Manuel Indexleme
              </h2>

              <p className="text-gray-600 text-sm mb-4">
                Belirli bir süre içinde eklenen haberleri manuel olarak Google&apos;a bildirebilirsiniz.
              </p>

              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
                <button
                  onClick={() => runGooglePing(6)}
                  disabled={isIndexing}
                  className={`py-3 px-4 rounded-lg font-medium text-sm transition-all ${
                    isIndexing
                      ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                  }`}
                >
                  Son 6 Saat
                </button>
                <button
                  onClick={() => runGooglePing(24)}
                  disabled={isIndexing}
                  className={`py-3 px-4 rounded-lg font-medium text-sm transition-all ${
                    isIndexing
                      ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                  }`}
                >
                  Son 24 Saat
                </button>
                <button
                  onClick={() => runGooglePing(72)}
                  disabled={isIndexing}
                  className={`py-3 px-4 rounded-lg font-medium text-sm transition-all ${
                    isIndexing
                      ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                  }`}
                >
                  Son 3 Gün
                </button>
                <button
                  onClick={() => runGooglePing(168)}
                  disabled={isIndexing}
                  className={`py-3 px-4 rounded-lg font-medium text-sm transition-all ${
                    isIndexing
                      ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                  }`}
                >
                  Son 1 Hafta
                </button>
              </div>

              <button
                onClick={() => runGooglePing(720)}
                disabled={isIndexing}
                className={`w-full py-4 rounded-xl font-bold text-lg transition-all flex items-center justify-center gap-3 ${
                  isIndexing
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    : 'bg-gradient-to-r from-green-600 to-green-700 text-white hover:from-green-700 hover:to-green-800 shadow-lg'
                }`}
              >
                {isIndexing ? (
                  <>
                    <Loader2 className="w-6 h-6 animate-spin" />
                    Gönderiliyor...
                  </>
                ) : (
                  <>
                    <Search className="w-6 h-6" />
                    Tüm Haberleri Gönder (Son 30 Gün)
                  </>
                )}
              </button>

              {/* Sonuç */}
              {indexResult && (
                <div className={`mt-4 p-4 rounded-lg ${
                  indexResult.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'
                }`}>
                  <div className="flex items-center gap-2">
                    {indexResult.success ? (
                      <CheckCircle2 className="w-5 h-5 text-green-600" />
                    ) : (
                      <XCircle className="w-5 h-5 text-red-600" />
                    )}
                    <span className={indexResult.success ? 'text-green-700' : 'text-red-700'}>
                      {indexResult.message}
                    </span>
                  </div>
                  {indexResult.urlCount && (
                    <p className="text-sm text-gray-600 mt-2">
                      Toplam {indexResult.urlCount} URL gönderildi
                    </p>
                  )}
                </div>
              )}
            </div>

            {/* Google Search Console */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Globe className="w-5 h-5 text-red-600" />
                Google Search Console
              </h2>

              <div className="space-y-4">
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium text-gray-900 mb-2">Site Doğrulama</h4>
                  <p className="text-sm text-gray-600 mb-3">
                    Google Search Console&apos;da sitenizi doğruladınız mı? Meta tag eklenmiş durumda.
                  </p>
                  <a
                    href="https://search.google.com/search-console"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:text-blue-700 text-sm font-medium"
                  >
                    Google Search Console&apos;u Aç →
                  </a>
                </div>

                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium text-gray-900 mb-2">Sitemap Gönder</h4>
                  <p className="text-sm text-gray-600 mb-3">
                    Search Console → Siteler → Sitemap bölümünden sitemap URL&apos;sini ekleyin:
                  </p>
                  <div className="flex items-center gap-2 p-3 bg-white border rounded-lg">
                    <code className="flex-1 text-sm text-gray-700">{siteUrl}/sitemap.xml</code>
                    <button
                      onClick={() => copyToClipboard(`${siteUrl}/sitemap.xml`, 'sitemap')}
                      className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                    >
                      {copied === 'sitemap' ? <Check className="w-4 h-4 text-green-600" /> : <Copy className="w-4 h-4 text-gray-600" />}
                    </button>
                  </div>
                </div>

                <div className="p-4 bg-blue-50 rounded-lg border border-blue-100">
                  <h4 className="font-medium text-blue-900 mb-2">📊 Indexleme İpuçları</h4>
                  <ul className="text-blue-800 text-sm space-y-1 list-disc list-inside">
                    <li>Yeni siteler için indexleme 1-2 hafta sürebilir</li>
                    <li>Kaliteli ve özgün içerik indexleme hızını artırır</li>
                    <li>Social media paylaşımları indexlemeyi hızlandırır</li>
                    <li>Sitemap.xml düzenli güncellenmeli (otomatik)</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* İLÇELER TAB */}
        {activeTab === 'districts' && (
          <div className="space-y-6">
            {/* Bilgi */}
            <div className="bg-blue-50 rounded-2xl p-6 border border-blue-100">
              <div className="flex items-start gap-3">
                <MapPin className="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="font-bold text-blue-900 mb-2">Van İlçe Haberleri</h3>
                  <p className="text-blue-800 text-sm">
                    Van ilçelerinden haber çekmek için aşağıdaki kaynak siteleri kullanabilirsiniz.
                    Haberlerde ilçe adı geçtiğinde otomatik olarak ilgili ilçe sayfasında listelenir.
                  </p>
                </div>
              </div>
            </div>

            {/* Otomatik İlçe Tespiti */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <CheckCircle2 className="w-5 h-5 text-green-600" />
                Otomatik İlçe Tespiti
              </h2>
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <div className="flex items-center gap-3">
                  <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse" />
                  <span className="font-medium text-green-800">Aktif</span>
                </div>
                <p className="text-sm text-green-700 mt-2">
                  Her haber eklendiğinde başlık ve içerikte ilçe adı aranır.
                  Tespit edilen ilçe otomatik olarak habere atanır ve ilçe sayfasında görünür.
                </p>
              </div>
              <div className="mt-4 grid grid-cols-3 md:grid-cols-5 gap-2">
                {['İpekyolu', 'Tuşba', 'Edremit', 'Erciş', 'Özalp', 'Çaldıran', 'Muradiye', 'Başkale', 'Gürpınar', 'Gevaş', 'Saray', 'Çatak', 'Bahçesaray'].map(district => (
                  <a
                    key={district}
                    href={`/ilce/${district.toLowerCase().replace('ı', 'i').replace('ş', 's').replace('ö', 'o').replace('ü', 'u').replace('ç', 'c').replace('ğ', 'g')}`}
                    className="px-3 py-2 bg-gray-100 rounded-lg text-sm text-center hover:bg-red-100 hover:text-red-700 transition-colors"
                  >
                    {district}
                  </a>
                ))}
              </div>
            </div>

            {/* Önerilen İlçe Kaynakları */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Newspaper className="w-5 h-5 text-purple-600" />
                Önerilen İlçe Haber Kaynakları
              </h2>
              <p className="text-gray-600 text-sm mb-4">
                Bu kaynakları ekleyerek ilçe haberlerini zenginleştirebilirsiniz.
                Not: Bazı siteler RSS desteği sunmayabilir, önce kontrol edin.
              </p>
              <div className="space-y-3">
                {DISTRICT_SOURCES.map((source, i) => (
                  <div key={i} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg border border-gray-200">
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-gray-900">{source.name}</span>
                        <span className="text-xs px-2 py-0.5 bg-purple-100 text-purple-700 rounded-full">
                          {source.district}
                        </span>
                      </div>
                      <span className="text-xs text-gray-500">{source.url}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <a
                        href={source.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="p-2 text-gray-500 hover:bg-gray-200 rounded-lg transition-colors"
                        title="Kaynağı kontrol et"
                      >
                        <ExternalLink className="w-4 h-4" />
                      </a>
                      <button
                        onClick={() => {
                          const yerelCat = categories.find(c => c.id === 'yerel');
                          if (yerelCat) {
                            addSourceToCategory('yerel', { name: source.name, url: source.url, isLocal: true });
                            alert('Kaynak Yerel kategorisine eklendi!');
                          }
                        }}
                        className="px-3 py-1 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition-colors"
                      >
                        Ekle
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* İlçe Gezilecek Yerler Kaynakları */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Globe className="w-5 h-5 text-orange-600" />
                Gezilecek Yerler & Turizm Kaynakları
              </h2>
              <p className="text-gray-600 text-sm mb-4">
                Van ilçelerinin turistik yerlerini ve gezilecek noktalarını eklemek için:
              </p>
              <div className="grid md:grid-cols-2 gap-4">
                <a
                  href="https://www.kulturportali.gov.tr/turkiye/van"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-4 border border-gray-200 rounded-lg hover:border-orange-300 hover:bg-orange-50 transition-colors"
                >
                  <div className="font-medium text-gray-900">Kültür Portalı - Van</div>
                  <div className="text-sm text-gray-500">T.C. Kültür ve Turizm Bakanlığı</div>
                </a>
                <a
                  href="https://www.van.gov.tr/turizm"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-4 border border-gray-200 rounded-lg hover:border-orange-300 hover:bg-orange-50 transition-colors"
                >
                  <div className="font-medium text-gray-900">Van Valiliği - Turizm</div>
                  <div className="text-sm text-gray-500">Resmi turizm bilgileri</div>
                </a>
                <a
                  href="https://tr.wikipedia.org/wiki/Van_(il)"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-4 border border-gray-200 rounded-lg hover:border-orange-300 hover:bg-orange-50 transition-colors"
                >
                  <div className="font-medium text-gray-900">Wikipedia - Van</div>
                  <div className="text-sm text-gray-500">Genel bilgi kaynağı</div>
                </a>
                <a
                  href="https://www.tripadvisor.com.tr/Attractions-g298033-Activities-Van_Van_Province.html"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-4 border border-gray-200 rounded-lg hover:border-orange-300 hover:bg-orange-50 transition-colors"
                >
                  <div className="font-medium text-gray-900">TripAdvisor - Van</div>
                  <div className="text-sm text-gray-500">Gezgin yorumları</div>
                </a>
              </div>
            </div>

            {/* İpuçları */}
            <div className="bg-yellow-50 rounded-2xl p-6 border border-yellow-100">
              <div className="flex items-start gap-3">
                <AlertTriangle className="w-6 h-6 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="font-bold text-yellow-900 mb-2">İlçe Haberi Ekleme İpuçları</h3>
                  <ul className="text-yellow-800 text-sm space-y-1 list-disc list-inside">
                    <li>Haber başlığında veya içeriğinde ilçe adı geçmelidir</li>
                    <li>Yerel kaynaklar öncelikli olarak çekilir</li>
                    <li>İlçe sayfaları otomatik güncellenir</li>
                    <li>Kaynak RSS&apos;i çalışmıyorsa manuel haber ekleyebilirsiniz</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* HABERLER SEKMESİ */}
        {activeTab === 'articles' && (
          <div className="space-y-6">
            {/* Arama */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <Search className="w-5 h-5 text-red-600" />
                Haber Ara & Yönet
              </h2>
              <div className="flex gap-3">
                <input
                  type="text"
                  value={articleSearch}
                  onChange={(e) => setArticleSearch(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && fetchArticles(articleSearch, 1)}
                  placeholder="Haber başlığı veya kategori ara..."
                  className="flex-1 p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-red-500 focus:border-red-500"
                />
                <button
                  onClick={() => fetchArticles(articleSearch, 1)}
                  disabled={isLoadingArticles}
                  className="px-6 py-3 bg-red-600 text-white rounded-xl hover:bg-red-700 disabled:opacity-50 flex items-center gap-2"
                >
                  {isLoadingArticles ? <Loader2 className="w-5 h-5 animate-spin" /> : <Search className="w-5 h-5" />}
                  Ara
                </button>
              </div>
              <p className="text-sm text-gray-500 mt-2">
                Toplam {totalArticles} haber bulundu
              </p>
            </div>

            {/* Haber Listesi */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
              <h2 className="text-lg font-bold text-gray-900 mb-4">Haberler</h2>

              {isLoadingArticles ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-8 h-8 animate-spin text-red-600" />
                </div>
              ) : articles.length === 0 ? (
                <div className="text-center py-12 text-gray-500">
                  <Newspaper className="w-12 h-12 mx-auto mb-3 opacity-50" />
                  <p>Henüz haber yok veya arama sonucu bulunamadı</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {articles.map((article) => (
                    <div
                      key={article.id}
                      className="p-4 border border-gray-200 rounded-xl hover:border-gray-300 transition-colors"
                    >
                      <div className="flex items-start gap-4">
                        {article.imageUrl && (
                          <img
                            src={article.imageUrl}
                            alt=""
                            className="w-20 h-14 object-cover rounded-lg flex-shrink-0"
                          />
                        )}
                        <div className="flex-1 min-w-0">
                          <h3 className="font-medium text-gray-900 line-clamp-2 mb-1">
                            {article.title}
                          </h3>
                          <div className="flex items-center gap-3 text-sm text-gray-500">
                            <span className="px-2 py-0.5 bg-red-100 text-red-700 rounded-full text-xs font-medium">
                              {article.category}
                            </span>
                            <span>{article.source}</span>
                            <span>{new Date(article.createdAt).toLocaleDateString('tr-TR')}</span>
                          </div>
                        </div>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          <a
                            href={`/haber/${article.slug}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                            title="Görüntüle"
                          >
                            <ExternalLink className="w-4 h-4" />
                          </a>
                          <button
                            onClick={() => setEditingArticle({
                              id: article.id,
                              title: article.title,
                              category: article.category,
                            })}
                            className="p-2 text-gray-500 hover:text-orange-600 hover:bg-orange-50 rounded-lg transition-colors"
                            title="Düzenle"
                          >
                            <Settings className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => deleteArticle(article.id, article.title)}
                            className="p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Sil"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Sayfalama */}
              {totalArticles > 20 && (
                <div className="flex items-center justify-center gap-2 mt-6">
                  <button
                    onClick={() => fetchArticles(articleSearch, articlePage - 1)}
                    disabled={articlePage === 1 || isLoadingArticles}
                    className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                  >
                    Önceki
                  </button>
                  <span className="px-4 py-2 text-gray-600">
                    Sayfa {articlePage} / {Math.ceil(totalArticles / 20)}
                  </span>
                  <button
                    onClick={() => fetchArticles(articleSearch, articlePage + 1)}
                    disabled={articlePage >= Math.ceil(totalArticles / 20) || isLoadingArticles}
                    className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                  >
                    Sonraki
                  </button>
                </div>
              )}
            </div>

            {/* Düzenleme Modal */}
            {editingArticle && (
              <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                <div className="bg-white rounded-2xl p-6 max-w-lg w-full shadow-xl">
                  <h3 className="text-lg font-bold text-gray-900 mb-4">Haber Düzenle</h3>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Başlık</label>
                      <input
                        type="text"
                        value={editingArticle.title}
                        onChange={(e) => setEditingArticle({ ...editingArticle, title: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-red-500"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Kategori</label>
                      <select
                        value={editingArticle.category}
                        onChange={(e) => setEditingArticle({ ...editingArticle, category: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-red-500"
                      >
                        {SITE_CATEGORIES.map(cat => (
                          <option key={cat} value={cat}>{cat}</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div className="flex justify-end gap-3 mt-6">
                    <button
                      onClick={() => setEditingArticle(null)}
                      className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50"
                    >
                      İptal
                    </button>
                    <button
                      onClick={updateArticle}
                      className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
                    >
                      Kaydet
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* REKLAMLAR TAB */}
        {activeTab === 'ads' && (
          <div className="space-y-6">
            {/* Bilgi */}
            <div className="bg-gradient-to-r from-orange-50 to-amber-50 rounded-2xl p-6 border border-orange-200">
              <div className="flex items-start gap-3">
                <span className="text-2xl">📢</span>
                <div>
                  <h3 className="font-bold text-orange-900 mb-2">Reklam Yönetimi</h3>
                  <p className="text-orange-800 text-sm">
                    Aşağıdan reklam alanlarını aktif/pasif edebilir ve reklam kodlarınızı (Google AdSense, özel banner vb.) ekleyebilirsiniz.
                    Kodlar HTML formatında eklenmelidir.
                  </p>
                </div>
              </div>
            </div>

            {isLoadingAds ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="w-8 h-8 animate-spin text-red-600" />
              </div>
            ) : (
              <>
                {/* Masaüstü Reklamları */}
                <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                  <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                    🖥️ Masaüstü Reklam Alanları
                  </h2>

                  <div className="space-y-4">
                    {Object.entries(adSettings)
                      .filter(([key]) => !key.startsWith('mobile_'))
                      .map(([key, slot]) => (
                        <div key={key} className="border border-gray-200 rounded-xl p-4">
                          <div className="flex items-start justify-between mb-3">
                            <div>
                              <div className="flex items-center gap-2">
                                <h3 className="font-semibold text-gray-900">{slot.name}</h3>
                                <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">
                                  {slot.size}
                                </span>
                              </div>
                              <p className="text-sm text-gray-500">{slot.description}</p>
                            </div>
                            <label className="relative inline-flex items-center cursor-pointer">
                              <input
                                type="checkbox"
                                checked={slot.enabled}
                                onChange={(e) => setAdSettings({
                                  ...adSettings,
                                  [key]: { ...slot, enabled: e.target.checked }
                                })}
                                className="sr-only peer"
                              />
                              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-red-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-red-600"></div>
                            </label>
                          </div>
                          <textarea
                            value={slot.code}
                            onChange={(e) => setAdSettings({
                              ...adSettings,
                              [key]: { ...slot, code: e.target.value }
                            })}
                            placeholder="Reklam kodunu buraya yapıştırın (HTML)"
                            className="w-full h-24 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                          />
                        </div>
                      ))}
                  </div>
                </div>

                {/* Mobil Reklamları */}
                <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                  <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                    📱 Mobil Reklam Alanları
                  </h2>

                  <div className="space-y-4">
                    {Object.entries(adSettings)
                      .filter(([key]) => key.startsWith('mobile_'))
                      .map(([key, slot]) => (
                        <div key={key} className="border border-gray-200 rounded-xl p-4">
                          <div className="flex items-start justify-between mb-3">
                            <div>
                              <div className="flex items-center gap-2">
                                <h3 className="font-semibold text-gray-900">{slot.name}</h3>
                                <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">
                                  {slot.size}
                                </span>
                              </div>
                              <p className="text-sm text-gray-500">{slot.description}</p>
                            </div>
                            <label className="relative inline-flex items-center cursor-pointer">
                              <input
                                type="checkbox"
                                checked={slot.enabled}
                                onChange={(e) => setAdSettings({
                                  ...adSettings,
                                  [key]: { ...slot, enabled: e.target.checked }
                                })}
                                className="sr-only peer"
                              />
                              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-red-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-red-600"></div>
                            </label>
                          </div>
                          <textarea
                            value={slot.code}
                            onChange={(e) => setAdSettings({
                              ...adSettings,
                              [key]: { ...slot, code: e.target.value }
                            })}
                            placeholder="Reklam kodunu buraya yapıştırın (HTML)"
                            className="w-full h-24 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                          />
                        </div>
                      ))}
                  </div>
                </div>

                {/* Kaydet Butonu */}
                <div className="flex justify-end">
                  <button
                    onClick={saveAdSettings}
                    disabled={adSaveStatus === 'saving'}
                    className={`px-6 py-3 rounded-xl font-semibold transition-all flex items-center gap-2 ${
                      adSaveStatus === 'saved'
                        ? 'bg-green-600 text-white'
                        : adSaveStatus === 'error'
                        ? 'bg-red-600 text-white'
                        : 'bg-red-600 text-white hover:bg-red-700'
                    }`}
                  >
                    {adSaveStatus === 'saving' ? (
                      <>
                        <Loader2 className="w-5 h-5 animate-spin" />
                        Kaydediliyor...
                      </>
                    ) : adSaveStatus === 'saved' ? (
                      <>
                        <CheckCircle2 className="w-5 h-5" />
                        Kaydedildi!
                      </>
                    ) : adSaveStatus === 'error' ? (
                      <>
                        <XCircle className="w-5 h-5" />
                        Hata Oluştu
                      </>
                    ) : (
                      <>
                        <Save className="w-5 h-5" />
                        Reklam Ayarlarını Kaydet
                      </>
                    )}
                  </button>
                </div>

                {/* Reklam Yerleşim Haritası */}
                <div className="bg-gray-50 rounded-2xl p-6 border border-gray-200">
                  <h3 className="font-bold text-gray-900 mb-4">📍 Reklam Yerleşim Haritası</h3>

                  <div className="grid md:grid-cols-2 gap-6">
                    {/* Desktop */}
                    <div className="bg-white rounded-xl p-4 border border-gray-200">
                      <h4 className="text-sm font-semibold text-gray-700 mb-3">🖥️ Masaüstü Görünümü</h4>
                      <div className="space-y-2 text-xs">
                        <div className="bg-orange-100 text-orange-700 px-3 py-2 rounded text-center">
                          Üst Banner (728x90)
                        </div>
                        <div className="flex gap-2">
                          <div className="flex-1 space-y-2">
                            <div className="bg-blue-100 text-blue-700 px-3 py-2 rounded text-center">
                              Haber Başı (728x90)
                            </div>
                            <div className="bg-gray-200 text-gray-600 px-3 py-6 rounded text-center">
                              Haber İçeriği
                            </div>
                            <div className="bg-purple-100 text-purple-700 px-3 py-2 rounded text-center">
                              Haber Ortası (336x280)
                            </div>
                            <div className="bg-gray-200 text-gray-600 px-3 py-6 rounded text-center">
                              Haber Devamı
                            </div>
                            <div className="bg-green-100 text-green-700 px-3 py-2 rounded text-center">
                              Haber Sonu (728x90)
                            </div>
                          </div>
                          <div className="w-24 space-y-2">
                            <div className="bg-red-100 text-red-700 px-2 py-3 rounded text-center text-[10px]">
                              Sidebar Üst (300x250)
                            </div>
                            <div className="bg-yellow-100 text-yellow-700 px-2 py-6 rounded text-center text-[10px]">
                              Sidebar Orta (300x600)
                            </div>
                            <div className="bg-pink-100 text-pink-700 px-2 py-3 rounded text-center text-[10px]">
                              Sidebar Alt (300x250)
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Mobile */}
                    <div className="bg-white rounded-xl p-4 border border-gray-200">
                      <h4 className="text-sm font-semibold text-gray-700 mb-3">📱 Mobil Görünümü</h4>
                      <div className="max-w-[200px] mx-auto space-y-2 text-xs">
                        <div className="bg-orange-100 text-orange-700 px-3 py-2 rounded text-center">
                          Mobil Üst (320x100)
                        </div>
                        <div className="bg-gray-200 text-gray-600 px-3 py-6 rounded text-center">
                          Haber İçeriği
                        </div>
                        <div className="bg-purple-100 text-purple-700 px-3 py-2 rounded text-center">
                          Mobil Haber İçi (300x250)
                        </div>
                        <div className="bg-gray-200 text-gray-600 px-3 py-6 rounded text-center">
                          Haber Devamı
                        </div>
                        <div className="border-2 border-dashed border-teal-400 bg-teal-50 text-teal-700 px-3 py-2 rounded text-center">
                          Mobil Yapışkan (320x50)
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Örnek AdSense Kodu */}
                <div className="bg-blue-50 rounded-2xl p-6 border border-blue-200">
                  <h3 className="font-bold text-blue-900 mb-3">💡 Örnek Google AdSense Kodu</h3>
                  <pre className="bg-gray-900 text-green-400 p-4 rounded-lg text-xs overflow-x-auto">
{`<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-XXXXXXX"
     data-ad-slot="XXXXXXX"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>`}
                  </pre>
                  <p className="text-blue-700 text-sm mt-3">
                    <strong>Not:</strong> AdSense kodlarınızı doğrudan textarea alanlarına yapıştırabilirsiniz.
                    Script tagı dahil tüm kodu ekleyebilirsiniz.
                  </p>
                </div>
              </>
            )}
          </div>
        )}

        {/* BACKLINKS TAB */}
        {activeTab === 'backlinks' && (
          <div className="space-y-6">
            {/* Bilgi */}
            <div className="bg-gradient-to-r from-green-50 to-emerald-50 rounded-2xl p-6 border border-green-200">
              <div className="flex items-start gap-3">
                <span className="text-2xl">🔗</span>
                <div>
                  <h3 className="font-bold text-green-900 mb-2">SEO Backlink Yönetimi</h3>
                  <p className="text-green-800 text-sm">
                    Aşağıdan SEO amaçlı backlink ekleyebilirsiniz. Linkleri footer, haber içi, kategori sayfaları veya sidebar'a yerleştirebilirsiniz.
                    <strong> Dofollow</strong> seçeneği ile link juice geçişini kontrol edebilirsiniz.
                  </p>
                </div>
              </div>
            </div>

            {isLoadingBacklinks ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="w-8 h-8 animate-spin text-red-600" />
              </div>
            ) : (
              <>
                {/* Backlink Listesi */}
                <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                      🔗 Backlink Listesi
                      <span className="text-sm font-normal text-gray-500">({backlinks.length} link)</span>
                    </h2>
                    <button
                      onClick={addBacklink}
                      className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2"
                    >
                      <Plus className="w-4 h-4" />
                      Yeni Backlink
                    </button>
                  </div>

                  {backlinks.length === 0 ? (
                    <div className="text-center py-12 text-gray-500">
                      <span className="text-4xl mb-3 block">🔗</span>
                      <p>Henüz backlink eklenmemiş</p>
                      <p className="text-sm">Yukarıdaki butona tıklayarak yeni backlink ekleyebilirsiniz.</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {backlinks.map((link, index) => (
                        <div
                          key={link.id}
                          className={`border rounded-xl p-4 ${
                            link.enabled ? 'border-green-200 bg-green-50/30' : 'border-gray-200 bg-gray-50'
                          }`}
                        >
                          <div className="flex items-start gap-4">
                            {/* Sıra */}
                            <div className="flex flex-col items-center gap-1">
                              <span className="text-xs text-gray-400">#{index + 1}</span>
                            </div>

                            {/* Ana içerik */}
                            <div className="flex-1 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                              {/* Başlık (Anchor Text) */}
                              <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">Anchor Text</label>
                                <input
                                  type="text"
                                  value={link.title}
                                  onChange={(e) => updateBacklink(link.id, 'title', e.target.value)}
                                  placeholder="Link metni"
                                  className="w-full p-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500"
                                />
                              </div>

                              {/* URL */}
                              <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">URL</label>
                                <input
                                  type="url"
                                  value={link.url}
                                  onChange={(e) => updateBacklink(link.id, 'url', e.target.value)}
                                  placeholder="https://..."
                                  className="w-full p-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500"
                                />
                              </div>

                              {/* Konum */}
                              <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">Konum</label>
                                <select
                                  value={link.placement}
                                  onChange={(e) => updateBacklink(link.id, 'placement', e.target.value)}
                                  className="w-full p-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500"
                                >
                                  <option value="footer">Footer</option>
                                  <option value="article">Haber İçi</option>
                                  <option value="category">Kategori Sayfası</option>
                                  <option value="sidebar">Sidebar</option>
                                  <option value="all">Tümü</option>
                                </select>
                              </div>

                              {/* Açıklama */}
                              <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">Açıklama (Title)</label>
                                <input
                                  type="text"
                                  value={link.description || ''}
                                  onChange={(e) => updateBacklink(link.id, 'description', e.target.value)}
                                  placeholder="Title attribute"
                                  className="w-full p-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500"
                                />
                              </div>
                            </div>

                            {/* Kontroller */}
                            <div className="flex items-center gap-3">
                              {/* Dofollow Toggle */}
                              <div className="flex flex-col items-center">
                                <span className="text-xs text-gray-500 mb-1">Dofollow</span>
                                <label className="relative inline-flex items-center cursor-pointer">
                                  <input
                                    type="checkbox"
                                    checked={link.dofollow}
                                    onChange={(e) => updateBacklink(link.id, 'dofollow', e.target.checked)}
                                    className="sr-only peer"
                                  />
                                  <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-green-600"></div>
                                </label>
                              </div>

                              {/* Aktif Toggle */}
                              <div className="flex flex-col items-center">
                                <span className="text-xs text-gray-500 mb-1">Aktif</span>
                                <label className="relative inline-flex items-center cursor-pointer">
                                  <input
                                    type="checkbox"
                                    checked={link.enabled}
                                    onChange={(e) => updateBacklink(link.id, 'enabled', e.target.checked)}
                                    className="sr-only peer"
                                  />
                                  <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-red-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-red-600"></div>
                                </label>
                              </div>

                              {/* Sil */}
                              <button
                                onClick={() => removeBacklink(link.id)}
                                className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                title="Sil"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Kaydet Butonu */}
                <div className="flex justify-end">
                  <button
                    onClick={saveBacklinks}
                    disabled={backlinkSaveStatus === 'saving'}
                    className={`px-6 py-3 rounded-xl font-semibold transition-all flex items-center gap-2 ${
                      backlinkSaveStatus === 'saved'
                        ? 'bg-green-600 text-white'
                        : backlinkSaveStatus === 'error'
                        ? 'bg-red-600 text-white'
                        : 'bg-green-600 text-white hover:bg-green-700'
                    }`}
                  >
                    {backlinkSaveStatus === 'saving' ? (
                      <>
                        <Loader2 className="w-5 h-5 animate-spin" />
                        Kaydediliyor...
                      </>
                    ) : backlinkSaveStatus === 'saved' ? (
                      <>
                        <CheckCircle2 className="w-5 h-5" />
                        Kaydedildi!
                      </>
                    ) : backlinkSaveStatus === 'error' ? (
                      <>
                        <XCircle className="w-5 h-5" />
                        Hata Oluştu
                      </>
                    ) : (
                      <>
                        <Save className="w-5 h-5" />
                        Backlink Ayarlarını Kaydet
                      </>
                    )}
                  </button>
                </div>

                {/* Konum Açıklamaları */}
                <div className="bg-gray-50 rounded-2xl p-6 border border-gray-200">
                  <h3 className="font-bold text-gray-900 mb-4">📍 Backlink Konumları</h3>
                  <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="bg-white rounded-xl p-4 border border-gray-100">
                      <h4 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
                        <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                        Footer
                      </h4>
                      <p className="text-sm text-gray-600">Sayfa altındaki footer bölümünde görünür. Tüm sayfalarda gösterilir.</p>
                    </div>
                    <div className="bg-white rounded-xl p-4 border border-gray-100">
                      <h4 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
                        <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                        Haber İçi
                      </h4>
                      <p className="text-sm text-gray-600">Haber detay sayfalarında içerik sonunda "İlgili Bağlantılar" olarak görünür.</p>
                    </div>
                    <div className="bg-white rounded-xl p-4 border border-gray-100">
                      <h4 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
                        <span className="w-2 h-2 bg-purple-500 rounded-full"></span>
                        Kategori
                      </h4>
                      <p className="text-sm text-gray-600">Kategori sayfalarında "Önerilen Siteler" olarak grid şeklinde görünür.</p>
                    </div>
                    <div className="bg-white rounded-xl p-4 border border-gray-100">
                      <h4 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
                        <span className="w-2 h-2 bg-orange-500 rounded-full"></span>
                        Sidebar
                      </h4>
                      <p className="text-sm text-gray-600">Sağ kolondaki sidebar'da "Faydalı Linkler" olarak liste şeklinde görünür.</p>
                    </div>
                  </div>
                </div>

                {/* SEO Bilgisi */}
                <div className="bg-blue-50 rounded-2xl p-6 border border-blue-200">
                  <h3 className="font-bold text-blue-900 mb-3">💡 SEO Hakkında</h3>
                  <div className="text-blue-800 text-sm space-y-2">
                    <p>
                      <strong>Dofollow:</strong> Arama motorlarına linkin takip edilmesi gerektiğini söyler.
                      Bu linkler PageRank ve link juice aktarır.
                    </p>
                    <p>
                      <strong>Nofollow:</strong> Arama motorlarına linkin takip edilmemesi gerektiğini söyler.
                      Sponsorlu veya güvenilir olmayan linkler için kullanılır.
                    </p>
                    <p>
                      <strong>Anchor Text:</strong> Kullanıcıların gördüğü tıklanabilir metin.
                      SEO için hedef anahtar kelimeyi içermesi önerilir.
                    </p>
                  </div>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
