import React, { useEffect, useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Globe, 
  Plus, 
  Edit2, 
  Trash2, 
  X, 
  ExternalLink, 
  Video, 
  Image as ImageIcon,
  Upload,
  Check,
  AlertCircle,
  Play,
  RefreshCw
} from 'lucide-react';
import { PageHeader } from '../../components/ui/PageHeader';
import { PageLayout } from '../../components/layout/PageLayout';
import { 
  getEcosystemOfferings, 
  createEcosystemOffering, 
  updateEcosystemOffering, 
  deleteEcosystemOffering,
  uploadEcosystemFile,
  getShowcaseContent,
  createShowcaseContent,
  updateShowcaseContent,
  deleteShowcaseContent,
  getYoutubeMeta,
} from '../../services/ecosystem-api';
import type { EcosystemOffering, ContentShowcase } from '../../services/ecosystem-api';

// Custom Brand Logo renderer with remote URL preset load + high-fidelity SVG fallback
export const BrandLogo: React.FC<{ name: string; className?: string }> = ({ name, className = "h-7" }) => {
  const [hasError, setHasError] = useState(false);
  const normName = name.toLowerCase().trim();

  // Custom URLs provided by the user
  const presetMap: Record<string, string> = {
    tech4biz: 'https://www.tech4bizsolutions.com/images/logos/logo-light.webp',
    cloudtopiaa: 'https://cloudtopiaa.com/images/logo.jpg',
    auditraxlabs: 'https://auditraxlabs.com/favicon.svg',
    audittrax: 'https://auditraxlabs.com/favicon.svg',
    auditrax: 'https://auditraxlabs.com/favicon.svg',
    codenuk: 'https://codenuk.com/assets/logo-C8NcFwVR.png',
  };

  const resolvedUrl = presetMap[normName] || (name.startsWith('http') || name.startsWith('/uploads') ? name : null);

  // Reset error flag if name changes
  useEffect(() => {
    setHasError(false);
  }, [name]);

  if (resolvedUrl && !hasError) {
    const isTech4biz = normName.includes('tech4biz');
    return (
      <div className={`inline-flex items-center justify-center p-1.5 rounded-xl transition-all ${
        isTech4biz ? 'bg-ink-900/90 dark:bg-ink-0/10' : 'bg-transparent'
      }`}>
        <img
          src={resolvedUrl}
          alt={name}
          className={`${className} object-contain max-w-[140px]`}
          onError={() => setHasError(true)}
        />
      </div>
    );
  }

  // Fallback premium vectors
  if (normName.includes('tech4biz')) {
    return (
      <svg viewBox="0 0 120 30" className={className} fill="currentColor">
        <path d="M10 6h12v4H16v14h-4V10H10V6zm20 8h8v3h-8v4h9v3h-13V10h13v3h-9v1zm19 5c0 1.7-.6 3.1-1.7 4.1C46.2 24.2 44.7 24.7 43 24.7c-2 0-3.6-.6-4.7-1.7-1.1-1.1-1.6-2.6-1.6-4.5v-4.5c0-1.9.5-3.4 1.6-4.5 1.1-1.1 2.7-1.7 4.7-1.7 1.8 0 3.2.5 4.3 1.5 1 1 1.5 2.5 1.5 4.3h-4c0-.9-.2-1.5-.6-1.9-.4-.4-.9-.6-1.7-.6-.7 0-1.3.3-1.6.8-.3.5-.5 1.3-.5 2.3v4.3c0 1 .2 1.8.5 2.3.3.5.9.8 1.6.8.8 0 1.3-.2 1.7-.6.4-.4.6-1 .6-1.9v-1h-2.5v-3h6.5v8.5zm13-13h4v8h8V6h4v18h-4v-7h-8v7h-4V6zm21 0h3.5l5 12 5-12h3.5v18h-3.5v-12.5l-5 12.5h-1l-5-12.5V24h-3.5V6zm19 0h4v18h-4V6z" className="text-ink-900 dark:text-ink-0" />
      </svg>
    );
  }
  if (normName.includes('cloudtopiaa')) {
    return (
      <svg viewBox="0 0 140 30" className={className} fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M15 9c-3.3 0-6 2.7-6 6s2.7 6 6 6h12c2.2 0 4-1.8 4-4s-1.8-4-4-4h-2c-1.1 0-2-.9-2-2s.9-2 2-2h4v-2c0-1.1-.9-2-2-2h-8z" fill="#0EA5E9" />
        <text x="36" y="21" fontFamily="sans-serif" fontWeight="900" fontSize="13" fill="currentColor" className="text-ink-900 dark:text-ink-0">Cloudtopiaa</text>
      </svg>
    );
  }
  if (normName.includes('codenuk')) {
    return (
      <svg viewBox="0 0 110 30" className={className} fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M8 8l-6 7 6 7M18 8l6 7-6 7M14 6l-3 18" stroke="#6366F1" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        <text x="32" y="21" fontFamily="sans-serif" fontWeight="900" fontSize="14" fill="currentColor" className="text-ink-900 dark:text-ink-0">CodeNuk</text>
      </svg>
    );
  }
  if (normName.includes('auditrax') || normName.includes('audittrax')) {
    return (
      <svg viewBox="0 0 130 30" className={className} fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M12 4L4 7v8c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V7l-8-3z" fill="#10B981" />
        <path d="M9 13.5l2 2 4-4" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        <text x="28" y="20" fontFamily="sans-serif" fontWeight="900" fontSize="11" fill="currentColor" className="text-ink-900 dark:text-ink-0">AUDITRAX LABS</text>
      </svg>
    );
  }

  return (
    <div className="flex items-center gap-1 text-ink-500 font-bold text-xs uppercase tracking-wider">
      <Globe className="w-4 h-4" />
      <span>{name}</span>
    </div>
  );
};

// ── Helper: Extract YouTube video ID from any URL format ──
const extractYouTubeVideoId = (url: string): string | null => {
  const patterns = [
    /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/,
    /(?:youtube-nocookie\.com\/embed\/)([a-zA-Z0-9_-]{11})/,
  ];
  for (const pattern of patterns) {
    const match = url.match(pattern);
    if (match) return match[1];
  }
  return null;
};

