import React, { useState, useEffect, useCallback } from 'react';

const API = '/api/super-admin';

// ── Feature Keys ──────────────────────────────────────────────────────────────
const PLAN_FEATURE_KEYS: { key: string; label: string; icon: string; desc: string }[] = [
  { key: 'products', label: 'Products', icon: '📦', desc: 'পণ্য যোগ/সম্পাদনা/মুছুন' },
  { key: 'categories', label: 'Categories', icon: '🏷️', desc: 'ক্যাটাগরি ম্যানেজমেন্ট' },
  { key: 'orders', label: 'Orders', icon: '🛒', desc: 'অর্ডার দেখা ও পরিচালনা' },
  { key: 'leads', label: 'Leads', icon: '📞', desc: 'Lead / Customer ট্র্যাকিং' },
  { key: 'reviews', label: 'Reviews', icon: '⭐', desc: 'Customer রিভিউ ম্যানেজমেন্ট' },
  { key: 'stock', label: 'Stock', icon: '🗄️', desc: 'স্টক ও ইনভেন্টরি' },
  { key: 'marketing', label: 'Marketing', icon: '🎯', desc: 'কুপন ও প্রমো অফার' },
  { key: 'courier', label: 'Courier', icon: '🚚', desc: 'কুরিয়ার সেটিংস ও অর্ডার' },
  { key: 'home_editor', label: 'Home Editor', icon: '🏠', desc: 'হোমপেজ কাস্টমাইজেশন' },
  { key: 'landing_editor', label: 'Landing Pages', icon: '🎨', desc: 'প্রোডাক্ট ল্যান্ডিং পেজ' },
  { key: 'messenger_ai', label: 'Messenger AI', icon: '🤖', desc: 'AI চ্যাটবট ইন্টিগ্রেশন' },
  { key: 'ubaidi_ai', label: 'Ubaidi AI', icon: '✨', desc: 'Shop & Admin AI ফিচার অ্যাক্সেস' },
  { key: 'ubaidi_ads_marketer', label: 'Ubaidi Ads Marketer', icon: '🤖', desc: 'AI দিয়ে Meta Ads Analysis' },
];

// Default free/trial features
const DEFAULT_FREE_FEATURES: Record<string, any> = {
  products: true, categories: false, orders: true, leads: false,
  reviews: false, stock: false, marketing: false, courier: false,
  home_editor: false, landing_editor: false, messenger_ai: false, ubaidi_ai: false, ubaidi_ads_marketer: false,
  allowed_home_themes: ['01'],   // only theme 01 by default
  max_landing_pages: 0,          // 0 = no landing pages
};

// All available homepage themes
const ALL_HOME_THEMES = [
  { id: '01', label: 'Theme 01', emoji: '🟣' },
  { id: '02', label: 'Theme 02', emoji: '🟠' },
  { id: '03', label: 'Theme 03', emoji: '🟢' },
  { id: '04', label: 'Theme 04', emoji: '⚫' },
  { id: '05', label: 'Theme 05', emoji: '🔵' },
];

// ── Types ─────────────────────────────────────────────────────────────────────
interface Tenant {
  id: number; name: string; phone: string; email: string;
  business_name: string; business_slug: string; business_category: string;
  subscription_status: string; subscription_expires_at: string;
  plan_name: string; plan_price: number; created_at: string;
}
interface Subscription {
  id: number; tenant_id: number; tenant_name: string; tenant_phone: string;
  business_name: string; business_slug: string;
  plan_name: string; plan_price: number;
  payment_method: string; payment_number: string; transaction_id: string;
  amount: number; payment_screenshot: string; status: string;
  admin_notes: string; created_at: string;
}
interface Plan {
  id: number; name: string; price: number; regular_price?: number; duration_days: number;
  features: Record<string, boolean>; display_features?: string[]; is_active: number; sort_order: number;
  is_popular?: boolean;
}
interface Stats {
  total_tenants: number; active_tenants: number; trial_tenants: number;
  pending_subs: number; total_revenue: number; this_month_revenue: number; new_today: number;
}

// ── SuperAdminLogin ───────────────────────────────────────────────────────────
const SuperAdminLogin: React.FC<{ onLogin: (token: string) => void }> = ({ onLogin }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setError(''); setLoading(true);
    try {
      const res = await fetch(`${API}?action=login`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (data.success) { localStorage.setItem('satoken', data.token); onLogin(data.token); }
      else setError(data.error || 'Login failed');
    } catch { setError('Network error'); } finally { setLoading(false); }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4" style={{ background: 'linear-gradient(135deg, #0f0c29, #302b63)' }}>
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <div className="w-16 h-16 rounded-3xl mx-auto flex items-center justify-center text-3xl mb-4" style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)' }}>👑</div>
          <h1 className="text-2xl font-black text-white">Super Admin</h1>
          <p className="text-white/50 text-sm mt-1">ShophyFast Platform Control</p>
        </div>
        <form onSubmit={handleSubmit} className="bg-white/10 backdrop-blur-sm border border-white/20 rounded-3xl p-8 space-y-4">
          {error && <div className="bg-red-500/20 border border-red-400/30 rounded-2xl p-3 text-red-200 text-sm">{error}</div>}
          <div>
            <label className="text-white/60 text-xs font-bold block mb-1.5">Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-2xl text-white placeholder-white/30 text-sm outline-none focus:border-purple-400"
              placeholder="admin@email.com" required />
          </div>
          <div>
            <label className="text-white/60 text-xs font-bold block mb-1.5">Password</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-2xl text-white placeholder-white/30 text-sm outline-none focus:border-purple-400"
              placeholder="••••••••" required />
          </div>
          <button type="submit" disabled={loading}
            className="w-full py-3.5 rounded-2xl font-black text-white transition-all disabled:opacity-50"
            style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)' }}>
            {loading ? '⏳ Login হচ্ছে...' : '👑 Login'}
          </button>
        </form>
      </div>
    </div>
  );
};

