/**
 * Brand Assets Module
 *
 * Manage logos, favicons, social media images, and other brand assets.
 * Supports both file upload and URL input for asset sources.
 */

'use client';

import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useSearchParams } from 'next/navigation';
import { Image, Upload, Link, X, Check, Trash2, Edit, Plus, Download, Eye, Calendar, FileText, Tag, Loader2, CheckCircle2, XCircle, Info, Search, Wand2, Database, ChevronDown, ChevronRight, Sparkles, LayoutGrid, List, ChevronLeft, Edit2 } from 'lucide-react';
import { brandAssetApi, API_URL } from '@/services/api';
import ImageGenerationModal from './ImageGenerationModal';
import PrimaryLogoFlowModal from './PrimaryLogoFlowModal';
import SecondaryLogoFlowModal from './SecondaryLogoFlowModal';
import LogoVariationsFlowModal from './LogoVariationsFlowModal';
import BrandPatternFlowModal from './BrandPatternFlowModal';
import WatermarkFlowModal from './WatermarkFlowModal';
import BrandIdentityRoadmap from './BrandIdentityRoadmap';
import { useAuthStore, useCompanyStore, useDataStore, usePermissionStore } from '@/stores';
import AssetSelectionModal from '@/modules/shared/AssetSelectionModal';
import FounderEmployeeSelector from '@/modules/shared/FounderEmployeeSelector';
import { cn } from '@/utils/cn';
import { isGibberish, isSpecialCharOnly, isNumericOnly } from '@/utils/inputValidation';
import { escapeCsv, escapeCsvArray, escapeCsvBool, exportCsv, BASE64_MARKER, sanitizeDataUrl, parseTabularCsv, validateBrandAssetCsv, csvRowToBrandAsset, generateBrandAssetTemplate } from '@/utils/export';
import { ClearAllConfirm, AutoResizeTextarea, DeleteConfirm } from '@/components/ui';
import { Button } from '@/components/ui/Button';
import { IconButton } from '@/components/ui/Tooltip';
import { PaginationBar } from '@/components/shared/PaginationBar';
import { useToast } from '@/contexts/ToastContext';
import { formatDateTime } from '@/utils';
import type { BrandAsset, DataSourceKey } from '@/types/entities';
import { ASSET_TYPE_GROUPS, findCategoryByValue, getDownloadFormats, type AssetTypeCategory, type AiGenerationContext } from './assetTypes';
import { BRAND_ASSET_DATA_SOURCES } from './brandAssetDataSources';
import { DataSourceSelector } from '@/modules/sales/whatsapp-nurturing/components/shared/DataSourceSelector';
import { useFoundationalContext, prefetchFoundationalContext } from '@/modules/sales/whatsapp-nurturing/hooks/useFoundationalContext';
// ============================================
// BRAND ASSET TAGS
// ============================================

const BRAND_ASSET_TAGS = [
  { value: 'logo-primary', label: 'Primary Logo' },
  { value: 'logo-secondary', label: 'Secondary Logo' },
  { value: 'logo-icon', label: 'Logo Icon' },
  { value: 'favicon', label: 'Favicon' },
  { value: 'social-og', label: 'Social OG' },
  { value: 'social-twitter', label: 'Twitter Card' },
  { value: 'social-linkedin', label: 'LinkedIn' },
  { value: 'social-instagram', label: 'Instagram' },
  { value: 'social-facebook', label: 'Facebook' },
  { value: 'social-tiktok', label: 'TikTok' },
  { value: 'social-youtube', label: 'YouTube' },
  { value: 'email-header', label: 'Email Header' },
  { value: 'email-footer', label: 'Email Footer' },
  { value: 'email-signature', label: 'Email Signature' },
  { value: 'presentation', label: 'Presentation' },
  { value: 'document', label: 'Document' },
  { value: 'web-banner', label: 'Web Banner' },
  { value: 'app-icon', label: 'App Icon' },
  { value: 'pattern', label: 'Pattern' },
  { value: 'background', label: 'Background' },
  { value: 'print-ready', label: 'Print Ready' },
  { value: 'vector', label: 'Vector' },
  { value: 'transparent', label: 'Transparent' },
  { value: 'dark-version', label: 'Dark Version' },
  { value: 'light-version', label: 'Light Version' },
];

// ============================================
// ASSET TYPES
// ============================================

const ASSET_TYPES = [
  { value: 'logo', label: 'Primary Logo' },
  { value: 'secondary-logo', label: 'Secondary Logo' },
  { value: 'wordmark', label: 'Wordmark' },
  { value: 'logo-icon', label: 'Logo Icon' },
  { value: 'logoMarkLight', label: 'Light Logo Mark' },
  { value: 'logoMarkDark', label: 'Dark Logo Mark' },
  { value: 'logoHorizontal', label: 'Horizontal Logo' },
  { value: 'logoVertical', label: 'Vertical Logo' },
  { value: 'favicon', label: 'Favicon' },
  { value: 'social-og', label: 'Social OG Image' },
  { value: 'social-twitter', label: 'Twitter Card' },
  { value: 'social-linkedin', label: 'LinkedIn Image' },
  { value: 'social-instagram', label: 'Instagram Image' },
  { value: 'social-facebook', label: 'Facebook Image' },
  { value: 'social-tiktok', label: 'TikTok Image' },
  { value: 'social-youtube', label: 'YouTube Thumbnail' },
  { value: 'email-header', label: 'Email Header' },
  { value: 'email-footer', label: 'Email Footer' },
  { value: 'presentation', label: 'Presentation Template' },
  { value: 'document', label: 'Document Template' },
  { value: 'web-banner', label: 'Web Banner' },
  { value: 'app-icon', label: 'App Icon' },
  { value: 'brandPattern', label: 'Brand Pattern' },
  { value: 'backgroundImage', label: 'Background Image' },
  { value: 'watermark', label: 'Watermark' },
  { value: 'virtual-background', label: 'Virtual Background (Zoom/Meet)' },
  { value: 'clear-space-guidelines', label: 'Clear Space Guidelines' },
  { value: 'minimum-size-guidelines', label: 'Minimum Size Guidelines' },
  { value: 'brand-usage-rules', label: 'Brand Usage Rules' },
  { value: 'dos-and-donts', label: "Do's and Don'ts" },
  { value: 'other', label: 'Other' },
];

// ============================================
// COMPONENT: Asset Card
// ============================================

