import { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { useShop } from "@/components/context/ShopContext";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Loader2, Search, Package, ChevronLeft, ChevronRight, Tag, Globe, ExternalLink, Plus, Trash2, Clock, CheckCircle, AlertCircle, Settings, Eye, Code } from "lucide-react";
import { API_URL } from "@/lib/config";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";
import ReactMarkdown from 'react-markdown';

interface StoreData {
  id: string;
  store_name: string | null;
  platform_name: string;
  store_url: string | null;
}

interface Category {
  category_id: string;
  category_name: string;
  product_count: number;
  is_excluded: boolean;
}

interface Product {
  id: string;
  name: string;
  sku: string;
  categories: { id: string; name: string; }[];
  enabled_in_context: boolean;
  excluded_by_individual: boolean;
  excluded_by_category: boolean;
  exclusion_reason: string | null;
}

type DataItem = Product;

interface DataResponse {
  success: boolean;
  data: DataItem[];
  total: number;
  enabled_count: number;
  disabled_count: number;
}

interface ScraperContent {
  id: string;
  url: string;
  content_type: 'shipping' | 'contacts' | 'terms' | 'faq';
  title?: string;
  content: string;
  scraped_at: string;
  metadata?: Record<string, unknown>;
}

interface ScraperCustomUrl {
  id: string;
  url: string;
  content_type: 'shipping' | 'contacts' | 'terms' | 'faq';
  enabled: boolean;
  created_at: string;
  last_scraped_at?: string;
  status?: 'pending' | 'completed' | 'failed';
}

interface ScraperShopStatus {
  id: string;
  url: string;
  custom_id?: string;
  status: 'active' | 'inactive';
  last_scraped_at?: string;
  next_scheduled_scrape?: string;
  scheduled_enabled: boolean;
  total_urls_found: number;
  total_content_items: number;
  scrape_count?: number;
  last_error?: string;
  last_error_at?: string;
  analytics?: {
    shipping_count: number;
    contacts_count: number;
    terms_count: number;
    faq_count: number;
  };
  created_at: string;
  updated_at: string;
}

interface ManageStoreDataContentProps {
  defaultTab?: "products" | "website";
}