// ── Main Dashboard ────────────────────────────────────────────────────────────
const SuperAdminDashboard: React.FC = () => {
  const [token, setToken] = useState(() => localStorage.getItem('satoken') || '');
  const [tab, setTab] = useState<'overview' | 'tenants' | 'subscriptions' | 'plans' | 'team' | 'settings'>('overview');
  const [stats, setStats] = useState<Stats | null>(null);
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [plans, setPlans] = useState<Plan[]>([]);
  const [subFilter, setSubFilter] = useState<'pending' | 'all'>('pending');
  const [tenantSearch, setTenantSearch] = useState('');
  const [notification, setNotification] = useState('');
  const [rejectModal, setRejectModal] = useState<{ id: number } | null>(null);
  const [rejectNotes, setRejectNotes] = useState('');
  const [planModal, setPlanModal] = useState<Partial<Plan> | null>(null);
  const [trialDays, setTrialDays] = useState<number>(14);
  const [globalSettingsSaving, setGlobalSettingsSaving] = useState(false);
  // Branding settings
  const [brandLogoUrl, setBrandLogoUrl] = useState('');
  const [brandFaviconUrl, setBrandFaviconUrl] = useState('');
  const [brandSiteName, setBrandSiteName] = useState('ShophyFast');
  const [brandUploading, setBrandUploading] = useState<string | null>(null);
  // Payment method settings
  const [pmBkash, setPmBkash] = useState('');
  const [pmNagad, setPmNagad] = useState('');
  const [pmRocket, setPmRocket] = useState('');
  const [pmBank, setPmBank] = useState('');
  const [pmEnabled, setPmEnabled] = useState({ bkash: true, nagad: true, rocket: false, bank: false });
  // Name Servers
  const [ns1, setNs1] = useState('ns1.shophyfast.com');
  const [ns2, setNs2] = useState('ns2.shophyfast.com');
  const [ns3, setNs3] = useState('');
  const [ns4, setNs4] = useState('');
  const [ns5, setNs5] = useState('');
  const [ns6, setNs6] = useState('');
  // Admin Dashboard Banners
  const [adminBanners, setAdminBanners] = useState<{ id: string, image_url: string, link: string }[]>([]);
  const [bannerUploading, setBannerUploading] = useState(false);

  // Team member state
  interface TeamMember { id: number; name: string; role: string; photo_url: string; sort_order: number; is_active: number; }
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>([]);
  const [teamModal, setTeamModal] = useState<Partial<TeamMember> | null>(null);
  const [teamUploading, setTeamUploading] = useState(false);
  const [teamSaving, setTeamSaving] = useState(false);

  const headers = { 'Content-Type': 'application/json', 'X-Super-Admin-Token': token };

  const toast = (msg: string) => { setNotification(msg); setTimeout(() => setNotification(''), 3000); };

  const apiFetch = useCallback(async (action: string, method = 'GET', body?: any) => {
    const url = `${API}?action=${action}`;
    const res = await fetch(url, {
      method, headers,
      body: body ? JSON.stringify(body) : undefined,
    });
    if (res.status === 401) { localStorage.removeItem('satoken'); setToken(''); return null; }
    return res.json();
  }, [token]);

  useEffect(() => { if (!token) return; fetchAll(); }, [token, tab, subFilter, tenantSearch]);

  // Load branding (favicon + logo + site name) on initial mount so it shows immediately
  useEffect(() => {
    if (!token) return;
    apiFetch('global_settings').then(d => {
      if (d?.success && d.settings) {
        if (d.settings.logo_url) setBrandLogoUrl(d.settings.logo_url);
        if (d.settings.favicon_url) setBrandFaviconUrl(d.settings.favicon_url);
        if (d.settings.site_name) setBrandSiteName(d.settings.site_name || 'ShophyFast');
        if (d.settings.default_trial_days) setTrialDays(parseInt(d.settings.default_trial_days) || 14);
        if (d.settings.pm_bkash) setPmBkash(d.settings.pm_bkash);
        if (d.settings.pm_nagad) setPmNagad(d.settings.pm_nagad);
        if (d.settings.pm_rocket) setPmRocket(d.settings.pm_rocket);
        if (d.settings.pm_bank) setPmBank(d.settings.pm_bank);
        if (d.settings.pm_enabled) { try { setPmEnabled(JSON.parse(d.settings.pm_enabled)); } catch { } }
        if (d.settings.admin_dashboard_banners) { try { setAdminBanners(JSON.parse(d.settings.admin_dashboard_banners)); } catch { } }
        if (d.settings.name_server_1) setNs1(d.settings.name_server_1);
        if (d.settings.name_server_2) setNs2(d.settings.name_server_2);
        if (d.settings.name_server_3) setNs3(d.settings.name_server_3);
        if (d.settings.name_server_4) setNs4(d.settings.name_server_4);
        if (d.settings.name_server_5) setNs5(d.settings.name_server_5);
        if (d.settings.name_server_6) setNs6(d.settings.name_server_6);
      }
    }).catch(() => { });
  }, [token]);

  // Favicon and Title update for Super Admin
  useEffect(() => {
    if (brandFaviconUrl) {
      let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
      if (!link) {
        link = document.createElement('link');
        link.rel = 'icon';
        document.getElementsByTagName('head')[0].appendChild(link);
      }
      link.href = brandFaviconUrl;
    }
    const title = brandSiteName ? `${brandSiteName} | Super Admin` : 'Super Admin';
    if (document.title !== title) {
      document.title = title;
    }
  }, [brandFaviconUrl, brandSiteName]);

  const fetchAll = async () => {
    if (tab === 'overview') {
      const d = await apiFetch('dashboard_stats');
      if (d?.success) setStats(d);
    } else if (tab === 'tenants') {
      const d = await apiFetch(`tenants&search=${encodeURIComponent(tenantSearch)}`);
      if (d?.success) setTenants(Array.isArray(d.data) ? d.data : []);
    } else if (tab === 'subscriptions') {
      const d = await apiFetch(`subscriptions&status=${subFilter}`);
      if (d?.success) setSubscriptions(Array.isArray(d.data) ? d.data : []);
    } else if (tab === 'plans') {
      const d = await apiFetch('plans');
      if (d?.success) {
        const normalized = (Array.isArray(d.data) ? d.data : []).map((p: any) => ({
          ...p,
          features: normalizeFeatures(p.features),
          display_features: Array.isArray(p.display_features) ? p.display_features : [],
        }));
        setPlans(normalized);
      }
    } else if (tab === 'team') {
      const d = await apiFetch('team_members');
      if (d?.success) setTeamMembers(Array.isArray(d.data) ? d.data : []);
    } else if (tab === 'settings') {
      const d = await apiFetch('global_settings');
      if (d?.success && d.settings) {
        if (d.settings.default_trial_days) setTrialDays(parseInt(d.settings.default_trial_days) || 14);
        if (d.settings.logo_url) setBrandLogoUrl(d.settings.logo_url);
        if (d.settings.favicon_url) setBrandFaviconUrl(d.settings.favicon_url);
        if (d.settings.site_name) setBrandSiteName(d.settings.site_name || 'ShophyFast');
        if (d.settings.pm_bkash) setPmBkash(d.settings.pm_bkash);
        if (d.settings.pm_nagad) setPmNagad(d.settings.pm_nagad);
        if (d.settings.pm_rocket) setPmRocket(d.settings.pm_rocket);
        if (d.settings.pm_bank) setPmBank(d.settings.pm_bank);
        if (d.settings.pm_enabled) { try { setPmEnabled(JSON.parse(d.settings.pm_enabled)); } catch { } }
        if (d.settings.admin_dashboard_banners) { try { setAdminBanners(JSON.parse(d.settings.admin_dashboard_banners)); } catch { } }
        if (d.settings.name_server_1) setNs1(d.settings.name_server_1);
        if (d.settings.name_server_2) setNs2(d.settings.name_server_2);
        if (d.settings.name_server_3) setNs3(d.settings.name_server_3);
        if (d.settings.name_server_4) setNs4(d.settings.name_server_4);
        if (d.settings.name_server_5) setNs5(d.settings.name_server_5);
        if (d.settings.name_server_6) setNs6(d.settings.name_server_6);
      }
    }
  };

  const saveGlobalSettings = async () => {
    setGlobalSettingsSaving(true);
    try {
      const d = await apiFetch('update_global_settings', 'POST', {
        default_trial_days: String(trialDays),
        logo_url: brandLogoUrl,
        favicon_url: brandFaviconUrl,
        site_name: brandSiteName,
        pm_bkash: pmBkash,
        pm_nagad: pmNagad,
        pm_rocket: pmRocket,
        pm_bank: pmBank,
        pm_enabled: JSON.stringify(pmEnabled),
        admin_dashboard_banners: JSON.stringify(adminBanners),
        name_server_1: ns1,
        name_server_2: ns2,
        name_server_3: ns3,
        name_server_4: ns4,
        name_server_5: ns5,
        name_server_6: ns6,
      });

      if (d?.success) {
        toast('✅ Settings saved!');

        // ✅ CRITICAL: Reload settings after save to update UI
        const settingsRes = await apiFetch('global_settings');
        if (settingsRes?.success && settingsRes.settings) {
          // Update payment method fields
          if (settingsRes.settings.pm_bkash) setPmBkash(settingsRes.settings.pm_bkash);
          if (settingsRes.settings.pm_nagad) setPmNagad(settingsRes.settings.pm_nagad);
          if (settingsRes.settings.pm_rocket) setPmRocket(settingsRes.settings.pm_rocket);
          if (settingsRes.settings.pm_bank) setPmBank(settingsRes.settings.pm_bank);
          if (settingsRes.settings.pm_enabled) {
            try {
              const enabled = JSON.parse(settingsRes.settings.pm_enabled);
              setPmEnabled(enabled);
            } catch { }
          }
          if (settingsRes.settings.admin_dashboard_banners) {
            try { setAdminBanners(JSON.parse(settingsRes.settings.admin_dashboard_banners)); } catch { }
          }
          // Update branding fields too
          if (settingsRes.settings.logo_url) setBrandLogoUrl(settingsRes.settings.logo_url);
          if (settingsRes.settings.favicon_url) setBrandFaviconUrl(settingsRes.settings.favicon_url);
          if (settingsRes.settings.site_name) setBrandSiteName(settingsRes.settings.site_name);
          if (settingsRes.settings.default_trial_days) setTrialDays(parseInt(settingsRes.settings.default_trial_days) || 14);
        }
      } else {
        toast('❌ ' + (d?.error || 'Error'));
      }
    } catch {
      toast('❌ Network error');
    }
    finally {
      setGlobalSettingsSaving(false);
    }
  };

  const uploadBrandingAsset = async (file: File, type: 'logo' | 'favicon') => {
    setBrandUploading(type);
    try {
      const fd = new FormData();
      fd.append('image', file);
      fd.append('type', 'general');

      const res = await fetch('/api/upload', { method: 'POST', headers: { 'X-Super-Admin-Token': token }, body: fd });
      const d = await res.json();
      if (d.success && d.url) {
        if (type === 'logo') setBrandLogoUrl(d.url);
        else setBrandFaviconUrl(d.url);
        toast('✅ ' + (type === 'logo' ? 'Logo' : 'Favicon') + ' uploaded!');
      } else toast('❌ Upload failed: ' + (d.error || 'error'));
    } catch { toast('❌ Upload network error'); }
    finally { setBrandUploading(null); }
  };

  const uploadAdminBanner = async (file: File) => {
    setBannerUploading(true);
    try {
      const fd = new FormData();
      fd.append('image', file);
      fd.append('type', 'general');

      const res = await fetch('/api/upload', { method: 'POST', headers: { 'X-Super-Admin-Token': token }, body: fd });
      const d = await res.json();
      if (d.success && d.url) {
        setAdminBanners(prev => [...prev, { id: Date.now().toString(), image_url: d.url, link: '' }]);
        toast('✅ Banner uploaded! Click Save Settings to apply.');
      } else toast('❌ Upload failed: ' + (d.error || 'error'));
    } catch { toast('❌ Upload network error'); }
    finally { setBannerUploading(false); }
  };

  // Normalize features: handle both legacy string[] and new Record<string, boolean>
  const normalizeFeatures = (raw: any): Record<string, boolean> => {
    if (!raw) return { ...DEFAULT_FREE_FEATURES };
    if (typeof raw === 'string') {
      try { raw = JSON.parse(raw); } catch { return { ...DEFAULT_FREE_FEATURES }; }
    }
    if (Array.isArray(raw)) {
      const result: Record<string, boolean> = { ...DEFAULT_FREE_FEATURES };
      PLAN_FEATURE_KEYS.forEach(({ key }) => { result[key] = false; });
      return result;
    }
    if (typeof raw === 'object') {
      const result: Record<string, boolean> = {};
      PLAN_FEATURE_KEYS.forEach(({ key }) => { result[key] = !!raw[key]; });
      return result;
    }
    return { ...DEFAULT_FREE_FEATURES };
  };

  const approveSub = async (id: number) => {
    const d = await apiFetch('approve_subscription', 'POST', { subscription_id: id, notes: '' });
    if (d?.success) { toast('✅ Subscription approved!'); fetchAll(); }
    else toast('❌ ' + (d?.error || 'Error'));
  };

  const rejectSub = async () => {
    if (!rejectModal) return;
    const d = await apiFetch('reject_subscription', 'POST', { subscription_id: rejectModal.id, notes: rejectNotes });
    if (d?.success) { toast('Subscription rejected'); setRejectModal(null); fetchAll(); }
    else toast('❌ Error');
  };

  const toggleTenant = async (id: number, status: string) => {
    const action = status === 'suspended' ? 'activate_tenant' : 'suspend_tenant';
    const d = await apiFetch(action, 'POST', { tenant_id: id });
    if (d?.success) { toast('✅ Done'); fetchAll(); }
  };

  const savePlan = async () => {
    if (!planModal) return;
    const action = planModal.id ? 'update_plan' : 'create_plan';
    const payload = { ...planModal, features: planModal.features || DEFAULT_FREE_FEATURES, display_features: planModal.display_features || [] };
    const d = await apiFetch(action, 'POST', payload);
    if (d?.success) { toast('✅ Plan saved'); setPlanModal(null); fetchAll(); }
    else toast('❌ ' + (d?.error || 'Error'));
  };

  const toggleFeature = (key: string, val: boolean) => {
    if (!planModal) return;
    setPlanModal({
      ...planModal,
      features: { ...(planModal.features || DEFAULT_FREE_FEATURES), [key]: val },
    });
  };

  const openNewPlan = () => {
    const allFeatures: Record<string, boolean> = {};
    PLAN_FEATURE_KEYS.forEach(({ key }) => { allFeatures[key] = false; });
    setPlanModal({ name: '', price: 0, regular_price: 0, duration_days: 30, features: allFeatures, display_features: [], is_active: 1 });
  };

  const saveTeamMember = async () => {
    if (!teamModal) return;
    setTeamSaving(true);
    try {
      const action = teamModal.id ? 'update_team_member' : 'create_team_member';
      const d = await apiFetch(action, 'POST', {
        id: teamModal.id,
        name: teamModal.name,
        role: teamModal.role,
        photo_url: teamModal.photo_url || '',
        sort_order: teamModal.sort_order || 0,
        is_active: teamModal.is_active !== undefined ? teamModal.is_active : 1,
      });
      if (d?.success) { toast('✅ Team member saved!'); setTeamModal(null); fetchAll(); }
      else toast('❌ ' + (d?.error || 'Error'));
    } catch { toast('❌ Network error'); }
    finally { setTeamSaving(false); }
  };

  const deleteTeamMember = async (id: number) => {
    if (!confirm('এই team member মুছে দিবেন?')) return;
    const d = await apiFetch('delete_team_member', 'POST', { id });
    if (d?.success) { toast('✅ Deleted'); fetchAll(); }
    else toast('❌ Error');
  };

  const uploadTeamPhoto = async (file: File) => {
    setTeamUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('type', 'team');
      const res = await fetch('/api/upload', { method: 'POST', headers: { 'X-Super-Admin-Token': token }, body: fd });
      const d = await res.json();
      if (d.success && d.url) {
        setTeamModal(m => m ? { ...m, photo_url: d.url } : m);
        toast('✅ Photo uploaded!');
      } else toast('❌ Upload failed: ' + (d.error || ''));
    } catch { toast('❌ Upload network error'); }
    finally { setTeamUploading(false); }
  };

  const countActiveFeatures = (f: Record<string, boolean>) =>
    Object.values(f).filter(Boolean).length;

  if (!token) return <SuperAdminLogin onLogin={t => { setToken(t); }} />;

  const STATUS_BADGE: Record<string, string> = {
    trial: 'bg-blue-100 text-blue-700',
    pending: 'bg-amber-100 text-amber-700',
    active: 'bg-green-100 text-green-700',
    expired: 'bg-red-100 text-red-700',
    suspended: 'bg-slate-100 text-slate-600',
  };

  return (
    <div className="min-h-screen bg-slate-50 font-sans" style={{ fontFamily: "'Inter', sans-serif" }}>
      {/* Toast */}
      {notification && (
        <div className="fixed top-5 right-5 z-[300] bg-slate-900 text-white px-5 py-3 rounded-2xl shadow-2xl text-sm font-bold">{notification}</div>
      )}

      {/* Sidebar + Content Layout */}
      <div className="flex min-h-screen">
        {/* Sidebar */}
        <aside className="w-60 shrink-0 sticky top-0 h-screen overflow-y-auto flex flex-col" style={{ background: 'linear-gradient(180deg, #0f0c29, #302b63)' }}>
          <div className="p-6 border-b border-white/10">
            {brandLogoUrl ? (
              <div className="flex justify-center mb-2">
                <img src={brandLogoUrl} className="max-h-12 max-w-[150px] object-contain" alt="Logo" />
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 rounded-xl bg-purple-500 flex items-center justify-center text-white font-black text-sm">👑</div>
                <div>
                  <p className="text-white font-black text-sm">Super Admin</p>
                  <p className="text-white/40 text-[10px]">{brandSiteName}</p>
                </div>
              </div>
            )}
          </div>

          <nav className="flex-1 p-4 space-y-1">
            {([
              ['overview', '📊', 'Overview'],
              ['tenants', '🏪', 'Tenants'],
              ['subscriptions', '💳', 'Subscriptions'],
              ['plans', '📦', 'Plans'],
              ['team', '👥', 'Team Members'],
              ['settings', '⚙️', 'Platform Settings'],
            ] as const).map(([key, icon, label]) => (
              <button key={key} onClick={() => setTab(key as any)}
                className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-sm font-bold transition-all ${tab === key ? 'bg-white/20 text-white' : 'text-white/50 hover:bg-white/10 hover:text-white'}`}>
                <span className="text-base">{icon}</span> {label}
                {key === 'subscriptions' && stats?.pending_subs ? (
                  <span className="ml-auto bg-red-500 text-white text-[10px] font-black rounded-full px-1.5 py-0.5">{stats.pending_subs}</span>
                ) : null}
              </button>
            ))}
          </nav>

          <div className="p-4 border-t border-white/10">
            <button onClick={() => { localStorage.removeItem('satoken'); setToken(''); }}
              className="w-full py-2.5 text-white/40 hover:text-red-300 text-sm font-bold transition rounded-2xl hover:bg-white/5">
              🚪 Logout
            </button>
          </div>
        </aside>

        {/* Main Content */}
        <main className="flex-1 overflow-y-auto p-8">

          {/* ── Overview ── */}
          {tab === 'overview' && (
            <div className="space-y-8">
              <h1 className="text-3xl font-black text-slate-800">📊 Overview</h1>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-5">
                {[
                  { label: 'Total Stores', value: stats?.total_tenants ?? '—', icon: '🏪', color: '#7c3aed' },
                  { label: 'Active', value: stats?.active_tenants ?? '—', icon: '✅', color: '#059669' },
                  { label: 'Pending Subs', value: stats?.pending_subs ?? '—', icon: '⏳', color: '#d97706' },
                  { label: 'New Today', value: stats?.new_today ?? '—', icon: '🆕', color: '#2563eb' },
                  { label: 'Total Revenue', value: `৳${(stats?.total_revenue ?? 0).toLocaleString()}`, icon: '💰', color: '#059669' },
                  { label: 'This Month', value: `৳${(stats?.this_month_revenue ?? 0).toLocaleString()}`, icon: '📅', color: '#db2777' },
                  { label: 'Trial Users', value: stats?.trial_tenants ?? '—', icon: '🎯', color: '#667eea' },
                ].map((s, i) => (
                  <div key={i} className="bg-white rounded-3xl p-6 border shadow-sm">
                    <div className="text-2xl mb-2">{s.icon}</div>
                    <p className="text-2xl font-black" style={{ color: s.color }}>{s.value}</p>
                    <p className="text-xs text-slate-400 mt-0.5 font-medium">{s.label}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* ── Tenants ── */}
          {tab === 'tenants' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h1 className="text-3xl font-black text-slate-800">🏪 Tenants</h1>
                <input value={tenantSearch} onChange={e => setTenantSearch(e.target.value)}
                  placeholder="Search name, phone, business..." className="px-4 py-2.5 rounded-2xl border text-sm w-64 bg-white focus:text-slate-900 outline-none focus:border-purple-400" />
              </div>
              <div className="bg-white rounded-3xl border shadow-sm overflow-hidden">
                <table className="w-full">
                  <thead className="bg-slate-50 text-[10px] font-black uppercase text-slate-400">
                    <tr>{['#', 'Business', 'Owner', 'Phone', 'Status', 'Plan', 'Joined', 'Action'].map(h => <th key={h} className="px-4 py-3 text-left">{h}</th>)}</tr>
                  </thead>
                  <tbody>
                    {tenants.map((t, i) => (
                      <tr key={t.id} className="border-t hover:bg-slate-50">
                        <td className="px-4 py-3 text-slate-400 text-sm">{i + 1}</td>
                        <td className="px-4 py-3">
                          <p className="font-black text-sm">{t.business_name}</p>
                          <a href={`https://${t.business_slug}.shophyfast.com`} target="_blank" rel="noreferrer" className="text-purple-500 text-[10px] hover:underline">{t.business_slug}.shophyfast.com ↗</a>
                        </td>
                        <td className="px-4 py-3 text-sm">{t.name}</td>
                        <td className="px-4 py-3 font-mono text-sm text-red-600">{t.phone}</td>
                        <td className="px-4 py-3">
                          <span className={`text-[10px] font-black px-2 py-1 rounded-full ${STATUS_BADGE[t.subscription_status] || 'bg-slate-100 text-slate-600'}`}>
                            {t.subscription_status}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-xs text-slate-500">{t.plan_name || '-'}</td>
                        <td className="px-4 py-3 text-xs text-slate-400">{new Date(t.created_at).toLocaleDateString('bn-BD')}</td>
                        <td className="px-4 py-3">
                          <button onClick={() => toggleTenant(t.id, t.subscription_status)}
                            className={`text-[10px] font-black px-3 py-1.5 rounded-xl transition ${t.subscription_status === 'suspended' ? 'bg-green-50 text-green-600 hover:bg-green-100' : 'bg-red-50 text-red-600 hover:bg-red-100'}`}>
                            {t.subscription_status === 'suspended' ? '✅ Activate' : '🚫 Suspend'}
                          </button>
                        </td>
                      </tr>
                    ))}
                    {tenants.length === 0 && <tr><td colSpan={8} className="px-4 py-12 text-center text-slate-400">কোনো tenant নেই</td></tr>}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* ── Subscriptions ── */}
          {tab === 'subscriptions' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h1 className="text-3xl font-black text-slate-800">💳 Subscriptions</h1>
                <div className="flex gap-2">
                  {(['pending', 'all'] as const).map(f => (
                    <button key={f} onClick={() => setSubFilter(f)}
                      className={`px-4 py-2 rounded-xl text-xs font-black transition ${subFilter === f ? 'bg-purple-600 text-white' : 'bg-white border text-slate-600'}`}>
                      {f === 'pending' ? '⏳ Pending' : '📋 All'}
                    </button>
                  ))}
                </div>
              </div>
              <div className="space-y-4">
                {subscriptions.map(sub => (
                  <div key={sub.id} className="bg-white rounded-3xl border shadow-sm p-6">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <p className="font-black text-lg">{sub.business_name}</p>
                          <span className={`text-[10px] font-black px-2 py-1 rounded-full ${sub.status === 'pending' ? 'bg-amber-100 text-amber-700' : sub.status === 'approved' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                            {sub.status}
                          </span>
                        </div>
                        <p className="text-sm text-slate-500">{sub.tenant_name} • {sub.tenant_phone}</p>
                        <div className="mt-3 grid grid-cols-2 md:grid-cols-4 gap-3">
                          <div className="bg-slate-50 rounded-2xl p-3">
                            <p className="text-[10px] text-slate-400 font-bold">Plan</p>
                            <p className="font-black text-sm">{sub.plan_name}</p>
                          </div>
                          <div className="bg-slate-50 rounded-2xl p-3">
                            <p className="text-[10px] text-slate-400 font-bold">Amount</p>
                            <p className="font-black text-sm text-green-600">৳{sub.amount}</p>
                          </div>
                          <div className="bg-slate-50 rounded-2xl p-3">
                            <p className="text-[10px] text-slate-400 font-bold">Method</p>
                            <p className="font-black text-sm capitalize">{sub.payment_method}</p>
                          </div>
                          <div className="bg-slate-50 rounded-2xl p-3">
                            <p className="text-[10px] text-slate-400 font-bold">TrxID</p>
                            <p className="font-mono text-xs font-bold truncate">{sub.transaction_id}</p>
                          </div>
                        </div>
                        {sub.payment_screenshot && (
                          <a href={sub.payment_screenshot} target="_blank" rel="noreferrer" className="inline-block mt-3 text-xs text-blue-500 hover:underline font-bold">📸 Payment Screenshot দেখুন ↗</a>
                        )}
                        {sub.admin_notes && <p className="mt-2 text-xs text-slate-500 italic">Note: {sub.admin_notes}</p>}
                      </div>
                      {sub.status === 'pending' && (
                        <div className="flex flex-col gap-2 shrink-0">
                          <button onClick={() => approveSub(sub.id)}
                            className="px-5 py-2.5 bg-green-600 hover:bg-green-700 text-white font-black text-sm rounded-2xl transition">
                            ✅ Approve
                          </button>
                          <button onClick={() => { setRejectModal({ id: sub.id }); setRejectNotes(''); }}
                            className="px-5 py-2.5 bg-red-50 hover:bg-red-100 text-red-600 font-black text-sm rounded-2xl transition">
                            ❌ Reject
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
                {subscriptions.length === 0 && <div className="bg-white rounded-3xl border p-12 text-center text-slate-400">কোনো subscription request নেই</div>}
              </div>
            </div>
          )}

          {/* ── Plans ── */}
          {tab === 'plans' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <h1 className="text-3xl font-black text-slate-800">📦 Subscription Plans</h1>
                  <p className="text-slate-400 text-sm mt-1">প্রতিটি plan-এ কোন কোন feature চালু থাকবে তা নির্ধারণ করুন · ⭐ চিহ্নিত plan টি landing page-এ "সবচেয়ে জনপ্রিয়" হিসেবে দেখাবে</p>
                </div>
                <button onClick={openNewPlan}
                  className="px-5 py-2.5 bg-purple-600 text-white font-black text-sm rounded-2xl hover:bg-purple-700 transition">
                  + New Plan
                </button>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {plans.map(plan => {
                  const features = typeof plan.features === 'object' && !Array.isArray(plan.features)
                    ? plan.features
                    : DEFAULT_FREE_FEATURES;
                  const activeCount = countActiveFeatures(features);
                  return (
                    <div key={plan.id} style={{
                      borderRadius: 24,
                      padding: 24,
                      position: 'relative',
                      transition: 'all .3s',
                      background: plan.is_popular
                        ? 'linear-gradient(145deg,#fdf4ff,#f5f3ff)'
                        : '#fff',
                      border: plan.is_popular
                        ? '2px solid #a78bfa'
                        : '1px solid #e2e8f0',
                      boxShadow: plan.is_popular
                        ? '0 0 0 4px rgba(167,139,250,.15), 0 8px 32px rgba(139,92,246,.15)'
                        : '0 2px 12px rgba(0,0,0,.05)',
                    }}>
                      {/* Popular badge */}
                      {plan.is_popular && (
                        <div style={{
                          position: 'absolute', top: -14, left: '50%', transform: 'translateX(-50%)',
                          background: 'linear-gradient(135deg,#FBBF24,#F59E0B)',
                          color: '#78350F', fontSize: 11, fontWeight: 900,
                          padding: '6px 18px', borderRadius: 99,
                          boxShadow: '0 4px 16px rgba(251,191,36,.45)',
                          whiteSpace: 'nowrap', display: 'flex', gap: 4, alignItems: 'center',
                        }}>
                          ⭐ সবচেয়ে জনপ্রিয় — Landing Page-এ দেখাচ্ছে
                        </div>
                      )}

                      <div className="flex justify-between items-start mb-3" style={{ marginTop: plan.is_popular ? 12 : 0 }}>
                        <div>
                          <h3 className="font-black text-xl">{plan.name}</h3>
                          <p className="text-slate-400 text-sm">{plan.duration_days} দিন</p>
                        </div>
                        <span className={`text-[10px] font-black px-2 py-1 rounded-full ${plan.is_active ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-500'}`}>
                          {plan.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </div>
                      <div className="flex flex-col mb-4">
                        {plan.regular_price && plan.regular_price > plan.price && (
                          <p className="text-sm font-black text-slate-400 line-through decoration-red-500/50 mb-0.5">
                            ৳{plan.regular_price?.toLocaleString()}
                          </p>
                        )}
                        <div className="flex items-center gap-2">
                          <p style={{ fontSize: 28, fontWeight: 900, color: plan.is_popular ? '#7C3AED' : '#6D28D9' }}>৳{plan.price?.toLocaleString()}</p>
                          {plan.regular_price && plan.regular_price > plan.price && (
                             <span className="bg-green-100 text-green-700 text-[10px] font-black px-2 py-0.5 rounded-full uppercase tracking-wider">Discount</span>
                          )}
                        </div>
                      </div>
                      <p className="text-xs text-slate-400 mb-3 font-medium">{activeCount}/{PLAN_FEATURE_KEYS.length} features চালু</p>
                      <div className="grid grid-cols-2 gap-1.5 mb-5">
                        {PLAN_FEATURE_KEYS.map(({ key, label, icon }) => (
                          <div key={key} className={`flex items-center gap-1.5 px-2 py-1 rounded-lg text-[10px] font-bold ${features[key] ? 'bg-green-50 text-green-700' : 'bg-slate-50 text-slate-300'}`}>
                            <span>{features[key] ? '✓' : '×'}</span>
                            <span>{icon} {label}</span>
                          </div>
                        ))}
                      </div>
                      <div className="flex gap-2">
                        <button onClick={() => setPlanModal({ ...plan, features: normalizeFeatures(plan.features) })}
                          className="flex-1 py-2.5 border border-purple-200 text-purple-600 rounded-2xl font-black text-xs hover:bg-purple-50 transition">
                          ✏️ Edit Plan
                        </button>
                        <button
                          onClick={async () => {
                            const newVal = !plan.is_popular;
                            await apiFetch('toggle_plan_popular', 'POST', { id: plan.id, is_popular: newVal });
                            setPlans(prev => prev.map(p => ({ ...p, is_popular: p.id === plan.id ? newVal : false })));
                            toast(newVal ? '⭐ Popular plan set! Landing page-এ দেখাবে' : 'Popular সরানো হয়েছে');
                          }}
                          style={{
                            padding: '10px 14px',
                            borderRadius: 16,
                            fontWeight: 900,
                            fontSize: 11,
                            cursor: 'pointer',
                            border: plan.is_popular ? 'none' : '1px dashed #d1d5db',
                            background: plan.is_popular
                              ? 'linear-gradient(135deg,#FBBF24,#F59E0B)'
                              : 'transparent',
                            color: plan.is_popular ? '#fff' : '#94a3b8',
                            boxShadow: plan.is_popular ? '0 4px 14px rgba(251,191,36,.4)' : 'none',
                            transition: 'all .25s',
                            whiteSpace: 'nowrap',
                          }}
                          title={plan.is_popular ? 'Popular সরান' : 'সবচেয়ে জনপ্রিয় হিসেবে সেট করুন'}
                          onMouseEnter={e => { if (!plan.is_popular) { e.currentTarget.style.borderColor = '#FBBF24'; e.currentTarget.style.color = '#D97706'; } }}
                          onMouseLeave={e => { if (!plan.is_popular) { e.currentTarget.style.borderColor = '#d1d5db'; e.currentTarget.style.color = '#94a3b8'; } }}
                        >
                          {plan.is_popular ? '⭐ জনপ্রিয়' : '☆ জনপ্রিয় করুন'}
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* ── Team Members ── */}
          {tab === 'team' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <h1 className="text-3xl font-black text-slate-800">👥 Team Members</h1>
                  <p className="text-slate-400 text-sm mt-1">ল্যান্ডিং পেজে দেখানো টিম মেম্বার পরিচালনা করুন</p>
                </div>
                <button
                  onClick={() => setTeamModal({ name: '', role: '', photo_url: '', sort_order: teamMembers.length, is_active: 1 })}
                  className="px-5 py-2.5 bg-purple-600 text-white font-black text-sm rounded-2xl hover:bg-purple-700 transition"
                >+ নতুন সদস্য</button>
              </div>

              <div className="grid grid-cols-2 md:grid-cols-4 gap-5">
                {teamMembers.map((m) => (
                  <div key={m.id} className="bg-white rounded-3xl border shadow-sm p-5 text-center relative">
                    {!m.is_active && <div className="absolute top-3 right-3 text-[9px] font-black bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full">Hidden</div>}
                    <div className="w-20 h-20 rounded-2xl overflow-hidden mx-auto mb-3 bg-gradient-to-br from-purple-100 to-blue-100 flex items-center justify-center">
                      {m.photo_url
                        ? <img src={m.photo_url} alt={m.name} className="w-full h-full object-cover" />
                        : <span className="text-3xl font-black text-purple-400">{m.name.charAt(0)}</span>}
                    </div>
                    <p className="font-black text-sm text-slate-800 mb-0.5">{m.name}</p>
                    <p className="text-[11px] text-slate-400 font-medium mb-4">{m.role}</p>
                    <div className="flex gap-2">
                      <button onClick={() => setTeamModal({ ...m })}
                        className="flex-1 py-2 text-xs font-black text-purple-600 bg-purple-50 rounded-xl hover:bg-purple-100 transition">
                        ✏️ Edit
                      </button>
                      <button onClick={() => deleteTeamMember(m.id)}
                        className="flex-1 py-2 text-xs font-black text-red-500 bg-red-50 rounded-xl hover:bg-red-100 transition">
                        🗑️ Delete
                      </button>
                    </div>
                  </div>
                ))}
                {teamMembers.length === 0 && (
                  <div className="col-span-4 bg-white rounded-3xl border p-12 text-center text-slate-400">
                    কোনো team member নেই — নতুন সদস্য যোগ করুন
                  </div>
                )}
              </div>
            </div>
          )}

          {/* ── Platform Settings ── */}
          {tab === 'settings' && (
            <div className="space-y-8 max-w-full">
              <div>
                <h1 className="text-3xl font-black text-slate-800">⚙️ Platform Settings</h1>
                <p className="text-slate-400 text-sm mt-1">পুরো platform-এর global configuration এখানে পরিচালনা করুন</p>
              </div>

              {/* Free Trial Duration */}
              <div className="bg-white rounded-3xl border shadow-sm p-8">
                <div className="flex items-center gap-3 mb-2">
                  <span className="text-3xl">🎯</span>
                  <div>
                    <h2 className="font-black text-xl text-slate-800">Free Trial Period</h2>
                    <p className="text-slate-400 text-sm">নতুন store register করলে কতদিন free trial পাবে</p>
                  </div>
                </div>

                <div className="mt-6 p-5 bg-blue-50 rounded-2xl border border-blue-100">
                  <label className="text-xs font-black text-blue-700 block mb-2 uppercase tracking-wider">Default Trial Duration (দিন)</label>
                  <div className="flex items-center gap-4">
                    <input
                      type="number"
                      min={1} max={365}
                      value={trialDays}
                      onChange={e => setTrialDays(Math.max(1, parseInt(e.target.value) || 14))}
                      className="w-32 text-center text-3xl font-black text-blue-800 bg-white border-2 border-blue-200 rounded-2xl px-4 py-3 text-slate-900 outline-none focus:border-blue-500"
                    />
                    <span className="text-blue-700 font-bold">দিন</span>
                  </div>
                  <p className="text-xs text-blue-500 mt-3">
                    ⚠️ এই পরিবর্তন শুধুমাত্র নতুন account-গুলোতে apply হবে। বিদ্যমান trial account-গুলো আগের মতো থাকবে।
                  </p>
                </div>

                <div className="mt-4 grid grid-cols-3 gap-3">
                  {[7, 14, 30].map(d => (
                    <button key={d} onClick={() => setTrialDays(d)}
                      className={`py-3 rounded-2xl font-black text-sm transition-all border-2 ${trialDays === d
                        ? 'border-blue-500 bg-blue-500 text-white'
                        : 'border-slate-200 bg-white text-slate-600 hover:border-blue-300'
                        }`}>
                      {d} দিন
                    </button>
                  ))}
                </div>

                <button
                  onClick={saveGlobalSettings}
                  disabled={globalSettingsSaving}
                  className="mt-6 w-full py-4 rounded-2xl font-black text-white text-sm transition-all disabled:opacity-60"
                  style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)' }}
                >
                  {globalSettingsSaving ? '⏳ Saving...' : '💾 Save Settings'}
                </button>
              </div>

              {/* Branding — Logo */}
              <div className="bg-white rounded-3xl border shadow-sm p-8">
                <div className="flex items-center gap-3 mb-6">
                  <span className="text-3xl">🎨</span>
                  <div>
                    <h2 className="font-black text-xl text-slate-800">Logo & Favicon</h2>
                    <p className="text-slate-400 text-sm">ল্যান্ডিং পেজে দেখানো Logo ও Browser Tab Favicon</p>
                  </div>
                </div>

                {/* Site Name */}
                <div className="mb-5">
                  <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">🏠 Site Name</label>
                  <input
                    value={brandSiteName}
                    onChange={e => setBrandSiteName(e.target.value)}
                    className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold"
                    placeholder="ShophyFast"
                  />
                </div>

                {/* Logo */}
                <div className="mb-5 p-5 bg-purple-50 rounded-2xl border border-purple-100">
                  <label className="text-xs font-black text-purple-700 block mb-3 uppercase tracking-wider">🖼️ Main Logo (Navbar ও Footer)</label>
                  <div className="w-40 h-16 rounded-2xl border-2 border-purple-200 bg-white flex items-center justify-center mb-3 overflow-hidden">
                    {brandLogoUrl
                      ? <img src={brandLogoUrl} alt="Logo" className="max-h-full max-w-full object-contain" />
                      : <span className="text-2xl font-black text-purple-300">S</span>}
                  </div>
                  <input
                    value={brandLogoUrl}
                    onChange={e => setBrandLogoUrl(e.target.value)}
                    className="w-full px-4 py-3 bg-white rounded-xl border text-sm text-slate-900 outline-none focus:border-purple-400 mb-3"
                    placeholder="https://example.com/logo.png"
                  />
                  <label className="flex items-center gap-2 cursor-pointer w-fit">
                    <span className="text-xs font-black text-purple-600 bg-purple-100 px-3 py-2 rounded-xl hover:bg-purple-200 transition">
                      {brandUploading === 'logo' ? '⏳ Uploading...' : '📷 Upload Logo'}
                    </span>
                    <input type="file" accept="image/*" className="hidden" disabled={brandUploading !== null}
                      onChange={e => { const f = e.target.files?.[0]; if (f) uploadBrandingAsset(f, 'logo'); }} />
                  </label>
                </div>

                {/* Favicon */}
                <div className="p-5 bg-amber-50 rounded-2xl border border-amber-100">
                  <label className="text-xs font-black text-amber-700 block mb-3 uppercase tracking-wider">⭐ Favicon (Browser Tab Icon)</label>
                  <div className="w-12 h-12 rounded-xl border-2 border-amber-200 bg-white flex items-center justify-center mb-3 overflow-hidden">
                    {brandFaviconUrl
                      ? <img src={brandFaviconUrl} alt="Favicon" className="max-h-full max-w-full object-contain" />
                      : <span className="text-lg font-black text-amber-400">S</span>}
                  </div>
                  <p className="text-xs text-amber-600 mb-3">সেরা ফলাফলের জন্য 32×32 বা 64×64 px PNG ব্যবহার করুন</p>
                  <input
                    value={brandFaviconUrl}
                    onChange={e => setBrandFaviconUrl(e.target.value)}
                    className="w-full px-4 py-3 bg-white rounded-xl border text-sm text-slate-900 outline-none focus:border-amber-400 mb-3"
                    placeholder="https://example.com/favicon.png"
                  />
                  <label className="flex items-center gap-2 cursor-pointer w-fit">
                    <span className="text-xs font-black text-amber-600 bg-amber-100 px-3 py-2 rounded-xl hover:bg-amber-200 transition">
                      {brandUploading === 'favicon' ? '⏳ Uploading...' : '📷 Upload Favicon'}
                    </span>
                    <input type="file" accept="image/*" className="hidden" disabled={brandUploading !== null}
                      onChange={e => { const f = e.target.files?.[0]; if (f) uploadBrandingAsset(f, 'favicon'); }} />
                  </label>
                </div>

                <button
                  onClick={saveGlobalSettings}
                  disabled={globalSettingsSaving}
                  className="mt-6 w-full py-4 rounded-2xl font-black text-white text-sm transition-all disabled:opacity-60"
                  style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)' }}
                >
                  {globalSettingsSaving ? '⏳ Saving...' : '💾 Branding সেভ করুন'}
                </button>
              </div>

              {/* Name Servers */}
              <div className="bg-white rounded-3xl border shadow-sm p-8">
                <div className="flex items-center gap-3 mb-6">
                  <span className="text-3xl">🌐</span>
                  <div>
                    <h2 className="font-black text-xl text-slate-800">Domain Name Servers</h2>
                    <p className="text-slate-400 text-sm">Tenant-দের Custom Domain-এর জন্য Name Server</p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 1 (Required)</label>
                    <input value={ns1} onChange={e => setNs1(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="ns1.shophyfast.com" />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 2 (Required)</label>
                    <input value={ns2} onChange={e => setNs2(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="ns2.shophyfast.com" />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 3 (Optional)</label>
                    <input value={ns3} onChange={e => setNs3(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="Optional" />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 4 (Optional)</label>
                    <input value={ns4} onChange={e => setNs4(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="Optional" />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 5 (Optional)</label>
                    <input value={ns5} onChange={e => setNs5(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="Optional" />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 block mb-1.5 uppercase tracking-wider">Name Server 6 (Optional)</label>
                    <input value={ns6} onChange={e => setNs6(e.target.value)} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400 font-bold" placeholder="Optional" />
                  </div>
                </div>
                <button
                  onClick={saveGlobalSettings}
                  disabled={globalSettingsSaving}
                  className="mt-6 w-full py-4 rounded-2xl font-black text-white text-sm transition-all disabled:opacity-60"
                  style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)' }}
                >
                  {globalSettingsSaving ? '⏳ Saving...' : '💾 Name Server সেভ করুন'}
                </button>
              </div>

              {/* ── Payment Methods ── */}
              <div className="bg-white rounded-3xl border shadow-sm p-8">
                <div className="flex items-center gap-3 mb-6">
                  <span className="text-3xl">💳</span>
                  <div>
                    <h2 className="font-black text-xl text-slate-800">Payment Methods</h2>
                    <p className="text-slate-400 text-sm">Admin-রা plan কিনতে কোন নাম্বারে payment পাঠাবে তা সেট করুন</p>
                  </div>
                </div>

                {/* Enable/Disable Toggles */}
                <div className="grid grid-cols-2 gap-3 mb-6">
                  {(['bkash', 'nagad', 'rocket', 'bank'] as const).map(m => {
                    const icons: Record<string, string> = { bkash: '📱 bKash', nagad: '📱 Nagad', rocket: '📱 Rocket', bank: '🏦 Bank' };
                    return (
                      <label key={m} className={`flex items-center justify-between px-4 py-3 rounded-2xl border-2 cursor-pointer transition ${pmEnabled[m] ? 'border-purple-400 bg-purple-50' : 'border-slate-200 bg-slate-50'
                        }`}>
                        <span className="font-black text-sm text-slate-700">{icons[m]}</span>
                        <button
                          onClick={() => setPmEnabled(prev => ({ ...prev, [m]: !prev[m] }))}
                          className={`relative w-10 h-5 rounded-full transition-colors ${pmEnabled[m] ? 'bg-purple-500' : 'bg-slate-300'}`}
                        >
                          <div className={`absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all ${pmEnabled[m] ? 'left-5' : 'left-0.5'}`} />
                        </button>
                      </label>
                    );
                  })}
                </div>

                {/* Number/Detail Inputs */}
                <div className="space-y-4">
                  {pmEnabled.bkash && (
                    <div>
                      <label className="text-xs font-black text-pink-600 uppercase tracking-wider block mb-1.5">📱 bKash নাম্বার</label>
                      <input value={pmBkash} onChange={e => setPmBkash(e.target.value)}
                        placeholder="01XXXXXXXXX" className="w-full px-4 py-3 bg-pink-50 border border-pink-200 rounded-2xl text-sm text-slate-900 outline-none focus:border-pink-400 font-mono font-bold" />
                    </div>
                  )}
                  {pmEnabled.nagad && (
                    <div>
                      <label className="text-xs font-black text-orange-600 uppercase tracking-wider block mb-1.5">📱 Nagad নাম্বার</label>
                      <input value={pmNagad} onChange={e => setPmNagad(e.target.value)}
                        placeholder="01XXXXXXXXX" className="w-full px-4 py-3 bg-orange-50 border border-orange-200 rounded-2xl text-sm text-slate-900 outline-none focus:border-orange-400 font-mono font-bold" />
                    </div>
                  )}
                  {pmEnabled.rocket && (
                    <div>
                      <label className="text-xs font-black text-purple-600 uppercase tracking-wider block mb-1.5">📱 Rocket নাম্বার</label>
                      <input value={pmRocket} onChange={e => setPmRocket(e.target.value)}
                        placeholder="01XXXXXXXXX" className="w-full px-4 py-3 bg-purple-50 border border-purple-200 rounded-2xl text-sm text-slate-900 outline-none focus:border-purple-400 font-mono font-bold" />
                    </div>
                  )}
                  {pmEnabled.bank && (
                    <div>
                      <label className="text-xs font-black text-blue-600 uppercase tracking-wider block mb-1.5">🏦 Bank Account Details</label>
                      <textarea value={pmBank} onChange={e => setPmBank(e.target.value)}
                        rows={3} placeholder="Bank Name, Account Number, Account Name, Branch..."
                        className="w-full px-4 py-3 bg-blue-50 border border-blue-200 rounded-2xl text-sm text-slate-900 outline-none focus:border-blue-400 resize-none" />
                    </div>
                  )}
                </div>
                <button onClick={saveGlobalSettings} disabled={globalSettingsSaving}
                  className="mt-6 w-full py-4 rounded-2xl font-black text-white text-sm transition-all disabled:opacity-60"
                  style={{ background: 'linear-gradient(135deg, #10b981, #059669)' }}>
                  {globalSettingsSaving ? '⏳ Saving...' : '💾 Payment Methods সেভ করুন'}
                </button>
              </div>

              {/* ── Admin Dashboard Banners ── */}
              <div className="bg-white rounded-3xl border shadow-sm p-8">
                <div className="flex items-center gap-3 mb-6">
                  <span className="text-3xl">🖼️</span>
                  <div>
                    <h2 className="font-black text-xl text-slate-800">Admin Dashboard Banners</h2>
                    <p className="text-slate-400 text-sm">স্টোর এডমিনদের ড্যাশবোর্ডে স্লাইডার হিসেবে দেখাবে (Size: 1080x280)</p>
                  </div>
                </div>

                <div className="space-y-4 mb-6">
                  {adminBanners.map((banner, index) => (
                    <div key={banner.id} className="relative bg-slate-50 border rounded-2xl p-4 flex gap-4 items-center">
                      <div className="w-48 h-16 bg-slate-200 rounded-xl overflow-hidden shrink-0 border border-slate-300">
                        <img src={banner.image_url} alt="Banner" className="w-full h-full object-cover" />
                      </div>
                      <div className="flex-1 space-y-2">
                        <div>
                          <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Image URL</label>
                          <input
                            type="text"
                            value={banner.image_url}
                            onChange={(e) => {
                              const newBanners = [...adminBanners];
                              newBanners[index].image_url = e.target.value;
                              setAdminBanners(newBanners);
                            }}
                            className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs outline-none focus:border-purple-400"
                          />
                        </div>
                        <div>
                          <label className="text-[10px] font-black uppercase text-slate-500 block mb-1">Link (Optional)</label>
                          <input
                            type="text"
                            value={banner.link || ''}
                            onChange={(e) => {
                              const newBanners = [...adminBanners];
                              newBanners[index].link = e.target.value;
                              setAdminBanners(newBanners);
                            }}
                            placeholder="https://"
                            className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs outline-none focus:border-purple-400"
                          />
                        </div>
                      </div>
                      <button
                        onClick={() => {
                          const newBanners = adminBanners.filter((_, i) => i !== index);
                          setAdminBanners(newBanners);
                        }}
                        className="p-3 bg-red-50 hover:bg-red-100 text-red-500 rounded-xl transition-colors shrink-0"
                      >
                        🗑️
                      </button>
                    </div>
                  ))}
                  {adminBanners.length === 0 && (
                    <div className="text-center p-6 bg-slate-50 rounded-2xl border border-dashed border-slate-300 text-slate-400 text-sm font-bold">
                      কোনো ব্যানার নেই
                    </div>
                  )}
                </div>

                <label className="flex items-center justify-center gap-2 cursor-pointer w-full py-4 border-2 border-dashed border-purple-300 rounded-2xl bg-purple-50 hover:bg-purple-100 transition-colors text-purple-600 font-black text-sm">
                  {bannerUploading ? '⏳ Uploading...' : '📷 Upload New Banner (1080x280px)'}
                  <input type="file" accept="image/*" className="hidden" disabled={bannerUploading}
                    onChange={e => { const f = e.target.files?.[0]; if (f) uploadAdminBanner(f); }} />
                </label>

                <button onClick={saveGlobalSettings} disabled={globalSettingsSaving}
                  className="mt-6 w-full py-4 rounded-2xl font-black text-white text-sm transition-all disabled:opacity-60"
                  style={{ background: 'linear-gradient(135deg, #8b5cf6, #6366f1)' }}>
                  {globalSettingsSaving ? '⏳ Saving...' : '💾 Banners সেভ করুন'}
                </button>
              </div>
            </div>
          )}


        </main>
      </div>

      {/* ── Reject Modal ── */}
      {rejectModal && (
        <div className="fixed inset-0 z-[300] bg-black/50 flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl p-8 w-full max-w-md shadow-2xl">
            <h3 className="font-black text-xl mb-4">❌ Reject Subscription</h3>
            <textarea value={rejectNotes} onChange={e => setRejectNotes(e.target.value)}
              placeholder="Rejection কারণ লিখুন (optional)..."
              className="w-full p-4 bg-slate-50 rounded-2xl border text-sm min-h-[100px] resize-none text-slate-900 outline-none focus:border-red-400" />
            <div className="flex gap-3 mt-5">
              <button onClick={() => setRejectModal(null)} className="flex-1 py-3 border rounded-2xl font-black text-sm hover:bg-slate-50 transition">Cancel</button>
              <button onClick={rejectSub} className="flex-1 py-3 bg-red-600 text-white rounded-2xl font-black text-sm hover:bg-red-700 transition">Reject করুন</button>
            </div>
          </div>
        </div>
      )}

      {/* ── Plan Edit Modal (Feature Checkbox Grid) ── */}
      {planModal && (
        <div className="fixed inset-0 z-[300] bg-black/50 flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl p-8 w-full max-w-2xl shadow-2xl max-h-[90vh] overflow-y-auto">
            <h3 className="font-black text-2xl mb-1">{planModal.id ? '✏️ Edit Plan' : '+ New Plan'}</h3>
            <p className="text-slate-400 text-sm mb-6">Plan-এর তথ্য ও কোন feature চালু রাখবেন তা নির্বাচন করুন</p>

            {/* Basic Info */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
              <div className="md:col-span-1">
                <label className="text-xs font-black text-slate-400 block mb-1">Plan Name</label>
                <input value={planModal.name || ''} onChange={e => setPlanModal({ ...planModal, name: e.target.value })}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400" placeholder="e.g. Starter" />
              </div>
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">Regular Price</label>
                <input type="number" value={planModal.regular_price || ''} onChange={e => setPlanModal({ ...planModal, regular_price: +e.target.value })}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400" placeholder="(Optional)" />
              </div>
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">Price (৳/মাস)</label>
                <input type="number" value={planModal.price || ''} onChange={e => setPlanModal({ ...planModal, price: +e.target.value })}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400" />
              </div>
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">Duration (দিন)</label>
                <input type="number" value={planModal.duration_days || 30} onChange={e => setPlanModal({ ...planModal, duration_days: +e.target.value })}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400" />
              </div>
            </div>

            {/* Feature Toggles */}
            <div className="mb-6">
              <div className="flex items-center justify-between mb-3">
                <label className="text-sm font-black text-slate-700">🎛️ Feature Access</label>
                <div className="flex gap-2">
                  <button onClick={() => { const all: Record<string, boolean> = {}; PLAN_FEATURE_KEYS.forEach(({ key }) => { all[key] = true; }); setPlanModal({ ...planModal, features: all }); }}
                    className="text-[10px] font-black px-2.5 py-1 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition">
                    সব চালু
                  </button>
                  <button onClick={() => { const none: Record<string, boolean> = {}; PLAN_FEATURE_KEYS.forEach(({ key }) => { none[key] = false; }); setPlanModal({ ...planModal, features: none }); }}
                    className="text-[10px] font-black px-2.5 py-1 bg-red-50 text-red-500 rounded-lg hover:bg-red-100 transition">
                    সব বন্ধ
                  </button>
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-2.5">
                {PLAN_FEATURE_KEYS.map(({ key, label, icon, desc }) => {
                  const isOn = !!(planModal.features as any)?.[key];
                  return (
                    <button
                      key={key}
                      onClick={() => toggleFeature(key, !isOn)}
                      className={`flex items-center gap-3 p-3.5 rounded-2xl border-2 text-left transition-all ${isOn
                        ? 'border-green-400 bg-green-50'
                        : 'border-slate-100 bg-slate-50 hover:border-slate-200'
                        }`}
                    >
                      <div className={`w-9 h-5 rounded-full transition-all flex items-center px-0.5 shrink-0 ${isOn ? 'bg-green-500' : 'bg-slate-300'}`}>
                        <div className={`w-4 h-4 rounded-full bg-white shadow transition-transform ${isOn ? 'translate-x-4' : 'translate-x-0'}`} />
                      </div>
                      <span className="text-lg shrink-0">{icon}</span>
                      <div className="min-w-0">
                        <p className={`font-black text-sm ${isOn ? 'text-green-800' : 'text-slate-500'}`}>{label}</p>
                        <p className={`text-[10px] ${isOn ? 'text-green-600' : 'text-slate-400'}`}>{desc}</p>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Title Display Features (Bullet Points) */}
            <div className="mb-6 p-4 bg-blue-50 rounded-2xl border border-blue-100">
              <label className="text-sm font-black text-blue-800 block mb-2">📝 Display Features (Bullet Points)</label>
              <p className="text-xs text-blue-600 mb-3">Customer-রা ল্যান্ডিং পেজে এই feature-গুলো বুলেট পয়েন্ট হিসেবে দেখতে পাবে।</p>
              <div className="space-y-2 mb-3">
                {(planModal.display_features || []).map((feat, idx) => (
                  <div key={idx} className="flex gap-2">
                    <input
                      value={feat}
                      onChange={e => {
                        const newFeats = [...(planModal.display_features || [])];
                        newFeats[idx] = e.target.value;
                        setPlanModal({ ...planModal, display_features: newFeats });
                      }}
                      className="flex-1 px-3 py-2 bg-white rounded-xl border text-sm text-slate-900 outline-none focus:border-blue-400"
                      placeholder="e.g. ✓ 5টি পণ্য"
                    />
                    <button onClick={() => {
                      const newFeats = [...(planModal.display_features || [])];
                      newFeats.splice(idx, 1);
                      setPlanModal({ ...planModal, display_features: newFeats });
                    }}
                      className="px-3 bg-red-50 text-red-500 rounded-xl font-bold hover:bg-red-100 transition">
                      Delete
                    </button>
                  </div>
                ))}
              </div>
              <button
                onClick={() => setPlanModal({ ...planModal, display_features: [...(planModal.display_features || []), ''] })}
                className="text-xs font-black px-4 py-2 bg-blue-100 text-blue-700 rounded-xl hover:bg-blue-200 transition text-center">
                + Add Bullet Point
              </button>
            </div>

            {/* ── Homepage Theme Access ── */}
            {!!(planModal.features as any)?.home_editor && (
              <div className="mb-6 p-4 bg-purple-50 rounded-2xl border border-purple-100">
                <label className="text-sm font-black text-purple-800 block mb-3">🏠 অনুমোদিত Homepage Themes</label>
                <p className="text-xs text-purple-500 mb-3">এই plan-এর users কোন কোন homepage theme ব্যবহার করতে পারবে?</p>
                <div className="flex flex-wrap gap-2">
                  {ALL_HOME_THEMES.map(th => {
                    const allowed: string[] = (planModal.features as any)?.allowed_home_themes || [];
                    const isAllowed = allowed.includes(th.id);
                    return (
                      <button
                        key={th.id}
                        onClick={() => {
                          const cur: string[] = (planModal.features as any)?.allowed_home_themes || [];
                          const next = isAllowed ? cur.filter(x => x !== th.id) : [...cur, th.id];
                          setPlanModal({ ...planModal, features: { ...(planModal.features as any), allowed_home_themes: next } });
                        }}
                        className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-black border-2 transition-all ${isAllowed ? 'border-purple-500 bg-purple-100 text-purple-800' : 'border-slate-200 bg-white text-slate-400 hover:border-purple-200'
                          }`}
                      >
                        <span>{th.emoji}</span> {th.label}
                        {isAllowed && <span className="text-purple-500">✓</span>}
                      </button>
                    );
                  })}
                </div>
                {((planModal.features as any)?.allowed_home_themes || []).length === 0 && (
                  <p className="text-[10px] text-red-400 mt-2 font-bold">⚠️ কমপক্ষে একটি theme select করুন</p>
                )}
              </div>
            )}

            {/* ── Max Landing Pages ── */}
            {!!(planModal.features as any)?.landing_editor && (
              <div className="mb-6 p-4 bg-amber-50 rounded-2xl border border-amber-100">
                <label className="text-sm font-black text-amber-800 block mb-2">🎨 সর্বোচ্চ Landing Page সংখ্যা</label>
                <p className="text-xs text-amber-600 mb-3">এই plan-এর users সর্বোচ্চ কতটি product landing page বানাতে পারবে?</p>
                <div className="flex items-center gap-3">
                  <input
                    type="number"
                    min="0" max="999"
                    value={(planModal.features as any)?.max_landing_pages ?? 0}
                    onChange={e => setPlanModal({
                      ...planModal,
                      features: { ...(planModal.features as any), max_landing_pages: Math.max(0, +e.target.value) }
                    })}
                    className="w-32 px-4 py-3 bg-white border-2 border-amber-200 rounded-2xl text-lg font-black text-amber-800 text-slate-900 outline-none focus:border-amber-400 text-center"
                  />
                  <span className="text-sm text-amber-700 font-bold">টি landing page</span>
                  <button
                    onClick={() => setPlanModal({ ...planModal, features: { ...(planModal.features as any), max_landing_pages: 9999 } })}
                    className="ml-auto text-[10px] font-black px-3 py-2 bg-green-50 text-green-600 rounded-xl hover:bg-green-100 transition"
                  >Unlimited</button>
                </div>
              </div>
            )}

            {/* Active toggle */}
            <div className="flex items-center gap-3 mb-6 p-4 bg-slate-50 rounded-2xl">
              <input type="checkbox" id="isActive" checked={!!planModal.is_active}
                onChange={e => setPlanModal({ ...planModal, is_active: e.target.checked ? 1 : 0 })}
                className="w-4 h-4 accent-purple-600" />
              <label htmlFor="isActive" className="text-sm font-bold text-slate-700">
                Plan টি Active করুন (Customers দেখতে পাবে)
              </label>
            </div>

            <div className="flex gap-3">
              <button onClick={() => setPlanModal(null)} className="flex-1 py-3.5 border rounded-2xl font-black text-sm hover:bg-slate-50 transition">Cancel</button>
              <button onClick={savePlan}
                className="flex-1 py-3.5 text-white rounded-2xl font-black text-sm transition"
                style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}>
                💾 Plan Save করুন
              </button>
            </div>
          </div>
        </div>
      )}
      {/* ── Team Member Modal ── */}
      {teamModal !== null && (
        <div className="fixed inset-0 z-[300] bg-black/50 flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl p-8 w-full max-w-md shadow-2xl">
            <h3 className="font-black text-2xl mb-1">{teamModal.id ? '✏️ Edit Member' : '+ নতুন সদস্য'}</h3>
            <p className="text-slate-400 text-sm mb-6">ল্যান্ডিং পেজে দেখানো টিম মেম্বার-এর তথ্য</p>

            {/* Photo Preview */}
            <div className="flex items-center gap-4 mb-5">
              <div className="w-20 h-20 rounded-2xl overflow-hidden bg-gradient-to-br from-purple-100 to-blue-100 flex items-center justify-center shrink-0">
                {teamModal.photo_url
                  ? <img src={teamModal.photo_url} alt="" className="w-full h-full object-cover" />
                  : <span className="text-3xl font-black text-purple-300">{(teamModal.name || '?').charAt(0)}</span>}
              </div>
              <div className="flex-1">
                <label className="text-xs font-black text-slate-400 block mb-1">ফোটো URL</label>
                <input
                  value={teamModal.photo_url || ''}
                  onChange={e => setTeamModal(m => m ? { ...m, photo_url: e.target.value } : m)}
                  className="w-full px-3 py-2.5 bg-slate-50 rounded-xl border text-sm text-slate-900 outline-none focus:border-purple-400"
                  placeholder="https://example.com/photo.jpg"
                />
                <label className="mt-2 flex items-center gap-2 cursor-pointer">
                  <span className="text-[11px] font-black text-purple-600 bg-purple-50 px-3 py-1.5 rounded-lg hover:bg-purple-100 transition">
                    {teamUploading ? '⏳ Uploading...' : '📷 Upload Photo'}
                  </span>
                  <input type="file" accept="image/*" className="hidden"
                    disabled={teamUploading}
                    onChange={e => { const f = e.target.files?.[0]; if (f) uploadTeamPhoto(f); }} />
                </label>
              </div>
            </div>

            <div className="space-y-3 mb-5">
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">নাম *</label>
                <input
                  value={teamModal.name || ''}
                  onChange={e => setTeamModal(m => m ? { ...m, name: e.target.value } : m)}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400"
                  placeholder="যেমন: আরমান হোসেন"
                />
              </div>
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">পদবি</label>
                <input
                  value={teamModal.role || ''}
                  onChange={e => setTeamModal(m => m ? { ...m, role: e.target.value } : m)}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400"
                  placeholder="যেমন: প্রতিষ্ঠাতা ও সিইও"
                />
              </div>
              <div>
                <label className="text-xs font-black text-slate-400 block mb-1">সিরিয়াল নম্বার (কোন পর দেখাবে)</label>
                <input
                  type="number" min="0"
                  value={teamModal.sort_order ?? 0}
                  onChange={e => setTeamModal(m => m ? { ...m, sort_order: +e.target.value } : m)}
                  className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm text-slate-900 outline-none focus:border-purple-400"
                />
              </div>
              <div className="flex items-center gap-3 p-4 bg-slate-50 rounded-2xl">
                <input type="checkbox" id="tmActive" checked={!!teamModal.is_active}
                  onChange={e => setTeamModal(m => m ? { ...m, is_active: e.target.checked ? 1 : 0 } : m)}
                  className="w-4 h-4 accent-purple-600" />
                <label htmlFor="tmActive" className="text-sm font-bold text-slate-700">ল্যান্ডিং পেজে দেখাহো (সক্রিয়)</label>
              </div>
            </div>

            <div className="flex gap-3">
              <button onClick={() => setTeamModal(null)} className="flex-1 py-3.5 border rounded-2xl font-black text-sm hover:bg-slate-50 transition">Cancel</button>
              <button onClick={saveTeamMember} disabled={teamSaving}
                className="flex-1 py-3.5 text-white rounded-2xl font-black text-sm transition disabled:opacity-60"
                style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}>
                {teamSaving ? '⏳ Saving...' : '💾 Save করুন'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SuperAdminDashboard;