// ── Content Showcase Manager Component ──
const ContentShowcaseManager: React.FC = () => {
  const [items, setItems] = useState<ContentShowcase[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<ContentShowcase | null>(null);
  const [deleteItem, setDeleteItem] = useState<ContentShowcase | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [formError, setFormError] = useState('');

  // Form fields
  const [scTitle, setScTitle] = useState('');
  const [scDescription, setScDescription] = useState('');
  const [scYoutubeUrl, setScYoutubeUrl] = useState('');
  const [scThumbnailUrl, setScThumbnailUrl] = useState('');
  const [scRedirectUrl, setScRedirectUrl] = useState('');
  const [scRedirectLabel, setScRedirectLabel] = useState('Learn More');
  const [scOrderIndex, setScOrderIndex] = useState(0);
  const [scIsActive, setScIsActive] = useState(true);

  // File Upload states for Thumbnail
  const [uploadingThumbnail, setUploadingThumbnail] = useState(false);
  const thumbnailFileRef = useRef<HTMLInputElement>(null);

  // Auto-fetching metadata states
  const [isFetchingMeta, setIsFetchingMeta] = useState(false);

  // Action to fetch metadata explicitly
  const handleScrapeMetadata = async () => {
    const url = scYoutubeUrl.trim();
    if (!url) return;
    
    const lower = url.toLowerCase();
    const isYt = lower.includes('youtube.com') || lower.includes('youtu.be') || lower.includes('youtube-nocookie.com');
    const isIg = lower.includes('instagram.com');
    const isTw = lower.includes('twitter.com') || lower.includes('x.com');

    if (!isYt && !isIg && !isTw) {
      setFormError('Please enter a valid YouTube, Instagram, or Twitter/X URL.');
      return;
    }

    setIsFetchingMeta(true);
    setFormError('');
    try {
      const meta = await getYoutubeMeta(url);
      setScTitle(meta.title || '');
      setScDescription(meta.description || '');
      if (meta.thumbnailUrl) {
        setScThumbnailUrl(meta.thumbnailUrl);
      }
    } catch (err: any) {
      console.error('Failed to fetch video meta:', err);
      setFormError('Failed to fetch video metadata. You can enter the title and description manually.');
    } finally {
      setIsFetchingMeta(false);
    }
  };

  useEffect(() => { fetchItems(); }, []);

  const fetchItems = async () => {
    try {
      setLoading(true);
      const data = await getShowcaseContent();
      setItems(data);
    } catch (err) {
      console.error('Failed to load showcase content:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleThumbnailUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingThumbnail(true);
    setFormError('');
    try {
      const res = await uploadEcosystemFile(file);
      setScThumbnailUrl(res.url);
    } catch (err: any) {
      setFormError('Failed to upload thumbnail image.');
    } finally {
      setUploadingThumbnail(false);
    }
  };

  const openAddModal = () => {
    setEditingItem(null);
    setScTitle('');
    setScDescription('');
    setScYoutubeUrl('');
    setScThumbnailUrl('');
    setScRedirectUrl('');
    setScRedirectLabel('Learn More');
    setScOrderIndex(items.length);
    setScIsActive(true);
    setFormError('');
    setIsModalOpen(true);
  };

  const openEditModal = (item: ContentShowcase) => {
    setEditingItem(item);
    setScTitle(item.title);
    setScDescription(item.description || '');
    setScYoutubeUrl(item.youtubeUrl);
    setScThumbnailUrl(item.thumbnailUrl || '');
    setScRedirectUrl(item.redirectUrl || '');
    setScRedirectLabel(item.redirectLabel || 'Learn More');
    setScOrderIndex(item.orderIndex);
    setScIsActive(item.isActive);
    setFormError('');
    setIsModalOpen(true);
  };

  const handleSave = async () => {
    if (!scTitle.trim() || !scYoutubeUrl.trim()) {
      setFormError('Title and Media URL are required.');
      return;
    }

    const detectPlatform = (url: string) => {
      const norm = url.toLowerCase();
      if (norm.includes('youtube.com') || norm.includes('youtu.be') || norm.includes('youtube-nocookie.com')) return 'YOUTUBE';
      if (norm.includes('instagram.com')) return 'INSTAGRAM';
      if (norm.includes('twitter.com') || norm.includes('x.com')) return 'TWITTER';
      return 'UNKNOWN';
    };

    if (detectPlatform(scYoutubeUrl) === 'UNKNOWN') {
      setFormError('Please enter a valid URL from YouTube, Instagram, or Twitter/X.');
      return;
    }

    setIsSaving(true);
    setFormError('');
    try {
      const payload = {
        title: scTitle.trim(),
        description: scDescription.trim() || null,
        youtubeUrl: scYoutubeUrl.trim(),
        thumbnailUrl: scThumbnailUrl.trim() || null,
        redirectUrl: scRedirectUrl.trim() || null,
        redirectLabel: scRedirectLabel.trim() || 'Learn More',
        orderIndex: scOrderIndex,
        isActive: scIsActive,
      };

      if (editingItem) {
        await updateShowcaseContent(editingItem.id, payload);
      } else {
        await createShowcaseContent(payload);
      }
      setIsModalOpen(false);
      fetchItems();
    } catch (err: any) {
      setFormError(err.response?.data?.error || 'Failed to save content.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteItem) return;
    try {
      await deleteShowcaseContent(deleteItem.id);
      setDeleteItem(null);
      fetchItems();
    } catch (err) {
      console.error('Failed to delete:', err);
    }
  };

  // Auto-thumbnail from the current YouTube URL field
  const previewVideoId = extractYouTubeVideoId(scYoutubeUrl);
  const previewThumbnail = previewVideoId ? `https://img.youtube.com/vi/${previewVideoId}/mqdefault.jpg` : null;

  return (
    <div className="space-y-4 pt-2 border-t border-ink-200 mt-6">
      <div className="flex justify-between items-center pb-2">
        <div className="text-sm font-bold text-ink-500 uppercase tracking-widest">
          {items.length} Content Showcase Items
        </div>
        <button
          onClick={openAddModal}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-black tracking-wider uppercase bg-ink-900 text-ink-0 hover:bg-ink-800 hover:shadow-lg transition-all cursor-pointer"
        >
          <Plus className="w-4 h-4" />
          <span>Add Video Content</span>
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-10">
          <div className="w-6 h-6 border-3 border-ink-900/30 border-t-ink-900 rounded-full animate-spin"></div>
        </div>
      ) : items.length === 0 ? (
        <div className="text-center py-12 bg-ink-0 border border-ink-200 rounded-2xl">
          <Video className="w-10 h-10 text-ink-300 mx-auto mb-3" />
          <p className="text-xs font-bold text-ink-500">No showcase content yet</p>
          <p className="text-[10px] text-ink-400 mt-1">Add YouTube videos to showcase on the Explore More page</p>
        </div>
      ) : (
        <div className="overflow-x-auto border border-ink-200 rounded-2xl bg-ink-0 shadow-sm">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-ink-50 border-b border-ink-200">
                <th className="text-left py-3 px-6 text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Thumbnail</th>
                <th className="text-left py-3 px-6 text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Title</th>
                <th className="text-left py-3 px-6 text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Redirect</th>
                <th className="text-left py-3 px-6 text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Status</th>
                <th className="text-right py-3 px-6 text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Actions</th>
              </tr>
            </thead>
            <tbody>
              {items.map(item => {
                const videoId = extractYouTubeVideoId(item.youtubeUrl);
                const thumb = item.thumbnailUrl || (videoId ? `https://img.youtube.com/vi/${videoId}/mqdefault.jpg` : null);
                return (
                  <tr key={item.id} className="border-b border-ink-100 last:border-0 hover:bg-ink-50/50 transition-colors">
                    <td className="py-3 px-6">
                      {thumb ? (
                        <img src={thumb} alt={item.title} className="w-24 h-14 rounded-lg object-cover border border-ink-200 shadow-sm" />
                      ) : (
                        <div className="w-24 h-14 rounded-lg bg-ink-100 flex items-center justify-center border border-ink-200">
                          <Video className="w-5 h-5 text-ink-400" />
                        </div>
                      )}
                    </td>
                    <td className="py-3 px-6">
                      <div className="text-xs font-bold text-ink-900">{item.title}</div>
                      {item.description && <div className="text-[10px] text-ink-500 mt-0.5 truncate max-w-[200px]">{item.description}</div>}
                    </td>
                    <td className="py-3 px-6 text-xs font-bold text-ink-500">
                      {item.redirectUrl ? (
                        <a href={item.redirectUrl} target="_blank" rel="noreferrer" className="hover:underline flex items-center gap-1 hover:text-ink-900">
                          {item.redirectLabel || 'Link'}
                          <ExternalLink className="w-3 h-3" />
                        </a>
                      ) : (
                        <span className="text-ink-300 font-normal">None</span>
                      )}
                    </td>
                    <td className="py-3 px-6">
                      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider ${
                        item.isActive
                          ? 'bg-green-500/10 text-green-600 border border-green-500/20'
                          : 'bg-ink-150 text-ink-500 border border-ink-300'
                      }`}>
                        {item.isActive ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="py-3 px-6 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button onClick={() => openEditModal(item)} className="p-1.5 rounded-lg border border-ink-200 text-ink-500 hover:text-ink-900 hover:bg-ink-100 transition-all cursor-pointer" title="Edit">
                          <Edit2 className="w-3.5 h-3.5" />
                        </button>
                        <button onClick={() => setDeleteItem(item)} className="p-1.5 rounded-lg border border-red-200 text-red-500 hover:text-red-700 hover:bg-red-50 transition-all cursor-pointer" title="Delete">
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* ── Add/Edit Content Showcase Modal ── */}
      <AnimatePresence>
        {isModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsModalOpen(false)}
              className="fixed inset-0 bg-ink-900/40 backdrop-blur-md z-45"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 10 }}
              className="fixed inset-y-6 right-6 w-full max-w-lg bg-ink-0 border border-ink-200 rounded-3xl p-6 shadow-2xl z-50 flex flex-col overflow-y-auto"
            >
              <div className="flex justify-between items-start border-b border-ink-200 pb-4 mb-5">
                <div>
                  <h3 className="text-lg font-black tracking-tight text-ink-900">
                    {editingItem ? 'Edit Video Content' : 'Add Video Content'}
                  </h3>
                  <p className="text-[10px] font-bold text-ink-500 uppercase tracking-widest mt-1">
                    YouTube Showcase
                  </p>
                </div>
                <button onClick={() => setIsModalOpen(false)} className="p-2 rounded-xl bg-ink-100 hover:bg-ink-200 text-ink-700 transition-colors">
                  <X className="w-4 h-4" />
                </button>
              </div>

              <div className="space-y-4 flex-1">
                {/* Media URL */}
                <div>
                  <div className="flex justify-between items-center mb-1.5">
                    <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest">Media URL *</label>
                  </div>
                  <div className="flex gap-2">
                    <input
                      value={scYoutubeUrl}
                      onChange={e => setScYoutubeUrl(e.target.value)}
                      placeholder="YouTube watch/shorts/embed URL, Instagram URL, or Twitter/X URL..."
                      className="flex-1 px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                    />
                    <button
                      type="button"
                      onClick={handleScrapeMetadata}
                      disabled={isFetchingMeta || !scYoutubeUrl.trim()}
                      className="px-4 py-2 border border-blue-200 hover:border-blue-400 bg-blue-50 hover:bg-blue-100 text-blue-700 disabled:opacity-50 disabled:border-ink-200 disabled:bg-ink-50 disabled:text-ink-400 text-xs font-bold rounded-xl transition-all cursor-pointer flex items-center gap-1.5 shrink-0"
                    >
                      {isFetchingMeta ? (
                        <>
                          <span className="w-3.5 h-3.5 border-2 border-blue-700 border-t-transparent rounded-full animate-spin inline-block" />
                          <span>Scraping...</span>
                        </>
                      ) : (
                        <>
                          <RefreshCw className="w-3.5 h-3.5" />
                          <span>Fetch Meta</span>
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* Custom Thumbnail */}
                <div>
                  <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Thumbnail (URL or File Upload)</label>
                  <div className="flex gap-2">
                    <input
                      value={scThumbnailUrl}
                      onChange={e => setScThumbnailUrl(e.target.value)}
                      placeholder="https://... (or upload an image below)"
                      className="flex-1 px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                    />
                    <input
                      type="file"
                      ref={thumbnailFileRef}
                      onChange={handleThumbnailUpload}
                      accept="image/*"
                      className="hidden"
                    />
                    <button
                      type="button"
                      onClick={() => thumbnailFileRef.current?.click()}
                      disabled={uploadingThumbnail}
                      className="px-4 py-2 border border-ink-200 hover:border-ink-400 hover:bg-ink-50 text-xs font-bold rounded-xl transition-all cursor-pointer flex items-center gap-1"
                    >
                      <Upload className="w-3.5 h-3.5" />
                      <span>{uploadingThumbnail ? 'Uploading...' : 'Upload'}</span>
                    </button>
                  </div>

                  {/* Thumbnail preview */}
                  {previewThumbnail && (
                    <div className="mt-2.5 rounded-xl overflow-hidden border border-ink-200 shadow-sm relative aspect-video bg-ink-100 max-w-[240px]">
                      <img src={previewThumbnail} alt="Thumbnail Preview" className="w-full h-full object-cover" />
                      <div className="absolute inset-0 flex items-center justify-center bg-ink-900/10">
                        <Play className="w-8 h-8 text-white drop-shadow-md" fill="currentColor" />
                      </div>
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Title *</label>
                  <input
                    value={scTitle}
                    onChange={e => setScTitle(e.target.value)}
                    placeholder="e.g., Platform Demo, Case Study, Webinar..."
                    className="w-full px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                  />
                </div>

                <div>
                  <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Description</label>
                  <textarea
                    value={scDescription}
                    onChange={e => setScDescription(e.target.value)}
                    rows={2}
                    placeholder="Brief description of this content..."
                    className="w-full px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all resize-none"
                  />
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Redirect URL</label>
                    <input
                      value={scRedirectUrl}
                      onChange={e => setScRedirectUrl(e.target.value)}
                      placeholder="https://..."
                      className="w-full px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Redirect Label</label>
                    <input
                      value={scRedirectLabel}
                      onChange={e => setScRedirectLabel(e.target.value)}
                      placeholder="Learn More"
                      className="w-full px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Display Order</label>
                    <input
                      type="number"
                      value={scOrderIndex}
                      onChange={e => setScOrderIndex(parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2.5 border border-ink-200 rounded-xl text-xs font-semibold text-ink-900 bg-ink-50 outline-none focus:border-ink-400 focus:ring-2 ring-ink-900/10 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-extrabold text-ink-500 uppercase tracking-widest mb-1.5">Visibility</label>
                    <div
                      onClick={() => setScIsActive(!scIsActive)}
                      className={`flex items-center gap-2 px-3 py-2.5 border rounded-xl text-xs font-bold cursor-pointer transition-all ${
                        scIsActive ? 'bg-green-50 border-green-200 text-green-700' : 'bg-ink-50 border-ink-200 text-ink-500'
                      }`}
                    >
                      <div className={`w-3 h-3 rounded-full border-2 ${scIsActive ? 'bg-green-500 border-green-600' : 'bg-ink-300 border-ink-400'}`} />
                      {scIsActive ? 'Active' : 'Inactive'}
                    </div>
                  </div>
                </div>

                {formError && (
                  <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-xl text-xs text-red-700 font-bold">
                    <AlertCircle className="w-4 h-4 shrink-0" />
                    <span>{formError}</span>
                  </div>
                )}
              </div>

              <div className="flex gap-3 pt-5 mt-auto border-t border-ink-200">
                <button
                  onClick={() => setIsModalOpen(false)}
                  className="flex-1 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider border border-ink-200 text-ink-700 hover:bg-ink-50 transition-colors cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSave}
                  disabled={isSaving}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-xs font-black uppercase tracking-wider bg-ink-900 text-ink-0 hover:bg-ink-800 disabled:opacity-60 transition-all cursor-pointer"
                >
                  {isSaving ? (
                    <div className="w-4 h-4 border-2 border-ink-0/30 border-t-ink-0 rounded-full animate-spin" />
                  ) : (
                    <>
                      <Check className="w-4 h-4" />
                      <span>{editingItem ? 'Update' : 'Create'}</span>
                    </>
                  )}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* ── Delete Confirmation ── */}
      <AnimatePresence>
        {deleteItem && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setDeleteItem(null)}
              className="fixed inset-0 bg-ink-900/40 backdrop-blur-md z-45"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-ink-0 border border-ink-200 rounded-3xl p-6 shadow-2xl z-50 text-center"
            >
              <div className="w-12 h-12 rounded-full bg-red-500/10 text-red-500 flex items-center justify-center mx-auto mb-4 border border-red-200">
                <Trash2 className="w-6 h-6" />
              </div>
              <h3 className="text-base font-black text-ink-900 mb-2">Delete Video Content?</h3>
              <p className="text-xs font-medium text-ink-600 mb-6">
                Are you sure you want to delete <strong className="text-ink-900">{deleteItem.title}</strong>? This action is permanent.
              </p>
              <div className="flex gap-3 justify-center">
                <button onClick={() => setDeleteItem(null)} className="px-4 py-2.5 rounded-xl text-xs font-bold uppercase border border-ink-200 text-ink-700 hover:bg-ink-50 transition-colors cursor-pointer">
                  Cancel
                </button>
                <button onClick={handleDelete} className="px-4 py-2.5 rounded-xl text-xs font-black uppercase bg-red-600 text-ink-0 hover:bg-red-700 transition-colors cursor-pointer">
                  Yes, Delete
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
};

export const EcosystemManagerPage: React.FC = () => {
  const [offerings, setOfferings] = useState<EcosystemOffering[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOffering, setSelectedOffering] = useState<EcosystemOffering | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [offeringToDelete, setOfferingToDelete] = useState<EcosystemOffering | null>(null);

  // Form states
  const [name, setName] = useState('');
  const [type, setType] = useState<'PRODUCT' | 'SERVICE'>('PRODUCT');
  const [tagline, setTagline] = useState('');
  const [description, setDescription] = useState('');
  const [benefitsText, setBenefitsText] = useState('');
  const [websiteUrl, setWebsiteUrl] = useState('');
  const [ctaText, setCtaText] = useState('');
  const [logoIcon] = useState('Globe');
  const [logoUrl, setLogoUrl] = useState('');
  const [mediaUrl, setMediaUrl] = useState('');
  const [mediaType, setMediaType] = useState<'IMAGE' | 'VIDEO' | 'GIF' | 'NONE'>('NONE');
  const [orderIndex, setOrderIndex] = useState(0);
  const [isActive, setIsActive] = useState(true);
  const [error, setError] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  // Upload/preset control states
  const [logoTab, setLogoTab] = useState<'preset' | 'upload' | 'link'>('preset');
  const [mediaTab, setMediaTab] = useState<'upload' | 'link'>('link');
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const [uploadingMedia, setUploadingMedia] = useState(false);

  const logoFileRef = useRef<HTMLInputElement>(null);
  const mediaFileRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    fetchOfferings();
  }, []);

  const fetchOfferings = async () => {
    try {
      setLoading(true);
      const data = await getEcosystemOfferings();
      setOfferings(data);
    } catch (err) {
      console.error('Failed to load offerings:', err);
    } finally {
      setLoading(false);
    }
  };

  const openAddModal = () => {
    setSelectedOffering(null);
    setName('');
    setType('PRODUCT');
    setTagline('');
    setDescription('');
    setBenefitsText('');
    setWebsiteUrl('');
    setCtaText('Visit Website');
    setLogoUrl('tech4biz');
    setMediaUrl('');
    setMediaType('NONE');
    setOrderIndex(offerings.length);
    setIsActive(true);
    setError('');
    setLogoTab('preset');
    setMediaTab('link');
    setIsModalOpen(true);
  };

  const openEditModal = (offering: EcosystemOffering) => {
    setSelectedOffering(offering);
    setName(offering.name);
    setType(offering.type as any);
    setTagline(offering.tagline);
    setDescription(offering.description);
    setBenefitsText(offering.benefits.join('\n'));
    setWebsiteUrl(offering.websiteUrl);
    setCtaText(offering.ctaText);
    
    const rawLogo = offering.logoUrl || '';
    setLogoUrl(rawLogo);
    
    // Determine the active tab based on saved logo value
    if (['tech4biz', 'cloudtopiaa', 'codenuk', 'auditraxlabs', 'audittrax'].includes(rawLogo.toLowerCase().trim())) {
      setLogoTab('preset');
    } else if (rawLogo.startsWith('/uploads/')) {
      setLogoTab('upload');
    } else if (rawLogo.startsWith('http')) {
      setLogoTab('link');
    } else {
      setLogoTab('preset');
    }

    setMediaUrl(offering.mediaUrl || '');
    const mType = (offering.mediaType || 'NONE') as any;
    setMediaType(mType);
    setMediaTab(offering.mediaUrl?.startsWith('/uploads/') ? 'upload' : 'link');

    setOrderIndex(offering.orderIndex);
    setIsActive(offering.isActive);
    setError('');
    setIsModalOpen(true);
  };

  const handleDeleteClick = (offering: EcosystemOffering) => {
    setOfferingToDelete(offering);
    setIsDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    if (!offeringToDelete) return;
    try {
      await deleteEcosystemOffering(offeringToDelete.id);
      setIsDeleteConfirmOpen(false);
      setOfferingToDelete(null);
      fetchOfferings();
    } catch (err: any) {
      console.error('Failed to delete offering:', err);
    }
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingLogo(true);
    setError('');
    try {
      const res = await uploadEcosystemFile(file);
      setLogoUrl(res.url);
    } catch (err: any) {
      setError('Failed to upload logo image.');
    } finally {
      setUploadingLogo(false);
    }
  };

  const handleMediaUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingMedia(true);
    setError('');
    try {
      const res = await uploadEcosystemFile(file);
      setMediaUrl(res.url);
      if (file.type.startsWith('video/')) {
        setMediaType('VIDEO');
      } else if (file.name.endsWith('.gif')) {
        setMediaType('GIF');
      } else {
        setMediaType('IMAGE');
      }
    } catch (err: any) {
      setError('Failed to upload media file.');
    } finally {
      setUploadingMedia(false);
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name || !tagline || !description || !websiteUrl) {
      setError('Please fill in all required fields.');
      return;
    }

    setIsSaving(true);
    setError('');

    const benefits = benefitsText
      .split('\n')
      .map(b => b.trim())
      .filter(b => b.length > 0);

    const payload = {
      name,
      type,
      tagline,
      description,
      benefits,
      websiteUrl,
      ctaText: ctaText || 'Visit Website',
      logoIcon,
      logoUrl: logoUrl || null,
      mediaUrl: mediaUrl || null,
      mediaType: mediaType === 'NONE' ? null : mediaType,
      orderIndex: Number(orderIndex),
      isActive
    };

    try {
      if (selectedOffering) {
        await updateEcosystemOffering(selectedOffering.id, payload);
      } else {
        await createEcosystemOffering(payload);
      }
      setIsModalOpen(false);
      fetchOfferings();
    } catch (err: any) {
      console.error('Failed to save offering:', err);
      setError(err.response?.data?.error || 'Failed to save ecosystem offering.');
    } finally {
      setIsSaving(false);
    }
  };

  const presetBrands = [
    { key: 'tech4biz', name: 'Tech4Biz Solutions', url: 'https://www.tech4bizsolutions.com/images/logos/logo-light.webp' },
    { key: 'cloudtopiaa', name: 'Cloudtopiaa', url: 'https://cloudtopiaa.com/images/logo.jpg' },
    { key: 'codenuk', name: 'CodeNuk', url: 'https://codenuk.com/assets/logo-C8NcFwVR.png' },
    { key: 'auditraxlabs', name: 'Audittrax Labs', url: 'https://auditraxlabs.com/favicon.svg' },
  ];

  return (
    <PageLayout
      header={
        <PageHeader
          title="Ecosystem Offerings Manager"
          subtitle="Admin interface to create, modify, and delete products, services, and associated branding media links."
        />
      }
    >
      <div className="p-6 space-y-6 flex flex-col min-h-0 flex-1 overflow-y-auto">
        <div className="flex justify-between items-center border-b border-ink-200 pb-4">
          <div className="text-sm font-bold text-ink-500 uppercase tracking-widest">
            {offerings.length} Ecosystem Offerings Listed
          </div>
          <button
            onClick={openAddModal}
            className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-black tracking-wider uppercase bg-ink-900 text-ink-0 hover:bg-ink-800 hover:shadow-lg transition-all cursor-pointer"
          >
            <Plus className="w-4 h-4" />
            <span>Add New Offering</span>
          </button>
        </div>

        {loading ? (
          <div className="flex flex-1 items-center justify-center py-20">
            <div className="w-8 h-8 border-4 border-ink-900/30 border-t-ink-900 rounded-full animate-spin"></div>
          </div>
        ) : (
          <div className="overflow-x-auto border border-ink-200 rounded-2xl bg-ink-0 shadow-sm">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-ink-200 bg-ink-50 text-[10px] font-black uppercase tracking-wider text-ink-500">
                  <th className="py-4 px-6 w-40">Logo / Brand</th>
                  <th className="py-4 px-6">Name</th>
                  <th className="py-4 px-6 w-28">Type</th>
                  <th className="py-4 px-6">Tagline</th>
                  <th className="py-4 px-6 w-36">Redirection URL</th>
                  <th className="py-4 px-6 w-24">Media</th>
                  <th className="py-4 px-6 w-24">Status</th>
                  <th className="py-4 px-6 w-28 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-ink-200">
                {offerings.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="py-12 text-center text-sm font-semibold text-ink-400">
                      No offerings found. Click "Add New Offering" to create one.
                    </td>
                  </tr>
                ) : (
                  offerings.map((offering) => (
                    <tr key={offering.id} className="hover:bg-ink-50/50 transition-colors">
                      {/* Logo / Brand */}
                      <td className="py-4 px-6">
                        <div className="h-10 flex items-center">
                          {offering.logoUrl ? (
                            <BrandLogo name={offering.logoUrl} className="max-h-6 max-w-[120px] object-contain" />
                          ) : (
                            <div className="w-8 h-8 rounded-lg bg-ink-100 flex items-center justify-center text-ink-855 border border-ink-200 shadow-sm">
                              <Globe className="w-4 h-4" />
                            </div>
                          )}
                        </div>
                      </td>

                      {/* Name */}
                      <td className="py-4 px-6 font-extrabold text-ink-900 text-sm">
                        {offering.name}
                      </td>

                      {/* Type */}
                      <td className="py-4 px-6">
                        <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[9px] font-black tracking-widest uppercase border ${
                          offering.type === 'PRODUCT'
                            ? 'bg-blue-500/10 text-blue-600 border-blue-500/20'
                            : 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20'
                        }`}>
                          {offering.type}
                        </span>
                      </td>

                      {/* Tagline */}
                      <td className="py-4 px-6 text-xs font-semibold text-ink-600 max-w-xs truncate">
                        {offering.tagline}
                      </td>

                      {/* Redirection URL */}
                      <td className="py-4 px-6 text-xs font-bold text-ink-500">
                        <a 
                          href={offering.websiteUrl} 
                          target="_blank" 
                          rel="noreferrer"
                          className="hover:underline flex items-center gap-1 hover:text-ink-900"
                        >
                          {new URL(offering.websiteUrl).hostname}
                          <ExternalLink className="w-3 h-3" />
                        </a>
                      </td>

                      {/* Media */}
                      <td className="py-4 px-6 text-xs text-ink-600 font-bold">
                        {offering.mediaType && offering.mediaType !== 'NONE' ? (
                          <span className="flex items-center gap-1">
                            {offering.mediaType === 'VIDEO' ? <Video className="w-3.5 h-3.5 text-blue-500" /> : <ImageIcon className="w-3.5 h-3.5 text-purple-500" />}
                            <span className="capitalize text-[10px]">{offering.mediaType.toLowerCase()}</span>
                          </span>
                        ) : (
                          <span className="text-ink-300 font-normal">None</span>
                        )}
                      </td>

                      {/* Status */}
                      <td className="py-4 px-6">
                        <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider ${
                          offering.isActive
                            ? 'bg-green-500/10 text-green-600 border border-green-500/20'
                            : 'bg-ink-150 text-ink-500 border border-ink-300'
                        }`}>
                          {offering.isActive ? 'Active' : 'Inactive'}
                        </span>
                      </td>

                      {/* Actions */}
                      <td className="py-4 px-6 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => openEditModal(offering)}
                            className="p-1.5 rounded-lg border border-ink-200 text-ink-500 hover:text-ink-900 hover:bg-ink-100 transition-all cursor-pointer"
                            title="Edit Offering"
                          >
                            <Edit2 className="w-3.5 h-3.5" />
                          </button>
                          <button
                            onClick={() => handleDeleteClick(offering)}
                            className="p-1.5 rounded-lg border border-red-200 text-red-500 hover:text-red-700 hover:bg-red-50 transition-all cursor-pointer"
                            title="Delete Offering"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* ══════════════════════════════════════════════════════════════════ */}
        {/* ── Content Showcase Manager (YouTube Videos) ── */}
        {/* ══════════════════════════════════════════════════════════════════ */}
        <ContentShowcaseManager />

        {/* ── Add / Edit Modal ── */}
        <AnimatePresence>
          {isModalOpen && (
            <>
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setIsModalOpen(false)}
                className="fixed inset-0 bg-ink-900/40 backdrop-blur-md z-45"
              />
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                className="fixed inset-y-6 right-6 w-full max-w-xl bg-ink-0 border border-ink-200 rounded-3xl p-6 md:p-8 shadow-2xl z-50 flex flex-col"
              >
                <div className="flex justify-between items-start border-b border-ink-200 pb-4 mb-6">
                  <div>
                    <h3 className="text-lg font-black tracking-tight text-ink-900">
                      {selectedOffering ? 'Edit Offering' : 'Add New Offering'}
                    </h3>
                    <p className="text-xs font-bold text-ink-500 uppercase tracking-widest mt-1">
                      {selectedOffering ? selectedOffering.name : 'Ecosystem Catalog'}
                    </p>
                  </div>
                  <button
                    onClick={() => setIsModalOpen(false)}
                    className="p-2 rounded-xl bg-ink-100 hover:bg-ink-200 text-ink-700 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <form onSubmit={handleSave} className="flex-1 overflow-y-auto space-y-5 pr-1">
                  {error && (
                    <div className="p-3.5 rounded-xl border border-red-200 bg-red-500/10 text-xs font-semibold text-red-600 flex items-center gap-2">
                      <AlertCircle className="w-4 h-4 shrink-0" />
                      <span>{error}</span>
                    </div>
                  )}

                  {/* Name & Type */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Name *</label>
                      <input
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        placeholder="e.g. CodeNuk"
                        className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Type *</label>
                      <select
                        value={type}
                        onChange={(e) => setType(e.target.value as any)}
                        className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                      >
                        <option value="PRODUCT">PRODUCT</option>
                        <option value="SERVICE">SERVICE</option>
                      </select>
                    </div>
                  </div>

                  {/* Tagline */}
                  <div>
                    <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Tagline *</label>
                    <input
                      type="text"
                      value={tagline}
                      onChange={(e) => setTagline(e.target.value)}
                      placeholder="e.g. AI-powered backend generator."
                      className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                    />
                  </div>

                  {/* Description */}
                  <div>
                    <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Description *</label>
                    <textarea
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      placeholder="Detailed description of the company/offering..."
                      rows={3}
                      className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0 resize-none"
                    />
                  </div>

                  {/* Key Benefits */}
                  <div>
                    <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Key Benefits (one per line)</label>
                    <textarea
                      value={benefitsText}
                      onChange={(e) => setBenefitsText(e.target.value)}
                      placeholder="Benefit 1&#10;Benefit 2&#10;Benefit 3..."
                      rows={2}
                      className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0 resize-none"
                    />
                  </div>

                  {/* Redirection URL & CTA Text */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Redirection URL *</label>
                      <input
                        type="url"
                        value={websiteUrl}
                        onChange={(e) => setWebsiteUrl(e.target.value)}
                        placeholder="https://example.com"
                        className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">CTA Button Text</label>
                      <input
                        type="text"
                        value={ctaText}
                        onChange={(e) => setCtaText(e.target.value)}
                        placeholder="Visit Website"
                        className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                      />
                    </div>
                  </div>

                  {/* Logo Brand Picker Tab Interface */}
                  <div className="border border-ink-200 rounded-2xl p-4 bg-ink-50 space-y-4">
                    <div className="flex justify-between items-center">
                      <label className="text-[10px] font-black uppercase tracking-wider text-ink-500">Logo Configuration</label>
                      <div className="flex bg-ink-200 p-0.5 rounded-lg text-[9px] font-black uppercase tracking-wider">
                        <button
                          type="button"
                          onClick={() => setLogoTab('preset')}
                          className={`px-2 py-1 rounded ${logoTab === 'preset' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500'}`}
                        >
                          Preset Brand
                        </button>
                        <button
                          type="button"
                          onClick={() => setLogoTab('upload')}
                          className={`px-2 py-1 rounded ${logoTab === 'upload' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500'}`}
                        >
                          Upload File
                        </button>
                        <button
                          type="button"
                          onClick={() => setLogoTab('link')}
                          className={`px-2 py-1 rounded ${logoTab === 'link' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500'}`}
                        >
                          Custom Link
                        </button>
                      </div>
                    </div>

                    {logoTab === 'preset' && (
                      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                        {presetBrands.map((brand) => {
                          const isSelected = logoUrl.toLowerCase() === brand.key.toLowerCase();
                          return (
                            <button
                              key={brand.key}
                              type="button"
                              onClick={() => setLogoUrl(brand.key)}
                              className={`flex flex-col items-center justify-center p-3 rounded-xl border transition-all relative min-h-[70px] ${
                                isSelected 
                                  ? 'bg-ink-0 border-ink-900 shadow-md ring-2 ring-ink-900/10' 
                                  : 'bg-ink-0/60 border-ink-200 hover:border-ink-400 hover:bg-ink-0'
                              }`}
                            >
                              {isSelected && (
                                <span className="absolute top-1.5 right-1.5 bg-ink-900 text-ink-0 rounded-full p-0.5">
                                  <Check className="w-2.5 h-2.5" />
                                </span>
                              )}
                              <BrandLogo name={brand.key} className="h-5" />
                              <span className="text-[9px] font-extrabold text-ink-500 uppercase tracking-wider mt-2.5">
                                {brand.name}
                              </span>
                            </button>
                          );
                        })}
                      </div>
                    )}

                    {logoTab === 'upload' && (
                      <div className="space-y-3">
                        <input
                          type="file"
                          ref={logoFileRef}
                          onChange={handleLogoUpload}
                          accept="image/*"
                          className="hidden"
                        />
                        <div 
                          onClick={() => logoFileRef.current?.click()}
                          className="border-2 border-dashed border-ink-300 hover:border-ink-500 rounded-xl p-5 text-center cursor-pointer bg-ink-0 transition-all flex flex-col items-center justify-center gap-2"
                        >
                          <Upload className="w-6 h-6 text-ink-400" />
                          <div className="text-xs font-bold text-ink-700">
                            {uploadingLogo ? 'Uploading to Storage...' : 'Click to select logo image'}
                          </div>
                          <p className="text-[10px] text-ink-400">Supports PNG, JPG, SVG, WebP</p>
                        </div>
                        {logoUrl && logoUrl.startsWith('/uploads/') && (
                          <div className="flex items-center gap-3 p-2 border border-green-200 bg-green-500/5 rounded-xl">
                            <BrandLogo name={logoUrl} className="h-6" />
                            <span className="text-[10px] font-bold text-green-700 truncate">{logoUrl}</span>
                          </div>
                        )}
                      </div>
                    )}

                    {logoTab === 'link' && (
                      <div>
                        <input
                          type="url"
                          value={logoUrl}
                          onChange={(e) => setLogoUrl(e.target.value)}
                          placeholder="https://example.com/logo.png"
                          className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                        />
                        {logoUrl && logoUrl.startsWith('http') && (
                          <div className="mt-3 flex items-center gap-3 p-2 border border-ink-200 bg-ink-0 rounded-xl">
                            <BrandLogo name={logoUrl} className="h-6" />
                            <span className="text-[10px] font-bold text-ink-500 truncate">{logoUrl}</span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Media Content Settings */}
                  <div className="border border-ink-200 rounded-2xl p-4 bg-ink-50 space-y-4">
                    <div className="flex justify-between items-center">
                      <label className="text-[10px] font-black uppercase tracking-wider text-ink-500">Media Preview / Embeds</label>
                      <div className="flex bg-ink-200 p-0.5 rounded-lg text-[9px] font-black uppercase tracking-wider">
                        <button
                          type="button"
                          onClick={() => setMediaTab('link')}
                          className={`px-2 py-1 rounded ${mediaTab === 'link' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500'}`}
                        >
                          Media Link
                        </button>
                        <button
                          type="button"
                          onClick={() => setMediaTab('upload')}
                          className={`px-2 py-1 rounded ${mediaTab === 'upload' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500'}`}
                        >
                          Upload File
                        </button>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-[9px] font-black uppercase tracking-wider text-ink-400 mb-1.5">Media Type</label>
                        <select
                          value={mediaType}
                          onChange={(e) => setMediaType(e.target.value as any)}
                          className="w-full px-3 py-2 rounded-xl border border-ink-200 text-xs font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                        >
                          <option value="NONE">None</option>
                          <option value="IMAGE">Image / Screenshot</option>
                          <option value="VIDEO">Video / Iframe</option>
                          <option value="GIF">Animated GIF</option>
                        </select>
                      </div>

                      {mediaTab === 'link' ? (
                        <div>
                          <label className="block text-[9px] font-black uppercase tracking-wider text-ink-400 mb-1.5">External Media Link</label>
                          <input
                            type="text"
                            value={mediaUrl}
                            onChange={(e) => setMediaUrl(e.target.value)}
                            placeholder="e.g. YouTube iframe or Image URL"
                            className="w-full px-3 py-2 rounded-xl border border-ink-200 text-xs font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                            disabled={mediaType === 'NONE'}
                          />
                        </div>
                      ) : (
                        <div>
                          <label className="block text-[9px] font-black uppercase tracking-wider text-ink-400 mb-1.5">Upload File</label>
                          <input
                            type="file"
                            ref={mediaFileRef}
                            onChange={handleMediaUpload}
                            accept="image/*,video/*"
                            className="hidden"
                          />
                          <button
                            type="button"
                            onClick={() => mediaFileRef.current?.click()}
                            disabled={mediaType === 'NONE' || uploadingMedia}
                            className="w-full flex items-center justify-center gap-1.5 py-2 px-3 border border-ink-300 hover:border-ink-500 rounded-xl bg-ink-0 text-xs font-bold text-ink-700 hover:bg-ink-50 transition-colors disabled:opacity-50 cursor-pointer"
                          >
                            <Upload className="w-3.5 h-3.5" />
                            <span>{uploadingMedia ? 'Uploading...' : 'Select File'}</span>
                          </button>
                        </div>
                      )}
                    </div>

                    {mediaUrl && mediaType !== 'NONE' && (
                      <div className="border border-ink-200 rounded-xl overflow-hidden bg-ink-0 p-1 relative aspect-video flex items-center justify-center">
                        {mediaType === 'VIDEO' ? (
                          mediaUrl.includes('youtube.com') || mediaUrl.includes('youtube-nocookie.com') || mediaUrl.includes('vimeo.com') ? (
                            <iframe src={mediaUrl} className="w-full h-full border-0 rounded-lg" allowFullScreen />
                          ) : (
                            <video src={mediaUrl} controls className="w-full h-full object-cover rounded-lg" />
                          )
                        ) : (
                          <img src={mediaUrl} alt="Preview" className="w-full h-full object-cover rounded-lg" />
                        )}
                      </div>
                    )}
                  </div>

                  {/* Order Index & Active Toggle */}
                  <div className="grid grid-cols-2 gap-4 pt-2">
                    <div>
                      <label className="block text-[10px] font-black uppercase tracking-wider text-ink-500 mb-2">Order Index</label>
                      <input
                        type="number"
                        value={orderIndex}
                        onChange={(e) => setOrderIndex(Number(e.target.value))}
                        className="w-full px-4 py-2.5 rounded-xl border border-ink-200 text-sm font-semibold focus:outline-none focus:border-ink-600 bg-ink-0"
                      />
                    </div>
                    <div className="flex items-center gap-3 pt-6">
                      <input
                        type="checkbox"
                        id="isActiveToggle"
                        checked={isActive}
                        onChange={(e) => setIsActive(e.target.checked)}
                        className="w-4 h-4 rounded text-ink-900 border-ink-300 focus:ring-ink-900"
                      />
                      <label htmlFor="isActiveToggle" className="text-xs font-bold text-ink-700 select-none">
                        Active Solution (Show in Catalog)
                      </label>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="border-t border-ink-200 pt-6 mt-6 flex justify-end gap-3">
                    <button
                      type="button"
                      onClick={() => setIsModalOpen(false)}
                      className="px-5 py-3 rounded-xl text-xs font-bold tracking-wider uppercase border border-ink-200 text-ink-700 hover:bg-ink-50 transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      disabled={isSaving}
                      className="px-5 py-3 rounded-xl text-xs font-black tracking-wider uppercase bg-ink-900 text-ink-0 hover:bg-ink-800 transition-colors disabled:opacity-50"
                    >
                      {isSaving ? 'Saving...' : 'Save Offering'}
                    </button>
                  </div>
                </form>
              </motion.div>
            </>
          )}
        </AnimatePresence>

        {/* ── Delete Confirmation Dialog ── */}
        <AnimatePresence>
          {isDeleteConfirmOpen && (
            <>
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setIsDeleteConfirmOpen(false)}
                className="fixed inset-0 bg-ink-900/40 backdrop-blur-md z-45"
              />
              <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.95 }}
                className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-ink-0 border border-ink-200 rounded-3xl p-6 shadow-2xl z-50 text-center"
              >
                <div className="w-12 h-12 rounded-full bg-red-500/10 text-red-500 flex items-center justify-center mx-auto mb-4 border border-red-200">
                  <Trash2 className="w-6 h-6" />
                </div>
                <h3 className="text-base font-black text-ink-900 mb-2">Delete Ecosystem Offering?</h3>
                <p className="text-xs font-medium text-ink-600 mb-6">
                  Are you sure you want to delete <strong className="text-ink-900">{offeringToDelete?.name}</strong>? This action is permanent and cannot be undone.
                </p>
                <div className="flex gap-3 justify-center">
                  <button
                    onClick={() => setIsDeleteConfirmOpen(false)}
                    className="px-4 py-2.5 rounded-xl text-xs font-bold uppercase border border-ink-200 text-ink-700 hover:bg-ink-50 transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={confirmDelete}
                    className="px-4 py-2.5 rounded-xl text-xs font-black uppercase bg-red-600 text-ink-0 hover:bg-red-700 transition-colors"
                  >
                    Yes, Delete
                  </button>
                </div>
              </motion.div>
            </>
          )}
        </AnimatePresence>
      </div>
    </PageLayout>
  );
};

export default EcosystemManagerPage;