export function ManageStoreDataContent({ defaultTab }: ManageStoreDataContentProps = {}) {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();
  const { t } = useTranslation();
  const { selectedShop } = useShop();

  const [stores, setStores] = useState<StoreData[]>([]);
  const [selectedStore, setSelectedStore] = useState<StoreData | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"products" | "website">(defaultTab || "products");

  // Track if we're on a dedicated page (Products or Website Content)
  const isDedicatedPage = defaultTab !== undefined;

  // Filter and search state
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<"all" | "enabled" | "disabled">("all");
  const [categoryFilter, setCategoryFilter] = useState<string>("all");

  // Data state
  const [data, setData] = useState<DataItem[]>([]);
  const [dataLoading, setDataLoading] = useState(false);
  const [totalCount, setTotalCount] = useState(0);
  const [enabledCount, setEnabledCount] = useState(0);
  const [disabledCount, setDisabledCount] = useState(0);

  // Categories state
  const [categories, setCategories] = useState<Category[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);

  // Pagination state
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(25);

  // Selection state
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [selectAll, setSelectAll] = useState(false);

  // Confirmation dialog state
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    title: string;
    description: string;
    action: () => void;
  }>({
    open: false,
    title: "",
    description: "",
    action: () => { },
  });

  // Website content state
  const [scraperStatus, setScraperStatus] = useState<ScraperShopStatus | null>(null);
  const [scraperContent, setScraperContent] = useState<ScraperContent[]>([]);
  const [customUrls, setCustomUrls] = useState<ScraperCustomUrl[]>([]);
  const [websiteLoading, setWebsiteLoading] = useState(false);
  const [contentTypeFilter, setContentTypeFilter] = useState<string>("all");
  const [newCustomUrl, setNewCustomUrl] = useState("");
  const [newCustomUrlType, setNewCustomUrlType] = useState<'shipping' | 'contacts' | 'terms' | 'faq'>('faq');

  // Content preview modal state
  const [previewContent, setPreviewContent] = useState<ScraperContent | null>(null);
  const [previewMode, setPreviewMode] = useState<'raw' | 'rendered'>('rendered');

  // Fetch stores on mount
  useEffect(() => {
    const fetchStores = async () => {
      try {
        const sessionData = localStorage.getItem('session_data');
        if (!sessionData) {
          throw new Error('No session data found');
        }

        const session = JSON.parse(sessionData);
        const response = await fetch(`${API_URL}/api/stores`, {
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error('Failed to fetch stores');
        }

        const result = await response.json();
        if (result.success) {
          const storesList = result.stores || [];
          setStores(storesList);

          // For dedicated pages (Products/Website Content), DON'T set selectedStore here
          // It will be set by the useEffect that watches selectedShop
          if (!isDedicatedPage) {
            // For non-dedicated pages, select store from URL parameter or first store
            const shopId = searchParams.get('shop');
            if (shopId) {
              const store = storesList.find((s: StoreData) => s.id === shopId);
              if (store) {
                setSelectedStore(store);
              } else if (storesList.length > 0) {
                setSelectedStore(storesList[0]);
              }
            } else if (storesList.length > 0) {
              setSelectedStore(storesList[0]);
            }
          }
        }
      } catch (error) {
        console.error('Error fetching stores:', error);
        toast({
          title: t('manageStoreData.toast.errorLoadStoresTitle'),
          description: t('manageStoreData.toast.errorLoadStoresDescription'),
          variant: "destructive"
        });
      } finally {
        setLoading(false);
      }
    };

    fetchStores();
  }, [searchParams, toast, isDedicatedPage]);

  // Update selected store when global shop context changes (for dedicated pages)
  useEffect(() => {
    if (isDedicatedPage && selectedShop) {
      setSelectedStore(selectedShop);
      // Reset state when shop changes
      setPage(1);
      setSearchQuery("");
      setStatusFilter("all");
      setCategoryFilter("all");
      setSelectedItems(new Set());
      setSelectAll(false);

      // Clear data from previous shop
      setData([]);
      setCategories([]);
      setTotalCount(0);
      setEnabledCount(0);
      setDisabledCount(0);

      // Clear website content data from previous shop
      setScraperStatus(null);
      setScraperContent([]);
      setCustomUrls([]);
      setContentTypeFilter("all");
    }
  }, [selectedShop, isDedicatedPage]);

  // Fetch categories when store changes
  useEffect(() => {
    if (selectedStore) {
      fetchCategories();
    }
  }, [selectedStore]);

  // Fetch data when tab, store, or filters change
  useEffect(() => {
    if (selectedStore) {
      if (activeTab === "products") {
        fetchData();
      } else if (activeTab === "website") {
        fetchWebsiteData();
      }
    }
  }, [selectedStore, activeTab, page, pageSize, searchQuery, statusFilter, categoryFilter, contentTypeFilter]);

  // Fetch website data when website tab is active
  const fetchWebsiteData = async () => {
    if (!selectedStore) return;

    setWebsiteLoading(true);
    try {
      await Promise.all([
        fetchScraperStatus(),
        fetchScraperContent(),
        fetchCustomUrls(),
      ]);
    } catch (error) {
      console.error('Error fetching website data:', error);
      toast({
        title: t('common.error'),
        description: "Failed to load website content data",
        variant: "destructive"
      });
    } finally {
      setWebsiteLoading(false);
    }
  };

  const fetchCategories = async () => {
    if (!selectedStore) return;

    setCategoriesLoading(true);
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/api/store-data/categories?store_id=${selectedStore.id}`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch categories');
      }

      const result = await response.json();
      if (result.success) {
        setCategories(result.categories || []);
      }
    } catch (error) {
      console.error('Error fetching categories:', error);
      // Don't show toast for categories - it's not critical
    } finally {
      setCategoriesLoading(false);
    }
  };

  const fetchData = async () => {
    if (!selectedStore) return;

    setDataLoading(true);
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      // Build query parameters
      const params = new URLSearchParams({
        store_id: selectedStore.id,
        page: page.toString(),
        limit: pageSize.toString(),
      });

      if (searchQuery) {
        params.append('search', searchQuery);
      }

      if (statusFilter !== 'all') {
        params.append('enabled', statusFilter === 'enabled' ? 'true' : 'false');
      }

      if (categoryFilter !== 'all') {
        params.append('category', categoryFilter);
      }

      const endpoint = `/api/store-data/${activeTab}?${params.toString()}`;
      const response = await fetch(`${API_URL}${endpoint}`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch data');
      }

      const result: DataResponse = await response.json();
      if (result.success) {
        setData(result.data);
        setTotalCount(result.total);
        setEnabledCount(result.enabled_count);
        setDisabledCount(result.disabled_count);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      toast({
        title: t('manageStoreData.toast.errorLoadDataTitle'),
        description: t('manageStoreData.toast.errorLoadDataDescription', { type: activeTab }),
        variant: "destructive"
      });
    } finally {
      setDataLoading(false);
    }
  };

  const fetchScraperStatus = async () => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/scraper-management/shop-status?store_id=${selectedStore.id}`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const result = await response.json();
        setScraperStatus(result.shop_data || null);
      }
    } catch (error) {
      console.error('Error fetching scraper status:', error);
    }
  };

  const fetchScraperContent = async () => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);
      const params = new URLSearchParams({
        store_id: selectedStore.id,
      });

      if (contentTypeFilter !== 'all') {
        params.append('content_type', contentTypeFilter);
      }

      if (searchQuery) {
        params.append('search', searchQuery);
      }

      const response = await fetch(`${API_URL}/scraper-management/shop-content?${params.toString()}`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const result = await response.json();
        setScraperContent(result.content || []);
      } else if (response.status === 404 || response.status === 500) {
        // Shop not found in scraper system - this is expected for some platforms
        // Silently set empty content without logging error
        setScraperContent([]);
      }
    } catch (error) {
      // Only log unexpected errors, not 404/500 from scraper API
      console.error('Error fetching scraper content:', error);
    }
  };

  const fetchCustomUrls = async () => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/scraper-management/custom-urls?store_id=${selectedStore.id}`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const result = await response.json();
        setCustomUrls(result.custom_urls || []);
      } else if (response.status === 404 || response.status === 500) {
        // Shop not found in scraper system - this is expected for some platforms
        // Silently set empty URLs without logging error
        setCustomUrls([]);
      }
    } catch (error) {
      // Only log unexpected errors, not 404/500 from scraper API
      console.error('Error fetching custom URLs:', error);
    }
  };

  const handleAddCustomUrl = async () => {
    if (!selectedStore || !newCustomUrl) return;

    // Validate same domain
    if (selectedStore.store_url) {
      try {
        const storeDomain = new URL(selectedStore.store_url).hostname.toLowerCase();
        const customDomain = new URL(newCustomUrl).hostname.toLowerCase();

        if (customDomain !== storeDomain && !customDomain.endsWith(`.${storeDomain}`)) {
          toast({
            title: t('common.error'),
            description: t('manageStoreData.website.toast.differentDomainError') || 'Custom URL must be from the same domain as your store',
            variant: "destructive"
          });
          return;
        }
      } catch (urlError) {
        toast({
          title: t('common.error'),
          description: t('manageStoreData.website.toast.invalidUrlError') || 'Invalid URL format',
          variant: "destructive"
        });
        return;
      }
    }

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/scraper-management/custom-urls`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
          url: newCustomUrl,
          content_type: newCustomUrlType,
        })
      });

      if (response.ok) {
        toast({
          title: t('common.success'),
          description: t('manageStoreData.website.toast.urlAddSuccess') || 'Custom URL added successfully',
        });
        setNewCustomUrl("");
        fetchCustomUrls();
      } else {
        const error = await response.json();
        throw new Error(error.error || 'Failed to add custom URL');
      }
    } catch (error) {
      toast({
        title: t('common.error'),
        description: error.message || t('manageStoreData.website.toast.urlAddError'),
        variant: "destructive"
      });
    }
  };

  const handleToggleCustomUrl = async (customUrlId: string, currentEnabled: boolean) => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);

      // Update the scraper-management endpoint to support this
      const response = await fetch(`${API_URL}/scraper-management/custom-urls/${customUrlId}/toggle`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
          enabled: !currentEnabled,
        })
      });

      if (response.ok) {
        toast({
          title: t('common.success'),
          description: !currentEnabled ? t('manageStoreData.website.toast.urlEnabled') || 'URL enabled' : t('manageStoreData.website.toast.urlDisabled') || 'URL disabled',
        });
        fetchCustomUrls();
      } else {
        const error = await response.json();
        throw new Error(error.error || 'Failed to update custom URL');
      }
    } catch (error) {
      toast({
        title: t('common.error'),
        description: error.message || t('manageStoreData.website.toast.urlToggleError') || 'Failed to update URL',
        variant: "destructive"
      });
    }
  };

  const handleDeleteCustomUrl = async (customUrlId: string) => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) throw new Error('No session data found');

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/scraper-management/custom-urls/${customUrlId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
        })
      });

      if (response.ok) {
        toast({
          title: t('common.success'),
          description: t('manageStoreData.website.toast.urlDeleted') || 'Custom URL deleted successfully',
        });
        fetchCustomUrls();
      } else {
        const error = await response.json();
        throw new Error(error.error || 'Failed to delete custom URL');
      }
    } catch (error) {
      toast({
        title: t('common.error'),
        description: error.message || t('manageStoreData.website.toast.urlDeleteError') || 'Failed to delete URL',
        variant: "destructive"
      });
    }
  };

  const handleToggleItem = async (itemId: string, currentEnabled: boolean, product?: Product) => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      // Optimistic update
      setData(prevData =>
        prevData.map(item =>
          item.id === itemId
            ? { ...item, enabled_in_context: !currentEnabled }
            : item
        )
      );

      const response = await fetch(`${API_URL}/api/store-data/${activeTab}/${itemId}/toggle`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
          enabled: !currentEnabled
        })
      });

      if (!response.ok) {
        // Revert on error
        setData(prevData =>
          prevData.map(item =>
            item.id === itemId
              ? { ...item, enabled_in_context: currentEnabled }
              : item
          )
        );
        throw new Error('Failed to update item');
      }

      // Update counts
      if (currentEnabled) {
        setEnabledCount(prev => prev - 1);
        setDisabledCount(prev => prev + 1);
      } else {
        setEnabledCount(prev => prev + 1);
        setDisabledCount(prev => prev - 1);
      }

      toast({
        title: t('manageStoreData.toast.successToggleTitle'),
        description: !currentEnabled ? t('manageStoreData.toast.successToggleEnabled') : t('manageStoreData.toast.successToggleDisabled'),
      });
    } catch (error) {
      console.error('Error toggling item:', error);
      toast({
        title: t('manageStoreData.toast.errorToggleTitle'),
        description: t('manageStoreData.toast.errorToggleDescription'),
        variant: "destructive"
      });
    }
  };

  const handleToggleCategory = async (categoryId: string, categoryName: string, currentExcluded: boolean) => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      const response = await fetch(`${API_URL}/api/store-data/categories/${categoryId}/exclude`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
          category_name: categoryName,
          exclude: !currentExcluded
        })
      });

      if (!response.ok) {
        throw new Error('Failed to update category');
      }

      toast({
        title: t('common.success'),
        description: `Category "${categoryName}" ${!currentExcluded ? 'excluded' : 'included'} successfully`,
      });

      // Refresh categories and products
      fetchCategories();
      fetchData();
    } catch (error) {
      console.error('Error toggling category:', error);
      toast({
        title: t('common.error'),
        description: 'Failed to update category',
        variant: "destructive"
      });
    }
  };

  const handleBulkAction = async (enable: boolean) => {
    if (!selectedStore || selectedItems.size === 0) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      const response = await fetch(`${API_URL}/api/store-data/${activeTab}/bulk-toggle`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id,
          item_ids: Array.from(selectedItems),
          enabled: enable
        })
      });

      if (!response.ok) {
        throw new Error('Failed to update items');
      }

      toast({
        title: t('manageStoreData.toast.successBulkTitle'),
        description: enable ? t('manageStoreData.toast.successBulkEnabled', { count: selectedItems.size }) : t('manageStoreData.toast.successBulkDisabled', { count: selectedItems.size }),
      });

      setSelectedItems(new Set());
      setSelectAll(false);
      fetchData();
    } catch (error) {
      console.error('Error with bulk action:', error);
      toast({
        title: t('manageStoreData.toast.errorBulkTitle'),
        description: t('manageStoreData.toast.errorBulkDescription'),
        variant: "destructive"
      });
    }
  };

  const handleEnableAll = async () => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      const response = await fetch(`${API_URL}/api/store-data/${activeTab}/enable-all`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id
        })
      });

      if (!response.ok) {
        throw new Error('Failed to enable all items');
      }

      toast({
        title: t('manageStoreData.toast.successEnableAllTitle'),
        description: t('manageStoreData.toast.successEnableAllDescription', { type: activeTab }),
      });

      // Refresh categories (in case they were excluded) and products
      fetchCategories();
      fetchData();
    } catch (error) {
      console.error('Error enabling all:', error);
      toast({
        title: t('manageStoreData.toast.errorEnableAllTitle'),
        description: t('manageStoreData.toast.errorEnableAllDescription'),
        variant: "destructive"
      });
    }
  };

  const handleDisableAll = async () => {
    if (!selectedStore) return;

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      const response = await fetch(`${API_URL}/api/store-data/${activeTab}/disable-all`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          store_id: selectedStore.id
        })
      });

      if (!response.ok) {
        throw new Error('Failed to disable all items');
      }

      toast({
        title: t('manageStoreData.toast.successDisableAllTitle'),
        description: t('manageStoreData.toast.successDisableAllDescription', { type: activeTab }),
      });

      fetchData();
    } catch (error) {
      console.error('Error disabling all:', error);
      toast({
        title: t('manageStoreData.toast.errorDisableAllTitle'),
        description: t('manageStoreData.toast.errorDisableAllDescription'),
        variant: "destructive"
      });
    }
  };

  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      // Only select items that are not excluded by category (or are enabled)
      const selectableItems = data.filter(item =>
        !(item.excluded_by_category && !item.enabled_in_context)
      );
      setSelectedItems(new Set(selectableItems.map(item => item.id)));
    } else {
      setSelectedItems(new Set());
    }
  };

  const handleSelectItem = (itemId: string, checked: boolean) => {
    const newSelected = new Set(selectedItems);
    if (checked) {
      newSelected.add(itemId);
    } else {
      newSelected.delete(itemId);
    }
    setSelectedItems(newSelected);

    // Check if all selectable items are selected
    const selectableItems = data.filter(item =>
      !(item.excluded_by_category && !item.enabled_in_context)
    );
    setSelectAll(newSelected.size === selectableItems.length);
  };

  const renderProductRow = (product: Product) => {
    const firstCategory = product.categories && product.categories.length > 0
      ? product.categories[0]
      : null;

    return (
      <TableRow key={product.id}>
        <TableCell>
          {/* Hide checkbox for products excluded by category */}
          {!(product.excluded_by_category && !product.enabled_in_context) && (
            <Checkbox
              checked={selectedItems.has(product.id)}
              onCheckedChange={(checked) => handleSelectItem(product.id, checked as boolean)}
            />
          )}
        </TableCell>
        <TableCell className="text-white font-medium">{product.name}</TableCell>
        <TableCell className="text-white">{product.sku || 'N/A'}</TableCell>
        <TableCell className="flex flex-wrap">
          {product.categories.map((category) => (
            <Badge variant="outline" className="text-xs text-white">
              {category.name}
            </Badge>
          ))}
        </TableCell>
        <TableCell>
          <div className="flex items-center gap-2">
            {/* Hide switch for products excluded by category */}
            {!(product.excluded_by_category && !product.enabled_in_context) && (
              <Switch
                checked={product.enabled_in_context}
                onCheckedChange={() => handleToggleItem(product.id, product.enabled_in_context, product)}
                className="data-[state=checked]:bg-cyan-500"
              />
            )}
            {!product.enabled_in_context && product.exclusion_reason && (
              <Badge
                variant={product.exclusion_reason === 'category' ? 'secondary' : 'destructive'}
                className="text-xs"
              >
                {product.exclusion_reason === 'category' ? t('manageStoreData.exclusionReasons.byCategory') : t('manageStoreData.exclusionReasons.individual')}
              </Badge>
            )}
          </div>
        </TableCell>
      </TableRow>
    );
  };

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center min-h-screen bg-slate-900">
        <Loader2 className="w-8 h-8 text-cyan-500 animate-spin" />
      </div>
    );
  }

  // For dedicated pages, wait for selectedShop from context
  if (isDedicatedPage && !selectedStore) {
    return (
      <div className="flex-1 flex items-center justify-center min-h-screen bg-slate-900">
        <Loader2 className="w-8 h-8 text-cyan-500 animate-spin" />
      </div>
    );
  }

  if (stores.length === 0) {
    return (
      <div className="flex-1 space-y-6 p-8 bg-slate-900">
        <div className="flex items-center justify-center min-h-[60vh]">
          <div className="text-center">
            <Package className="w-16 h-16 text-slate-600 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">{t('manageStoreData.noStores.title')}</h3>
            <p className="text-slate-400 mb-6">
              {t('manageStoreData.noStores.description')}
            </p>
            <Button
              className="bg-cyan-500 hover:bg-cyan-600 text-white"
              onClick={() => window.location.href = '/webshops'}
            >
              {t('manageStoreData.noStores.button')}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  const totalPages = Math.ceil(totalCount / pageSize);

  return (
    <div className="flex-1 space-y-6 p-8 bg-slate-900">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight text-white">
            {isDedicatedPage
              ? activeTab === "products"
                ? t('sidebar.products')
                : t('sidebar.websiteContent')
              : t('manageStoreData.title')
            }
          </h2>
          <p className="text-slate-400">
            {isDedicatedPage
              ? selectedStore?.store_name || t('manageStoreData.storeSelector.unnamedStore')
              : t('manageStoreData.subtitle')
            }
          </p>
        </div>
        {!isDedicatedPage && stores.length > 1 && (
          <Select value={selectedStore?.id} onValueChange={(value) => {
            const store = stores.find(s => s.id === value);
            if (store) setSelectedStore(store);
          }}>
            <SelectTrigger className="w-[300px] bg-slate-700 border-slate-600 text-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent className="bg-slate-700 border-slate-600">
              {stores.map((store) => (
                <SelectItem key={store.id} value={store.id}>
                  <div className="flex items-center gap-2">
                    <span className="text-white">{store.store_name || t('manageStoreData.storeSelector.unnamedStore')}</span>
                    <span className="text-slate-400 text-sm capitalize">({store.platform_name})</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      </div>

      <Card className="bg-slate-800 border-slate-700">
        <CardHeader>
          <CardTitle className="text-white">{t('manageStoreData.tabs.dataManagement')}</CardTitle>
        </CardHeader>
        <CardContent>
          <Tabs value={activeTab} onValueChange={(value) => {
            setActiveTab(value as "products");
            setPage(1);
            setSelectedItems(new Set());
            setSelectAll(false);
          }}>
            {/* Hide tabs on dedicated pages (Products/Website Content pages) */}
            {!isDedicatedPage && (
              <TabsList className="bg-slate-700 mb-6">
                <TabsTrigger value="products" className="data-[state=active]:bg-slate-600 data-[state=active]:text-white">
                  <Package className="w-4 h-4 mr-2" />
                  {t('manageStoreData.tabs.products')} ({enabledCount}/{totalCount})
                </TabsTrigger>
                <TabsTrigger value="website" className="data-[state=active]:bg-slate-600 data-[state=active]:text-white">
                  <Globe className="w-4 h-4 mr-2" />
                  {t('manageStoreData.tabs.website')}
                </TabsTrigger>
              </TabsList>
            )}

            {/* Search and Filter Bar - Only show for products tab */}
            {activeTab === "products" && (
              <div className="flex gap-4 mb-6">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder={t('manageStoreData.search.placeholder', { type: t('manageStoreData.search.products') })}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-10 bg-slate-700 border-slate-600 text-white"
                  />
                </div>
                <Select value={statusFilter} onValueChange={(value) => setStatusFilter(value as "all" | "enabled" | "disabled")}>
                  <SelectTrigger className="w-[180px] bg-slate-700 border-slate-600 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600 text-white">
                    <SelectItem value="all">{t('manageStoreData.filters.all')}</SelectItem>
                    <SelectItem value="enabled">{t('manageStoreData.filters.enabled')}</SelectItem>
                    <SelectItem value="disabled">{t('manageStoreData.filters.disabled')}</SelectItem>
                  </SelectContent>
                </Select>

                {/* Category Filter */}
                {categories.length > 0 && (
                  <Select value={categoryFilter} onValueChange={(value) => setCategoryFilter(value)}>
                    <SelectTrigger className="w-[200px] bg-slate-700 border-slate-600 text-white">
                      <Tag className="w-4 h-4 mr-2" />
                      <SelectValue placeholder={t('manageStoreData.filters.categories.placeholder')} />
                    </SelectTrigger>
                    <SelectContent className="bg-slate-700 border-slate-600">
                      <SelectItem value="all">{t('manageStoreData.filters.allCategories')}</SelectItem>
                      {categories.map((cat) => (
                        <SelectItem key={cat.category_id} value={cat.category_id}>
                          <div className="flex items-center justify-between w-full gap-2">
                            <span className={cat.is_excluded ? 'line-through text-slate-500' : 'text-white'}>
                              {cat.category_name}
                            </span>
                            <Badge variant="secondary" className="text-xs text-white">
                              {cat.product_count}
                            </Badge>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              </div>
            )}

            {/* Category Management Section - Only show for products tab */}
            {activeTab === "products" && categories.length > 0 && (
              <div className="mb-6 p-4 bg-slate-700/30 rounded-lg border border-slate-600">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-white font-medium flex items-center gap-2">
                    <Tag className="w-4 h-4" />
                    {t('manageStoreData.categoryManagement.title')}
                  </h3>
                </div>
                <div className="flex flex-wrap gap-2">
                  {categories.map((cat) => (
                    <div
                      key={cat.category_id}
                      className={`flex items-center gap-2 px-3 py-1.5 rounded-md border ${cat.is_excluded
                          ? 'bg-red-900/20 border-red-800 text-red-300'
                          : 'bg-slate-700 border-slate-600 text-white'
                        }`}
                    >
                      <span className="text-sm">{cat.category_name}</span>
                      <Badge variant="secondary" className="text-xs">
                        {cat.product_count}
                      </Badge>
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-6 px-2 text-xs"
                        onClick={() => handleToggleCategory(cat.category_id, cat.category_name, cat.is_excluded)}
                      >
                        {cat.is_excluded ? t('manageStoreData.categoryManagement.include') : t('manageStoreData.categoryManagement.exclude')}
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Bulk Actions - Only show for products tab */}
            {activeTab === "products" && selectedItems.size > 0 && (
              <div className="flex gap-2 mb-4 p-3 bg-slate-700/50 rounded-lg">
                <span className="text-white mr-4">{t('manageStoreData.bulkActions.selectedCount', { count: selectedItems.size })}</span>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => handleBulkAction(true)}
                  className="border-cyan-500 text-cyan-500 hover:bg-cyan-500 hover:text-white"
                >
                  {t('manageStoreData.bulkActions.enableSelected')}
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => handleBulkAction(false)}
                  className="bg-slate-700 border-slate-600 text-white"
                >
                  {t('manageStoreData.bulkActions.disableSelected')}
                </Button>
              </div>
            )}

            {/* Enable/Disable All Actions - Only show for products tab */}
            {activeTab === "products" && (
              <div className="flex gap-2 mb-4">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setConfirmDialog({
                    open: true,
                    title: t('manageStoreData.confirmDialog.enableAllTitle', { type: activeTab }),
                    description: t('manageStoreData.confirmDialog.enableAllDescription', { type: activeTab }),
                    action: handleEnableAll
                  })}
                  className="bg-slate-700 border-slate-600 text-white"
                >
                  {t('manageStoreData.bulkActions.enableAll')}
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setConfirmDialog({
                    open: true,
                    title: t('manageStoreData.confirmDialog.disableAllTitle', { type: activeTab }),
                    description: t('manageStoreData.confirmDialog.disableAllDescription', { type: activeTab }),
                    action: handleDisableAll
                  })}
                  className="bg-slate-700 border-slate-600 text-white"
                >
                  {t('manageStoreData.bulkActions.disableAll')}
                </Button>
              </div>
            )}

            <TabsContent value="products">
              {dataLoading ? (
                <div className="flex justify-center py-8">
                  <Loader2 className="w-6 h-6 text-cyan-500 animate-spin" />
                </div>
              ) : data.length === 0 ? (
                <div className="text-center py-8 text-slate-400">
                  {t('manageStoreData.table.noProducts')}
                </div>
              ) : (
                <div className="rounded-md border border-slate-700">
                  <Table>
                    <TableHeader className="bg-slate-700/50">
                      <TableRow>
                        <TableHead className="w-12">
                          <Checkbox
                            checked={selectAll}
                            onCheckedChange={handleSelectAll}
                          />
                        </TableHead>
                        <TableHead className="text-slate-300">{t('manageStoreData.table.name')}</TableHead>
                        <TableHead className="text-slate-300">{t('manageStoreData.table.sku')}</TableHead>
                        <TableHead className="text-slate-300">{t('manageStoreData.table.category')}</TableHead>
                        <TableHead className="text-slate-300">{t('manageStoreData.table.status')}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody className="bg-slate-800">
                      {data.map(item => renderProductRow(item as Product))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </TabsContent>

            <TabsContent value="website">
              {websiteLoading ? (
                <div className="flex justify-center py-8">
                  <Loader2 className="w-6 h-6 text-cyan-500 animate-spin" />
                </div>
              ) : (
                <div className="space-y-6">
                  {/* Scraper Status Section */}
                  {scraperStatus && (
                    <Card className="bg-slate-800 border-slate-700">
                      <CardHeader>
                        <CardTitle className="text-white flex items-center gap-2">
                          <Settings className="w-5 h-5" />
                          {t('manageStoreData.website.scraperStatus.title') || 'Scraper Status'}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {/* Main Statistics Grid */}
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                          <div className="bg-slate-700/50 rounded-lg p-3">
                            <div className="text-slate-400 text-sm">{t('manageStoreData.website.contentViewer.statusLabels.status')}</div>
                            <div className="text-white font-medium flex items-center gap-1 mt-1">
                              {scraperStatus.status === 'active' ? (
                                <><CheckCircle className="w-4 h-4 text-green-500" /> Active</>
                              ) : (
                                <><AlertCircle className="w-4 h-4 text-yellow-500" /> Inactive</>
                              )}
                            </div>
                          </div>
                          <div className="bg-slate-700/50 rounded-lg p-3">
                            <div className="text-slate-400 text-sm">{t('manageStoreData.website.contentViewer.statusLabels.urlsFound') || 'URLs Found'}</div>
                            <div className="text-white font-medium text-xl mt-1">{scraperStatus.total_urls_found}</div>
                          </div>
                          <div className="bg-slate-700/50 rounded-lg p-3">
                            <div className="text-slate-400 text-sm">{t('manageStoreData.website.contentViewer.statusLabels.contentItems') || 'Content Sections'}</div>
                            <div className="text-white font-medium text-xl mt-1">{scraperStatus.total_content_items}</div>
                          </div>
                          <div className="bg-slate-700/50 rounded-lg p-3">
                            <div className="text-slate-400 text-sm">{t('manageStoreData.website.contentViewer.statusLabels.totalScrapes') || 'Total Scrapes'}</div>
                            <div className="text-white font-medium text-xl mt-1">{scraperStatus.scrape_count || 0}</div>
                          </div>
                        </div>

                        {/* Content Type Breakdown */}
                        {scraperStatus.analytics && (
                          <div className="border border-slate-700 rounded-lg p-4">
                            <div className="text-white font-medium mb-3">{t('manageStoreData.website.contentViewer.statusLabels.contentBreakdown') || 'Content Breakdown'}</div>
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                              <div className="flex items-center justify-between p-2 bg-slate-700/30 rounded">
                                <span className="text-slate-400 text-sm">FAQ</span>
                                <Badge variant="secondary">{scraperStatus.analytics.faq_count}</Badge>
                              </div>
                              <div className="flex items-center justify-between p-2 bg-slate-700/30 rounded">
                                <span className="text-slate-400 text-sm">Shipping</span>
                                <Badge variant="secondary">{scraperStatus.analytics.shipping_count}</Badge>
                              </div>
                              <div className="flex items-center justify-between p-2 bg-slate-700/30 rounded">
                                <span className="text-slate-400 text-sm">Terms</span>
                                <Badge variant="secondary">{scraperStatus.analytics.terms_count}</Badge>
                              </div>
                              <div className="flex items-center justify-between p-2 bg-slate-700/30 rounded">
                                <span className="text-slate-400 text-sm">Contacts</span>
                                <Badge variant="secondary">{scraperStatus.analytics.contacts_count}</Badge>
                              </div>
                            </div>
                          </div>
                        )}

                        {/* Scheduling Control */}
                        {/* Timestamps and Error Display */}
                        <div className="flex flex-wrap gap-4 text-sm">
                          {scraperStatus.last_scraped_at && (
                            <div className="text-slate-400">
                              <Clock className="w-4 h-4 inline mr-1" />
                              Last scraped: <span className="text-white">{new Date(scraperStatus.last_scraped_at).toLocaleString()}</span>
                            </div>
                          )}
                          {scraperStatus.next_scheduled_scrape && scraperStatus.scheduled_enabled && (
                            <div className="text-slate-400">
                              <Clock className="w-4 h-4 inline mr-1" />
                              Next scrape: <span className="text-white">{new Date(scraperStatus.next_scheduled_scrape).toLocaleString()}</span>
                            </div>
                          )}
                        </div>

                        {/* Error Display */}
                        {scraperStatus.last_error && (
                          <div className="border border-red-800 bg-red-900/20 rounded-lg p-4">
                            <div className="flex items-start gap-2">
                              <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
                              <div className="flex-1">
                                <div className="text-red-300 font-medium mb-1">{t('manageStoreData.website.scraperStatus.lastError') || 'Last Error'}</div>
                                <div className="text-red-200 text-sm">{scraperStatus.last_error}</div>
                                {scraperStatus.last_error_at && (
                                  <div className="text-red-400 text-xs mt-2">
                                    {new Date(scraperStatus.last_error_at).toLocaleString()}
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  )}

                  {/* Content Type Filter */}
                  <div className="flex gap-4 mb-6">
                    <div className="flex-1 relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                      <Input
                        placeholder={t('manageStoreData.website.contentViewer.searchPlaceholder')}
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-10 bg-slate-700 border-slate-600 text-white"
                      />
                    </div>
                    <Select value={contentTypeFilter} onValueChange={setContentTypeFilter}>
                      <SelectTrigger className="w-[180px] bg-slate-700 border-slate-600 text-white">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-slate-700 border-slate-600 text-white">
                        <SelectItem value="all">{t('manageStoreData.website.contentViewer.filters.allContent')}</SelectItem>
                        <SelectItem value="faq">FAQ</SelectItem>
                        <SelectItem value="terms">Terms & Conditions</SelectItem>
                        <SelectItem value="shipping">Shipping Info</SelectItem>
                        <SelectItem value="contacts">Contact Info</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Custom URLs Section */}
                  <Card className="bg-slate-800 border-slate-700">
                    <CardHeader>
                      <CardTitle className="text-white">{t('manageStoreData.website.customUrls.title')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex gap-2 mb-4">
                        <Input
                          placeholder={t('manageStoreData.website.customUrls.urlPlaceholder')}
                          value={newCustomUrl}
                          onChange={(e) => setNewCustomUrl(e.target.value)}
                          className="flex-1 bg-slate-700 border-slate-600 text-white"
                        />
                        <Select value={newCustomUrlType} onValueChange={(value: string) => setNewCustomUrlType(value)}>
                          <SelectTrigger className="w-[140px] bg-slate-700 border-slate-600 text-white">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-700 border-slate-600">
                            <SelectItem value="faq">FAQ</SelectItem>
                            <SelectItem value="terms">Terms</SelectItem>
                            <SelectItem value="shipping">Shipping</SelectItem>
                            <SelectItem value="contacts">Contacts</SelectItem>
                          </SelectContent>
                        </Select>
                        <Button
                          onClick={handleAddCustomUrl}
                          className="bg-cyan-500 hover:bg-cyan-600 text-white"
                          disabled={!newCustomUrl}
                        >
                          <Plus className="w-4 h-4 mr-2" />
                          {t('manageStoreData.website.customUrls.addButton')}
                        </Button>
                      </div>

                      {customUrls.length > 0 && (
                        <div className="space-y-2">
                          {customUrls.map((customUrl) => (
                            <div key={customUrl.id} className="flex items-center gap-3 p-3 bg-slate-700/50 rounded-lg">
                              <div className="flex-1">
                                <div className="text-white text-sm flex items-center gap-2">
                                  <ExternalLink className="w-4 h-4" />
                                  <a href={customUrl.url} target="_blank" rel="noopener noreferrer" className="hover:text-cyan-400 underline">
                                    {customUrl.url}
                                  </a>
                                </div>
                                <div className="text-slate-400 text-xs flex items-center gap-2 mt-1">
                                  <Badge variant="outline" className="text-xs">
                                    {customUrl.content_type}
                                  </Badge>
                                  {customUrl.status && (
                                    <Badge variant={
                                      customUrl.status === 'completed' ? 'default' :
                                      customUrl.status === 'failed' ? 'destructive' : 'secondary'
                                    } className="text-xs">
                                      {customUrl.status}
                                    </Badge>
                                  )}
                                  {customUrl.last_scraped_at && (
                                    <span className="text-xs">
                                      <Clock className="w-3 h-3 inline mr-1" />
                                      {new Date(customUrl.last_scraped_at).toLocaleDateString()}
                                    </span>
                                  )}
                                </div>
                              </div>
                              <div className="flex items-center gap-2">
                                <Switch
                                  checked={customUrl.enabled}
                                  onCheckedChange={() => handleToggleCustomUrl(customUrl.id, customUrl.enabled)}
                                  className="data-[state=checked]:bg-cyan-500"
                                />
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => setConfirmDialog({
                                    open: true,
                                    title: t('manageStoreData.website.customUrls.deleteTitle') || 'Delete Custom URL',
                                    description: t('manageStoreData.website.customUrls.deleteDescription') || 'Are you sure you want to delete this custom URL? This action cannot be undone.',
                                    action: () => handleDeleteCustomUrl(customUrl.id)
                                  })}
                                  className="text-red-400 hover:text-red-300 hover:bg-red-900/20"
                                >
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </CardContent>
                  </Card>

                  {/* Scraped Content */}
                  <Card className="bg-slate-800 border-slate-700">
                    <CardHeader>
                      <div className="flex items-center justify-between">
                        <CardTitle className="text-white">{t('manageStoreData.website.contentViewer.title')} ({scraperContent.length})</CardTitle>
                        {scraperContent.length > 0 && (
                          <div className="text-sm text-slate-400">
                            {t('manageStoreData.website.contentViewer.groupedByCategory') || 'Grouped by category'}
                          </div>
                        )}
                      </div>
                    </CardHeader>
                    <CardContent>
                      {scraperContent.length === 0 ? (
                        <div className="text-center py-8 text-slate-400">
                          {scraperStatus?.status === 'active' ? (
                            <div>
                              <Loader2 className="w-8 h-8 mx-auto mb-3 animate-spin text-cyan-500" />
                              <p>{t('manageStoreData.website.contentViewer.scrapingInProgress') || 'Scraping in progress...'}</p>
                            </div>
                          ) : (
                            <div>
                              <p>{t('manageStoreData.website.contentViewer.noContentDescription')}</p>
                            </div>
                          )}
                        </div>
                      ) : (
                        <div className="space-y-4">
                          {/* Group content by category */}
                          {Object.entries(
                            scraperContent.reduce((acc, content) => {
                              if (!acc[content.content_type]) {
                                acc[content.content_type] = [];
                              }
                              acc[content.content_type].push(content);
                              return acc;
                            }, {} as Record<string, typeof scraperContent>)
                          ).map(([category, contents]) => (
                            <div key={category} className="border border-slate-600 rounded-lg overflow-hidden">
                              {/* Category Header */}
                              <div className="bg-slate-700/50 p-3 border-b border-slate-600">
                                <div className="flex items-center justify-between">
                                  <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2">
                                      <Tag className="w-4 h-4 text-cyan-400 flex-shrink-0" />
                                      <span className="text-white font-medium capitalize">{category}</span>
                                    </div>
                                    <div className="text-slate-400 text-xs mt-1">
                                      {contents.length} {contents.length === 1 ? 'item' : 'items'}
                                    </div>
                                  </div>
                                </div>
                              </div>

                              {/* Content Items */}
                              <div className="divide-y divide-slate-600">
                                {contents.map((content) => (
                                  <div key={content.id} className="p-4 bg-slate-800/50 hover:bg-slate-700/30 transition-colors">
                                    <div className="flex items-start justify-between mb-2">
                                      <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 mb-1">
                                          <Globe className="w-3 h-3 text-slate-400 flex-shrink-0" />
                                          <a
                                            href={content.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-white hover:text-cyan-400 underline truncate text-sm"
                                          >
                                            {content.title || content.url.split('/').pop() || 'Untitled'}
                                          </a>
                                          <ExternalLink className="w-3 h-3 text-slate-400 flex-shrink-0" />
                                        </div>
                                        <div className="text-slate-400 text-xs">
                                          {new Date(content.scraped_at).toLocaleString()}
                                        </div>
                                      </div>
                                      <div className="flex items-center gap-2 ml-2">
                                        <Button
                                          variant="outline"
                                          size="sm"
                                          onClick={() => {
                                            setPreviewContent(content);
                                            setPreviewMode('rendered');
                                          }}
                                          className="border-slate-600 hover:bg-slate-700"
                                        >
                                          <Eye className="w-3 h-3 mr-1" />
                                          Preview
                                        </Button>
                                        <Switch
                                          checked={(() => {
                                            // Check if this URL exists in customUrls as disabled
                                            const customUrl = customUrls.find(cu => cu.url === content.url);
                                            return customUrl ? customUrl.enabled : true;
                                          })()}
                                          onCheckedChange={async (checked) => {
                                            // Toggle URL enabled/disabled
                                            try {
                                              const sessionData = localStorage.getItem('session_data');
                                              if (!sessionData) throw new Error('No session data found');

                                              const session = JSON.parse(sessionData);

                                              // Check if URL already exists in custom URLs
                                              const existingCustomUrl = customUrls.find(cu => cu.url === content.url);

                                              if (existingCustomUrl) {
                                                // Update existing custom URL
                                                const response = await fetch(`${API_URL}/scraper-management/custom-urls/${existingCustomUrl.id}/toggle`, {
                                                  method: 'PATCH',
                                                  headers: {
                                                    'Authorization': `Bearer ${session.session.access_token}`,
                                                    'Content-Type': 'application/json'
                                                  },
                                                  body: JSON.stringify({
                                                    store_id: selectedStore?.id,
                                                    enabled: checked
                                                  })
                                                });

                                                if (!response.ok) {
                                                  throw new Error('Failed to toggle URL');
                                                }
                                              } else {
                                                // Add as new custom URL with specified enabled status
                                                const response = await fetch(`${API_URL}/scraper-management/custom-urls`, {
                                                  method: 'POST',
                                                  headers: {
                                                    'Authorization': `Bearer ${session.session.access_token}`,
                                                    'Content-Type': 'application/json'
                                                  },
                                                  body: JSON.stringify({
                                                    store_id: selectedStore?.id,
                                                    url: content.url,
                                                    content_type: content.content_type,
                                                  })
                                                });

                                                if (!response.ok) {
                                                  throw new Error('Failed to add custom URL');
                                                }

                                                // If we want to disable it, toggle it right after adding
                                                if (!checked) {
                                                  const newCustomUrl = await response.json();
                                                  await fetch(`${API_URL}/scraper-management/custom-urls/${newCustomUrl.id}/toggle`, {
                                                    method: 'PATCH',
                                                    headers: {
                                                      'Authorization': `Bearer ${session.session.access_token}`,
                                                      'Content-Type': 'application/json'
                                                    },
                                                    body: JSON.stringify({
                                                      store_id: selectedStore?.id,
                                                      enabled: false
                                                    })
                                                  });
                                                }
                                              }

                                              toast({
                                                title: checked ? "URL enabled" : "URL disabled",
                                                description: checked ? "This URL will be included in future scrapes" : "This URL will be skipped in future scrapes",
                                              });

                                              // Refresh both content and custom URLs
                                              fetchScraperContent();
                                              fetchCustomUrls();
                                            } catch (error) {
                                              console.error('Error toggling URL:', error);
                                              toast({
                                                title: "Error",
                                                description: "Failed to toggle URL status",
                                                variant: "destructive",
                                              });
                                            }
                                          }}
                                          className="data-[state=checked]:bg-cyan-500"
                                        />
                                      </div>
                                    </div>
                                  </div>
                                ))}
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </CardContent>
                  </Card>
                </div>
              )}
            </TabsContent>
          </Tabs>

          {/* Pagination */}
          {totalCount > 0 && (
            <div className="flex items-center justify-between mt-6">
              <div className="flex items-center gap-4">
                <Label className="text-slate-300">{t('manageStoreData.pagination.itemsPerPage')}</Label>
                <Select value={pageSize.toString()} onValueChange={(value) => {
                  setPageSize(Number(value));
                  setPage(1);
                }}>
                  <SelectTrigger className="w-[100px] bg-slate-700 border-slate-600 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600">
                    <SelectItem value="25">25</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                    <SelectItem value="100">100</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-center gap-2">
                <span className="text-slate-400 text-sm">
                  {t('manageStoreData.pagination.page')} {page} {t('manageStoreData.pagination.of')} {totalPages} ({t('manageStoreData.pagination.total', { count: totalCount })})
                </span>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setPage(prev => Math.max(1, prev - 1))}
                  disabled={page === 1}
                  className="border-slate-600 text-white"
                >
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setPage(prev => Math.min(totalPages, prev + 1))}
                  disabled={page === totalPages}
                  className="border-slate-600 text-white"
                >
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Content Preview Dialog */}
      <Dialog open={!!previewContent} onOpenChange={(open) => !open && setPreviewContent(null)}>
        <DialogContent className="bg-slate-800 border-slate-700 max-w-4xl max-h-[80vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="text-white flex items-center justify-between">
              <span className="truncate">
                {previewContent?.title || previewContent?.url.split('/').pop() || 'Content Preview'}
              </span>
              <div className="flex items-center gap-2 ml-4">
                <Button
                  variant={previewMode === 'rendered' ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setPreviewMode('rendered')}
                  className={previewMode === 'rendered' ? 'bg-cyan-500 hover:bg-cyan-600 text-white' : 'border-slate-600 text-slate-200 hover:text-white hover:bg-slate-700'}
                >
                  <Eye className="w-3 h-3 mr-1" />
                  Rendered
                </Button>
                <Button
                  variant={previewMode === 'raw' ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setPreviewMode('raw')}
                  className={previewMode === 'raw' ? 'bg-cyan-500 hover:bg-cyan-600 text-white' : 'border-slate-600 text-slate-200 hover:text-white hover:bg-slate-700'}
                >
                  <Code className="w-3 h-3 mr-1" />
                  Raw
                </Button>
              </div>
            </DialogTitle>
            <DialogDescription className="text-slate-400 flex items-center gap-4">
              <Badge variant="outline" className="text-xs">
                {previewContent?.content_type}
              </Badge>
              <a
                href={previewContent?.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-cyan-400 hover:text-cyan-300 underline text-xs flex items-center gap-1"
              >
                <Globe className="w-3 h-3" />
                Open source URL
                <ExternalLink className="w-3 h-3" />
              </a>
            </DialogDescription>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto mt-4">
            {previewMode === 'rendered' ? (
              <div className="prose prose-invert prose-cyan max-w-none prose-headings:text-white prose-p:text-slate-200 prose-li:text-slate-200 prose-strong:text-white prose-a:text-cyan-400">
                <ReactMarkdown>
                  {previewContent?.content || ''}
                </ReactMarkdown>
              </div>
            ) : (
              <pre className="bg-slate-900 p-4 rounded-lg text-slate-300 text-sm overflow-x-auto whitespace-pre-wrap">
                {previewContent?.content || ''}
              </pre>
            )}
          </div>
          {previewContent?.scraped_at && (
            <div className="mt-4 pt-4 border-t border-slate-700 text-slate-400 text-xs">
              <Clock className="w-3 h-3 inline mr-1" />
              Scraped: {new Date(previewContent.scraped_at).toLocaleString()}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Confirmation Dialog */}
      <AlertDialog open={confirmDialog.open} onOpenChange={(open) => setConfirmDialog({ ...confirmDialog, open })}>
        <AlertDialogContent className="bg-slate-800 border-slate-700">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-white">{confirmDialog.title}</AlertDialogTitle>
            <AlertDialogDescription className="text-slate-400">
              {confirmDialog.description}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-slate-700 text-white border-slate-600">
              {t('manageStoreData.confirmDialog.cancel')}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                confirmDialog.action();
                setConfirmDialog({ ...confirmDialog, open: false });
              }}
              className="bg-cyan-500 hover:bg-cyan-600 text-white"
            >
              {t('manageStoreData.confirmDialog.confirm')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