function AssetCard({
  asset,
  onView,
  onEdit,
  onDelete,
  onSetPrimary,
  canEdit = true,
  canDelete = true,
}: {
  asset: BrandAsset;
  onView: (asset: BrandAsset) => void;
  onEdit: (asset: BrandAsset) => void;
  onDelete: (id: string) => void;
  onSetPrimary: (id: string, isPrimary: boolean) => void;
  canEdit?: boolean;
  canDelete?: boolean;
}) {
  const [imageError, setImageError] = useState(false);
  const [imageSrc, setImageSrc] = useState<string | null>(null);
  const [isLoadingImage, setIsLoadingImage] = useState(false);

  // Determine if this asset has an image to display
  // New records have url pointing to /uploads/brand-assets/... (filesystem path)
  // Legacy records may have base64Data or a data: URL
  const hasImageUrl = asset.url && !asset.url.startsWith('data:');

  useEffect(() => {
    // New records: url is a filesystem path (/uploads/brand-assets/...)
    // or an external URL (https://...)
    if (hasImageUrl) {
      setImageSrc(asset.url!);
      return;
    }
    // Legacy records: base64Data may be available directly
    if (asset.base64Data) {
      setImageSrc(asset.base64Data);
      return;
    }
    // Legacy records where base64Data was excluded from list — fetch on demand
    if ((asset.source === 'upload' || asset.source === 'ai-generation') && asset.id) {
      setIsLoadingImage(true);
      brandAssetApi.getBase64(asset.id).then((res) => {
        // Prefer URL (filesystem path) for migrated records; fall back to base64Data for legacy
        if (res.data?.url) {
          setImageSrc(res.data.url);
        } else if (res.data?.base64Data) {
          setImageSrc(res.data.base64Data);
        }
        setIsLoadingImage(false);
      }).catch(() => {
        setIsLoadingImage(false);
      });
    }
  }, [asset.id, hasImageUrl, asset.base64Data, asset.source, asset.url]);

  const getAssetIcon = () => {
    if (asset.type?.includes('logo')) return '🔷';
    if (asset.type?.includes('favicon')) return '🔖';
    if (asset.type?.includes('social')) return '📱';
    if (asset.type?.includes('email')) return '📧';
    if (asset.type?.includes('presentation')) return '📊';
    if (asset.type?.includes('document')) return '📄';
    if (asset.type === 'virtual-background') return '🖥️';
    if (asset.type === 'clear-space-guidelines') return '📐';
    if (asset.type === 'minimum-size-guidelines') return '📏';
    if (asset.type === 'brand-usage-rules') return '📋';
    if (asset.type === 'dos-and-donts') return '✅';
    return '🎨';
  };

  // Check if this is a guidelines asset (text content, not image)
  const isGuidelinesAsset = asset.type === 'clear-space-guidelines'
    || asset.type === 'minimum-size-guidelines'
    || asset.type === 'brand-usage-rules'
    || asset.type === 'dos-and-donts';

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return '';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <div className="bg-slate-900/50 border border-slate-800 rounded-xl overflow-hidden hover:border-slate-600 transition-colors">
      {/* Preview */}
      <div className="aspect-video bg-slate-800/50 relative group">
        {isGuidelinesAsset ? (
          // Guidelines asset: show document-style preview
          <div className="w-full h-full flex flex-col items-center justify-center p-4">
            <div className="text-6xl mb-2">{getAssetIcon()}</div>
            <div className="text-sm text-slate-300 text-center font-medium">{ASSET_TYPES.find(t => t.value === asset.type)?.label || asset.type}</div>
            {asset.contentData && (
              <div className="text-xs text-slate-500 mt-1 text-center">AI-Generated Guidelines</div>
            )}
          </div>
        ) : isLoadingImage ? (
          <div className="w-full h-full flex items-center justify-center">
            <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : imageSrc && !imageError ? (
          <img
            src={imageSrc}
            alt={asset.name}
            className="w-full h-full object-contain p-4"
            onError={() => setImageError(true)}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <div className="text-6xl">{getAssetIcon()}</div>
          </div>
        )}

        {/* Hover Actions */}
        <div className="absolute inset-0 bg-slate-950/80 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
          <button
            onClick={() => onView(asset)}
            className="p-2 bg-slate-700 hover:bg-slate-600 rounded-lg text-white"
            title="View Details"
          >
            <Eye className="w-5 h-5" />
          </button>
          {canEdit && (
            <button
              onClick={() => onEdit(asset)}
              className="p-2 bg-primary-500 hover:bg-primary-400 rounded-lg text-slate-900"
              title="Edit"
            >
              <Edit className="w-5 h-5" />
            </button>
          )}
          {canDelete && (
            <button
              onClick={() => onDelete(asset.id)}
              className="p-2 bg-red-500 hover:bg-red-400 rounded-lg text-white"
              title="Delete"
            >
              <Trash2 className="w-5 h-5" />
            </button>
          )}
        </div>
      </div>

      {/* Info */}
      <div className="p-4 space-y-3">
        <div className="flex items-start justify-between">
          <div>
            <h3 className="font-medium text-slate-200">{asset.name}</h3>
            <p className="text-xs text-slate-500">
              {ASSET_TYPES.find(t => t.value === asset.type)?.label || asset.type}
            </p>
          </div>
          {asset.isPrimary && (
            <span className="px-2 py-1 bg-[#C8FF2E]/20 text-[#C8FF2E] text-xs rounded-full font-medium">
              Primary
            </span>
          )}
        </div>

        {/* Tags */}
        {asset.tags && asset.tags.length > 0 && (
          <div className="flex flex-wrap gap-1">
            {asset.tags.slice(0, 3).map((tag) => (
              <span
                key={tag}
                className="px-2 py-0.5 bg-slate-800 text-slate-400 text-xs rounded"
              >
                {BRAND_ASSET_TAGS.find(t => t.value === tag)?.label || tag}
              </span>
            ))}
            {asset.tags.length > 3 && (
              <span className="text-xs text-slate-500">+{asset.tags.length - 3}</span>
            )}
          </div>
        )}

        {/* Metadata */}
        <div className="flex items-center justify-between text-xs text-slate-500 pt-2 border-t border-slate-800">
          <span>{formatFileSize(asset.fileSize)}</span>
          {asset.dimensions?.width && asset.dimensions?.height && (
            <span>{asset.dimensions.width}×{asset.dimensions.height}</span>
          )}
        </div>

        {/* Source Type & Design Link */}
        <div className="flex items-center gap-3 text-xs text-slate-500">
          <span className="flex items-center gap-1">
            {asset.source === 'upload' || asset.source === 'ai-generation' ? (
              <>
                <Upload className="w-3 h-3" />
                <span>Uploaded</span>
              </>
            ) : (
              <>
                <Link className="w-3 h-3" />
                <span>URL</span>
              </>
            )}
          </span>
          {asset.sourceUrl && (
            <a
              href={asset.sourceUrl}
              target="_blank"
              rel="noopener noreferrer"
              onClick={(e) => e.stopPropagation()}
              className="flex items-center gap-1 text-primary-400 hover:text-primary-300"
            >
              <span>Design File</span>
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================
// COMPONENT: Asset Form Modal
// ============================================

function AssetFormModal({
  isOpen,
  onClose,
  onSave,
  asset,
  onGenerateWithAi,
  companyId,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: any) => void;
  asset?: BrandAsset | null;
  onGenerateWithAi?: (context: AiGenerationContext) => void;
  companyId?: string;
}) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const foundationalContext = useFoundationalContext();
  const [assetTypeCategory, setAssetTypeCategory] = useState<AssetTypeCategory | ''>('');
  const [showDataSources, setShowDataSources] = useState(false);
  const [selectedSources, setSelectedSources] = useState<DataSourceKey[]>([]);
  const [linkedData, setLinkedData] = useState<Record<string, string[] | string | undefined>>({});
  const [formData, setFormData] = useState({
    name: '',
    type: '',
    description: '',
    url: '',
    sourceUrl: '', // Canva/Figma/design file URL
    tags: [] as string[],
    isPrimary: false,
  });
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [isUploading, setIsUploading] = useState(false);
  const [editFormat, setEditFormat] = useState('png');
  const [isEditDownloading, setIsEditDownloading] = useState(false);
  const [fileSizeError, setFileSizeError] = useState<string>('');
  const [nameError, setNameError] = useState<string>('');

  useEffect(() => {
    if (asset) {
      // When editing an existing asset, find the matching group for its type
      const matchingGroup = ASSET_TYPE_GROUPS.find(g =>
        g.categories.some(cat => cat.value === asset.type)
      );
      // Set default download format based on asset type
      const formats = getDownloadFormats(asset.type);
      if (formats.length > 0) {
        setEditFormat(formats[0].value);
      }
      setAssetTypeCategory(matchingGroup?.id || '');
      setFormData({
        name: asset.name || '',
        type: asset.type || '',
        description: asset.description || '',
        url: asset.url || '',
        sourceUrl: asset.sourceUrl || '',
        tags: asset.tags || [],
        isPrimary: asset.isPrimary || false,
      });
      // If asset has an image URL (filesystem path or external), show it as preview
      if (asset.url && !asset.url.startsWith('data:')) {
        setPreviewUrl(asset.url);
      } else if (asset.base64Data) {
        // Legacy record with base64Data
        setPreviewUrl(asset.base64Data);
      } else if ((asset.source === 'upload' || asset.source === 'ai-generation') && asset.id) {
        // base64Data excluded from list response — fetch it on demand
        brandAssetApi.getBase64(asset.id).then((res) => {
          if (res.data?.url) {
            setPreviewUrl(res.data.url);
          } else if (res.data?.base64Data) {
            setPreviewUrl(res.data.base64Data);
          }
        }).catch(() => {
          // Preview unavailable — user can still re-upload
        });
      }
      setSelectedFile(null);
      setFileSizeError('');
    } else {
      setAssetTypeCategory('');
      setFormData({
        name: '',
        type: '',
        description: '',
        url: '',
        sourceUrl: '',
        tags: [],
        isPrimary: false,
      });
      setSelectedFile(null);
      setPreviewUrl('');
      setFileSizeError('');
      setNameError('');
      setShowDataSources(false);
      setSelectedSources([]);
      setLinkedData({});
    }
  }, [asset, isOpen]);

  const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
  const MIN_FILE_SIZE = 1 * 1024; // 1 KB

  const validateFileSize = (file: File): boolean => {
    if (file.size > MAX_FILE_SIZE) {
      setFileSizeError(`File size (${(file.size / (1024 * 1024)).toFixed(2)} MB) exceeds the 10 MB limit. Please choose a smaller file.`);
      return false;
    }
    if (file.size < MIN_FILE_SIZE) {
      setFileSizeError(`File size (${(file.size / 1024).toFixed(2)} KB) is below the 1 KB minimum. The file may be corrupted or empty.`);
      return false;
    }
    setFileSizeError('');
    return true;
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (!validateFileSize(file)) {
        setSelectedFile(null);
        setPreviewUrl(asset?.base64Data || '');
        // Reset the file input so the same file can be re-selected after correction
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
        return;
      }
      setFileSizeError('');
      setSelectedFile(file);
      setPreviewUrl(URL.createObjectURL(file));
    }
  };

  // Extract format from file or URL
  const getFormat = (): string => {
    if (selectedFile) {
      const ext = selectedFile.name.split('.').pop()?.toLowerCase();
      if (!ext) return 'png';
      // Normalise jpeg → jpg to match backend enum
      return ext === 'jpeg' ? 'jpg' : ext;
    }
    if (formData.url) {
      try {
        const url = new URL(formData.url);
        const pathname = url.pathname;
        const ext = pathname.split('.').pop()?.toLowerCase();
        if (ext && ['svg', 'png', 'jpg', 'jpeg', 'webp', 'pdf', 'ico', 'gif'].includes(ext)) {
          return ext === 'jpeg' ? 'jpg' : ext;
        }
      } catch {
        // Invalid URL, fallback to png
      }
    }
    return 'png'; // Default format
  };

  // Real-time name validation
  const validateName = (name: string): string | null => {
    const trimmed = name.trim();
    if (!trimmed) return null; // Empty is handled by required check
    if (isSpecialCharOnly(trimmed)) return 'Asset name cannot contain only special characters. Please include letters or numbers.';
    if (isNumericOnly(trimmed)) return 'Asset name cannot be numbers only. Please include letters.';
    if (isGibberish(trimmed)) return 'Please enter a meaningful asset name.';
    return null;
  };

  const handleSave = async () => {
    if (!formData.name || !formData.type) return;

    // Validate name for gibberish/invalid input
    const nameValidationError = validateName(formData.name);
    if (nameValidationError) {
      setNameError(nameValidationError);
      return;
    }
    setNameError('');

    // Validate file size before upload
    if (selectedFile && !validateFileSize(selectedFile)) {
      setIsUploading(false);
      return;
    }

    setIsUploading(true);

    const format = getFormat();

    // If uploading a file, send multipart/form-data via the file upload API
    if (selectedFile) {
      onSave({
        ...formData,
        format,
        file: selectedFile,
        source: 'upload',
      });
      setIsUploading(false);
    } else {
      const data: any = {
        ...formData,
        format,
        source: 'url',
      };
      onSave(data);
      setIsUploading(false);
    }
  };

  const toggleTag = (tagValue: string) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.includes(tagValue)
        ? prev.tags.filter(t => t !== tagValue)
        : [...prev.tags, tagValue],
    }));
  };

  if (!isOpen) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[9998] flex items-center justify-center p-2 sm:p-4"
      style={{ width: '100vw', height: '100vh' }}
    >
      {/* Backdrop overlay */}
      <div
        className="absolute inset-0 bg-black/45 backdrop-blur-sm"
        style={{ backdropFilter: 'blur(8px)' }}
        onClick={onClose}
      />
      {/* Modal content */}
      <div className="relative z-[9999] bg-slate-900 border border-slate-800 rounded-2xl w-full max-w-7xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl">
        {/* Header */}
        <div className="px-4 sm:px-6 py-4 border-b border-slate-800 flex items-center justify-between">
          <h2 className="text-lg sm:text-xl font-semibold text-slate-200">
            {asset ? 'Edit Asset' : 'Add Asset'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-slate-800 rounded-lg text-slate-400 hover:text-slate-200 transition-colors"
            title="Close"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4 sm:space-y-6">
          {/* Upload Section - Optional */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Upload Asset File
              <span className="text-slate-500 font-normal ml-2">- or use URLs below</span>
            </label>
            <div
              onClick={() => fileInputRef.current?.click()}
              onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); }}
              onDrop={(e) => {
                e.preventDefault();
                e.stopPropagation();
                const file = e.dataTransfer.files?.[0];
                if (file) {
                  if (validateFileSize(file)) {
                    setSelectedFile(file);
                    if (file.type.startsWith('image/')) {
                      setPreviewUrl(URL.createObjectURL(file));
                    } else {
                      setPreviewUrl('');
                    }
                  } else {
                    setSelectedFile(null);
                    setPreviewUrl(asset?.base64Data || '');
                  }
                }
              }}
              className={cn(
                'border-2 border-dashed rounded-xl p-6 cursor-pointer transition-colors',
                selectedFile || (previewUrl && asset)
                  ? 'border-primary-500 bg-primary-500/10'
                  : 'border-slate-700 hover:border-slate-600 bg-slate-800/30'
              )}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*,.svg,.pdf"
                onChange={handleFileChange}
                className="hidden"
              />
              {selectedFile ? (
                <div className="text-center">
                  {previewUrl ? (
                    <img
                      src={previewUrl}
                      alt="Preview"
                      className="w-24 h-24 object-contain mx-auto mb-3 rounded-lg"
                    />
                  ) : (
                    <div className="w-12 h-12 bg-primary-500/20 rounded-xl flex items-center justify-center mx-auto mb-3">
                      <Check className="w-6 h-6 text-primary-400" />
                    </div>
                  )}
                  <p className="text-slate-200 font-medium text-sm">{selectedFile.name}</p>
                  <p className="text-xs text-slate-500">
                    {(selectedFile.size / 1024).toFixed(1)} KB
                  </p>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setSelectedFile(null);
                      setPreviewUrl(asset?.base64Data || '');
                    }}
                    className="mt-2 text-sm text-red-400 hover:text-red-300"
                  >
                    Remove
                  </button>
                </div>
              ) : previewUrl && asset ? (
                <div className="text-center">
                  {previewUrl && !asset.fileName?.toLowerCase().endsWith('.pdf') ? (
                    <img
                      src={previewUrl}
                      alt="Current file preview"
                      className="w-24 h-24 object-contain mx-auto mb-3 rounded-lg"
                    />
                  ) : (
                    <div className="w-12 h-12 bg-primary-500/20 rounded-xl flex items-center justify-center mx-auto mb-3">
                      <Image className="w-6 h-6 text-primary-400" />
                    </div>
                  )}
                  <p className="text-slate-200 font-medium text-sm">
                    {asset.fileName || 'Current file'}
                  </p>
                  {asset.fileSize && (
                    <p className="text-xs text-slate-500">
                      {(asset.fileSize / 1024).toFixed(1)} KB
                    </p>
                  )}
                  {asset.fileType && (
                    <p className="text-xs text-slate-500">
                      {asset.fileType}
                    </p>
                  )}
                  <div className="flex items-center justify-center gap-3 mt-2">
                    {previewUrl && (() => {
                      const editFormats = asset ? getDownloadFormats(asset.type) : [];
                      const isImage = editFormats.length > 0;
                      const handleEditDownload = async () => {
                        if (!asset?.id) return;
                        setIsEditDownloading(true);
                        try {
                          const token = useAuthStore.getState().token;
                          const downloadUrl = brandAssetApi.getDownloadUrl(asset.id, editFormat);
                          const response = await fetch(`${API_URL}${downloadUrl}`, {
                            headers: { Authorization: `Bearer ${token}` },
                          });
                          if (!response.ok) throw new Error('Download failed');
                          const blob = await response.blob();
                          const url = URL.createObjectURL(blob);
                          const link = document.createElement('a');
                          const extMap: Record<string, string> = { png: 'png', jpg: 'jpg', svg: 'svg', ico: 'ico' };
                          const sanitizedName = (asset.name || 'asset').toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9\-]/g, '');
                          link.href = url;
                          link.download = `${sanitizedName}.${extMap[editFormat] || editFormat}`;
                          document.body.appendChild(link);
                          link.click();
                          document.body.removeChild(link);
                          URL.revokeObjectURL(url);
                        } catch {
                          // Fallback to direct URL download
                          const link = document.createElement('a');
                          link.href = previewUrl;
                          link.download = asset?.fileName || 'asset';
                          document.body.appendChild(link);
                          link.click();
                          document.body.removeChild(link);
                        } finally {
                          setIsEditDownloading(false);
                        }
                      };
                      return isImage ? (
                        <div className="flex items-center gap-2">
                          <select
                            value={editFormat}
                            onChange={(e) => setEditFormat(e.target.value)}
                            onClick={(e) => e.stopPropagation()}
                            className="px-2 py-1 bg-slate-800 border border-slate-700 rounded text-slate-200 text-xs focus:outline-none focus:ring-1 focus:ring-primary-500"
                          >
                            {editFormats.map((fmt) => (
                              <option key={fmt.value} value={fmt.value}>{fmt.label}</option>
                            ))}
                          </select>
                          <button
                            onClick={(e) => { e.stopPropagation(); handleEditDownload(); }}
                            disabled={isEditDownloading}
                            className="text-sm text-primary-400 hover:text-primary-300 flex items-center gap-1 disabled:opacity-50"
                          >
                            {isEditDownloading ? (
                              <div className="w-3.5 h-3.5 border-2 border-primary-400 border-t-transparent rounded-full animate-spin" />
                            ) : (
                              <Download className="w-3.5 h-3.5" />
                            )}
                            {isEditDownloading ? 'Converting...' : `Download ${editFormat.toUpperCase()}`}
                          </button>
                        </div>
                      ) : (
                        <a
                          href={previewUrl}
                          download={asset.fileName || 'asset'}
                          onClick={(e) => e.stopPropagation()}
                          className="text-sm text-primary-400 hover:text-primary-300 flex items-center gap-1"
                        >
                          <Download className="w-3.5 h-3.5" />
                          Download
                        </a>
                      );
                    })()}
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        fileInputRef.current?.click();
                      }}
                      className="text-sm text-slate-400 hover:text-slate-300"
                    >
                      Replace file
                    </button>
                  </div>
                  <p className="text-xs text-slate-500 mt-2">
                    Click area or "Replace file" to upload a new file
                  </p>
                </div>
              ) : (
                <div className="text-center">
                  <div className="w-12 h-12 bg-slate-800 rounded-xl flex items-center justify-center mx-auto mb-2">
                    <Upload className="w-6 h-6 text-slate-400" />
                  </div>
                  <p className="text-slate-300 font-medium text-sm">Click to upload file</p>
                  <p className="text-xs text-slate-500 mt-1">
                    SVG, PNG, JPG, WebP, PDF (1 KB – 10 MB)
                  </p>
                </div>
              )}
            </div>
            {fileSizeError && (
              <p className="mt-2 text-sm text-red-400 flex items-center gap-1">
                <X className="w-4 h-4 flex-shrink-0" />
                {fileSizeError}
              </p>
            )}
          </div>

          {/* URL Fields - Two Column Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Asset URL */}
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">
                Asset URL
                <span className="text-slate-500 font-normal ml-1">- External link</span>
              </label>
              <input
                type="url"
                value={formData.url}
                onChange={(e) => setFormData(prev => ({ ...prev, url: e.target.value }))}
                placeholder="https://cdn.example.com/logo.png"
                className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"
              />
            </div>

            {/* Source Design URL */}
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">
                Source Design URL
                <span className="text-slate-500 font-normal ml-1">- Canva, Figma, etc.</span>
              </label>
              <input
                type="url"
                value={formData.sourceUrl}
                onChange={(e) => setFormData(prev => ({ ...prev, sourceUrl: e.target.value }))}
                placeholder="https://www.figma.com/file/..."
                className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"
              />
            </div>
          </div>

          {/* Name and Type - Two Column Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Name */}
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">
                Asset Name<span className="text-red-400">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => { setFormData(prev => ({ ...prev, name: e.target.value })); setNameError(validateName(e.target.value) || ''); }}
                placeholder="e.g., Primary Logo Dark"
                className={`w-full px-4 py-3 bg-slate-800 border rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none ${nameError ? 'border-red-500' : 'border-slate-700'}`}
              />
              {nameError && <p className="mt-1 text-xs text-red-400">{nameError}</p>}
            </div>

            {/* Asset Type Category */}
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">
                Asset Type<span className="text-red-400">*</span>
              </label>
              <select
                value={assetTypeCategory}
                onChange={(e) => {
                  setAssetTypeCategory(e.target.value as AssetTypeCategory | '');
                  setFormData(prev => ({ ...prev, type: '' }));
                }}
                className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"
              >
                <option value="">Select type...</option>
                {ASSET_TYPE_GROUPS.map(group => (
                  <option key={group.id} value={group.id}>
                    {group.icon} {group.label}
                  </option>
                ))}
              </select>
              {assetTypeCategory && (
                <p className="text-xs text-slate-500 mt-1">
                  {ASSET_TYPE_GROUPS.find(g => g.id === assetTypeCategory)?.description}
                </p>
              )}
            </div>
          </div>

          {/* Category (Conditional) */}
          {assetTypeCategory && (
            <div className="w-full md:w-1/2">
              <label className="block text-sm font-medium text-slate-300 mb-2">
                Category<span className="text-red-400">*</span>
              </label>
              <select
                value={formData.type}
                onChange={(e) => setFormData(prev => ({ ...prev, type: e.target.value }))}
                className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"
              >
                <option value="">Select category...</option>
                {ASSET_TYPE_GROUPS.find(g => g.id === assetTypeCategory)?.categories.map(cat => (
                  <option key={cat.value} value={cat.value}>
                    {cat.label}
                  </option>
                ))}
              </select>
            </div>
          )}

          {/* Generate with AI button — appears when category is selected */}
          {formData.type && onGenerateWithAi && (
            <div className="bg-primary-500/5 border border-primary-500/20 rounded-xl p-4 space-y-3">
              <div className="flex items-center gap-2">
                <Sparkles className="w-5 h-5 text-primary-400" />
                <h4 className="text-sm font-medium text-primary-400">AI Generation</h4>
              </div>
              <p className="text-sm text-slate-400">
                Generate a {findCategoryByValue(formData.type)?.label || 'asset'} using AI with brand-aware context.
                The AI will use your brand strategy, visual identity, and business profile data.
              </p>
              <div className="flex flex-col gap-2">
                <button
                  onClick={() => {
                    const category = findCategoryByValue(formData.type);
                    if (!category) return;
                    const context: AiGenerationContext = {
                      assetTypeCategory: assetTypeCategory as AssetTypeCategory,
                      assetCategory: formData.type,
                      assetName: formData.name || `${category.label}`,
                      requirements: formData.description || '',
                      linkedData,
                      defaultStyle: category.defaultStyle,
                      defaultPlatform: category.defaultPlatform,
                      defaultAspectRatio: category.defaultAspectRatio,
                      promptHint: category.promptHint,
                    };
                    onGenerateWithAi(context);
                  }}
                  className="flex items-center justify-center gap-2 px-4 py-2.5 bg-primary-500 hover:bg-primary-400 text-neutral-900 font-medium rounded-lg transition-all"
                >
                  <Wand2 className="w-4 h-4" />
                  Generate with AI
                </button>

                {/* Data Sources toggle */}
                <button
                  onClick={() => setShowDataSources(!showDataSources)}
                  className="flex items-center gap-2 text-sm text-slate-400 hover:text-slate-200 transition-colors"
                >
                  <Database className="w-4 h-4" />
                  {showDataSources ? 'Hide' : 'Select'} Brand Data Sources
                  {Object.values(linkedData).some(v => Array.isArray(v) ? v.length > 0 : typeof v === 'string' && v.length > 0) && (
                    <span className="bg-primary-500/20 text-primary-400 px-2 py-0.5 rounded-full text-xs">
                      {Object.entries(linkedData).filter(([, v]) => Array.isArray(v) ? v.length > 0 : typeof v === 'string' && v.length > 0).length} linked
                    </span>
                  )}
                  {showDataSources ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                </button>
              </div>

              {showDataSources && (
                <div className="mt-3">
                  <DataSourceSelector
                    selected={selectedSources}
                    onChange={setSelectedSources}
                    sources={BRAND_ASSET_DATA_SOURCES}
                    linkedData={linkedData}
                    onLinkedDataChange={setLinkedData}
                    foundationalContext={foundationalContext}
                    title="Brand Data Sources"
                    description="Select brand data to enrich AI-generated images with your brand identity, voice, and audience insights."
                  />
                </div>
              )}
            </div>
          )}

          {/* Description - Full Width */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Description (Optional)
            </label>
            <AutoResizeTextarea
              value={formData.description}
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              placeholder="Optional — brief description of this asset..."
              rows={2}
              className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"
            />
          </div>

          {/* Primary Toggle - Full Width */}
          <div className="flex items-center gap-3 p-4 bg-slate-800/50 rounded-xl">
            <input
              type="checkbox"
              id="isPrimary"
              checked={formData.isPrimary}
              onChange={(e) => setFormData(prev => ({ ...prev, isPrimary: e.target.checked }))}
              className="w-5 h-5 rounded border-slate-600 bg-slate-700 text-primary-500 focus:ring-primary-500 cursor-pointer"
            />
            <label htmlFor="isPrimary" className="flex-1 cursor-pointer">
              <span className="text-sm font-medium text-slate-300">
                Set as Primary Asset for this Type
              </span>
              <p className="text-xs text-slate-500">
                This will be the default asset for this type
              </p>
            </label>
          </div>
        </div>

        {/* Footer */}
        <div className="px-4 sm:px-6 py-4 border-t border-slate-800 flex flex-col sm:flex-row justify-end gap-2 sm:gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-slate-300 hover:text-slate-200 font-medium transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={!formData.name || !formData.type || (!selectedFile && !formData.url && !asset) || isUploading || !!nameError}
            className="px-6 py-2 bg-primary-500 hover:bg-primary-400 disabled:opacity-50 disabled:cursor-not-allowed text-slate-900 font-medium rounded-lg flex items-center justify-center gap-2 transition-colors"
          >
            {isUploading ? (
              <>
                <div className="w-4 h-4 border-2 border-slate-900 border-t-transparent rounded-full animate-spin" />
                Uploading...
              </>
            ) : (
              <>
                <Check className="w-4 h-4" />
                {asset ? 'Save Changes' : 'Add Asset'}
              </>
            )}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ============================================
// COMPONENT: Asset Detail Modal (Read-only view)
// ============================================

function AssetDetailModal({
  isOpen,
  onClose,
  asset,
  canDownload = true,
}: {
  isOpen: boolean;
  onClose: () => void;
  asset: BrandAsset | null;
  canDownload?: boolean;
}) {
  const [imageError, setImageError] = useState(false);
  const [fullAsset, setFullAsset] = useState<BrandAsset | null>(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);
  const [selectedFormat, setSelectedFormat] = useState('png');
  const [isDownloading, setIsDownloading] = useState(false);

  // Fetch the full asset (including base64Data) when the modal opens
  useEffect(() => {
    if (isOpen && asset?.id) {
      setIsLoadingDetail(true);
      brandAssetApi.getById(asset.id).then((res) => {
        if (res.data) {
          setFullAsset(res.data as BrandAsset);
        }
        setIsLoadingDetail(false);
      }).catch(() => {
        setFullAsset(asset);
        setIsLoadingDetail(false);
      });
    } else {
      setFullAsset(null);
    }
  }, [isOpen, asset?.id]);

  // Reset format selection when asset changes
  useEffect(() => {
    if (asset?.type) {
      const formats = getDownloadFormats(asset.type);
      if (formats.length > 0) {
        setSelectedFormat(formats[0].value);
      }
    }
  }, [asset?.type]);

  const displayAsset = fullAsset || asset;

  if (!isOpen || !displayAsset) return null;

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return 'N/A';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const formatDate = (dateStr?: string) => {
    if (!dateStr) return 'N/A';
    try {
      return new Date(dateStr).toLocaleDateString('en-GB', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      });
    } catch {
      return dateStr;
    }
  };

  const assetImage = displayAsset.url || displayAsset.base64Data;

  // Download formats available for this asset type
  const downloadFormats = displayAsset ? getDownloadFormats(displayAsset.type) : [];
  const isImageAsset = downloadFormats.length > 0;

  // Handle authenticated download with format conversion
  const handleFormatDownload = async () => {
    if (!displayAsset?.id || !selectedFormat) return;
    setIsDownloading(true);
    try {
      const token = useAuthStore.getState().token;
      const downloadUrl = brandAssetApi.getDownloadUrl(displayAsset.id, selectedFormat);
      const response = await fetch(`${API_URL}${downloadUrl}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: 'Download failed' }));
        throw new Error(errorData.error || 'Download failed');
      }
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      const extMap: Record<string, string> = { png: 'png', jpg: 'jpg', svg: 'svg', ico: 'ico' };
      const sanitizedName = (displayAsset.name || 'asset').toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9\-]/g, '');
      link.href = url;
      link.download = `${sanitizedName}.${extMap[selectedFormat] || selectedFormat}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } catch (err: any) {
      console.error('Download failed:', err);
      // Fallback: try direct download from URL
      const link = document.createElement('a');
      link.href = assetImage || '';
      link.download = displayAsset?.fileName || displayAsset?.name || 'asset';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } finally {
      setIsDownloading(false);
    }
  };

  return createPortal(
    <div className="fixed inset-0 z-[9998] flex items-center justify-center" style={{ width: '100vw', height: '100vh' }}>
      <div className="absolute inset-0 bg-black/45 backdrop-blur-sm" style={{ WebkitBackdropFilter: 'blur(8px)', backdropFilter: 'blur(8px)' }} onClick={onClose} />
      <div className="relative z-[9999] w-full max-w-6xl bg-[#0d1117] rounded-xl border border-white/10 overflow-hidden flex flex-col max-h-[90vh] sm:max-h-[95vh] mx-4">
        {/* Header */}
        <div className="sticky top-0 z-10 bg-[#0d1117] border-b border-white/10 px-4 sm:px-6 py-4 flex items-center justify-between shrink-0">
          <h2 className="text-lg font-bold text-white">Asset Details</h2>
          <button
            onClick={onClose}
            className="p-1.5 text-[#686f7e] hover:text-white shrink-0 transition-colors"
            title="Close"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-4 sm:p-6 space-y-4 sm:space-y-6 overflow-y-auto flex-1">
          {isLoadingDetail ? (
            <div className="flex items-center justify-center py-12">
              <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : (
          <>
            {/* Preview Image */}
            {assetImage && !imageError && (
              <div className="bg-slate-800/50 rounded-xl overflow-hidden border border-slate-700">
                <img
                  src={assetImage}
                  alt={displayAsset.name}
                  className="w-full max-h-64 object-contain p-4"
                  onError={() => setImageError(true)}
                />
              </div>
            )}

            {/* Name */}
            <div>
              <span className="text-xs text-slate-500 uppercase tracking-wider">Name</span>
              <p className="text-lg font-semibold text-slate-200 mt-1">{displayAsset.name}</p>
            </div>

            {/* Type & Format */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider">Type</span>
                <p className="text-sm text-slate-300 mt-1">
                  {ASSET_TYPES.find(t => t.value === displayAsset.type)?.label || displayAsset.type}
                </p>
              </div>
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider">Format</span>
                <p className="text-sm text-slate-300 mt-1 uppercase">{displayAsset.format || '—'}</p>
              </div>
            </div>

            {/* Primary Status */}
            <div>
              <span className="text-xs text-slate-500 uppercase tracking-wider">Primary</span>
              <div className="mt-1">
                {displayAsset.isPrimary ? (
                  <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-[#C8FF2E]/10 text-[#C8FF2E]">
                    <Check className="w-3 h-3" />
                    Primary Asset
                  </span>
                ) : (
                  <span className="text-sm text-slate-400">No</span>
                )}
              </div>
            </div>

            {/* Description */}
            {displayAsset.description && (
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider">Description</span>
                <p className="text-sm text-slate-300 mt-1 whitespace-pre-wrap">{displayAsset.description}</p>
              </div>
            )}

            {/* Details Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* File Name */}
              <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">File Name</span>
                <p className="text-sm text-slate-200 truncate" title={displayAsset.fileName || '—'}>
                  {displayAsset.fileName || '—'}
                </p>
              </div>

              {/* File Size */}
              <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">File Size</span>
                <p className="text-sm text-slate-200">{formatFileSize(displayAsset.fileSize)}</p>
              </div>

              {/* File Type */}
              {displayAsset.fileType && (
                <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
                  <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">File Type</span>
                  <p className="text-sm text-slate-200">{displayAsset.fileType}</p>
                </div>
              )}

              {/* Source */}
              <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Source</span>
                <p className="text-sm text-slate-200 flex items-center gap-1.5">
                  {displayAsset.source === 'upload' || displayAsset.source === 'ai-generation' ? (
                    <>
                      <Upload className="w-3.5 h-3.5" />
                      Uploaded
                    </>
                  ) : (
                    <>
                      <Link className="w-3.5 h-3.5" />
                      URL
                    </>
                  )}
                </p>
              </div>

              {/* Dimensions */}
              {displayAsset.dimensions?.width && displayAsset.dimensions?.height && (
                <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
                  <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Dimensions</span>
                  <p className="text-sm text-slate-200">{displayAsset.dimensions.width} × {displayAsset.dimensions.height} px</p>
                </div>
              )}
            </div>

            {/* URLs */}
            {(displayAsset.url || displayAsset.sourceUrl) && (
              <div className="space-y-3">
                {displayAsset.url && !displayAsset.url.startsWith('data:') && (
                  <div>
                    <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Asset URL</span>
                    <a
                      href={displayAsset.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-sm text-primary-400 hover:text-primary-300 break-all flex items-center gap-1.5"
                    >
                      {displayAsset.url}
                      <svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                      </svg>
                    </a>
                  </div>
                )}
                {displayAsset.sourceUrl && (
                  <div>
                    <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Source Design URL</span>
                    <a
                      href={displayAsset.sourceUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-sm text-purple-400 hover:text-purple-300 break-all flex items-center gap-1.5"
                    >
                      {displayAsset.sourceUrl}
                      <svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                      </svg>
                    </a>
                  </div>
                )}
              </div>
            )}

            {/* Tags */}
            {displayAsset.tags && displayAsset.tags.length > 0 && (
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-2">Tags</span>
                <div className="flex flex-wrap gap-2">
                  {displayAsset.tags.map((tag) => (
                    <span
                      key={tag}
                      className="px-2.5 py-1 bg-slate-800 text-slate-400 text-xs rounded-full border border-slate-700"
                    >
                      {BRAND_ASSET_TAGS.find(t => t.value === tag)?.label || tag}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Guidelines Content (for text-based guideline assets) */}
            {displayAsset.contentData && (() => {
              try {
                const guidelines = typeof displayAsset.contentData === 'string'
                  ? JSON.parse(displayAsset.contentData)
                  : displayAsset.contentData;
                return (
                  <div className="space-y-4">
                    <h3 className="text-sm font-medium text-slate-200 flex items-center gap-2">
                      📐 Generated Guidelines
                    </h3>
                    {guidelines.summary && (
                      <div className="bg-slate-800/50 rounded-lg p-4">
                        <p className="text-sm text-slate-300 leading-relaxed">{guidelines.summary}</p>
                      </div>
                    )}
                    {(guidelines.rules || guidelines.measurements || guidelines.sections || guidelines.items || guidelines.digitalMinimums || guidelines.printMinimums || guidelines.scalingRules) && (
                      <div className="space-y-3">
                        {(guidelines.rules as any[])?.map((r: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3">
                            <p className="text-sm text-slate-200 font-medium">{r.rule}</p>
                            {r.explanation && <p className="text-xs text-slate-400 mt-1">{r.explanation}</p>}
                          </div>
                        ))}
                        {(guidelines.measurements as any[])?.map((m: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3 flex items-center justify-between">
                            <p className="text-sm text-slate-200">{m.context}</p>
                            <p className="text-sm text-primary-400 font-medium">{m.minimumSpace} {m.unit}</p>
                          </div>
                        ))}
                        {(guidelines.digitalMinimums as any[])?.map((m: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3 flex items-center justify-between">
                            <p className="text-sm text-slate-200">{m.context}</p>
                            <p className="text-sm text-primary-400 font-medium">{m.minWidth} × {m.minHeight}</p>
                          </div>
                        ))}
                        {(guidelines.printMinimums as any[])?.map((m: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3 flex items-center justify-between">
                            <p className="text-sm text-slate-200">{m.context}</p>
                            <p className="text-sm text-primary-400 font-medium">{m.width} × {m.height} {m.unit}</p>
                          </div>
                        ))}
                        {(guidelines.scalingRules as any[])?.map((r: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3">
                            <p className="text-sm text-slate-200 font-medium">{r.rule}</p>
                            {r.explanation && <p className="text-xs text-slate-400 mt-1">{r.explanation}</p>}
                          </div>
                        ))}
                        {(guidelines.backgrounds as any[])?.map((b: any, i: number) => (
                          <div key={i} className="bg-slate-800/50 rounded-lg p-3 flex items-center justify-between">
                            <p className="text-sm text-slate-200">{b.type}</p>
                            <span className={`px-2 py-0.5 rounded text-xs font-medium ${b.allowed ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'}`}>
                              {b.allowed ? '✓ Allowed' : '✗ Not Allowed'}
                            </span>
                          </div>
                        ))}
                        {(guidelines.sections as any[])?.map((section: any, i: number) => (
                          <div key={i} className="space-y-2">
                            <h4 className="text-sm font-medium text-primary-400">{section.category}</h4>
                            {section.rules?.map((r: any, j: number) => (
                              <div key={j} className="bg-slate-800/50 rounded-lg p-3 ml-3">
                                <p className="text-sm text-slate-200">{r.rule}</p>
                                {r.details && <p className="text-xs text-slate-400 mt-1">{r.details}</p>}
                              </div>
                            ))}
                          </div>
                        ))}
                        {(guidelines.items as any[])?.map((item: any, i: number) => (
                          <div key={i} className="space-y-3">
                            <h4 className="text-sm font-medium text-primary-400">{item.category}</h4>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 ml-3">
                              <div className="space-y-2">
                                <p className="text-xs text-green-400 font-medium uppercase tracking-wider">{"Do's"}</p>
                                {item.dos?.map((d: any, j: number) => (
                                  <div key={j} className="bg-green-500/10 border border-green-500/20 rounded-lg p-3">
                                    <p className="text-sm text-green-300 font-medium">{d.title}</p>
                                    {d.description && <p className="text-xs text-slate-400 mt-1">{d.description}</p>}
                                  </div>
                                ))}
                              </div>
                              <div className="space-y-2">
                                <p className="text-xs text-red-400 font-medium uppercase tracking-wider">{"Don'ts"}</p>
                                {item.donts?.map((d: any, j: number) => (
                                  <div key={j} className="bg-red-500/10 border border-red-500/20 rounded-lg p-3">
                                    <p className="text-sm text-red-300 font-medium">{d.title}</p>
                                    {d.description && <p className="text-xs text-slate-400 mt-1">{d.description}</p>}
                                    {d.why && <p className="text-xs text-red-400/70 mt-1 italic">Why: {d.why}</p>}
                                  </div>
                                ))}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              } catch {
                return (
                  <div className="bg-slate-800/50 rounded-lg p-4">
                    <p className="text-sm text-slate-400">Guidelines content available</p>
                  </div>
                );
              }
            })()}

            {/* Dates */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-4 border-t border-slate-800">
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Created</span>
                <p className="text-sm text-slate-400">{formatDate(displayAsset.createdAt)}</p>
              </div>
              <div>
                <span className="text-xs text-slate-500 uppercase tracking-wider block mb-1">Updated</span>
                <p className="text-sm text-slate-400">{formatDate(displayAsset.updatedAt)}</p>
              </div>
            </div>
          </>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-4 sm:px-6 py-4 border-t border-white/10 shrink-0">
          {canDownload && assetImage && isImageAsset && downloadFormats.length > 0 && (
            <div className="flex items-center gap-2">
              <select
                value={selectedFormat}
                onChange={(e) => setSelectedFormat(e.target.value)}
                className="px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"
              >
                {downloadFormats.map((fmt) => (
                  <option key={fmt.value} value={fmt.value}>{fmt.label}</option>
                ))}
              </select>
              <button
                onClick={handleFormatDownload}
                disabled={isDownloading}
                className="px-4 py-2 text-sm font-medium text-slate-300 bg-slate-800 border border-slate-700 rounded-lg hover:bg-slate-700 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isDownloading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-slate-400 border-t-transparent rounded-full animate-spin" />
                    Converting...
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4" />
                    Download {selectedFormat.toUpperCase()}
                  </>
                )}
              </button>
            </div>
          )}
          {canDownload && assetImage && !isImageAsset && (
            <a
              href={assetImage}
              download={displayAsset.fileName || displayAsset.name}
              className="px-4 py-2 text-sm font-medium text-slate-300 bg-slate-800 border border-slate-700 rounded-lg hover:bg-slate-700 flex items-center gap-2 transition-colors"
            >
              <Download className="w-4 h-4" />
              Download
            </a>
          )}
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-semibold bg-[#C8FF2E] text-[#0d1117] rounded-lg hover:bg-[#d4ff5c] transition-colors"
          >
            Close
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ============================================
// MAIN PAGE
// ============================================

export default function BrandAssetsPage() {
  const user = useAuthStore(s => s.user);
  const storeCompanyId = useCompanyStore(s => s.activeCompanyId);
  const companyId = user?.activeCompanyId || storeCompanyId;
  const { setItems: setStoreItems } = useDataStore();
  const { toast } = useToast();

  // RBAC: gate management actions by the user's brand-assets permissions so
  // view-only users see data only.
  const hasPermission = usePermissionStore((s) => s.hasPermission);
  const resolvedPermissions = usePermissionStore((s) => s.resolvedPermissions);
  void resolvedPermissions; // re-render when permissions load
  const canCreate = hasPermission('brand-assets', 'create');
  const canEdit = hasPermission('brand-assets', 'edit');
  const canDelete = hasPermission('brand-assets', 'delete');
  const canAIGenerate = hasPermission('brand-assets', 'ai-generate');
  const canUpload = hasPermission('brand-assets', 'upload');
  const canDownload = hasPermission('brand-assets', 'download');
  const canExport = hasPermission('brand-assets', 'export');

  const [assets, setAssets] = useState<BrandAsset[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingAsset, setEditingAsset] = useState<BrandAsset | null>(null);
  const [viewingAsset, setViewingAsset] = useState<BrandAsset | null>(null);
  const [filter, setFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [layoutMode, setLayoutMode] = useState<'card' | 'table'>('table');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [showClearConfirm, setShowClearConfirm] = useState(false);
  const [isClearing, setIsClearing] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [importFile, setImportFile] = useState<File | null>(null);
  const [importPreview, setImportPreview] = useState<{ row: number; data: Record<string, string>; valid: boolean; errors: string[] }[] | null>(null);
  const [importErrors, setImportErrors] = useState<string[]>([]);
  const [isImporting, setIsImporting] = useState(false);
  const [importSuccess, setImportSuccess] = useState(false);
  const [showImportToast, setShowImportToast] = useState(false);
  const [importToastMessage, setImportToastMessage] = useState('');
  const [showDeleteToast, setShowDeleteToast] = useState(false);
  const [deleteToastMessage, setDeleteToastMessage] = useState('');
  const [showSuccessToast, setShowSuccessToast] = useState(false);
  const [successToastMessage, setSuccessToastMessage] = useState('');
  const [showImageGenerationModal, setShowImageGenerationModal] = useState(false);
  const [aiGenerationContext, setAiGenerationContext] = useState<AiGenerationContext | null>(null);
  const [showAssetSelectionModal, setShowAssetSelectionModal] = useState(false);
  const [showPrimaryLogoFlow, setShowPrimaryLogoFlow] = useState(false);
  const [showSecondaryLogoFlow, setShowSecondaryLogoFlow] = useState(false);
  const [showLogoVariationsFlow, setShowLogoVariationsFlow] = useState(false);
  const [showBrandPatternFlow, setShowBrandPatternFlow] = useState(false);
  const [showWatermarkFlow, setShowWatermarkFlow] = useState(false);
  const [imageGenInitialCategory, setImageGenInitialCategory] = useState<string | undefined>(undefined);

  // Dropdown states for custom filter dropdowns
  const [typeDropdownOpen, setTypeDropdownOpen] = useState(false);
  const [dropdownUp, setDropdownUp] = useState(false);
  const typeDropdownRef = useRef<HTMLDivElement>(null);
  const selectAllRef = useRef<HTMLInputElement>(null);

  // Delete confirmation state
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<BrandAsset | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false);
  const [isBulkDeleting, setIsBulkDeleting] = useState(false);

  // Close filter dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (typeDropdownRef.current && !typeDropdownRef.current.contains(e.target as Node)) {
        setTypeDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Check dropdown direction (up or down)
  const checkDropdownDirection = (ref: React.RefObject<HTMLDivElement | null>) => {
    if (ref.current) {
      const rect = ref.current.getBoundingClientRect();
      const spaceBelow = window.innerHeight - rect.bottom;
      setDropdownUp(spaceBelow < 280);
    }
  };

  // Whether a primary logo already exists — drives the roadmap vs guided CTA.
  const hasPrimaryLogo = useMemo(
    () => assets.some((a) => a.type === 'logo' && a.isPrimary),
    [assets]
  );

  // -------------------------------------------
  // Workflow-step detection — mirrors the Brand Identity Roadmap stages.
  // The top-level "Generate" CTA label + action follow the FIRST incomplete
  // step; only when every step is done does it fall back to the generic
  // "Generate Image" (general image generation).
  // -------------------------------------------
  const SECONDARY_LOGO_TYPES = ['secondary-logo', 'wordmark', 'logoHorizontal', 'logoVertical', 'logoIconOnly'];
  const LOGO_VARIATION_TYPES = ['logoMarkLight', 'logoMarkDark', 'logoIconOnly', 'logoHorizontal', 'logoVertical', 'logo-icon'];

  const workflowStep = useMemo(() => {
    if (!assets.some((a) => a.type === 'logo' && a.isPrimary)) {
      return { label: 'Generate Primary Logo', kind: 'primary' as const };
    }
    if (!assets.some((a) => SECONDARY_LOGO_TYPES.includes(a.type))) {
      return { label: 'Generate Secondary Logo', kind: 'secondary' as const };
    }
    if (!assets.some((a) => LOGO_VARIATION_TYPES.includes(a.type))) {
      return { label: 'Generate Logo Variations', kind: 'variations' as const };
    }
    if (!assets.some((a) => a.type === 'brandPattern')) {
      return { label: 'Generate Brand Patterns', kind: 'patterns' as const };
    }
    if (!assets.some((a) => a.type === 'watermark')) {
      return { label: 'Generate Watermark', kind: 'watermark' as const };
    }
    return { label: 'Generate Image', kind: 'generic' as const };
  }, [assets]);

  const handleWorkflowGenerate = () => {
    if (workflowStep.kind === 'primary') {
      setShowPrimaryLogoFlow(true);
    } else if (workflowStep.kind === 'secondary') {
      setShowSecondaryLogoFlow(true);
    } else if (workflowStep.kind === 'variations') {
      setShowLogoVariationsFlow(true);
    } else if (workflowStep.kind === 'patterns') {
      setShowBrandPatternFlow(true);
    } else if (workflowStep.kind === 'watermark') {
      setShowWatermarkFlow(true);
    } else {
      // All steps complete — generic image generation.
      setImageGenInitialCategory(undefined);
      setAiGenerationContext(null);
      setShowImageGenerationModal(true);
      setIsModalOpen(false);
      setEditingAsset(null);
    }
  };

  // Auto-open from URL param (gated by ai-generate perm). When the module is
  // empty, route ?generate=true to the guided Primary Logo flow; otherwise open
  // the standard image-generation modal.
  const searchParams = useSearchParams();
  useEffect(() => {
    if (searchParams?.get('generate') === 'true' && canAIGenerate) {
      if (assets.length === 0) {
        setShowPrimaryLogoFlow(true);
      } else {
        setShowImageGenerationModal(true);
      }
    }
  }, [searchParams, canAIGenerate, assets.length]);

  const showSuccess = (message: string) => {
    setSuccessToastMessage(message);
    setShowSuccessToast(true);
    setTimeout(() => setShowSuccessToast(false), 3000);
  };

  // Load assets
  const refreshAssets = useCallback(async () => {
    if (!companyId) {
      setAssets([]);
      setStoreItems('brandAssets', []);
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    const response = await brandAssetApi.getAll(companyId);
    if (response.data) {
      setAssets(response.data as BrandAsset[]);
      setStoreItems('brandAssets', response.data as BrandAsset[]);
    }
    setIsLoading(false);
  }, [companyId]);

  useEffect(() => {
    refreshAssets();
  }, [refreshAssets]);

  // Warm the foundational context cache (Business Profile, Brand Strategy,
  // Visual Identity, …) on mount so the Generate Image workflow opens instantly.
  useEffect(() => {
    prefetchFoundationalContext(companyId);
  }, [companyId]);

  const handleCreate = async (data: any) => {
    if (!companyId) return;

    let response;
    if (data.file) {
      // File upload path — use multipart/form-data
      const { file, ...metadata } = data;
      response = await brandAssetApi.createWithFile(file, {
        companyId,
        name: metadata.name,
        type: metadata.type,
        description: metadata.description,
        format: metadata.format,
        sourceUrl: metadata.sourceUrl,
        tags: metadata.tags,
        isPrimary: metadata.isPrimary,
      });
    } else {
      // URL-based or metadata-only path — use JSON body
      response = await brandAssetApi.create({
        ...data,
        companyId,
      });
    }

    if (response.data) {
      const newAssets = [...assets, response.data as BrandAsset];
      setAssets(newAssets);
      setStoreItems('brandAssets', newAssets);
      setIsModalOpen(false);
      toast.success('Brand asset created successfully.');
    } else if (response.error) {
      toast.error('Failed to create brand asset: ' + response.error);
      showSuccess('Asset created successfully.');
    }
  };

  const handleUpdate = async (id: string, data: any) => {
    let response;
    if (data.file) {
      // File replacement — use multipart/form-data
      const { file, ...metadata } = data;
      response = await brandAssetApi.updateWithFile(id, file, metadata);
    } else {
      // Metadata-only update — use JSON body
      response = await brandAssetApi.update(id, data);
    }
    if (response.data) {
      const updatedAssets = assets.map(item => (item.id === id ? (response.data as BrandAsset) : item));
      setAssets(updatedAssets);
      setStoreItems('brandAssets', updatedAssets);
      setIsModalOpen(false);
      setEditingAsset(null);
      toast.success('Brand asset updated successfully.');
    } else if (response.error) {
      toast.error('Failed to update brand asset: ' + response.error);
      showSuccess('Asset updated successfully.');
    }
  };

  const handleDelete = (asset: BrandAsset) => {
    setItemToDelete(asset);
    setShowDeleteConfirm(true);
  };

  // For compatibility with AssetCard which passes id
  const handleDeleteById = (id: string) => {
    const asset = assets.find(a => a.id === id);
    if (asset) {
      setItemToDelete(asset);
      setShowDeleteConfirm(true);
    }
  };

  const confirmDelete = async () => {
    if (!itemToDelete) return;
    setIsDeleting(true);
    try {
      const response = await brandAssetApi.delete(itemToDelete.id);
      if (!response.error) {
        const remainingAssets = assets.filter(item => item.id !== itemToDelete.id);
        setAssets(remainingAssets);
        setStoreItems('brandAssets', remainingAssets);
        toast.success('Brand asset deleted successfully.');
      } else {
        toast.error('Failed to delete brand asset.');
      }
    } catch (error) {
      console.error('Failed to delete brand asset:', error);
      toast.error('Failed to delete brand asset. Please try again.');
    } finally {
      setIsDeleting(false);
      setShowDeleteConfirm(false);
      setItemToDelete(null);
    }
  };

  const handleBulkDelete = () => {
    if (selectedItems.size === 0) return;
    setShowBulkDeleteConfirm(true);
  };

  const confirmBulkDelete = async () => {
    if (selectedItems.size === 0) return;
    setIsBulkDeleting(true);
    const ids = Array.from(selectedItems);
    let successCount = 0;
    let failCount = 0;
    for (const id of ids) {
      try {
        await brandAssetApi.delete(id);
        successCount++;
      } catch (err) {
        console.error('Failed to delete item:', err);
        failCount++;
      }
    }
    // Refresh list
    await refreshAssets();
    setSelectedItems(new Set());
    setIsBulkDeleting(false);
    setShowBulkDeleteConfirm(false);
    toast.success(`Deleted ${successCount} item${successCount !== 1 ? 's' : ''}${failCount > 0 ? `. Failed: ${failCount}` : ''}`);
  };

  const handleClearAll = async () => {
    setIsClearing(true);
    try {
      await Promise.all(assets.map((a) => brandAssetApi.delete(a.id)));
      setAssets([]);
      setStoreItems('brandAssets', []);
      toast.success('All brand assets deleted successfully.');
    } catch {
      toast.error('Failed to delete all brand assets.');
      setDeleteToastMessage('All assets deleted successfully.');
      setShowDeleteToast(true);
      setTimeout(() => setShowDeleteToast(false), 3000);
    } finally {
      setIsClearing(false);
      setShowClearConfirm(false);
    }
  };

  const handleSetPrimary = async (id: string, isPrimary: boolean) => {
    const asset = assets.find(a => a.id === id);
    if (!asset) return;

    // If setting as primary, remove primary from others of same type
    if (isPrimary) {
      const updates = assets
        .filter(a => a.type === asset.type && a.isPrimary && a.id !== id)
        .map(a => brandAssetApi.update(a.id, { isPrimary: false }));
      await Promise.all(updates);
    }

    await handleUpdate(id, { isPrimary });
  };

  const handleExportBrandAssets = () => {
    if (assets.length === 0) return;

    const headers = [
      'Name', 'Type', 'Format', 'Description', 'URL', 'Source URL', 'Source',
      'File Name', 'File Size', 'File Type', 'File Data',
      'Is Primary', 'Tags', 'Width', 'Height',
      'Created At', 'Updated At',
    ];

    const rows = assets.map(a => [
      escapeCsv(a.name),
      escapeCsv(a.type),
      escapeCsv(a.format),
      escapeCsv(a.description),
      escapeCsv(sanitizeDataUrl(a.url)),
      escapeCsv(sanitizeDataUrl(a.sourceUrl)),
      escapeCsv(a.source),
      escapeCsv(a.fileName),
      escapeCsv(a.fileSize),
      escapeCsv(a.fileType),
      a.base64Data ? escapeCsv(BASE64_MARKER) : escapeCsv(''),
      escapeCsvBool(a.isPrimary),
      escapeCsvArray(a.tags),
      escapeCsv(a.dimensions?.width),
      escapeCsv(a.dimensions?.height),
      escapeCsv(a.createdAt),
      escapeCsv(a.updatedAt),
    ]);

    exportCsv(headers, rows, 'brand-assets');
  };

  // CSV Import handlers
  const MAX_IMPORT_FILE_SIZE = 2 * 1024 * 1024; // 2 MB

  const handleImportFileSelect = (file: File) => {
    setImportErrors([]);
    setImportPreview(null);
    setImportSuccess(false);

    if (!file.name.toLowerCase().endsWith('.csv')) {
      setImportErrors(['Please upload a .csv file.']);
      return;
    }
    if (file.size > MAX_IMPORT_FILE_SIZE) {
      setImportErrors(['File size exceeds the 2 MB limit.']);
      return;
    }

    setImportFile(file);

    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target?.result as string;
      const { headers, rows, errors } = parseTabularCsv(content);
      if (errors.length > 0) {
        setImportErrors(errors);
        return;
      }
      if (rows.length === 0) {
        setImportErrors(['CSV file contains no data rows.']);
        return;
      }

      // Map rows to numbered entries for validation
      const validationResults = validateBrandAssetCsv(rows);
      setImportPreview(validationResults);

      const rowErrors = validationResults.filter(r => !r.valid);
      if (rowErrors.length > 0) {
        setImportErrors(rowErrors.flatMap(r => r.errors.map(err => `Row ${r.row}: ${err}`)));
      }
    };
    reader.readAsText(file);
  };

  const handleImportConfirm = async () => {
    if (!importPreview || !companyId) return;
    const validRows = importPreview.filter(r => r.valid);
    if (validRows.length === 0) return;

    setIsImporting(true);
    try {
      let successCount = 0;
      let failCount = 0;

      for (const row of validRows) {
        const assetData = csvRowToBrandAsset(row.data);
        try {
          await brandAssetApi.create({ companyId, ...assetData });
          successCount++;
        } catch (err) {
          console.error('Failed to import row:', err);
          failCount++;
        }
      }

      // Refresh assets list
      const refreshed = await brandAssetApi.getAll(companyId);
      if (refreshed.data) {
        setAssets(refreshed.data as BrandAsset[]);
        setStoreItems('brandAssets', refreshed.data as BrandAsset[]);
      }

      setImportSuccess(true);
      setImportToastMessage(`${successCount} asset${successCount !== 1 ? 's' : ''} imported successfully.${failCount > 0 ? ` ${failCount} failed.` : ''}`);
      setShowImportToast(true);
      setTimeout(() => {
        setShowImportModal(false);
        setImportFile(null);
        setImportPreview(null);
        setImportErrors([]);
        setImportSuccess(false);
      }, 1200);
      setTimeout(() => setShowImportToast(false), 4500);
    } catch (error) {
      console.error('Failed to import CSV:', error);
      setImportErrors(['Failed to save imported data. Please try again.']);
    }
    setIsImporting(false);
  };

  const filteredAssets = useMemo(() => {
    let result = assets.filter(asset => {
      const matchesSearch = asset.name.toLowerCase().includes(filter.toLowerCase()) ||
        asset.tags?.some(tag => tag.toLowerCase().includes(filter.toLowerCase()));
      const matchesType = !typeFilter || asset.type === typeFilter;
      return matchesSearch && matchesType;
    });
    return result;
  }, [assets, filter, typeFilter]);

  // Select All checkbox state
  const isAllSelected = filteredAssets.length > 0 && selectedItems.size === filteredAssets.length;
  const isSomeSelected = selectedItems.size > 0 && selectedItems.size < filteredAssets.length;

  // Update indeterminate state
  useEffect(() => {
    if (selectAllRef.current) {
      selectAllRef.current.indeterminate = isSomeSelected;
    }
  }, [isSomeSelected]);

  // Pagination
  const totalPages = Math.max(1, Math.ceil(filteredAssets.length / pageSize));
  const paginatedAssets = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return filteredAssets.slice(start, start + pageSize);
  }, [filteredAssets, currentPage, pageSize]);

  // Reset to page 1 when filters change
  useEffect(() => {
    setCurrentPage(1);
    setSelectedItems(new Set()); // Clear selection when filters change
  }, [filter, typeFilter]);

  const groupedAssets = filteredAssets.reduce((groups, asset) => {
    const type = asset.type || 'other';
    if (!groups[type]) groups[type] = [];
    groups[type].push(asset);
    return groups;
  }, {} as Record<string, BrandAsset[]>);

  if (!companyId) {
    return (
      <div className="text-center py-12">
        <p className="text-slate-400">Please select a company to manage brand assets.</p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="mx-auto space-y-6 sm:space-y-8 px-4 sm:px-6 lg:px-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-primary-500/10 rounded-xl flex items-center justify-center shrink-0">
            <Image className="w-6 h-6 text-primary-500" />
          </div>
          <div className="min-w-0">
            <h1 className="text-xl sm:text-2xl font-bold text-slate-200 truncate">Brand Assets</h1>
            <p className="text-slate-400 text-sm hidden sm:block">
              Manage logos, favicons, social images, and other brand assets
            </p>
          </div>
        </div>
        {/* Mobile: 2 columns (50% each), Desktop: flex-wrap with auto width */}
        <div className="grid grid-cols-2 sm:flex sm:flex-wrap items-center gap-2 sm:gap-3">
          {canAIGenerate && (
            <button
              onClick={handleWorkflowGenerate}
              className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2 bg-primary-500 hover:bg-primary-400 text-black font-medium rounded-lg transition-all border border-slate-600 text-sm sm:text-base"
            >
              <Sparkles className="w-4 h-4 text-black" />
              {workflowStep.label}
            </button>
          )}
          {canCreate && (
            <button
              onClick={() => {
                setEditingAsset(null);
                setIsModalOpen(true);
                setShowImageGenerationModal(false);
              }}
              className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2 bg-primary-500 hover:bg-primary-400 text-black font-medium rounded-lg text-sm sm:text-base"
            >
              <Plus className="w-4 h-4" />
              Add Asset
            </button>
          )}
        </div>
      </div>

      {/* Action buttons — Import / Export / Clear All */}
      <div className="flex flex-wrap items-center justify-end gap-2 sm:gap-3">
        {canExport && (
          <Button
            onClick={handleExportBrandAssets}
            variant="secondary"
            size="sm"
            leftIcon={<Download className="w-4 h-4" />}
            disabled={assets.length === 0}
            title={assets.length === 0 ? 'No data to export' : 'Export brand assets'}
          >
            Export
          </Button>
        )}
        {canUpload && (
          <Button
            onClick={() => { setShowImportModal(true); setImportFile(null); setImportPreview(null); setImportErrors([]); setImportSuccess(false); }}
            variant="secondary"
            size="sm"
            leftIcon={<Upload className="w-4 h-4" />}
          >
            Import
          </Button>
        )}
        {assets.length > 0 && canDelete && (
          <Button
            onClick={() => setShowClearConfirm(true)}
            disabled={isClearing}
            loading={isClearing}
            variant="ghost"
            size="sm"
            leftIcon={!isClearing ? <Trash2 className="w-4 h-4" /> : undefined}
            className="text-red-400 hover:text-red-300 hover:bg-red-500/10 border border-red-500/20"
          >
            {isClearing ? 'Clearing...' : 'Clear All'}
          </Button>
        )}
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
        <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-3 sm:p-4">
          <p className="text-xl sm:text-2xl font-bold text-slate-200">{assets.length}</p>
          <p className="text-xs sm:text-sm text-slate-500">Total Assets</p>
        </div>
        <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-3 sm:p-4">
          <p className="text-xl sm:text-2xl font-bold text-[#C8FF2E]">
            {assets.filter(a => a.isPrimary).length}
          </p>
          <p className="text-xs sm:text-sm text-slate-500">Primary Assets</p>
        </div>
        <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-3 sm:p-4">
          <p className="text-xl sm:text-2xl font-bold text-slate-200">
            {assets.filter(a => a.source === 'upload').length}
          </p>
          <p className="text-xs sm:text-sm text-slate-500">Uploaded</p>
        </div>
        <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-3 sm:p-4">
          <p className="text-xl sm:text-2xl font-bold text-slate-200">
            {new Set(assets.map(a => a.type)).size}
          </p>
          <p className="text-xs sm:text-sm text-slate-500">Asset Types</p>
        </div>
      </div>

      {/* Search & Filters - Desktop: Single horizontal row | Mobile: Vertical stack */}
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 relative z-10">
        {/* Search */}
        <div className="relative text-slate-400 w-full sm:w-64">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 pointer-events-none" />
          <input
            type="text"
            placeholder="Search assets..."
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="w-full pl-9 pr-8 py-2 bg-[#1a1d21] border border-white/10 rounded-lg text-sm text-white placeholder-[#878e9a] focus:outline-none focus:border-[#C8FF2E]/50 transition-colors"
          />
          {filter && (
            <button
              onClick={() => setFilter('')}
              className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:text-slate-200 transition-colors"
              aria-label="Clear search"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>

        {/* Type Dropdown */}
        <div ref={typeDropdownRef} className="relative sm:w-48">
          <button
            type="button"
            onClick={() => { checkDropdownDirection(typeDropdownRef); setTypeDropdownOpen(prev => !prev); }}
            className="w-full flex items-center justify-between gap-1 px-3 py-2 text-sm bg-[#0d1117] border border-white/10 rounded-lg text-white hover:border-white/20 transition-colors"
          >
            <span className="truncate">{typeFilter === '' ? 'All Types' : ASSET_TYPES.find(t => t.value === typeFilter)?.label || typeFilter}</span>
            <ChevronDown className={cn('w-4 h-4 shrink-0 transition-transform', typeDropdownOpen && 'rotate-180')} />
          </button>
          {typeDropdownOpen && (
            <div className={cn('absolute left-0 right-0 bg-[#1a1d21] border border-white/10 rounded-lg shadow-xl z-50 max-h-64 overflow-y-auto', dropdownUp ? 'bottom-full mb-1' : 'top-full mt-1')}>
              <button
                onClick={() => { setTypeFilter(''); setTypeDropdownOpen(false); setCurrentPage(1); }}
                className={cn('w-full text-left px-3 py-2 text-sm hover:bg-[#21262d] transition-colors', typeFilter === '' ? 'text-[#C8FF2E]' : 'text-white')}
              >
                All Types
              </button>
              {ASSET_TYPES.map(type => (
                <button
                  key={type.value}
                  onClick={() => { setTypeFilter(type.value); setTypeDropdownOpen(false); setCurrentPage(1); }}
                  className={cn('w-full text-left px-3 py-2 text-sm hover:bg-[#21262d] transition-colors', typeFilter === type.value ? 'text-[#C8FF2E]' : 'text-white')}
                >
                  {type.label}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Rows per Page */}
        <div className="flex items-center justify-end sm:justify-start gap-1.5 shrink-0 sm:ml-auto">
          <span className="text-xs text-[#878e9a] whitespace-nowrap">Rows per page</span>
          <select
            value={pageSize}
            onChange={(e) => { setPageSize(Number(e.target.value)); setCurrentPage(1); }}
            className="appearance-none pl-2 pr-6 py-1.5 rounded-lg text-sm transition-colors border cursor-pointer outline-none bg-[#1a1d21] border-white/10 text-[#878e9a] hover:border-[#C8FF2E]/30"
          >
            {[10, 25, 50, 100].map((n) => (
              <option key={n} value={n} className="bg-[#1a1d21] text-slate-200">{n}</option>
            ))}
          </select>
        </div>

        {/* Layout Toggle - Grid/List view */}
        <div className="flex items-center border border-slate-800 rounded-lg overflow-hidden shrink-0">
          <button
            onClick={() => setLayoutMode('card')}
            className={cn(
              'p-2 transition-colors',
              layoutMode === 'card' ? 'bg-primary-500/10 text-primary-400' : 'text-slate-500 hover:text-slate-200 hover:bg-white/5'
            )}
            title="Grid view"
          >
            <LayoutGrid className="w-4 h-4" />
          </button>
          <button
            onClick={() => setLayoutMode('table')}
            className={cn(
              'p-2 transition-colors',
              layoutMode === 'table' ? 'bg-primary-500/10 text-primary-400' : 'text-slate-500 hover:text-slate-200 hover:bg-white/5'
            )}
            title="List view"
          >
            <List className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Clear Filters - only show when filters are active */}
      {(filter || typeFilter) && (
        <div className="flex items-center gap-2">
          <button
            onClick={() => {
              setFilter('');
              setTypeFilter('');
            }}
            className="px-3 py-1.5 text-sm text-slate-400 hover:text-white border border-slate-700 hover:border-slate-600 rounded-lg transition-colors flex items-center gap-1.5"
          >
            <XCircle className="w-4 h-4" />
            Clear Filters
          </button>
        </div>
      )}

      {/* Bulk Actions Bar */}
      {selectedItems.size > 0 && (
        <div className="flex items-center gap-3 p-3 bg-[#C8FF2E]/10 border border-[#C8FF2E]/30 rounded-lg">
          <span className="text-sm text-[#C8FF2E] font-medium">{selectedItems.size} selected</span>

          {/* Delete button */}
          <button
            onClick={handleBulkDelete}
            className="px-3 py-1.5 text-xs bg-red-500/20 text-red-300 rounded hover:bg-red-500/30 transition-colors"
          >
            Delete Selected
          </button>

          <button
            onClick={() => setSelectedItems(new Set())}
            className="ml-auto text-xs text-slate-400 hover:text-white transition-colors"
          >
            Clear
          </button>
        </div>
      )}

      {/* Assets Grid/Table */}
      {assets.length === 0 ? (
        /* Guided empty state — start the brand identity with a primary logo */
        <div className="text-center py-16 bg-slate-900/30 border border-slate-800 rounded-xl px-4">
          <div className="w-16 h-16 bg-primary-500/10 border border-primary-500/30 rounded-xl flex items-center justify-center mx-auto mb-4">
            <Sparkles className="w-8 h-8 text-primary-400" />
          </div>
          <h3 className="text-lg font-medium text-slate-200 mb-2">
            Start your brand identity with a primary logo
          </h3>
          <p className="text-slate-400 max-w-md mx-auto mb-5">
            Our AI studies your business profile, brand strategy, and competitor
            landscape, then designs a differentiated primary logo for you.
          </p>
          <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
            <button
              onClick={() => setShowPrimaryLogoFlow(true)}
              disabled={!canAIGenerate}
              title={!canAIGenerate ? 'You need AI generate permission' : undefined}
              className="px-4 py-2 bg-primary-500 hover:bg-primary-400 disabled:opacity-40 disabled:cursor-not-allowed text-slate-900 font-medium rounded-lg flex items-center gap-2 transition-colors"
            >
              <Wand2 className="w-4 h-4" />
              Generate Primary Logo
            </button>
            {canCreate && (
              <button
                onClick={() => setShowAssetSelectionModal(true)}
                className="text-sm text-slate-400 hover:text-slate-200 underline underline-offset-4 transition-colors"
              >
                or add an asset manually
              </button>
            )}
          </div>
        </div>
      ) : filteredAssets.length === 0 ? (
        /* Assets exist but the current filter matches nothing */
        <div className="text-center py-16 bg-slate-900/30 border border-slate-800 rounded-xl px-4">
          <div className="w-16 h-16 bg-slate-800 rounded-xl flex items-center justify-center mx-auto mb-4">
            <Image className="w-8 h-8 text-slate-500" />
          </div>
          <h3 className="text-lg font-medium text-slate-300 mb-2">No assets match your filters</h3>
          <p className="text-slate-500 mb-4">Try clearing the search or type filter.</p>
        </div>
      ) : (
        <>
          {/* Brand Identity Roadmap — shown once assets exist (guided build order) */}
          <BrandIdentityRoadmap
            assets={assets}
            canAIGenerate={canAIGenerate}
            onPrimaryLogoFlow={() => setShowPrimaryLogoFlow(true)}
            onSecondaryLogoFlow={() => setShowSecondaryLogoFlow(true)}
            onLogoVariationsFlow={() => setShowLogoVariationsFlow(true)}
            onBrandPatternFlow={() => setShowBrandPatternFlow(true)}
            onWatermarkFlow={() => setShowWatermarkFlow(true)}
          />

          {/* Table View (List) */}
          {layoutMode === 'table' && (
            <div className="overflow-x-auto bg-slate-900/50 border border-slate-800 rounded-xl">
              <table className="w-full min-w-[900px]">
                <thead className="bg-slate-800/50 border-b border-slate-700">
                  <tr>
                    <th className="px-4 py-3 w-12">
                      <input
                        ref={selectAllRef}
                        type="checkbox"
                        className="rounded border-slate-600 bg-slate-700 text-primary-500 focus:ring-primary-500 cursor-pointer w-4 h-4"
                        checked={isAllSelected}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedItems(new Set(filteredAssets.map(a => a.id)));
                          } else {
                            setSelectedItems(new Set());
                          }
                        }}
                      />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider">Sr. No.</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider">Preview</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider">Name</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider">Type</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider hidden md:table-cell">Primary</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 uppercase tracking-wider hidden lg:table-cell">Created At</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-slate-400 uppercase tracking-wider">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800">
                  {paginatedAssets.map((asset, index) => {
                    const getAssetIcon = () => {
                      if (asset.type?.includes('logo')) return '🔷';
                      if (asset.type?.includes('favicon')) return '🔖';
                      if (asset.type?.includes('social')) return '📱';
                      if (asset.type?.includes('email')) return '📧';
                      if (asset.type?.includes('presentation')) return '📊';
                      if (asset.type?.includes('document')) return '📄';
                      if (asset.type === 'virtual-background') return '🖥️';
                      return '🎨';
                    };

                    const formatFileSize = (bytes?: number) => {
                      if (!bytes) return '';
                      if (bytes < 1024) return `${bytes} B`;
                      if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
                      return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
                    };

                    return (
                      <tr
                        key={asset.id}
                        onClick={() => setViewingAsset(asset)}
                        className={`hover:bg-slate-800/30 transition-colors cursor-pointer ${index % 2 === 1 ? 'bg-slate-900/20' : ''}`}
                      >
                        <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                          <input
                            type="checkbox"
                            className="rounded border-slate-600 bg-slate-700 text-primary-500 focus:ring-primary-500 cursor-pointer w-4 h-4"
                            checked={selectedItems.has(asset.id)}
                            onChange={(e) => {
                              const next = new Set(selectedItems);
                              if (next.has(asset.id)) next.delete(asset.id);
                              else next.add(asset.id);
                              setSelectedItems(next);
                            }}
                          />
                        </td>
                        <td className="px-4 py-3 text-sm text-slate-400">
                          {(currentPage - 1) * pageSize + index + 1}
                        </td>
                        <td className="px-4 py-3">
                          <div className="w-10 h-10 sm:w-12 sm:h-12 bg-slate-800 rounded-lg flex items-center justify-center overflow-hidden shrink-0">
                            {asset.url || asset.base64Data ? (
                              <img
                                src={asset.url || asset.base64Data}
                                alt={asset.name}
                                className="w-full h-full object-contain"
                              />
                            ) : (
                              <span className="text-xl">{getAssetIcon()}</span>
                            )}
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <div className="text-sm font-medium text-slate-200 truncate max-w-[12rem] sm:max-w-[16rem] md:max-w-[20rem]" title={asset.name}>
                            {asset.name}
                          </div>
                          {asset.isPrimary && (
                            <span className="mt-1 px-2 py-0.5 bg-[#C8FF2E]/20 text-[#C8FF2E] text-xs rounded-full inline-block">
                              Primary
                            </span>
                          )}
                        </td>
                        <td className="px-4 py-3">
                          <span className="text-sm text-slate-300 whitespace-nowrap">
                            {ASSET_TYPES.find(t => t.value === asset.type)?.label || asset.type}
                          </span>
                        </td>
                        <td className="px-4 py-3 hidden md:table-cell">
                          {asset.isPrimary ? (
                            <span className="px-2 py-1 bg-[#C8FF2E]/10 text-[#C8FF2E] text-xs rounded-full whitespace-nowrap">Yes</span>
                          ) : (
                            <span className="text-slate-500 text-xs whitespace-nowrap">No</span>
                          )}
                        </td>
                        <td className="px-4 py-3 hidden lg:table-cell">
                          <span className="text-sm text-slate-400 whitespace-nowrap">
                            {asset.createdAt ? formatDateTime(asset.createdAt) : '—'}
                          </span>
                        </td>
                        <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                          <div className="flex items-center justify-end gap-1">
                            {canEdit && (
                              <>
                                <IconButton
                                  icon={<Eye className="w-4 h-4" />}
                                  tooltip="View Details"
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => setViewingAsset(asset)}
                                />
                                <IconButton
                                  icon={<Edit2 className="w-4 h-4" />}
                                  tooltip="Edit"
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    setEditingAsset(asset);
                                    setIsModalOpen(true);
                                  }}
                                />
                                <IconButton
                                  icon={<Trash2 className="w-4 h-4" />}
                                  tooltip="Delete"
                                  variant="danger"
                                  size="sm"
                                  onClick={() => handleDeleteById(asset.id)}
                                />
                              </>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}

          {/* Card View (Grid) */}
          {layoutMode === 'card' && (
            <div className="space-y-8">
              {Object.entries(groupedAssets).map(([type, typeAssets]) => (
                <div key={type}>
                  <h3 className="text-sm font-medium text-slate-400 uppercase tracking-wider mb-4 flex items-center gap-2">
                    {ASSET_TYPES.find(t => t.value === type)?.label || type}
                    <span className="px-2 py-0.5 bg-slate-800 text-slate-400 text-xs rounded-full">
                      {typeAssets.length}
                    </span>
                  </h3>
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
                    {typeAssets.map(asset => (
                      <AssetCard
                        key={asset.id}
                        asset={asset}
                        onView={setViewingAsset}
                        onEdit={(a) => {
                          setEditingAsset(a);
                          setIsModalOpen(true);
                        }}
                        onDelete={handleDeleteById}
                        onSetPrimary={handleSetPrimary}
                        canEdit={canEdit}
                        canDelete={canDelete}
                      />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Pagination - Always show */}
          <PaginationBar
            currentPage={currentPage}
            totalPages={totalPages}
            totalItems={filteredAssets.length}
            pageSize={pageSize}
            onPageChange={setCurrentPage}
          />
        </>
      )}

      {/* Modal */}
      <AssetFormModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          setEditingAsset(null);
        }}
        onSave={(data) => {
          if (editingAsset) {
            handleUpdate(editingAsset.id, data);
          } else {
            handleCreate(data);
          }
        }}
        asset={editingAsset}
        companyId={companyId}
        onGenerateWithAi={(context) => {
          setAiGenerationContext(context);
          setIsModalOpen(false);
          setEditingAsset(null);
          setShowImageGenerationModal(true);
        }}
      />

      <ClearAllConfirm
        isOpen={showClearConfirm}
        onClose={() => setShowClearConfirm(false)}
        onConfirm={handleClearAll}
        itemName="Assets"
        itemCount={assets.length}
        loading={isClearing}
      />

      {/* Detail Modal */}
      <AssetDetailModal
        isOpen={!!viewingAsset}
        onClose={() => setViewingAsset(null)}
        asset={viewingAsset}
        canDownload={canDownload}
      />

      {/* CSV Import Modal */}
      {showImportModal && createPortal(
        <div
          className="fixed inset-0 z-[9998] flex items-center justify-center p-2 sm:p-4"
          style={{ width: '100vw', height: '100vh' }}
        >
          {/* Backdrop overlay */}
          <div
            className="absolute inset-0 bg-black/45 backdrop-blur-sm"
            style={{ backdropFilter: 'blur(8px)' }}
            onClick={() => setShowImportModal(false)}
          />
          {/* Modal content */}
          <div className="relative z-[9999] w-full max-w-4xl max-h-[90vh] bg-[#1a1d21] border border-slate-700 rounded-2xl shadow-2xl flex flex-col">
            <div className="flex items-center justify-between px-4 sm:px-6 py-4 border-b border-slate-700/60 shrink-0">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-[#C8FF2E]/10 flex items-center justify-center">
                  <Upload className="w-5 h-5 text-[#C8FF2E]" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-white">Import Brand Assets</h3>
                  <p className="text-sm text-slate-400 hidden sm:block">Upload a CSV file to import brand assets in bulk</p>
                </div>
              </div>
              <button
                onClick={() => setShowImportModal(false)}
                className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition-colors"
                title="Close"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-6 space-y-5">
              <div className="bg-slate-800/40 rounded-xl p-5 border border-slate-700/50">
                <div className="flex items-center gap-2.5 mb-3">
                  <div className="w-6 h-6 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center text-xs font-bold text-[#C8FF2E]">1</div>
                  <h4 className="text-sm font-semibold text-slate-200">Download Template</h4>
                </div>
                <p className="text-sm text-slate-400 mb-4 leading-relaxed">
                  Download the sample CSV template with all valid column headers and example rows. Use it as a reference to format your data.
                </p>
                <button
                  onClick={generateBrandAssetTemplate}
                  className="flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-[#C8FF2E] bg-[#C8FF2E]/10 border border-[#C8FF2E]/30 rounded-lg hover:bg-[#C8FF2E]/20 transition-colors"
                >
                  <FileText className="w-4 h-4" />
                  Download Template
                </button>
              </div>

              <div className="bg-slate-800/40 rounded-xl p-5 border border-slate-700/50">
                <div className="flex items-center gap-2.5 mb-3">
                  <div className="w-6 h-6 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center text-xs font-bold text-[#C8FF2E]">2</div>
                  <h4 className="text-sm font-semibold text-slate-200">Upload CSV File</h4>
                </div>
                <div
                  className={`relative border-2 border-dashed rounded-xl p-6 text-center transition-colors cursor-pointer ${
                    importFile
                      ? 'border-[#C8FF2E]/40 bg-[#C8FF2E]/5'
                      : 'border-slate-600 hover:border-slate-500 bg-slate-800/20'
                  }`}
                  onClick={() => {
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = '.csv';
                    input.onchange = (e) => {
                      const file = (e.target as HTMLInputElement).files?.[0];
                      if (file) handleImportFileSelect(file);
                    };
                    input.click();
                  }}
                  onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); }}
                  onDrop={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    const file = e.dataTransfer.files?.[0];
                    if (file) handleImportFileSelect(file);
                  }}
                >
                  {importFile ? (
                    <div className="flex items-center justify-center gap-3">
                      <FileText className="w-8 h-8 text-[#C8FF2E]" />
                      <div className="text-left">
                        <p className="text-sm font-medium text-white">{importFile.name}</p>
                        <p className="text-xs text-slate-400">{(importFile.size / 1024).toFixed(1)} KB</p>
                      </div>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      <Upload className="w-8 h-8 mx-auto text-slate-500" />
                      <p className="text-sm text-slate-400">
                        <span className="text-[#C8FF2E] font-medium">Click to upload</span> or drag and drop
                      </p>
                      <p className="text-xs text-slate-500">.csv files only, max 2 MB</p>
                    </div>
                  )}
                </div>
              </div>

              {importErrors.length > 0 && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-red-400">
                    <XCircle className="w-4 h-4" />
                    Validation Errors
                  </div>
                  <ul className="space-y-1">
                    {importErrors.map((err, i) => (
                      <li key={i} className="text-xs text-red-300/80 flex items-start gap-1.5">
                        <span className="text-red-400 mt-0.5">•</span>
                        {err}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {importPreview && importPreview.length > 0 && (
                <div className="bg-slate-800/40 rounded-xl p-5 border border-slate-700/50">
                  <div className="flex items-center gap-2.5 mb-3">
                    <div className="w-6 h-6 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center text-xs font-bold text-[#C8FF2E]">3</div>
                    <h4 className="text-sm font-semibold text-slate-200">Preview & Validation</h4>
                  </div>
                  <div className="flex items-center gap-3 mb-4 text-sm">
                    <span className="flex items-center gap-1.5 text-green-400">
                      <Check className="w-3.5 h-3.5" />
                      {importPreview.filter(r => r.valid).length} valid
                    </span>
                    {importPreview.filter(r => !r.valid).length > 0 && (
                      <span className="flex items-center gap-1.5 text-red-400">
                        <XCircle className="w-3.5 h-3.5" />
                        {importPreview.filter(r => !r.valid).length} with errors
                      </span>
                    )}
                  </div>
                  <div className="max-h-48 overflow-y-auto rounded-lg border border-slate-700/50">
                    <table className="w-full text-xs">
                      <thead className="bg-slate-800 sticky top-0">
                        <tr>
                          <th className="text-left px-3 py-2 text-slate-400 font-medium">Row</th>
                          <th className="text-left px-3 py-2 text-slate-400 font-medium">Name</th>
                          <th className="text-left px-3 py-2 text-slate-400 font-medium">Type</th>
                          <th className="text-center px-3 py-2 text-slate-400 font-medium w-16">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-700/30">
                        {importPreview.map((row, i) => (
                          <tr key={i} className={row.valid ? '' : 'bg-red-500/5'}>
                            <td className="px-3 py-2 text-slate-400">{row.row}</td>
                            <td className="px-3 py-2 text-slate-300 truncate max-w-[150px]">{row.data['Name'] || '—'}</td>
                            <td className="px-3 py-2 text-slate-400">{row.data['Type'] || '—'}</td>
                            <td className="px-3 py-2 text-center">
                              {row.valid ? (
                                <Check className="w-3.5 h-3.5 text-green-400 inline" />
                              ) : (
                                <XCircle className="w-3.5 h-3.5 text-red-400 inline" />
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  {importPreview.some(r => !r.valid) && (
                    <p className="text-xs text-amber-400/80 mt-3 flex items-start gap-1.5">
                      <Info className="w-3.5 h-3.5 mt-0.5 shrink-0" />
                      Rows with errors will be skipped. Only valid rows will be imported.
                    </p>
                  )}
                </div>
              )}

              {importSuccess && (
                <div className="bg-[#C8FF2E]/10 border border-[#C8FF2E]/30 rounded-xl p-4 flex items-center gap-3">
                  <Loader2 className="w-5 h-5 text-[#C8FF2E] animate-spin shrink-0" />
                  <div>
                    <p className="text-sm font-medium text-[#C8FF2E]">Import Successful</p>
                    <p className="text-xs text-slate-400">Closing…</p>
                  </div>
                </div>
              )}

              <div className="flex items-start gap-2.5 text-xs text-slate-500 bg-slate-800/30 rounded-lg p-3">
                <Info className="w-3.5 h-3.5 mt-0.5 shrink-0" />
                <div className="space-y-1">
                  <p>CSV must use column headers matching the template (Name, Type, Format, etc.).</p>
                  <p>Type must be a valid asset type. Format must be one of: svg, png, jpg, pdf, webp, ico. Tags are semicolon-separated.</p>
                </div>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-2 sm:gap-3 px-4 sm:px-6 py-4 border-t border-slate-700/60 shrink-0">
              <button
                onClick={() => setShowImportModal(false)}
                className="px-4 py-2.5 text-sm font-medium text-slate-300 bg-slate-700 rounded-xl hover:bg-slate-600 transition-colors"
              >
                Cancel
              </button>
              {!importSuccess && (
                <button
                  onClick={handleImportConfirm}
                  disabled={!importPreview || importPreview.filter(r => r.valid).length === 0 || isImporting}
                  className="flex items-center justify-center gap-2 px-5 py-2.5 text-sm font-semibold bg-[#C8FF2E] text-[#0d1117] rounded-xl hover:bg-[#d4ff5c] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isImporting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Importing…
                    </>
                  ) : (
                    <>
                      <Upload className="w-4 h-4" />
                      Import
                    </>
                  )}
                </button>
              )}
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Import Success Toast */}
      {showImportToast && (
        <div className="fixed bottom-6 right-6 z-[60] flex items-center gap-3 px-5 py-4 bg-[#1a1d21] border border-[#C8FF2E]/40 rounded-xl shadow-2xl shadow-black/50 animate-in slide-in-from-bottom-4 fade-in duration-300">
          <div className="w-9 h-9 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center shrink-0">
            <CheckCircle2 className="w-5 h-5 text-[#C8FF2E]" />
          </div>
          <div>
            <p className="text-sm font-semibold text-white">Import Complete</p>
            <p className="text-xs text-slate-400">{importToastMessage}</p>
          </div>
        </div>
      )}

      {/* Delete Success Toast */}
      {showDeleteToast && (
        <div className="fixed bottom-6 right-6 z-[60] flex items-center gap-3 px-5 py-4 bg-[#1a1d21] border border-[#C8FF2E]/40 rounded-xl shadow-2xl shadow-black/50 animate-in slide-in-from-bottom-4 fade-in duration-300">
          <div className="w-9 h-9 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center shrink-0">
            <Trash2 className="w-5 h-5 text-[#C8FF2E]" />
          </div>
          <div>
            <p className="text-sm font-semibold text-white">Deleted</p>
            <p className="text-xs text-slate-400">{deleteToastMessage}</p>
          </div>
        </div>
      )}

      {/* Create/Update Success Toast */}
      {showSuccessToast && (
        <div className="fixed bottom-6 right-6 z-[60] flex items-center gap-3 px-5 py-4 bg-[#1a1d21] border border-[#C8FF2E]/40 rounded-xl shadow-2xl shadow-black/50 animate-in slide-in-from-bottom-4 fade-in duration-300">
          <div className="w-9 h-9 rounded-full bg-[#C8FF2E]/20 flex items-center justify-center shrink-0">
            <CheckCircle2 className="w-5 h-5 text-[#C8FF2E]" />
          </div>
          <div>
            <p className="text-sm font-semibold text-white">Success</p>
            <p className="text-xs text-slate-400">{successToastMessage}</p>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      <DeleteConfirm
        isOpen={showDeleteConfirm}
        onClose={() => {
          setShowDeleteConfirm(false);
          setItemToDelete(null);
        }}
        onConfirm={confirmDelete}
        itemName={itemToDelete?.name || 'Brand Asset'}
        loading={isDeleting}
      />

      {/* Bulk Delete Confirmation Modal */}
      <DeleteConfirm
        isOpen={showBulkDeleteConfirm}
        onClose={() => setShowBulkDeleteConfirm(false)}
        onConfirm={confirmBulkDelete}
        itemName={`${selectedItems.size} Brand Asset${selectedItems.size !== 1 ? 's' : ''}`}
        loading={isBulkDeleting}
      />

      {/* Image Generation Modal */}
      <ImageGenerationModal
        isOpen={showImageGenerationModal}
        onClose={() => {
          setShowImageGenerationModal(false);
          setAiGenerationContext(null);
          setImageGenInitialCategory(undefined);
        }}
        onSaveToAssets={refreshAssets}
        initialContext={aiGenerationContext}
        initialCategory={imageGenInitialCategory}
      />

      {/* Guided Primary Logo Flow Modal */}
      <PrimaryLogoFlowModal
        isOpen={showPrimaryLogoFlow}
        onClose={() => setShowPrimaryLogoFlow(false)}
        companyId={companyId}
        onApproved={refreshAssets}
      />

      {/* Guided Secondary Logo Flow Modal — generated from the primary logo */}
      <SecondaryLogoFlowModal
        isOpen={showSecondaryLogoFlow}
        onClose={() => setShowSecondaryLogoFlow(false)}
        companyId={companyId}
        onApproved={refreshAssets}
      />

      {/* Guided Logo Variations Flow Modal — generated from the primary logo */}
      <LogoVariationsFlowModal
        isOpen={showLogoVariationsFlow}
        onClose={() => setShowLogoVariationsFlow(false)}
        companyId={companyId}
        onApproved={refreshAssets}
      />

      {/* Guided Brand Patterns Flow Modal — generated from the primary logo */}
      <BrandPatternFlowModal
        isOpen={showBrandPatternFlow}
        onClose={() => setShowBrandPatternFlow(false)}
        companyId={companyId}
        onApproved={refreshAssets}
      />

      {/* Guided Watermark Flow Modal — same structure as the Primary Logo step */}
      <WatermarkFlowModal
        isOpen={showWatermarkFlow}
        onClose={() => setShowWatermarkFlow(false)}
        companyId={companyId}
        onApproved={refreshAssets}
      />

      {/* Asset Selection Modal (empty state) */}
      <AssetSelectionModal
        isOpen={showAssetSelectionModal}
        onClose={() => setShowAssetSelectionModal(false)}
      />
    </div>
  );
}
