// MIAMO FOODS EXPORTS - Main React Application (v3.0 - All 14 Fixes Applied)
// Force Vercel Build Trigger: 20260803_1637

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ═══════════════════════════════════════════════════════════════
// FONT LOADER — Load all 25+ Google Fonts once on startup
// ═══════════════════════════════════════════════════════════════
(function loadGoogleFonts() {
  const fonts = [
    'Inter','Montserrat','Poppins','Outfit','Cinzel','Raleway','Nunito',
    'Playfair+Display','Josefin+Sans','Quicksand','Exo+2','Orbitron',
    'Barlow','Lato','Rubik','DM+Sans','Sora','Space+Grotesk','Kanit',
    'Bebas+Neue','Comfortaa','Righteous','Pacifico','Dancing+Script','Ubuntu'
  ];
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `https://fonts.googleapis.com/css2?${fonts.map(f => `family=${f}:wght@400;600;700;800;900`).join('&')}&display=swap`;
  document.head.appendChild(link);
})();

// ═══════════════════════════════════════════════════════════════
// FONT MAP — 25 Professional Fonts
// ═══════════════════════════════════════════════════════════════
const FONT_OPTIONS = [
  { value: "Inter",          label: "Inter — Clean Modern Sans",          css: "'Inter', sans-serif" },
  { value: "Montserrat",     label: "Montserrat — Bold Executive",        css: "'Montserrat', sans-serif" },
  { value: "Poppins",        label: "Poppins — Friendly Round",           css: "'Poppins', sans-serif" },
  { value: "Outfit",         label: "Outfit — Tech & Sleek",              css: "'Outfit', sans-serif" },
  { value: "Raleway",        label: "Raleway — Elegant Thin",             css: "'Raleway', sans-serif" },
  { value: "Nunito",         label: "Nunito — Soft & Rounded",            css: "'Nunito', sans-serif" },
  { value: "Playfair Display", label: "Playfair Display — Luxury Serif",  css: "'Playfair Display', serif" },
  { value: "Josefin Sans",   label: "Josefin Sans — Geometric Clean",     css: "'Josefin Sans', sans-serif" },
  { value: "Quicksand",      label: "Quicksand — Minimal Light",          css: "'Quicksand', sans-serif" },
  { value: "Exo 2",          label: "Exo 2 — Futuristic Tech",            css: "'Exo 2', sans-serif" },
  { value: "Orbitron",       label: "Orbitron — Space & Tech",            css: "'Orbitron', sans-serif" },
  { value: "Barlow",         label: "Barlow — Condensed Clean",           css: "'Barlow', sans-serif" },
  { value: "Lato",           label: "Lato — Professional Classic",        css: "'Lato', sans-serif" },
  { value: "Rubik",          label: "Rubik — Modern Rounded",             css: "'Rubik', sans-serif" },
  { value: "DM Sans",        label: "DM Sans — Contemporary Clean",       css: "'DM Sans', sans-serif" },
  { value: "Sora",           label: "Sora — Stylish Geometric",           css: "'Sora', sans-serif" },
  { value: "Space Grotesk",  label: "Space Grotesk — Developer Cool",     css: "'Space Grotesk', sans-serif" },
  { value: "Kanit",          label: "Kanit — Asian Bold Style",           css: "'Kanit', sans-serif" },
  { value: "Bebas Neue",     label: "Bebas Neue — Impact Display",        css: "'Bebas Neue', cursive" },
  { value: "Comfortaa",      label: "Comfortaa — Playful Circular",       css: "'Comfortaa', cursive" },
  { value: "Righteous",      label: "Righteous — Strong Retro",           css: "'Righteous', cursive" },
  { value: "Pacifico",       label: "Pacifico — Signature Script",        css: "'Pacifico', cursive" },
  { value: "Dancing Script", label: "Dancing Script — Handwritten",       css: "'Dancing Script', cursive" },
  { value: "Ubuntu",         label: "Ubuntu — Linux Pro Style",           css: "'Ubuntu', sans-serif" },
  { value: "Cinzel",         label: "Cinzel — Classic Serif Luxury",      css: "'Cinzel', serif" },
];

// Smart 5-Color Palette Parser from Canva / Coolors / ColorHunt / Adobe Color / Link URLs
function parsePaletteUrlOrHex(inputStr) {
  if (!inputStr) return null;
  // Extract all 6-character or 3-character hex codes from link string
  const matches = inputStr.match(/#?([0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b/g);
  if (!matches || matches.length === 0) return null;

  const hexes = matches.map(h => {
    let raw = h.replace('#', '');
    if (raw.length === 3) raw = raw.split('').map(c => c + c).join('');
    return `#${raw.toUpperCase()}`;
  });

  return {
    primary: hexes[0] || "#DA1C30",
    accent: hexes[1] || "#F59E0B",
    bg: hexes[2] || "#0B0F17",
    surface: hexes[3] || hexes[2] || "#1E293B",
    text: hexes[4] || (hexes[2] && hexes[2].toUpperCase() > "#888888" ? "#0F172A" : "#FFFFFF")
  };
}

// ═══════════════════════════════════════════════════════════════
// THEME OPTIONS — 16 Curated Modern Themes (Cute, Gaming, Corporate, Luxury)
// ═══════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════
// THEME OPTIONS — 17 Curated Modern Themes with High Contrast Presets
// ═══════════════════════════════════════════════════════════════
const THEME_OPTIONS = [
  { value: "dark",            label: "🌙 Dark Obsidian (Black)",    desc: "Classic dark obsidian theme",                                 colors: { primary: "#DA1C30", accent: "#F59E0B", bg: "#0B0F17", surface: "#1E293B", text: "#FFFFFF", subtext: "#94a3b8", border: "#334155", sidebar: "#0f172a", activeTab: "#e11d48" } },
  { value: "light",           label: "☀️ Executive White (Light)",  desc: "Crisp bright white clean screen",                              colors: { primary: "#DA1C30", accent: "#d97706", bg: "#ffffff", surface: "#f8fafc", text: "#0f172a", subtext: "#334155", border: "#cbd5e1", sidebar: "#f1f5f9", activeTab: "#e11d48" } },
  { value: "royal_pink",      label: "🌸 Royal Pink",              desc: "Vibrant cute pink theme",                                      colors: { primary: "#ec4899", accent: "#f43f5e", bg: "#fdf2f8", surface: "#fce7f3", text: "#831843", subtext: "#9d174d", border: "#fbcfe8", sidebar: "#fce7f3", activeTab: "#db2777" } },
  { value: "emerald_forest",  label: "🌿 Emerald Green",           desc: "Rich green theme with emerald tones",                         colors: { primary: "#10b981", accent: "#f59e0b", bg: "#022c22", surface: "#064e3b", text: "#ecfdf5", subtext: "#a7f3d0", border: "#047857", sidebar: "#022c22", activeTab: "#059669" } },
  { value: "cyberpunk_gold",  label: "⚡ Cyberpunk Neon (Gamer)",  desc: "Futuristic neon gaming theme",                                 colors: { primary: "#eab308", accent: "#ec4899", bg: "#18181b", surface: "#27272a", text: "#fef08a", subtext: "#d4d4d8", border: "#71717a", sidebar: "#09090b", activeTab: "#ca8a04" } },
  { value: "diamond_mint",    label: "🧊 Ice Diamond Mint",        desc: "Cool icy teal cyan and mint diamond theme",                  colors: { primary: "#06b6d4", accent: "#10b981", bg: "#042f2e", surface: "#115e59", text: "#ccfbf1", subtext: "#99f6e4", border: "#0d9488", sidebar: "#022c22", activeTab: "#0891b2" } }
];

// Safe React Icon component wrapper
function Icon({ name, className = "w-5 h-5" }) {
  const containerRef = useRef(null);
  useEffect(() => {
    if (containerRef.current && window.lucide) {
      const pascalName = (name || "").split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');
      const iconDef = window.lucide.icons?.[pascalName] || window.lucide.icons?.[name];
      if (iconDef && typeof iconDef.toSvg === 'function') {
        containerRef.current.innerHTML = iconDef.toSvg({ class: className });
      }
    }
  }, [name, className]);
  return <span ref={containerRef} className="inline-flex items-center justify-center pointer-events-none" />;
}

// Safe Fetch Timeout Helper (compatible with all browsers)
function fetchWithTimeout(url, options = {}, timeoutMs = 5000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);
  return fetch(url, { ...options, signal: controller.signal })
    .finally(() => clearTimeout(timer));
}

// ═══════════════════════════════════════════════════════════════
// LIVE LOCATION FETCH via ipapi.co (Free, No API Key)
// ═══════════════════════════════════════════════════════════════
async function fetchUserLocation() {
  try {
    const res = await fetchWithTimeout('https://ipapi.co/json/', {}, 4000);
    if (!res.ok) throw new Error('failed');
    const data = await res.json();
    return {
      city: data.city || 'Unknown',
      region: data.region || '',
      country: data.country_name || 'Unknown',
      ip: data.ip || '—',
      flag: data.country_code ? `https://flagcdn.com/24x18/${data.country_code.toLowerCase()}.png` : null
    };
  } catch {
    return { city: 'Unknown', region: '', country: 'Unknown', ip: '—', flag: null };
  }
}

// ═══════════════════════════════════════════════════════════════
// ELEVENLABS FREE PROXY via StreamElements TTS (No API Key Needed)
// StreamElements uses FakeYou backend — completely free human-sounding voices
// ═══════════════════════════════════════════════════════════════
async function speakWithStreamElements(text, voiceId = 'Brian') {
  try {
    // StreamElements free TTS — no API key required
    const url = `https://api.streamelements.com/kappa/v2/speech?voice=${voiceId}&text=${encodeURIComponent(text)}`;
    const res = await fetchWithTimeout(url, {}, 8000);
    if (!res.ok) throw new Error('SE TTS failed');
    const blob = await res.blob();
    const audioUrl = URL.createObjectURL(blob);
    const audio = new Audio(audioUrl);
    audio.play();
    return true;
  } catch {
    return false;
  }
}

// StreamElements available voice IDs (completely free)
const SE_VOICE_OPTIONS = [
  { id: "Brian",   label: "Brian — Deep British Male" },
  { id: "Amy",     label: "Amy — Warm British Female" },
  { id: "Emma",    label: "Emma — Clear British Female" },
  { id: "Joanna",  label: "Joanna — Professional US Female" },
  { id: "Kendra",  label: "Kendra — Bright US Female" },
  { id: "Matthew", label: "Matthew — Confident US Male" },
  { id: "Russell", label: "Russell — Calm Australian Male" },
  { id: "Nicole",  label: "Nicole — Soft Australian Female" },
  { id: "Raveena", label: "Raveena — Indian English Female" },
];

// Real-Time Transparent Product Image Renderer (Strips solid black background boxes automatically)
function TransparentProductImage({ photoUrl, alt, className, style }) {
  const [cleanedUrl, setCleanedUrl] = useState(photoUrl);

  useEffect(() => {
    if (!photoUrl) { setCleanedUrl(null); return; }

    const img = new Image();
    img.crossOrigin = "anonymous";
    img.onload = () => {
      try {
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);

        const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const data = imgData.data;
        let hasBlackBox = false;

        // Scan pixels for solid black background box (r < 28 && g < 28 && b < 28)
        for (let i = 0; i < data.length; i += 4) {
          if (data[i] < 28 && data[i + 1] < 28 && data[i + 2] < 28) {
            data[i + 3] = 0; // Turn solid black pixels 100% transparent!
            hasBlackBox = true;
          }
        }

        if (hasBlackBox) {
          ctx.putImageData(imgData, 0, 0);
          setCleanedUrl(canvas.toDataURL('image/png'));
        } else {
          setCleanedUrl(photoUrl);
        }
      } catch (e) {
        setCleanedUrl(photoUrl);
      }
    };
    img.onerror = () => setCleanedUrl(photoUrl);
    img.src = photoUrl;
  }, [photoUrl]);

  if (!cleanedUrl) return null;

  return (
    <img
      src={cleanedUrl}
      alt={alt}
      className={className}
      style={{ ...style, background: 'transparent' }}
    />
  );
}

function App() {
  // State Initialization from MiamoStore
  const [settings, setSettings] = useState(() => MiamoStore.getSettings());
  const [accounts, setAccounts] = useState(() => MiamoStore.getAccounts());
  const [session, setSession] = useState(() => MiamoStore.getSession());
  const [customThemes, setCustomThemes] = useState(() => MiamoStore.getCustomThemes() || []);
  const [theme, setTheme] = useState(() => {
    // getTheme() already validates & auto-migrates legacy themes to 'dark'
    return MiamoStore.getTheme() || "dark";
  });
  // themeRevision is a counter incremented whenever theme colors are edited
  // This forces the CSS useEffect to re-run even if the theme KEY didn't change
  const [themeRevision, setThemeRevision] = useState(0);
  const [activeTab, setActiveTab] = useState("welcome");

  // Modals & Authentication
  const [adminUnlocked, setAdminUnlocked] = useState(false);
  const [hikeUnlocked, setHikeUnlocked] = useState(false);
  const [showProfileModal, setShowProfileModal] = useState(false);
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const [showPdfPreview, setShowPdfPreview] = useState(false);

  // Mobile App Opening Splash GIF/Animation Screen (Phone Only: < 768px)
  const [showMobileSplash, setShowMobileSplash] = useState(() => window.innerWidth < 768);

  useEffect(() => {
    if (window.innerWidth < 768) {
      const timer = setTimeout(() => setShowMobileSplash(false), 2500);
      return () => clearTimeout(timer);
    }
  }, []);

  // 📲 PWA "Add to Phone Home Screen" Shortcut Handler
  const [deferredPrompt, setDeferredPrompt] = useState(null);
  const [showInstallBanner, setShowInstallBanner] = useState(false);

  useEffect(() => {
    const handler = (e) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setShowInstallBanner(true);
    };
    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  const handleInstallApp = () => {
    if (deferredPrompt) {
      deferredPrompt.prompt();
      deferredPrompt.userChoice.then(() => {
        setDeferredPrompt(null);
        setShowInstallBanner(false);
      });
    } else {
      alert("📲 To add shortcut to phone home screen:\n\n• On Android: Tap Chrome Menu (⋮) → 'Add to Home screen'\n• On iPhone: Tap Safari Share (⎋) → 'Add to Home Screen'");
    }
  };
  const [userLocation, setUserLocation] = useState({ city: '...', region: '', country: '...', ip: '—', flag: null });

  useEffect(() => {
    fetchUserLocation().then(loc => setUserLocation(loc));
  }, []);

  // ☁️ Fast 3-Second Cross-Device Cloud Auto-Sync — syncs settings, accounts, catalog
  const performCloudFetch = useCallback(() => {
    MiamoStore.fetchCloudSync().then(cloudData => {
      if (cloudData && MiamoStore.applyCloudSync(cloudData)) {
        // Refresh settings & accounts state (theme state is preserved locally)
        setSettings(MiamoStore.getSettings());
        setAccounts(MiamoStore.getAccounts());
        setCustomThemes(MiamoStore.getCustomThemes());
        setTheme(MiamoStore.getTheme());
      }
    });
  }, []);

  useEffect(() => {
    performCloudFetch();
    window.addEventListener("focus", performCloudFetch);
    const syncInterval = setInterval(performCloudFetch, 3000); // 3-second instant auto-sync!
    return () => {
      window.removeEventListener("focus", performCloudFetch);
      clearInterval(syncInterval);
    };
  }, [performCloudFetch]);

  // PC Shutdown / Browser Restart Session Security Check
  useEffect(() => {
    const isTabActive = sessionStorage.getItem("miamo_active_session_flag");
    if (!isTabActive && session) {
      // Browser was closed or PC shut down -> Force password re-login!
      MiamoStore.clearSession();
      setSession(null);
    }
  }, []);

  // 5-Hour Inactivity Auto-Logout (300 minutes default)
  const inactivityTimerRef = useRef(null);
  const [inactivityTimeout, setInactivityTimeout] = useState(() => {
    const stored = MiamoStore.getInactivityTimeout();
    return (stored && stored >= 60) ? stored : 300;
  });

  const resetInactivityTimer = useCallback(() => {
    if (inactivityTimerRef.current) clearTimeout(inactivityTimerRef.current);
    if (!session) return;
    const effectiveMins = Math.max(60, inactivityTimeout || 300);
    inactivityTimerRef.current = setTimeout(() => {
      // 5 Hours inactive -> Auto logout to login screen requiring password
      MiamoStore.clearSession();
      sessionStorage.removeItem("miamo_active_session_flag");
      setSession(null);
      alert(`🔒 Session locked after ${(effectiveMins/60).toFixed(0)} hours of inactivity. Please re-enter your password to continue.`);
    }, effectiveMins * 60 * 1000);
  }, [session, inactivityTimeout]);

  useEffect(() => {
    if (!session) return;
    const events = ["mousemove", "keydown", "click", "scroll", "touchstart"];
    const handleActivity = () => {
      resetInactivityTimer();
    };
    events.forEach(e => window.addEventListener(e, handleActivity, { passive: true }));
    resetInactivityTimer();
    return () => {
      events.forEach(e => window.removeEventListener(e, handleActivity));
      if (inactivityTimerRef.current) clearTimeout(inactivityTimerRef.current);
    };
  }, [session, inactivityTimeout, resetInactivityTimer]);

  // First-Time User Celebration Fireworks Modal State
  const [showFirstTimeModal, setShowFirstTimeModal] = useState(false);
  const [firstTimeUser, setFirstTimeUser] = useState(null);
  const [firstTimeTimer, setFirstTimeTimer] = useState(30);

  // Fireworks Animation Controller (Side cannons + 30s locked timer)
  useEffect(() => {
    let fireworksInterval = null;
    let timerInterval = null;

    if (showFirstTimeModal) {
      setFirstTimeTimer(30);

      // Continuous side-cannons firing every 350ms
      fireworksInterval = setInterval(() => {
        if (window.confetti) {
          window.confetti({ particleCount: 30, angle: 60, spread: 55, origin: { x: 0, y: 0.7 } });
          window.confetti({ particleCount: 30, angle: 120, spread: 55, origin: { x: 1, y: 0.7 } });
        }
      }, 350);

      // 30-Second Minimum Lock Countdown
      timerInterval = setInterval(() => {
        setFirstTimeTimer(prev => {
          if (prev <= 1) {
            clearInterval(timerInterval);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }

    return () => {
      if (fireworksInterval) clearInterval(fireworksInterval);
      if (timerInterval) clearInterval(timerInterval);
    };
  }, [showFirstTimeModal]);

  const handleCloseFirstTimeModal = () => {
    if (firstTimeTimer > 0) return; // Locked during first 30 seconds!
    setShowFirstTimeModal(false);
    setFirstTimeUser(null);
  };

  // ─── Human Voice Audio Engine (StreamElements Free + ElevenLabs + Browser) ───
  const speakTextWithHumanVoice = useCallback((text, userGender) => {
    if (!text) return;

    const mode = settings?.voice_engine_mode || "streamelements";
    const apiKey = settings?.elevenlabs_api_key;
    const voiceId = settings?.elevenlabs_voice_id || "21m00Tcm4TlvDq8ikWAM";
    const seVoice = settings?.se_voice_id || (userGender === "Female" ? "Amy" : "Brian");

    // Mode 1: ElevenLabs (user provides own key)
    if (mode === "elevenlabs" && apiKey && apiKey.trim()) {
      fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId.trim()}`, {
        method: "POST",
        headers: {
          "Accept": "audio/mpeg",
          "xi-api-key": apiKey.trim(),
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          text,
          model_id: "eleven_multilingual_v2",
          voice_settings: { stability: 0.5, similarity_boost: 0.85 }
        })
      })
      .then(res => { if (!res.ok) throw new Error("ElevenLabs API error"); return res.blob(); })
      .then(blob => { const audio = new Audio(URL.createObjectURL(blob)); audio.play(); })
      .catch(() => { speakWithStreamElements(text, seVoice).then(ok => { if (!ok) fallbackWebSpeech(text, userGender); }); });
      return;
    }

    // Mode 2: StreamElements Free (No API Key — default)
    if (mode === "streamelements" || mode === "natural_neural") {
      speakWithStreamElements(text, seVoice).then(ok => {
        if (!ok) fallbackWebSpeech(text, userGender);
      });
      return;
    }

    fallbackWebSpeech(text, userGender);
  }, [settings]);

  const fallbackWebSpeech = (text, userGender) => {
    if (!window.speechSynthesis) return;
    window.speechSynthesis.cancel();
    const utterance = new SpeechSynthesisUtterance(text);
    const voices = window.speechSynthesis.getVoices();
    const preferFemale = userGender === "Female";
    const naturalVoice = voices.find(v => {
      const n = v.name.toLowerCase();
      if (preferFemale) return (n.includes("natural") || n.includes("google") || n.includes("samantha")) && (n.includes("us") || n.includes("uk") || n.includes("english"));
      else return (n.includes("natural") || n.includes("google") || n.includes("daniel")) && (n.includes("us") || n.includes("uk") || n.includes("english"));
    }) || voices.find(v => preferFemale ? /female|samantha|zira|karen/i.test(v.name) : /male|david|daniel|mark/i.test(v.name)) || voices[0];
    if (naturalVoice) utterance.voice = naturalVoice;
    utterance.pitch = parseFloat(settings?.voice_pitch || 1.0);
    utterance.rate = parseFloat(settings?.voice_rate || 0.95);
    utterance.volume = 1.0;
    setTimeout(() => window.speechSynthesis.speak(utterance), 200);
  };

  const playGreeting = useCallback((user) => {
    const name = user?.display_name?.split(" ")[0] || "there";
    const gender = user?.gender || "Male";
    const hour = new Date().getHours();
    const timeOfDay = hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
    const greetingPools = {
      morning: [`Good morning, ${name}! Ready to close some great deals today?`, `Hey ${name}! Rise and shine — the export world awaits!`, `Good morning ${name}! Hope you have a fantastic and productive day ahead.`],
      afternoon: [`Good afternoon, ${name}! Keep up the great energy!`, `Hey ${name}! Hope your afternoon is going brilliantly.`, `Good afternoon ${name}! You're doing amazing — keep pushing!`],
      evening: [`Good evening, ${name}! Wrapping up the day strong?`, `Hey ${name}! Hope you had a wonderful productive day.`, `Good evening ${name}! Another great day in the books.`]
    };
    const todayKey = `${new Date().toDateString()}_${user?.user_email}`;
    const lastGreeting = MiamoStore.getLastGreetingDate();
    if (lastGreeting === todayKey) return;
    MiamoStore.saveLastGreetingDate(todayKey);
    const pool = greetingPools[timeOfDay];
    const msg = pool[Math.floor(Math.random() * pool.length)];
    speakTextWithHumanVoice(msg, gender);
  }, [speakTextWithHumanVoice]);

  const playFarewell = (user) => {
    const name = user?.display_name?.split(" ")[0] || "there";
    const gender = user?.gender || "Male";
    const hour = new Date().getHours();
    const timeGreet = hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
    speakTextWithHumanVoice(`Goodbye ${name}! Have a wonderful ${timeGreet}. See you soon!`, gender);
  };

  // Apply theme to body — 5-Color Palette Engine
  // Dependencies: theme key + themeRevision (forces re-run on color edit) + customThemes (for palette lookup)
  useEffect(() => {
    const customThemes = MiamoStore.getCustomThemes() || [];
    const allThemes = [...THEME_OPTIONS, ...customThemes].map(t => `${t.value}-theme`);
    const extraLegacyThemes = ['pink-theme','peach-theme','matcha-theme','cyberpunk-theme','arcade-theme','viper-theme','corporate-theme','tech-theme','swiss-theme','emirates-theme','diamond-theme','stealth-theme','tokyo-theme','evergreen-theme','amethyst-theme','sunburst-theme','light-theme','dark-theme'];
    document.body.classList.remove(...allThemes, ...extraLegacyThemes);
    const activeTheme = theme || localStorage.getItem("miamo_app_theme") || "dark";
    if (activeTheme && activeTheme !== "dark") {
      document.body.classList.add(`${activeTheme}-theme`);
    }

    // 🌟 5-COLOR PALETTE DYNAMIC CSS INJECTOR — Always applies to ALL themes on page load
    const themeOverrides = MiamoStore.getThemeColorOverrides() || {};
    const allAvailableThemes = [...THEME_OPTIONS, ...customThemes];
    const targetThemeObj = allAvailableThemes.find(t => t.value === activeTheme);
    const userOverride = themeOverrides[activeTheme];

    // Always inject dynamic CSS for ALL themes (light, dark, custom palettes, or overrides)
    const colors = userOverride || targetThemeObj?.colors || { primary: "#DA1C30", accent: "#F59E0B", bg: "#0B0F17", surface: "#1E293B", text: "#FFFFFF" };

    let styleTag = document.getElementById("miamo-dynamic-theme-style");
    if (colors) {
      if (!styleTag) {
        styleTag = document.createElement("style");
        styleTag.id = "miamo-dynamic-theme-style";
        document.head.appendChild(styleTag);
      }

      // Perceived Luminance helper to prevent black-on-black or white-on-white text
      const getLuminance = (hex) => {
        if (!hex || typeof hex !== 'string') return 0;
        let clean = hex.replace('#', '');
        if (clean.length === 3) clean = clean.split('').map(c => c+c).join('');
        const r = parseInt(clean.substring(0,2), 16) || 0;
        const g = parseInt(clean.substring(2,4), 16) || 0;
        const b = parseInt(clean.substring(4,6), 16) || 0;
        return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
      };

      const pHex = colors.primary || "#DA1C30";
      const aHex = colors.accent || "#F59E0B";
      const bgHex = colors.bg || "#0B0F17";
      const sHex = colors.surface || colors.card || "#1E293B";
      let tHex = colors.text || "#FFFFFF";

      const bgLum = getLuminance(bgHex);
      const textLum = getLuminance(tHex);

      // Dynamic High-Contrast Auto-Repair Guard:
      if (bgLum < 0.45 && textLum < 0.45) {
        tHex = "#FFFFFF";
      } else if (bgLum >= 0.45 && textLum >= 0.45) {
        tHex = "#0F172A";
      }

      const isLightBg = bgLum >= 0.45;
      const subHex = colors.subtext || (isLightBg ? "#334155" : "#94a3b8");
      const hlHex = colors.highlight || (isLightBg ? "#932F6D" : aHex);
      const bHex = colors.border || (isLightBg ? "#cbd5e1" : "#334155");
      const sbHex = colors.sidebar || (isLightBg ? "#f1f5f9" : "#0f172a");
      const tabHex = colors.activeTab || pHex;

      styleTag.innerHTML = `
        :root {
          --theme-primary: ${pHex};
          --theme-accent: ${aHex};
          --theme-bg: ${bgHex};
          --theme-surface: ${sHex};
          --theme-text: ${tHex};
          --theme-subtext: ${subHex};
          --theme-highlight: ${hlHex};
          --theme-border: ${bHex};
          --theme-sidebar: ${sbHex};
          --theme-active-tab: ${tabHex};
        }
        body, 
        body.${activeTheme}-theme, 
        body.${activeTheme}, 
        #root, 
        .app-main-layout {
          background-color: ${bgHex} !important;
          background: ${bgHex} !important;
          color: ${tHex} !important;
        }

        /* SIDEBAR & NAVIGATION BAR */
        aside,
        nav,
        .app-sidebar,
        .sidebar-container,
        div[class*="w-64"],
        div[class*="bg-slate-950"] {
          background-color: ${sbHex} !important;
        }

        /* ALL CARDS, PANELS, INPUTS, SELECTS & CONTAINERS (SURFACE) */
        .glass-panel, 
        .glass-card,
        div[class*="bg-slate-"],
        div[class*="bg-black/"],
        div[class*="bg-slate-900"],
        div[class*="bg-slate-950"],
        div[class*="bg-slate-800"],
        input,
        select,
        textarea {
          background-color: ${sHex} !important;
          color: ${tHex} !important;
        }

        /* ALL BORDERS (CARDS, INPUTS, DIVIDERS) */
        .glass-panel,
        .glass-card,
        [class*="border-"],
        [class*="border-slate-"],
        [class*="border-amber-"],
        [class*="border-rose-"],
        hr,
        input,
        select,
        textarea {
          border-color: ${bHex} !important;
        }

        /* 1. UNIFIED MAIN TEXT COLOR — ALL HEADINGS, TITLES, LABELS & MAIN TEXT */
        h1, h2, h3, h4, h5, h6, 
        label, th, td, strong, b,
        [class*="text-slate-100"],
        [class*="text-slate-200"],
        [class*="text-slate-300"],
        [class*="text-white"],
        .text-white,
        span.text-white {
          color: ${tHex} !important;
        }

        /* 2. UNIFIED SUB TEXT COLOR — ALL DESCRIPTIONS, PARAGRAPHS & HELPER TEXT */
        p, small, 
        span.text-slate-400, span.text-slate-500,
        [class*="text-slate-400"], 
        [class*="text-slate-500"], 
        [class*="text-slate-600"] {
          color: ${subHex} !important;
        }

        /* 3. UNIFIED ACCENT & BADGE HIGHLIGHT COLOR — ALL STATUS BADGES & ICONS */
        [class*="text-amber-"], 
        [class*="text-emerald-"], 
        [class*="text-rose-"], 
        [class*="text-yellow-"] {
          color: ${hlHex} !important;
        }

        /* BUTTONS & PRIMARY ACCENTS */
        button.bg-rose-600, 
        button.bg-amber-500, 
        button.bg-emerald-600,
        [class*="from-rose-600"],
        [class*="bg-gradient-to-r"] {
          background-color: ${pHex} !important;
          background-image: none !important;
          color: #ffffff !important;
        }

        /* ACTIVE NAVIGATION TAB HIGHLIGHT */
        .nav-item-active,
        button[class*="bg-rose-950"],
        div[class*="bg-rose-950"] {
          background-color: ${tabHex} !important;
          color: #ffffff !important;
        }

        /* BRAND LOGO STRICT SOLID WHITE PROTECTION ACROSS ALL THEMES */
        .brand-logo-container,
        .brand-logo-box,
        div[class*="brand-logo"] {
          background-color: #ffffff !important;
          background: #ffffff !important;
          border-radius: 12px !important;
          padding: 4px !important;
        }
      `;
    } else if (styleTag) {
      styleTag.innerHTML = `
        /* BRAND LOGO STRICT SOLID WHITE PROTECTION ACROSS ALL THEMES */
        .brand-logo-container,
        .brand-logo-box,
        div[class*="brand-logo"] {
          background-color: #ffffff !important;
          background: #ffffff !important;
          border-radius: 12px !important;
          padding: 4px !important;
        }
      `;
    }
  }, [theme, themeRevision, customThemes]);

  const handleSetTheme = (newTheme) => {
    if (!newTheme) return;
    setTheme(newTheme);
    MiamoStore.saveTheme(newTheme);
    if (currentUser?.user_email && accounts && accounts[currentUser.user_email]) {
      const updatedUser = { ...accounts[currentUser.user_email], theme: newTheme };
      const updatedAccounts = { ...accounts, [currentUser.user_email]: updatedUser };
      MiamoStore.saveAccounts(updatedAccounts);
      setAccounts(updatedAccounts);
      MiamoStore.saveSession(updatedUser);
    }
  };

  // Force CSS re-injection when theme colors are edited (same key, new colors)
  const handleThemeRevisionBump = () => setThemeRevision(r => r + 1);

  // ─── 12-Hour Sync Timer (Auto-Sync & Reset on 00:00:00) ───
  const [syncState, setSyncState] = useState(() => MiamoStore.getSyncState());
  const [timerCountdownStr, setTimerCountdownStr] = useState("12:00:00");

  useEffect(() => {
    const updateTimer = () => {
      const stored = MiamoStore.getSyncState();
      let target = stored?.next_sync_timestamp;

      // ⚡ If 12 hours completed (or target is missing/past), AUTO-SYNC & RESTART 12-HOUR COUNTDOWN!
      if (!target || target <= Date.now()) {
        const nextSync = Date.now() + 12 * 60 * 60 * 1000;
        const newState = {
          last_synced: new Date().toLocaleString(),
          last_synced_timestamp: Date.now(),
          next_sync_timestamp: nextSync,
          sync_status: "Active (12-Hour Auto Sync Enabled)"
        };
        MiamoStore.saveSyncState(newState);
        setSyncState(newState);
        target = nextSync;
      }

      const diff = Math.max(0, target - Date.now());
      const hrs = Math.floor(diff / (1000 * 60 * 60));
      const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      const secs = Math.floor((diff % (1000 * 60)) / 1000);
      setTimerCountdownStr(`${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`);
    };
    updateTimer();
    const interval = setInterval(updateTimer, 1000);
    return () => clearInterval(interval);
  }, []); // Empty deps — reads directly from localStorage, never resets

  // Form & Input States
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [selectedPort, setSelectedPort] = useState(settings.dest_port || "Cotonou, Benin");
  const [portSearchQuery, setPortSearchQuery] = useState("");
  const [freightRates, setFreightRates] = useState(() => MiamoStore.getDefaultFreightRates());
  const [customPrices, setCustomPrices] = useState({});
  const [selectedProducts, setSelectedProductsState] = useState(() => MiamoStore.getSelectedProducts());
  const [clientName, setClientName] = useState("VALUED CUSTOMER");
  const [clientPhone, setClientPhone] = useState("");
  const [quoteLang, setQuoteLang] = useState("English");
  const [lightboxImg, setLightboxImg] = useState(null);
  const [chats, setChats] = useState(() => MiamoStore.getChats());
  const [auditLogs, setAuditLogs] = useState(() => MiamoStore.getAuditLogs());
  const [suggestions, setSuggestions] = useState(() => MiamoStore.getSuggestions());
  const [sentQuotations, setSentQuotations] = useState(() => MiamoStore.getSentQuotations());

  const handleTabSelect = (tabId) => {
    setActiveTab(tabId);
    if (window.innerWidth < 1024) {
      setSidebarCollapsed(true);
      setMobileSidebarOpen(false);
    }
  };

  const handleSetSelectedProducts = (valOrFn) => {
    setSelectedProductsState(prev => {
      const nextVal = typeof valOrFn === 'function' ? valOrFn(prev) : valOrFn;
      return nextVal;
    });
    MiamoStore.saveSelectedProducts(typeof valOrFn === 'function' ? valOrFn(selectedProducts) : valOrFn);
  };

  const currentUser = useMemo(() => {
    if (!session || !session.user_email) return null;
    return accounts[session.user_email] || null;
  }, [session, accounts]);

  const isAdmin = currentUser?.role === "Admin";
  const userHikePct = currentUser?.hike_pct ?? 5.0;

  // Log activity with real location
  const logActivity = (action, details = {}) => {
    const entry = {
      Timestamp: new Date().toLocaleString(),
      "User Email": session?.user_email || "Anonymous",
      Action: action,
      "Real Client IP": userLocation.ip || "—",
      Location: userLocation.city && userLocation.country
        ? `${userLocation.city}${userLocation.region ? ', ' + userLocation.region : ''}, ${userLocation.country}`
        : "Fetching...",
      "Customer Name": details.customer || "N/A",
      "Destination Port": details.port || selectedPort,
      Language: details.language || quoteLang,
      "Selected Products": details.products || "N/A",
      "Hike Margin (%)": `${userHikePct}%`
    };
    MiamoStore.addAuditLog(entry);
    setAuditLogs(MiamoStore.getAuditLogs());
  };

  // Login Handler
  const handleLogin = async (email, password) => {
    const cleanEmail = email.trim().toLowerCase();
    const acc = accounts[cleanEmail];
    if (!acc) return { success: false, msg: "User account not found!" };
    if (acc.status === "Blocked") return { success: false, msg: "🚫 Your account has been BLOCKED by Admin!" };
    if (acc.status === "Pending Approval") return { success: false, msg: "⏳ Account pending Admin approval!" };
    if (acc.password !== password) return { success: false, msg: "❌ Invalid Email or Password!" };

    // Fetch location on login
    const loc = await fetchUserLocation();
    setUserLocation(loc);

    // Save session & mark active session flag for tab
    const isFirstTime = !acc.has_completed_first_login;
    const updatedAcc = { ...acc, user_email: cleanEmail, has_completed_first_login: true };
    const updatedAccounts = { ...accounts, [cleanEmail]: updatedAcc };
    MiamoStore.saveAccounts(updatedAccounts);
    setAccounts(updatedAccounts);

    const newSession = { user_email: cleanEmail, role: acc.role, timestamp: Date.now() };
    MiamoStore.saveSession(newSession);
    sessionStorage.setItem("miamo_active_session_flag", "true");
    setSession(newSession);

    // Log with location
    const entry = {
      Timestamp: new Date().toLocaleString(),
      "User Email": cleanEmail,
      Action: "User Logged In",
      "Real Client IP": loc.ip || "—",
      Location: `${loc.city}${loc.region ? ', ' + loc.region : ''}, ${loc.country}`,
      "Customer Name": "N/A", "Destination Port": selectedPort, Language: quoteLang,
      "Selected Products": "N/A", "Hike Margin (%)": `${acc.hike_pct ?? 5}%`
    };
    MiamoStore.addAuditLog(entry);
    setAuditLogs(MiamoStore.getAuditLogs());

    // Trigger First-Time Welcome Fireworks Modal ONLY for brand new user login
    if (isFirstTime) {
      setFirstTimeUser(updatedAcc);
      setShowFirstTimeModal(true);
    } else {
      const doGreet = () => playGreeting(acc);
      if (window.speechSynthesis.getVoices().length > 0) doGreet();
      else window.speechSynthesis.onvoiceschanged = doGreet;
    }
    return { success: true };
  };

  const handleLogout = () => {
    const user = currentUser;
    if (user) playFarewell(user);
    setTimeout(() => {
      logActivity("User Logged Out");
      MiamoStore.clearSession();
      setSession(null);
      setAdminUnlocked(false);
      setShowProfileModal(false);
      setShowLogoutConfirm(false);
    }, 1200);
  };

  // Price Calculation Engine
  const calculatedQuoteData = useMemo(() => {
    const hikeMultiplier = 1 + (userHikePct / 100);
    const norm = (s) => (s || '').toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]/g, '');
    const countryRates = MiamoStore.getCountryFreightRates() || {};
    const destNorm = norm(selectedPort);
    const destCountryNorm = norm((selectedPort || '').split(',')[1] || '');
    const findDestKey = (matrix) => {
      const keys = Object.keys(matrix || {});
      let hit = keys.find(k => norm(k) === destNorm);
      if (hit) return hit;
      hit = keys.find(k => {
        const parts = (k || '').split(',');
        return parts.length > 1 && destCountryNorm && norm(parts[1]) === destCountryNorm;
      });
      if (hit) return hit;
      hit = keys.find(k => destNorm && (norm(k).includes(destNorm) || destNorm.includes(norm(k))));
      return hit;
    };
    return selectedProducts.map(pName => {
      const specs = window.PRODUCT_CATALOG[pName];
      if (!specs) return null;
      const basePrice = customPrices[pName] !== undefined ? customPrices[pName] : specs.default_price;
      const origin = (specs.origin || 'CHINA').toUpperCase();
      const finalFob = basePrice * hikeMultiplier;
      const originTitle = origin.charAt(0) + origin.slice(1).toLowerCase();
      const matrix = countryRates[originTitle] || countryRates[origin] || {};
      const destKey = findDestKey(matrix);
      const matrixRate = destKey ? Number(matrix[destKey]) : NaN;
      const userRate = Number(freightRates[origin]);
      let freightVal;
      if (!isNaN(matrixRate) && matrixRate > 0) freightVal = matrixRate;
      else if (!isNaN(userRate) && userRate > 0) freightVal = userRate;
      else freightVal = 2500;
      const perCartonFreight = freightVal / (specs.cartons_per_20ft || 1000);
      const finalCif = finalFob + perCartonFreight;
      return { name: pName, basePrice, origin, cartons: specs.cartons_per_20ft, details: specs.details, fob: finalFob, cif: finalCif };
    }).filter(Boolean);
  }, [customPrices, userHikePct, freightRates, selectedProducts, selectedPort]);

  // PDF Export Engine
  const handleGeneratePdf = () => {
    const element = document.getElementById("pdf-render-capture");
    if (!element) return;
    try {
      html2canvas(element, { scale: 2, useCORS: true, allowTaint: true }).then(canvas => {
        const imgData = canvas.toDataURL("image/png");
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF("p", "mm", "a4");
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = pdf.internal.pageSize.getHeight();
        const imgHeightMm = (canvas.height * pdfWidth) / canvas.width;
        const ratio = pdfWidth / canvas.width;
        const scaledH = canvas.height * ratio;

        if (scaledH <= pdfHeight) {
          pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, imgHeightMm);
        } else {
          const pageImgH = pdfHeight * (canvas.width / pdfWidth);
          let renderedH = 0;
          let first = true;
          while (renderedH < canvas.height) {
            const sliceH = Math.min(pageImgH, canvas.height - renderedH);
            const sliceCanvas = document.createElement("canvas");
            sliceCanvas.width = canvas.width;
            sliceCanvas.height = sliceH;
            const ctx = sliceCanvas.getContext("2d");
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, sliceCanvas.width, sliceCanvas.height);
            ctx.drawImage(canvas, 0, renderedH, canvas.width, sliceH, 0, 0, canvas.width, sliceH);
            const sliceData = sliceCanvas.toDataURL("image/png");
            if (!first) pdf.addPage();
            pdf.addImage(sliceData, "PNG", 0, 0, pdfWidth, sliceH * ratio);
            first = false;
            renderedH += sliceH;
          }
        }

        pdf.save(`Quotation_${selectedPort.split(',')[0]}_${quoteLang}.pdf`);
        MiamoStore.incrementQuoteRef();
        setSettings(MiamoStore.getSettings());
        logActivity("Downloaded PDF Quotation", { customer: clientName, port: selectedPort, products: selectedProducts.join(", ") });
      }).catch(err => {
        console.error("[PDF] Render failed:", err);
        alert("❌ PDF generation failed. Please check your internet connection (product images may fail to load) and try again.");
      });
    } catch (err) {
      console.error("[PDF] Unexpected error:", err);
      alert("❌ PDF generation failed. Please try again.");
    }
  };

  const handleShareWhatsapp = () => {
    const cleanPhone = clientPhone.replace(/[^0-9]/g, '');
    const refNo = MiamoStore.getNextQuoteRef();
    const message = `Dear ${clientName},\n\nGreetings from Miamo Foods Exports! 🚀\n\nPlease find our official Price Quotation (Ref: ${refNo}) for destination port ${selectedPort}.\n\nThank you,\n${currentUser?.display_name || 'Miamo Exports'}\nMiamo Foods Exports`;
    window.open(`https://api.whatsapp.com/send?phone=${cleanPhone}&text=${encodeURIComponent(message)}`, "_blank");
    MiamoStore.addSentQuotation({ ref_no: refNo, client_name: clientName, client_phone: clientPhone, timestamp: new Date().toLocaleString(), dest_port: selectedPort, sent_by: currentUser?.display_name || "User" });
    setSentQuotations(MiamoStore.getSentQuotations());
    MiamoStore.incrementQuoteRef();
    setSettings(MiamoStore.getSettings());
    logActivity("Sent WhatsApp Quotation", { customer: clientName, port: selectedPort });
  };

  // ─── Auth Screen ───
  if (!session) {
    return (
      <div className="min-h-screen bg-slate-950 flex items-center justify-center p-4">
        <div className="max-w-md w-full glass-panel rounded-2xl p-8 border border-rose-500/20 shadow-2xl shadow-rose-900/20 text-center">
          <div className="w-16 h-16 bg-rose-600/20 border border-rose-500 text-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 font-black text-2xl">MF</div>
          <h1 className="text-2xl font-extrabold text-white mb-1">MIAMO FOODS EXPORTS</h1>
          <p className="text-xs text-rose-400 font-bold uppercase tracking-widest mb-6">BONHEUR AVEC SANTE</p>
          <p className="text-slate-400 text-sm mb-6">Member Login & Authentication Portal</p>
          <LoginForm onLogin={handleLogin} onRegister={(data) => {
            const cleanEmail = (data.email || '').trim().toLowerCase();
            if (accounts[cleanEmail]) {
              alert("❌ This email is already registered! Please login with your existing account.");
              return;
            }
            const accs = { ...accounts };
            accs[cleanEmail] = { password: data.password, role: "User", hike_pin: "1234", hike_pct: 5.0, status: "Pending Approval", display_name: data.display_name, designation: data.designation, member_code: MiamoStore.getNextMemberCode() };
            MiamoStore.saveAccounts(accs);
            setAccounts(accs);
            alert("✅ Registration submitted! Account pending Admin approval.");
          }} />
        </div>
      </div>
    );
  }

  // Get font CSS for current brand font
  const brandFontCss = FONT_OPTIONS.find(f => f.value === (settings?.brand_font_family || 'Inter'))?.css || "'Inter', sans-serif";

  return (
    <div className="app-main-layout flex h-screen overflow-hidden text-slate-100">
      {/* Mobile App Splash Animation Screen (Phone Only) */}
      {showMobileSplash && (
        <div className="fixed inset-0 z-50 bg-slate-950 flex flex-col items-center justify-center p-6 text-center animate-fade-in">
          <div className="relative mb-6">
            <div className="w-24 h-24 bg-gradient-to-tr from-rose-600 via-rose-500 to-amber-500 rounded-3xl p-1 shadow-2xl shadow-rose-900/60 animate-bounce">
              <div className="w-full h-full bg-slate-950 rounded-[22px] flex items-center justify-center overflow-hidden p-2">
                {settings?.mobile_splash_gif_url || settings?.brand_logo_url ? (
                  <img src={settings.mobile_splash_gif_url || settings.brand_logo_url} alt="Splash Logo" className="w-full h-full object-contain" />
                ) : (
                  <span className="font-black text-3xl text-rose-500 tracking-tighter">MF</span>
                )}
              </div>
            </div>
            <span className="absolute -bottom-2 -right-2 w-6 h-6 rounded-full bg-emerald-500 border-2 border-slate-950 animate-ping"></span>
          </div>
          <h2 className="text-2xl font-extrabold text-white tracking-wider uppercase mb-1 font-sans">
            {settings?.portal_title || "MIAMO FOODS EXPORTS"}
          </h2>
          <p className="text-xs text-rose-400 font-bold uppercase tracking-widest mb-6">BONHEUR AVEC SANTE</p>
          <div className="flex items-center gap-2 px-4 py-2 bg-slate-900/80 rounded-full border border-slate-800 text-xs text-slate-300">
            <span className="w-2 h-2 rounded-full bg-rose-500 animate-pulse"></span>
            <span className="font-semibold">Loading Portal...</span>
          </div>
        </div>
      )}
      {/* Sidebar */}
      {/* Mobile Sidebar Backdrop */}
      {mobileSidebarOpen && (
        <div
          className="fixed inset-0 z-30 bg-black/60 lg:hidden"
          onClick={() => setMobileSidebarOpen(false)}
        />
      )}

      <aside className={`fixed inset-y-0 left-0 z-40 w-72 bg-slate-900 border-r border-slate-800 flex flex-col transition-transform duration-300 ${mobileSidebarOpen ? 'translate-x-0' : (sidebarCollapsed ? '-translate-x-full' : '-translate-x-full lg:translate-x-0')}`}>
        {/* Brand Header */}
        <div className="p-6 border-b border-slate-800/80 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div
              className={`flex items-center justify-center overflow-hidden flex-shrink-0 shadow-md ${
                settings?.brand_logo_shape === "rounded-full" ? "rounded-full" :
                settings?.brand_logo_shape === "rounded-2xl" ? "rounded-2xl" :
                settings?.brand_logo_shape === "rounded-lg" ? "rounded-lg" :
                settings?.brand_logo_shape === "square" ? "rounded-none" : "rounded-full"
              } ${settings?.brand_logo_url ? 'bg-transparent' : 'bg-white'}`}
              style={{
                width: `${settings?.brand_logo_size_px || (settings?.brand_logo_size === 'small' ? 32 : settings?.brand_logo_size === 'large' ? 60 : settings?.brand_logo_size === 'xl' ? 76 : settings?.brand_logo_size === 'jumbo' ? 96 : 44)}px`,
                height: `${settings?.brand_logo_size_px || (settings?.brand_logo_size === 'small' ? 32 : settings?.brand_logo_size === 'large' ? 60 : settings?.brand_logo_size === 'xl' ? 76 : settings?.brand_logo_size === 'jumbo' ? 96 : 44)}px`
              }}
            >
              {settings?.brand_logo_url ? (
                <img src={settings.brand_logo_url} alt="Brand Logo" className="w-full h-full object-contain" style={{ display: 'block' }} />
              ) : (
                <span className="bg-white w-full h-full flex items-center justify-center font-black text-rose-600 text-xs">MF</span>
              )}
            </div>
            <div>
              <h2 className="font-black text-transparent bg-clip-text bg-gradient-to-r from-white via-slate-100 to-rose-200 text-sm tracking-wider uppercase font-sans drop-shadow-sm">
                {settings?.portal_title || "MIAMO EXPORTS"}
              </h2>
              <p className="text-[9px] text-rose-400 font-extrabold tracking-widest uppercase bg-rose-950/80 px-2 py-0.5 rounded border border-rose-800/60 inline-block shadow-sm">
                {settings?.portal_subtitle || "QUOTATION PORTAL"}
              </p>
            </div>
          </div>
          <button onClick={() => setMobileSidebarOpen(false)} className="lg:hidden text-slate-400 hover:text-white">
            <Icon name="x" className="w-5 h-5" />
          </button>
        </div>

        {/* User Profile Card */}
        <div className="p-4 mx-4 my-4 glass-card rounded-xl border border-slate-800 flex items-center gap-3 cursor-pointer hover:border-rose-500/40" onClick={() => setShowProfileModal(true)}>
          <div className="w-11 h-11 bg-white rounded-full flex items-center justify-center font-bold text-rose-600 text-lg border-2 border-white/80 shadow-md overflow-hidden flex-shrink-0">
            {currentUser?.avatar_url ? (
              <img src={currentUser.avatar_url} alt="Avatar" className="w-full h-full object-cover" style={{background:'white'}} />
            ) : (
              currentUser?.display_name?.[0]?.toUpperCase() || 'U'
            )}
          </div>
          <div className="flex-1 min-w-0">
            <h4 className="font-bold text-slate-100 text-sm truncate">{currentUser?.display_name}</h4>
            <p className="text-xs text-slate-400 truncate">{currentUser?.designation}</p>
            <span className="inline-block mt-1 px-2 py-0.5 bg-rose-950/80 text-rose-400 text-[10px] font-bold rounded border border-rose-800/50">{currentUser?.member_code}</span>
          </div>
        </div>

        {/* Navigation Menu — Clean Icons */}
        <nav className="flex-1 px-4 space-y-1 overflow-y-auto">
          <NavItem id="welcome"   label="Executive Welcome Hub"     icon="home"          active={activeTab} onClick={handleTabSelect} />
          <NavItem id="generator" label="Quotation Generator"       icon="file-text"     active={activeTab} onClick={handleTabSelect} />
          {!isAdmin && <NavItem id="margin" label="Margin & Profit Controller" icon="trending-up" active={activeTab} onClick={handleTabSelect} badge={hikeUnlocked ? "UNLOCKED" : "LOCKED"} />}
          <NavItem id="admin"     label="Admin Control Center"      icon="shield-alert"  active={activeTab} onClick={handleTabSelect} badge={isAdmin ? (adminUnlocked ? "UNLOCKED" : "LOCKED") : "ADMIN"} />
          <NavItem id="chat"      label="Team Chat & Directory"     icon="message-square" active={activeTab} onClick={handleTabSelect} />
          <NavItem id="contact"   label="Contact Desk & Feedback"  icon="help-circle"   active={activeTab} onClick={handleTabSelect} />

          {/* Destination Port & Freight (shown only in generator tab) */}
          {activeTab === "generator" && (
            <div className="mt-4 p-4 bg-slate-900/90 rounded-2xl border border-slate-800 space-y-4 text-xs">
              <div className="space-y-2">
                <h4 className="font-bold text-rose-400 text-xs flex items-center gap-1.5"><span>⚙️</span> Destination Port</h4>
                <input
                  type="text"
                  value={portSearchQuery || ""}
                  onChange={e => setPortSearchQuery(e.target.value)}
                  placeholder="Type e.g. lome, egypt..."
                  className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white placeholder-slate-500 focus:border-rose-500 focus:outline-none"
                />
                <select
                  value={selectedPort}
                  onChange={e => setSelectedPort(e.target.value)}
                  className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-medium focus:border-rose-500 focus:outline-none"
                >
                  {window.DESTINATION_PORTS.filter(p => !portSearchQuery || p.toLowerCase().includes(portSearchQuery.toLowerCase())).map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>

              {/* Quick Ocean Freight Rates in Sidebar — Enlarged & Easy Tap */}
              <div className="space-y-2 pt-3 border-t border-slate-800/80">
                <div className="flex items-center justify-between text-[11px] font-bold text-slate-300">
                  <span className="flex items-center gap-1"><span>🚢</span> Ocean Freight</span>
                  <span className="text-[10px] text-rose-400 font-normal">({(selectedPort || '').split(',')[0]})</span>
                </div>
                <div className="space-y-2">
                  {["CHINA", "MALAYSIA", "OMAN"].map(origin => (
                    <div key={origin} className="flex items-center justify-between bg-slate-950 px-3 py-2 rounded-xl border border-slate-800/80 text-[11px]">
                      <span className="font-mono font-bold text-rose-400 text-xs">{origin}</span>
                      <div className="flex items-center gap-1">
                        <span className="text-slate-400 font-bold">$</span>
                        <input
                          type="number"
                          value={freightRates[origin] !== undefined ? freightRates[origin] : ''}
                          placeholder="2500"
                          onChange={e => {
                            const val = e.target.value === '' ? '' : parseFloat(e.target.value);
                            const updated = { ...freightRates, [origin]: val };
                            setFreightRates(updated);
                            MiamoStore.saveDefaultFreightRates(updated);
                          }}
                          className="w-24 bg-slate-900 border border-slate-700 rounded-lg px-2.5 py-1.5 text-right font-mono font-extrabold text-amber-300 text-xs focus:outline-none focus:border-rose-500 focus:ring-1 focus:ring-rose-500 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none cursor-text"
                        />
                        <span className="text-slate-500 text-[10px] font-bold">USD</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </nav>

        {/* Live Location Display in Sidebar Footer */}
        <div className="px-4 py-2 border-t border-slate-800/60">
          <div className="flex items-center gap-2 text-[10px] text-slate-500">
            {userLocation.flag && <img src={userLocation.flag} alt="" className="w-4 h-3 rounded-sm" />}
            <span className="truncate">{userLocation.city ? `${userLocation.city}, ${userLocation.country}` : 'Locating...'}</span>
          </div>
        </div>

        <div className="p-4 border-t border-slate-800 flex items-center justify-between text-xs text-slate-400">
          <button onClick={() => setShowLogoutConfirm(true)} className="flex items-center gap-2 text-rose-400 hover:text-rose-300 font-semibold">
            <Icon name="log-out" className="w-4 h-4" /> Logout
          </button>
          <span>v3.0.0</span>
        </div>
      </aside>

      {/* Main Content Area */}
      <main className={`flex-1 flex flex-col min-w-0 overflow-hidden transition-all duration-300 ${sidebarCollapsed ? 'lg:pl-0' : 'lg:pl-72'}`} onClick={() => { if (mobileSidebarOpen) setMobileSidebarOpen(false); }}>
        {/* Top Header */}
        <header
          className={`h-16 px-6 flex items-center justify-between sticky top-0 z-30 transition-all ${
            settings?.header_bg_style === "deep_navy" ? "bg-slate-950/90 border-b border-indigo-900/60" :
            settings?.header_bg_style === "rose_glass" ? "bg-rose-950/40 border-b border-rose-900/40 backdrop-blur-md" :
            settings?.header_bg_style === "midnight_purple" ? "bg-purple-950/40 border-b border-purple-900/40 backdrop-blur-md" :
            settings?.header_bg_style === "emerald_dark" ? "bg-emerald-950/40 border-b border-emerald-900/40 backdrop-blur-md" :
            "bg-slate-900/60 border-b border-slate-800 backdrop-blur-md"
          }`}
          style={settings?.header_bg_style === "custom" && settings?.header_custom_hex ? { backgroundColor: settings.header_custom_hex } : {}}
        >
          <div className="flex items-center gap-3.5">
            {/* Hamburger */}
            <button
              onClick={() => {
                if (window.innerWidth < 1024) {
                  // Mobile: toggle mobile sidebar overlay
                  setMobileSidebarOpen(prev => !prev);
                } else {
                  // Desktop: collapse/expand sidebar
                  setSidebarCollapsed(prev => !prev);
                }
              }}
              className="p-2.5 rounded-xl bg-slate-800/80 hover:bg-rose-600 text-white font-black transition-all cursor-pointer flex items-center justify-center shadow-md border border-slate-700 hover:border-rose-500"
              title="Toggle Navigation Menu (☰)"
            >
              <div className="flex flex-col gap-1 w-4 h-4 justify-center items-center">
                <span className="w-4 h-0.5 bg-white rounded-full"></span>
                <span className="w-4 h-0.5 bg-white rounded-full"></span>
                <span className="w-4 h-0.5 bg-white rounded-full"></span>
              </div>
            </button>

            {/* Header Brand Logo */}
            <div className="flex items-center gap-3">
              <div
                className="brand-logo-container flex items-center justify-center overflow-hidden flex-shrink-0 shadow-md rounded-2xl bg-white p-1"
                style={{
                  backgroundColor: '#ffffff',
                  background: '#ffffff',
                  width: `${settings?.brand_logo_size_px || (settings?.brand_logo_size === 'small' ? 32 : settings?.brand_logo_size === 'large' ? 60 : settings?.brand_logo_size === 'xl' ? 76 : settings?.brand_logo_size === 'jumbo' ? 96 : 44)}px`,
                  height: `${settings?.brand_logo_size_px || (settings?.brand_logo_size === 'small' ? 32 : settings?.brand_logo_size === 'large' ? 60 : settings?.brand_logo_size === 'xl' ? 76 : settings?.brand_logo_size === 'jumbo' ? 96 : 44)}px`
                }}
              >
                {settings?.brand_logo_url ? (
                  <img src={settings.brand_logo_url} alt="Brand Logo" className="w-full h-full object-contain bg-white" style={{ display: 'block', backgroundColor: '#ffffff' }} />
                ) : (
                  <span className="bg-white w-full h-full flex items-center justify-center font-black text-rose-600 text-xs">MF</span>
                )}
              </div>

              <div>
                <h1
                  className={`tracking-tight font-black ${
                    settings?.brand_font_size === "small" ? "text-xs md:text-sm" :
                    settings?.brand_font_size === "large" ? "text-base md:text-lg" :
                    settings?.brand_font_size === "xl" ? "text-lg md:text-xl" : "text-sm md:text-base"
                  } ${
                    settings?.brand_title_color === "gold_luxury" ? "bg-gradient-to-r from-amber-200 via-amber-400 to-yellow-500 bg-clip-text text-transparent" :
                    settings?.brand_title_color === "emerald_glow" ? "bg-gradient-to-r from-emerald-300 via-teal-400 to-green-500 bg-clip-text text-transparent" :
                    settings?.brand_title_color === "pure_white" ? "text-white" :
                    settings?.brand_title_color === "cyber_cyan" ? "bg-gradient-to-r from-cyan-300 via-sky-400 to-blue-500 bg-clip-text text-transparent" :
                    "text-white"
                  }`}
                  style={{ fontFamily: brandFontCss }}
                >
                  {settings?.brand_title_text || "MIAMO FOODS EXPORTS"}
                </h1>
                <p className="text-[10px] text-slate-400 font-medium hidden md:block">
                  {settings?.brand_subtitle_text || "Price Quotation & Management Portal"} • {
                    activeTab === "welcome" ? "Executive Welcome Hub" :
                    activeTab === "generator" ? "Quotation Generator" :
                    activeTab === "freight" ? "Freight Rates" :
                    activeTab === "margin" ? "Margin Controller" :
                    activeTab === "admin" ? "Admin Control Center" :
                    activeTab === "chat" ? "Team Chat" : "Contact Desk"
                  }
                </p>
              </div>
            </div>
          </div>

          {/* Quick Status Pills */}
          <div className={`flex items-center gap-3 ${
            settings?.pills_location === "center" ? "mx-auto" :
            settings?.pills_location === "left" ? "mr-auto ml-4" : "ml-auto"
          }`}>
            {/* 12-Hour Sync Pill */}
            {settings?.show_sync_pill !== false && (
              <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs text-slate-300 ${
                settings?.pills_style === "vibrant_gradient" ? "bg-gradient-to-r from-rose-950/80 to-indigo-950/80 border border-rose-700/50 shadow-md" :
                settings?.pills_style === "neon_border" ? "bg-slate-950 border border-emerald-500/60 shadow-[0_0_10px_rgba(16,185,129,0.2)]" :
                settings?.pills_style === "minimal" ? "bg-slate-900/40 border border-slate-800/40" :
                "bg-slate-900/90 border border-slate-800 shadow-sm"
              }`} title="Google Sheets 12-Hour Price Auto Sync Timer">
                <span className="text-emerald-400 font-bold">⚡ 12h Sync:</span>
                <span className="font-mono font-bold text-amber-400">{timerCountdownStr}</span>
              </div>
            )}
            {/* Location Pill */}
            {userLocation.country !== '...' && (
              <div className="hidden lg:flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs text-slate-300 bg-slate-900/90 border border-slate-800 shadow-sm" title={`Your Location: ${userLocation.city}, ${userLocation.country}`}>
                {userLocation.flag && <img src={userLocation.flag} alt="" className="w-4 h-3 rounded-sm" />}
                <span className="text-slate-400">{userLocation.city}, {userLocation.country}</span>
              </div>
            )}



            {settings?.show_system_badge !== false && (
              <span className="hidden md:inline-flex items-center gap-1.5 px-3 py-1 bg-emerald-950/60 text-emerald-400 text-xs font-semibold rounded-full border border-emerald-800/40">
                <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span> Live System
              </span>
            )}

            <button onClick={() => setShowProfileModal(true)} className="p-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300">
              <Icon name="user" className="w-5 h-5" />
            </button>
          </div>
        </header>

        {/* View Router */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {activeTab === "welcome" && <WelcomeHubView settings={settings} onOpenLightbox={setLightboxImg} userHikePct={userHikePct} customPrices={customPrices} />}

          {activeTab === "generator" && (
            <QuotationGeneratorView
              selectedPort={selectedPort} setSelectedPort={setSelectedPort}
              customPrices={customPrices} setCustomPrices={setCustomPrices}
              selectedProducts={selectedProducts} setSelectedProducts={handleSetSelectedProducts}
              clientName={clientName} setClientName={setClientName}
              clientPhone={clientPhone} setClientPhone={setClientPhone}
              quoteLang={quoteLang} setQuoteLang={setQuoteLang}
              userHikePct={userHikePct} calculatedData={calculatedQuoteData}
              onPreviewPdf={() => setShowPdfPreview(true)}
              onGeneratePdf={handleGeneratePdf}
              onShareWhatsapp={handleShareWhatsapp}
            />
          )}

          {activeTab === "margin" && !isAdmin && (
            <MarginControllerView unlocked={hikeUnlocked} setUnlocked={setHikeUnlocked} currentUser={currentUser} accounts={accounts} setAccounts={setAccounts} userHikePct={userHikePct} />
          )}

          {activeTab === "admin" && (
            <ErrorBoundary>
              <AdminCenterView
                isAdmin={isAdmin} unlocked={adminUnlocked} setUnlocked={setAdminUnlocked}
                accounts={accounts} setAccounts={setAccounts}
                settings={settings} setSettings={setSettings}
                auditLogs={auditLogs} suggestions={suggestions} sentQuotations={sentQuotations}
                theme={theme} setTheme={setTheme} handleSetTheme={handleSetTheme}
                customThemes={customThemes} setCustomThemes={setCustomThemes}
                hikeUnlocked={hikeUnlocked} setHikeUnlocked={setHikeUnlocked}
                userHikePct={userHikePct} currentUser={currentUser}
                inactivityTimeout={inactivityTimeout}
                setInactivityTimeout={(mins) => { setInactivityTimeout(mins); MiamoStore.saveInactivityTimeout(mins); }}
                speakTextWithHumanVoice={speakTextWithHumanVoice}
                userLocation={userLocation}
              />
            </ErrorBoundary>
          )}

          {activeTab === "chat" && (
            <TeamChatView accounts={accounts} currentUser={currentUser} chats={chats} setChats={setChats} />
          )}

          {activeTab === "contact" && (
            <ContactDeskView onSubmitFeedback={(type, message) => {
              MiamoStore.addSuggestion({ type, message, user_email: currentUser?.display_name || "User", timestamp: new Date().toLocaleString(), status: "Pending Review" });
              setSuggestions(MiamoStore.getSuggestions());
              alert("✅ Feedback submitted to Admin Desk!");
            }} />
          )}
        </div>
      </main>

      {/* Hidden PDF Canvas */}
      <div className="fixed top-[-9999px] left-[-9999px]">
        <PdfTemplateRender
          captureId="pdf-render-capture"
          refNo={MiamoStore.getNextQuoteRef()} clientName={clientName}
          destPort={selectedPort} lang={quoteLang} data={calculatedQuoteData}
          brandLogoUrl={settings?.brand_logo_url}
          pdfBgTemplateUrl={settings?.pdf_bg_template_url}
          pdfBgStyle={settings?.pdf_bg_style}
        />
      </div>

      {/* Profile Modal */}
      {showProfileModal && (
        <ProfileModal
          user={currentUser} accounts={accounts} setAccounts={setAccounts}
          onSave={(updatedAcc) => {
            const updated = { ...accounts, [updatedAcc.user_email || currentUser.user_email]: updatedAcc };
            MiamoStore.saveAccounts(updated);
            MiamoStore.saveSession(updatedAcc);
            setAccounts(updated);
            setSession(prev => ({ ...prev, display_name: updatedAcc.display_name }));
          }}
          onClose={() => setShowProfileModal(false)}
        />
      )}

      {/* Logout Confirm Modal */}
      {showLogoutConfirm && (
        <div className="fixed inset-0 z-[60] modal-backdrop flex items-center justify-center p-4">
          <div className="max-w-sm w-full bg-slate-900 rounded-2xl p-8 border border-rose-800/60 text-center space-y-4 shadow-2xl">
            <div className="text-4xl">👋</div>
            <h3 className="text-lg font-bold text-white">Logout, {currentUser?.display_name?.split(' ')[0]}?</h3>
            <p className="text-sm text-slate-400">Are you sure you want to logout from the Miamo Portal?</p>
            <div className="flex gap-3 pt-2">
              <button onClick={handleLogout} className="flex-1 bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all">Yes, Logout</button>
              <button onClick={() => setShowLogoutConfirm(false)} className="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold py-3 rounded-xl border border-slate-700">Cancel</button>
            </div>
          </div>
        </div>
      )}

      {/* 🎆 First-Time User Celebration Fireworks Modal (30s Minimum Lock) */}
      {showFirstTimeModal && (
        <div
          className="fixed inset-0 z-[100] modal-backdrop flex items-center justify-center p-4 bg-black/85 backdrop-blur-md animate-fade-in"
          onClick={() => {
            if (firstTimeTimer === 0) handleCloseFirstTimeModal();
          }}
        >
          <div
            className="max-w-lg w-full bg-gradient-to-b from-slate-900 via-rose-950/40 to-slate-900 rounded-3xl p-6 sm:p-8 border-2 border-amber-400/80 shadow-[0_0_60px_rgba(245,158,11,0.4)] text-center space-y-5 relative overflow-hidden animate-scale-up"
            onClick={e => e.stopPropagation()}
          >
            {/* Sparkle Header */}
            <div className="flex items-center justify-center gap-2 text-amber-300 text-xs sm:text-sm font-black uppercase tracking-widest bg-amber-400/10 py-1.5 px-4 rounded-full border border-amber-400/30 w-fit mx-auto shadow-md">
              <span>✨</span>
              <span>{settings?.first_time_modal_title || "MIAMO FOODS EXPORTS"}</span>
              <span>✨</span>
            </div>

            {/* Big Headline & User Name */}
            <div className="space-y-1.5">
              <h1 className="text-4xl sm:text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-amber-200 via-amber-400 to-yellow-500 uppercase tracking-tight drop-shadow-lg">
                WELCOME
              </h1>
              <h2 className="text-2xl sm:text-3xl font-extrabold text-white tracking-wide uppercase drop-shadow-md">
                {firstTimeUser?.display_name || currentUser?.display_name || "MEMBER"}
              </h2>
            </div>

            {/* Custom Announcement Message */}
            <p className="text-xs sm:text-sm text-slate-200 leading-relaxed font-medium bg-slate-950/70 p-4 rounded-2xl border border-white/10 shadow-inner">
              {settings?.first_time_modal_message || "Welcome to your official MIAMO EXPORTS portal! Select products to build FOB/CIF price quotes in 1-Click."}
            </p>

            {/* Timer & Dismiss Controls */}
            <div className="pt-2">
              {firstTimeTimer > 0 ? (
                <div className="inline-flex items-center gap-2 px-5 py-3 rounded-full bg-amber-500/20 border border-amber-400/50 text-amber-300 text-xs font-bold shadow-lg animate-pulse">
                  <span className="w-2.5 h-2.5 rounded-full bg-amber-400 animate-ping"></span>
                  <span>🎆 Celebration Fireworks Active... (Locked for {firstTimeTimer}s)</span>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={handleCloseFirstTimeModal}
                  className="w-full py-3.5 px-6 bg-gradient-to-r from-amber-500 via-rose-600 to-amber-500 hover:from-amber-400 hover:to-rose-500 text-white text-xs sm:text-sm font-black rounded-2xl shadow-xl shadow-rose-900/50 cursor-pointer transform transition-transform hover:scale-[1.02] active:scale-95 animate-bounce"
                >
                  🚀 Tap Anywhere or Click Here to Enter Portal
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* PDF Preview Modal */}
      {showPdfPreview && (
        <div className="fixed inset-0 z-[60] modal-backdrop flex items-center justify-center p-4" onClick={() => setShowPdfPreview(false)}>
          <div className="max-w-4xl w-full bg-slate-900 rounded-2xl p-4 border border-slate-800 relative" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-base font-bold text-white">📄 PDF Preview</h3>
              <div className="flex gap-2">
                <button onClick={() => { setShowPdfPreview(false); handleGeneratePdf(); }} className="px-5 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-rose-900/30">⬇️ Download PDF</button>
                <button onClick={() => setShowPdfPreview(false)} className="p-2 bg-slate-800 text-slate-300 rounded-xl border border-slate-700"><Icon name="x" className="w-4 h-4" /></button>
              </div>
            </div>
            <div className="overflow-y-auto max-h-[80vh] rounded-xl bg-white">
              <PdfTemplateRender
                refNo={MiamoStore.getNextQuoteRef()} clientName={clientName}
                destPort={selectedPort} lang={quoteLang} data={calculatedQuoteData}
                brandLogoUrl={settings?.brand_logo_url}
                pdfBgTemplateUrl={settings?.pdf_bg_template_url}
                pdfBgStyle={settings?.pdf_bg_style}
              />
            </div>
          </div>
        </div>
      )}



      {/* Lightbox */}
      {lightboxImg && (
        <div className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4" onClick={() => setLightboxImg(null)}>
          <div className="max-w-3xl w-full bg-slate-900 rounded-2xl p-4 border border-slate-800 text-center relative" onClick={e => e.stopPropagation()}>
            <img src={lightboxImg} alt="Inspection Photo" className="max-h-[80vh] w-auto mx-auto rounded-lg" />
            <button onClick={() => setLightboxImg(null)} className="absolute top-4 right-4 bg-slate-800 text-white p-2 rounded-full"><Icon name="x" className="w-5 h-5" /></button>
          </div>
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// PROFILE MODAL — Edit own account details (display name, designation, password)
// ═══════════════════════════════════════════════════════════════
function ProfileModal({ user, accounts, setAccounts, onSave, onClose }) {
  const [displayName, setDisplayName] = useState(user?.display_name || "");
  const [designation, setDesignation] = useState(user?.designation || "");
  const [password, setPassword] = useState(user?.password || "");
  const [avatarUrl, setAvatarUrl] = useState(user?.avatar_url || "");
  const [err, setErr] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    const email = user?.user_email || "";
    if (!email || !accounts[email]) return setErr("Session account error!");
    if (!displayName.trim()) return setErr("Display name cannot be empty!");
    const updatedAcc = { ...user, display_name: displayName.trim(), designation: designation.trim() || "Sales Executive", password, avatar_url: avatarUrl.trim() };
    onSave(updatedAcc);
  };

  return (
    <div className="fixed inset-0 z-[60] modal-backdrop flex items-center justify-center p-4" onClick={onClose}>
      <div className="max-w-md w-full bg-slate-900 rounded-2xl p-6 border border-rose-800/60 shadow-2xl text-left" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-bold text-white flex items-center gap-2"><span>👤</span> My Profile</h3>
          <button onClick={onClose} className="p-2 bg-slate-800 text-slate-300 rounded-xl border border-slate-700"><Icon name="x" className="w-4 h-4" /></button>
        </div>
        {err && <div className="p-2.5 mb-3 bg-rose-950/80 border border-rose-800 text-rose-300 text-xs rounded-xl">{err}</div>}
        <form onSubmit={handleSubmit} className="space-y-3">
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Display Name</label>
            <input type="text" value={displayName} onChange={e => setDisplayName(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500 focus:outline-none" required />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Designation</label>
            <input type="text" value={designation} onChange={e => setDesignation(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500 focus:outline-none" />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Password</label>
            <input type="text" value={password} onChange={e => setPassword(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500 focus:outline-none" required />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Avatar URL (optional)</label>
            <input type="url" value={avatarUrl} onChange={e => setAvatarUrl(e.target.value)} placeholder="https://..." className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500 focus:outline-none" />
          </div>
          <div className="flex gap-3 pt-2">
            <button type="submit" className="flex-1 bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all">💾 Save Profile</button>
            <button type="button" onClick={onClose} className="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold py-3 rounded-xl border border-slate-700">Cancel</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// NAV ITEM — Clean Icon + Label Design
// ═══════════════════════════════════════════════════════════════
function NavItem({ id, label, icon, active, onClick, badge }) {
  const isActive = active === id;
  return (
    <button
      onClick={() => onClick(id)}
      className={`w-full flex items-center justify-between px-3 py-2.5 rounded-xl font-medium text-sm transition-all ${
        isActive
          ? 'bg-gradient-to-r from-rose-600 to-rose-700 text-white shadow-lg shadow-rose-900/30'
          : 'text-slate-400 hover:bg-slate-800/60 hover:text-slate-200'
      }`}
    >
      <div className="flex items-center gap-3">
        <Icon name={icon} className="w-4 h-4 flex-shrink-0" />
        <span className="text-xs">{label}</span>
      </div>
      {badge && (
        <span className={`text-[9px] font-bold px-1.5 py-0.5 rounded ${isActive ? 'bg-white/20 text-white' : 'bg-slate-800 text-rose-400'}`}>
          {badge}
        </span>
      )}
    </button>
  );
}

// ═══════════════════════════════════════════════════════════════
// MARGIN CONTROLLER VIEW
// ═══════════════════════════════════════════════════════════════
function MarginControllerView({ unlocked, setUnlocked, currentUser, accounts, setAccounts, userHikePct }) {
  const [pinInput, setPinInput] = useState("");
  const [pinErr, setPinErr] = useState("");
  const [marginInput, setMarginInput] = useState(userHikePct ?? 5.0);
  const expectedHikePin = currentUser?.hike_pin || "282911";

  const handleUpdateMargin = (e) => {
    e.preventDefault();
    const val = parseFloat(marginInput);
    if (isNaN(val) || val < 0) return alert("Please enter a valid margin percentage!");
    const email = currentUser?.user_email || "";
    if (!email || !accounts[email]) return alert("Session account error!");
    const updated = { ...accounts, [email]: { ...accounts[email], hike_pct: val } };
    MiamoStore.saveAccounts(updated);
    setAccounts(updated);
    alert(`✅ Hike Margin updated to +${val}%!`);
  };

  if (!unlocked) {
    return (
      <div className="max-w-md mx-auto glass-panel p-8 rounded-2xl border border-slate-800 text-center space-y-4">
        <div className="w-14 h-14 bg-rose-600/20 border border-rose-500 text-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-2">
          <Icon name="lock" className="w-7 h-7" />
        </div>
        <h3 className="text-xl font-bold text-white">Margin Security Lock</h3>
        <p className="text-xs text-slate-400">Enter Security PIN to access Margin Controller:</p>
        {pinErr && <div className="p-2.5 bg-rose-950/80 border border-rose-800 text-rose-300 text-xs rounded-xl">{pinErr}</div>}
        <form onSubmit={(e) => { e.preventDefault(); setPinErr(""); if (pinInput.trim() === expectedHikePin.trim()) { setUnlocked(true); } else { setPinErr("❌ Incorrect Security PIN!"); setPinInput(""); } }} className="space-y-3">
          {/* PIN Input — Backspace Fixed */}
          <input
            type="password"
            value={pinInput}
            onChange={e => setPinInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Backspace') { e.stopPropagation(); } }}
            placeholder="••••"
            className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-center text-xl tracking-widest text-white focus:outline-none focus:border-rose-500"
            required autoFocus
          />
          <button type="submit" className="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all">
            🔓 Access Margin Controller
          </button>
        </form>
      </div>
    );
  }

  return (
    <div className="max-w-xl mx-auto glass-panel p-8 rounded-2xl border border-slate-800 space-y-6 text-left">
      <div className="flex items-center justify-between border-b border-slate-800 pb-4">
        <div>
          <h3 className="text-xl font-bold text-white">📈 Margin & Profit Controller</h3>
          <p className="text-xs text-slate-400">Configure your active price hike margin percentage.</p>
        </div>
        <button onClick={() => setUnlocked(false)} className="px-3 py-1.5 bg-slate-900 text-slate-300 text-xs font-bold rounded-lg border border-slate-700">🔒 Lock Panel</button>
      </div>
      <div className="p-4 bg-slate-900 rounded-xl border border-slate-800 space-y-2">
        <p className="text-xs text-slate-300"><strong>Current Active Hike Margin:</strong> <span className="text-amber-400 font-extrabold text-sm">+{userHikePct}%</span></p>
        <p className="text-[11px] text-slate-400">This margin is automatically applied to calculate FOB & CIF prices in Quotation Generator without being displayed to customers.</p>
      </div>
      <form onSubmit={handleUpdateMargin} className="space-y-4">
        <div>
          <label className="text-xs font-semibold text-slate-300 block mb-1">Set New Margin Percentage (%)</label>
          <div className="flex gap-3">
            <input type="number" step="0.1" value={marginInput} onChange={e => setMarginInput(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white font-mono font-bold" required />
            <button type="submit" className="px-6 py-2.5 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-rose-900/30">💾 Save Margin</button>
          </div>
        </div>
      </form>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// LOGIN FORM
// ═══════════════════════════════════════════════════════════════
function LoginForm({ onLogin, onRegister }) {
  const [mode, setMode] = useState("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [designation, setDesignation] = useState("Sales Executive");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [otpSent, setOtpSent] = useState(false);
  const [otpInput, setOtpInput] = useState("");
  const [err, setErr] = useState("");
  const [msg, setMsg] = useState("");
  const [loading, setLoading] = useState(false);

  const roleSuggestions = useMemo(() => {
    const q = (designation || "").trim().toLowerCase();
    const master = window.DEFAULT_MASTER_ROLES || ["Export Director", "Sales Head", "International Business Manager", "Logistics Specialist", "Documentation Officer", "Finance Manager", "Regional Sales Representative"];
    if (!q) return master;
    return master.filter(r => r.toLowerCase().includes(q));
  }, [designation]);

  const handleRequestOtp = (e) => {
    e.preventDefault(); setErr(""); setMsg("");
    if (!email || !password || !name) return setErr("Please fill all required registration fields!");
    const code = MiamoStore.generateOtp(email);
    setOtpSent(true);
    setMsg(`📧 Verification OTP sent to ${email}! (Simulated OTP: ${code})`);
  };

  const handleVerifyAndRegister = (e) => {
    e.preventDefault(); setErr("");
    const verifyRes = MiamoStore.verifyOtp(email, otpInput);
    if (!verifyRes.success) return setErr(verifyRes.msg);
    onRegister({ email, password, display_name: name, designation });
    setMode("login"); setOtpSent(false); setOtpInput("");
    setMsg("✅ Email verified! Registration submitted for Admin Approval.");
  };

  const handleSubmitLogin = async (e) => {
    e.preventDefault(); setErr(""); setLoading(true);
    const res = await onLogin(email, password);
    setLoading(false);
    if (!res.success) setErr(res.msg);
  };

  return (
    <div className="space-y-4 text-left">
      {err && <div className="p-3 bg-rose-950/80 border border-rose-800 text-rose-300 text-xs rounded-xl">{err}</div>}
      {msg && <div className="p-3 bg-emerald-950/80 border border-emerald-800 text-emerald-300 text-xs rounded-xl">{msg}</div>}
      {mode === "login" ? (
        <form onSubmit={handleSubmitLogin} className="space-y-4">
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Email / User ID</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Enter your Email / User ID..." autoComplete="off" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500" required />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-300 block mb-1">Password</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500" required />
          </div>
          <button type="submit" disabled={loading} className="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all disabled:opacity-60">
            {loading ? "🔄 Signing In..." : "🚀 Sign In & Launch"}
          </button>
          <p className="text-center text-xs text-slate-400 pt-2">Don't have an account? <button type="button" onClick={() => { setMode("register"); setOtpSent(false); }} className="text-rose-400 font-bold hover:underline">Register New Account</button></p>
        </form>
      ) : !otpSent ? (
        <form onSubmit={handleRequestOtp} className="space-y-4">
          <div><label className="text-xs font-semibold text-slate-300 block mb-1">Official Email ID</label><input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="user@miamo.com" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500" required /></div>
          <div><label className="text-xs font-semibold text-slate-300 block mb-1">Full Name</label><input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Rahul Sharma" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500" required /></div>

          {/* Typeable Custom Designation Input with Live Auto-Suggest Dropdown */}
          <div className="relative">
            <label className="text-xs font-semibold text-slate-300 block mb-1">Designation / Role Title</label>
            <input
              type="text"
              value={designation}
              onChange={e => { setDesignation(e.target.value); setShowSuggestions(true); }}
              onFocus={() => setShowSuggestions(true)}
              placeholder="Type custom role title or select suggestion below..."
              className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500 font-medium"
              required
            />

            {/* Auto-Suggest Dropdown Box */}
            {showSuggestions && roleSuggestions.length > 0 && (
              <div className="absolute z-50 left-0 right-0 top-full mt-1 bg-slate-900 border border-slate-700 rounded-xl shadow-2xl overflow-hidden max-h-48 overflow-y-auto">
                <div className="px-3 py-1.5 text-[10px] font-bold text-slate-400 bg-slate-950/90 border-b border-slate-800 flex justify-between items-center">
                  <span>💡 Matching Role Suggestions (Click to select):</span>
                  <button type="button" onClick={() => setShowSuggestions(false)} className="text-slate-400 hover:text-white">✕</button>
                </div>
                {roleSuggestions.map(roleStr => (
                  <button
                    key={roleStr}
                    type="button"
                    onClick={() => { setDesignation(roleStr); setShowSuggestions(false); }}
                    className="w-full text-left px-4 py-2 text-xs font-semibold text-slate-200 hover:bg-rose-950/60 hover:text-rose-300 transition-colors border-b border-slate-800/40 last:border-0"
                  >
                    💼 {roleStr}
                  </button>
                ))}
              </div>
            )}
          </div>

          <div><label className="text-xs font-semibold text-slate-300 block mb-1">Password</label><input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500" required /></div>
          <button type="submit" className="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all">📩 Send Email OTP Code</button>
          <p className="text-center text-xs text-slate-400 pt-2">Already registered? <button type="button" onClick={() => setMode("login")} className="text-rose-400 font-bold hover:underline">Sign In</button></p>
        </form>
      ) : (
        <form onSubmit={handleVerifyAndRegister} className="space-y-4">
          <div className="p-3 bg-slate-900 border border-slate-800 rounded-xl text-xs space-y-1"><p className="text-slate-300 font-semibold">Step 2: Enter Email Verification OTP</p><p className="text-slate-400 text-[11px]">We sent a 6-digit code to <code className="text-rose-400">{email}</code></p></div>
          <div><label className="text-xs font-semibold text-slate-300 block mb-1">Enter 6-Digit OTP</label><input type="text" value={otpInput} onChange={e => setOtpInput(e.target.value)} placeholder="123456" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-center text-xl font-mono tracking-widest text-white focus:outline-none focus:border-rose-500" required autoFocus /></div>
          <button type="submit" className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-emerald-900/30 transition-all">✅ Verify OTP & Submit Registration</button>
          <button type="button" onClick={() => setOtpSent(false)} className="w-full bg-slate-900 hover:bg-slate-800 text-slate-400 py-2 rounded-xl text-xs">⬅️ Back to Registration Form</button>
        </form>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// WELCOME HUB VIEW — Ultra-HD Category Thematic Backdrops & 3D Floating Can Design
// ═══════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════
// WELCOME HUB VIEW — Dynamic 12-Photo Rotating HD Wallpapers & Mobile 2x2 Hero Groups
// ═══════════════════════════════════════════════════════════════
const CATEGORY_WALLPAPERS = {
  Sardines: {
    images: [
      "https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1505118380757-91f5f5632de0?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1518709268805-4e9042af9f23?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1682687220063-4742bd7fd538?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1506929562872-bb421503ef21?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1439405326854-014607f694d7?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1500375592092-40eb2168fd21?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1471922694854-ff5baf356986?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1468581264429-2548ef9eb732?w=1200&auto=format&fit=crop&q=90"
    ],
    gradient: "from-transparent via-sky-950/40 to-slate-950/95",
    border: "border-sky-400/60 shadow-sky-950/50",
    badgeBg: "bg-slate-950/90 text-sky-200 border-sky-400/60"
  },
  "Condensed Milk": {
    images: [
      "https://images.unsplash.com/photo-1527153857715-3908f2bae5e8?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1550583724-b2692b85b150?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1500595046743-cd271d694d30?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1464822759023-fed622ff2c3b?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1570042707223-2895697669d6?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1563636619-e9143da7973b?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1472214103451-9374bd1c798e?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1516253593875-bd7ba052fbc5?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1470240731273-7821a6eeb6bd?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1434725039720-aaad6dd32dfe?w=1200&auto=format&fit=crop&q=90"
    ],
    gradient: "from-transparent via-emerald-950/40 to-slate-950/95",
    border: "border-emerald-400/60 shadow-emerald-950/50",
    badgeBg: "bg-slate-950/90 text-emerald-200 border-emerald-400/60"
  },
  "Tomato Paste": {
    images: [
      "https://images.unsplash.com/photo-1592924357228-91a4daadcfea?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1518977676601-b53f82aba655?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1561136594-7f68413baa99?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1546094096-0df4bcaaa337?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1591857177580-dc82b9ac4e1e?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1582284540020-8acbe03f4924?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1524593689594-aae2f26b75ab?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1530836369250-ef72a3f5cda8?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1598170845058-12ef4a45753b?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1574316071802-0d684efa7bf5?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1500937386664-56d1dfef3854?w=1200&auto=format&fit=crop&q=90",
      "https://images.unsplash.com/photo-1590779033100-9f60a05a013d?w=1200&auto=format&fit=crop&q=90"
    ],
    gradient: "from-transparent via-rose-950/40 to-slate-950/95",
    border: "border-rose-400/60 shadow-rose-950/50",
    badgeBg: "bg-slate-950/90 text-rose-200 border-rose-400/60"
  }
};

function WelcomeHubView({ settings, onOpenLightbox, userHikePct = 5.0, customPrices = {} }) {
  const catalogPhotos = MiamoStore.getCatalogPhotos() || {};
  const customSpecs = MiamoStore.getProductSpecs();
  const catalogData = customSpecs || window.PRODUCT_CATALOG;
  const rawProducts = Object.entries(catalogData);

  // 📦 Sort products into exact 4-Item Hero Sets (Sardines, Tomato Paste, Sweetened Condensed Milk, Evaporated Milk)
  const HERO_ORDER = [
    "Sardines in Vegetable Oil (125 Gms Easy Open Can)",
    "Tomato Paste (400 Gms Easy Open Can)",
    "Sweetened Condensed Milk (1kg)",
    "Evaporated Milk 3% (170 Gms Easy Open Can)"
  ];

  const products = rawProducts.sort(([nameA], [nameB]) => {
    const idxA = HERO_ORDER.indexOf(nameA);
    const idxB = HERO_ORDER.indexOf(nameB);
    if (idxA !== -1 && idxB !== -1) return idxA - idxB;
    if (idxA !== -1) return -1;
    if (idxB !== -1) return 1;
    return 0;
  });

  // 🎬 Auto-rotating wallpaper index (changes through 12 HD images every 4 seconds!)
  const [bgIndex, setBgIndex] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setBgIndex(prev => (prev + 1) % 12);
    }, 4000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="space-y-6">
      {settings.home_custom_announcement && (
        <div className="p-4 bg-gradient-to-r from-rose-950/80 to-slate-900 border border-rose-800/60 rounded-2xl flex items-center gap-3 shadow-lg">
          <span className="text-2xl">📢</span>
          <p className="text-sm font-semibold text-rose-200">{settings.home_custom_announcement}</p>
        </div>
      )}
      <div>
        <h3 className="text-base sm:text-lg font-bold text-white mb-3 sm:mb-4">🌟 Featured Global Export Products</h3>
        <div className="grid grid-cols-2 lg:grid-cols-3 gap-2.5 sm:gap-6">
          {products.map(([name, spec]) => {
            const photoUrl = catalogPhotos[name] || spec.image;
            const catTheme = CATEGORY_WALLPAPERS[spec.category] || CATEGORY_WALLPAPERS["Sardines"];
            const activeBgUrl = catTheme.images[bgIndex % catTheme.images.length];

            const purchasePrice = customPrices[name] !== undefined ? customPrices[name] : (spec.default_price || 0);
            const hikePct = typeof userHikePct === 'number' ? userHikePct : 5.0;
            const fobPrice = purchasePrice * (1 + (hikePct / 100));

            return (
              <div
                key={name}
                className={`product-card-container relative rounded-2xl p-2.5 sm:p-5 border ${catTheme.border} flex flex-col justify-between h-full space-y-2.5 sm:space-y-4 shadow-2xl overflow-hidden group transition-all duration-500 hover:scale-[1.02]`}
              >
                {/* 🎬 HD Wallpaper Background — 100% Vibrant, NO pitch-black dark overlays */}
                <div
                  className="absolute inset-0 bg-cover bg-center transition-all duration-1000 opacity-95 filter contrast-110 saturate-125"
                  style={{ backgroundImage: `url(${activeBgUrl})` }}
                ></div>
                {/* Sheer subtle top-to-bottom glass shading — NO black box gradient */}
                <div className="absolute inset-0 bg-gradient-to-b from-black/10 via-transparent to-black/25"></div>

                {/* Card Content Overlay */}
                <div className="relative z-10 space-y-1.5 sm:space-y-3 flex-1 flex flex-col">
                  <div className="flex items-center justify-between gap-1 flex-wrap">
                    <span className={`px-2 py-0.5 sm:px-2.5 sm:py-1 ${catTheme.badgeBg} text-[9px] sm:text-xs font-black rounded-lg border shadow-md`}>
                      📍 {spec.origin || 'INDIA'}
                    </span>
                    <span className="text-[9px] sm:text-xs text-white font-black hidden sm:block bg-black/40 backdrop-blur-sm px-2 py-0.5 rounded-lg border border-white/20 shadow-md">
                      {spec.cartons_per_20ft || 1000} ctns
                    </span>
                  </div>

                  {/* 100% Transparent Floating Product Image Area — ZERO white box, ZERO black box */}
                  <div
                    className="w-full h-36 sm:h-56 relative cursor-pointer flex items-center justify-center flex-shrink-0 my-1 bg-transparent border-0 shadow-none"
                    onClick={() => photoUrl && onOpenLightbox(photoUrl)}
                  >
                    {photoUrl ? (
                      <TransparentProductImage
                        photoUrl={photoUrl}
                        alt={name}
                        className="max-h-full max-w-full object-contain filter drop-shadow-[0_25px_35px_rgba(0,0,0,0.95)] transform transition-all duration-500 group-hover:scale-115 group-hover:-translate-y-2 bg-transparent"
                      />
                    ) : (
                      <div className="text-center space-y-1 p-3 bg-black/20 backdrop-blur-sm rounded-2xl border border-white/20">
                        <span className="text-3xl">📦</span>
                        <p className="text-[11px] text-white font-medium">Packaging Spec</p>
                      </div>
                    )}
                    {photoUrl && (
                      <span className="absolute bottom-1 right-1 px-2 py-0.5 bg-black/60 backdrop-blur-md text-amber-300 text-[9px] sm:text-[10px] font-black rounded-lg border border-amber-400/40 shadow-md">
                        🔍 Zoom
                      </span>
                    )}
                  </div>

                  {/* Product Title & Spec Glass Shield — Sheer glass, ZERO dark black box */}
                  <div className="bg-slate-900/30 backdrop-blur-md p-2.5 sm:p-4 rounded-xl border border-white/20 shadow-xl space-y-1.5 flex-1 mt-auto">
                    <h4 className="font-black text-white text-[11px] sm:text-base leading-snug drop-shadow-[0_2px_8px_rgba(0,0,0,1)]">
                      {name}
                    </h4>
                    {/* HIDDEN ON MOBILE — shown on desktop only */}
                    <ul className="text-[10px] sm:text-xs text-white font-semibold space-y-1.5 pt-1.5 border-t border-white/20 hidden sm:block">
                      {(spec.details || []).map((d, i) => (
                        <li key={i} className="flex items-start gap-1.5 leading-normal drop-shadow-lg">
                          <span className="text-amber-300 font-bold">•</span>
                          <span>{d}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                {/* Price Bar — Sheer glass bar floating over wallpaper */}
                <div className="relative z-10 pt-2 sm:pt-3 border-t border-white/20 flex items-center justify-between mt-auto bg-slate-950/40 backdrop-blur-md -mx-2.5 -mb-2.5 sm:-mx-5 sm:-mb-5 p-2.5 sm:p-4">
                  <span className="text-[9px] sm:text-xs text-amber-300 font-black uppercase tracking-wider drop-shadow">
                    FOB Price:
                  </span>
                  <span className="text-xs sm:text-lg font-black text-amber-300 font-mono tracking-tight drop-shadow">
                    ${fobPrice.toFixed(2)}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// FREIGHT RATES VIEW
// ═══════════════════════════════════════════════════════════════
function FreightRatesView({ freightRates, setFreightRates, selectedPort }) {
  const portShort = (selectedPort || '').split(',')[0];
  const origins = [...new Set(Object.values(window.PRODUCT_CATALOG || {}).map(p => (p.origin || 'CHINA').toUpperCase()))];
  const handleUpdate = (origin, val) => {
    const updated = { ...freightRates, [origin]: parseFloat(val) || 0 };
    MiamoStore.saveDefaultFreightRates(updated);
    setFreightRates(updated);
  };
  return (
    <div className="space-y-6 max-w-2xl">
      <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-5">
        <div><h3 className="text-base font-bold text-white">🚢 Ocean Freight Rates</h3><p className="text-xs text-slate-400 mt-1">Set freight cost per 20ft FCL container from each origin country to <span className="text-rose-400 font-semibold">{portShort}</span>. Used to calculate CIF prices automatically.</p></div>
        <div className="space-y-3">
          {origins.map(origin => (
            <div key={origin} className="flex items-center gap-4 p-4 bg-white rounded-xl border border-slate-200 shadow-sm">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-mono font-bold text-rose-600 bg-rose-50 px-2 py-0.5 rounded border border-rose-200">{origin}</span>
                  <span className="text-slate-400 text-xs">→</span>
                  <span className="text-xs text-slate-700 font-semibold">{portShort}</span>
                </div>
                <p className="text-[11px] text-slate-400">Per 20ft container (FCL)</p>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-slate-500 text-sm font-bold">$</span>
                <input type="number" value={freightRates[origin] !== undefined ? freightRates[origin] : ''} placeholder="e.g. 2500" onChange={e => handleUpdate(origin, e.target.value)} className="w-28 bg-slate-50 border border-slate-300 rounded-xl px-3 py-2 text-slate-900 font-mono font-bold text-sm focus:border-rose-500 focus:outline-none" />
                <span className="text-slate-500 text-xs">USD</span>
              </div>
            </div>
          ))}
        </div>
        <p className="text-[11px] text-slate-500 border-t border-slate-800 pt-3">💡 Leave blank to use $2,500 as fallback. Changes are saved automatically.</p>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// QUOTATION GENERATOR VIEW — Single-Click Product Selector Fixed
// ═══════════════════════════════════════════════════════════════
function QuotationGeneratorView({ selectedPort, setSelectedPort, customPrices, setCustomPrices, selectedProducts, setSelectedProducts, clientName, setClientName, clientPhone, setClientPhone, quoteLang, setQuoteLang, userHikePct, calculatedData, onPreviewPdf, onGeneratePdf, onShareWhatsapp }) {
  const allProducts = Object.keys(window.PRODUCT_CATALOG || {});
  const [productSearch, setProductSearch] = useState("");
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const inputRef = useRef(null);
  const dropdownRef = useRef(null);

  const removeProduct = (name) => setSelectedProducts(prev => prev.filter(p => p !== name));

  // FIXED: Use mousedown instead of click to prevent blur-before-click race condition
  const addProduct = (name) => {
    if (!selectedProducts.includes(name)) {
      setSelectedProducts(prev => [...prev, name]);
    }
    setProductSearch("");
    // Keep dropdown open to allow adding more products
  };

  const availableProducts = allProducts.filter(p =>
    !selectedProducts.includes(p) &&
    (!productSearch || p.toLowerCase().includes(productSearch.toLowerCase()))
  );

  const portShort = (selectedPort || '').split(',')[0];

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  return (
    <div className="space-y-6 text-left">
      {/* Customer Name */}
      <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-2">
        <label className="text-xs font-semibold text-slate-300 block">Customer / Buyer Company Name:</label>
        <input type="text" value={clientName} onChange={e => setClientName(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white font-medium focus:border-rose-500 focus:outline-none" />
      </div>

      {/* Product Selector — Single Click Fixed */}
      <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-3 relative z-20">
        <h3 className="text-base font-bold text-white flex items-center gap-2"><span>📦</span> Select Products for this Quotation</h3>
        <label className="text-xs font-semibold text-slate-400 block">Choose Products (single click to add):</label>

        <div className="relative z-40" ref={dropdownRef}>
          {/* Tag Input Box */}
          <div
            className="w-full min-h-[46px] bg-slate-900 border border-slate-800 rounded-xl p-2 flex flex-wrap items-center gap-2 cursor-text hover:border-slate-700 transition-all"
            onClick={() => { setDropdownOpen(true); inputRef.current?.focus(); }}
          >
            {selectedProducts.map(pName => (
              <span key={pName} className="inline-flex items-center gap-1.5 px-3 py-1 bg-slate-800 text-white rounded-lg text-xs font-medium border border-slate-700 max-w-[240px]">
                <span className="truncate">{pName}</span>
                <button type="button" onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); removeProduct(pName); }} className="text-slate-400 hover:text-rose-400 font-bold ml-1">✕</button>
              </span>
            ))}
            <input
              ref={inputRef}
              type="text"
              value={productSearch}
              onChange={e => { setProductSearch(e.target.value); setDropdownOpen(true); }}
              onFocus={() => setDropdownOpen(true)}
              placeholder={selectedProducts.length === 0 ? "Type to search & select products..." : "Add more products..."}
              className="flex-1 bg-transparent border-none text-xs text-white placeholder-slate-500 focus:outline-none min-w-[140px] px-1 py-1"
            />
            <span className="text-slate-400 text-xs px-2">▼</span>
          </div>

          {/* Dropdown — mousedown prevents blur before selection */}
          {dropdownOpen && (
            <div className="absolute left-0 right-0 top-full mt-1 bg-slate-900 border border-slate-800 rounded-xl shadow-2xl z-[100] max-h-60 overflow-y-auto divide-y divide-slate-800/60">
              <div className="p-2 bg-slate-950 flex items-center justify-between text-[11px] text-slate-400 sticky top-0">
                <span>Select from {availableProducts.length} available products:</span>
                <div className="flex gap-2">
                  <button onMouseDown={(e) => { e.preventDefault(); setSelectedProducts(allProducts); }} className="text-emerald-400 font-semibold hover:underline">Select All</button>
                  {selectedProducts.length > 0 && (
                    <button onMouseDown={(e) => { e.preventDefault(); setSelectedProducts([]); }} className="text-rose-400 font-semibold hover:underline">Clear All</button>
                  )}
                </div>
              </div>
              {availableProducts.length === 0 ? (
                <div className="p-3 text-xs text-slate-500 text-center italic">No matching products found.</div>
              ) : (
                availableProducts.map(pName => {
                  const spec = window.PRODUCT_CATALOG[pName];
                  return (
                    <div
                      key={pName}
                      onMouseDown={(e) => { e.preventDefault(); addProduct(pName); }}
                      className="p-3 hover:bg-rose-900/30 cursor-pointer flex items-center justify-between transition-colors active:bg-rose-800/50"
                    >
                      <div>
                        <p className="text-xs font-semibold text-white">{pName}</p>
                        <p className="text-[10px] text-slate-400 font-mono">{(spec?.origin || 'CHINA').toUpperCase()} • {spec?.packaging || "Can Packaging"}</p>
                      </div>
                      <span className="text-xs font-bold text-rose-400 bg-rose-950/60 px-2 py-0.5 rounded border border-rose-800/40">+ Add</span>
                    </div>
                  );
                })
              )}
            </div>
          )}
        </div>
      </div>

      {/* Calculated Prices — Shown ONLY when products are selected, with ultra-sleek compact header banner */}
      {calculatedData.length > 0 && (
        <div className="space-y-3">
          <div className="glass-panel px-4 py-2 rounded-xl border border-slate-800 flex items-center justify-between gap-2 shadow-sm">
            <div className="flex items-center gap-2">
              <span className="text-sm">💰</span>
              <h3 className="text-xs sm:text-sm font-bold text-white leading-none">
                Base Purchase Prices & Calculated Rates (FOB / CIF)
              </h3>
              <span className="hidden md:inline text-[11px] text-slate-400">
                (Edit base prices or view auto FOB/CIF for <strong className="text-rose-400">{portShort}</strong>)
              </span>
            </div>
            <span className="px-2.5 py-0.5 bg-rose-950/80 text-rose-300 text-[10px] font-mono font-bold rounded-lg border border-rose-800/60 shadow-sm shrink-0">
              📍 Port: {portShort}
            </span>
          </div>

          {calculatedData.length > 4 && (
            <span className="text-[10px] text-emerald-400 bg-emerald-950/80 border border-emerald-800/60 px-2 py-0.5 rounded-full font-bold">
              📱 Compact 4-Column View ({calculatedData.length} Items)
            </span>
          )}

          <div className={calculatedData.length > 4 ? "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3" : "grid grid-cols-1 md:grid-cols-2 gap-3"}>
            {calculatedData.map(item => {
              const spec = window.PRODUCT_CATALOG[item.name] || {};
              const updateBasePrice = (delta) => {
                const updatedVal = Math.max(0, item.basePrice + delta);
                setCustomPrices({ ...customPrices, [item.name]: parseFloat(updatedVal.toFixed(2)) });
              };
              const isCompact = calculatedData.length > 4;
              return (
                <div key={item.name} className={`glass-panel rounded-2xl border border-slate-800 flex flex-col justify-between ${isCompact ? 'p-3 space-y-2 text-xs' : 'p-4 space-y-3'}`}>
                  <div className="space-y-1">
                    <h4 className={`font-bold text-white leading-snug ${isCompact ? 'text-xs truncate' : 'text-sm'}`} title={item.name}>{item.name}</h4>
                    {spec.image && <span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-emerald-950/80 text-emerald-400 border border-emerald-800/50 rounded text-[9px] font-bold">☑️ Photo</span>}
                  </div>
                  <div className="space-y-1">
                    <label className="text-[10px] text-slate-400 block font-medium">Base Price ($)</label>
                    <div className="flex items-center gap-1 bg-slate-900 border border-slate-800 rounded-lg p-1">
                      <input type="number" step="0.10" value={item.basePrice} onChange={e => setCustomPrices({ ...customPrices, [item.name]: parseFloat(e.target.value) || 0 })} className={`w-full bg-transparent px-1 text-white font-mono font-extrabold focus:outline-none ${isCompact ? 'text-xs' : 'text-sm'}`} />
                      <button type="button" onClick={() => updateBasePrice(-0.50)} className="w-5 h-5 bg-slate-800 hover:bg-slate-700 text-white rounded font-bold flex items-center justify-center text-xs" title="Decrease by $0.50">-</button>
                      <button type="button" onClick={() => updateBasePrice(0.50)} className="w-5 h-5 bg-slate-800 hover:bg-slate-700 text-white rounded font-bold flex items-center justify-center text-xs" title="Increase by $0.50">+</button>
                    </div>
                  </div>
                  <div className={`bg-indigo-950/40 border border-indigo-800/50 rounded-xl font-mono ${isCompact ? 'p-2 space-y-0.5 text-[10px]' : 'p-3 space-y-1 text-xs'}`}>
                    <div className="flex items-center justify-between text-indigo-200"><span>FOB ({item.origin}):</span><strong className={`text-amber-400 font-extrabold ${isCompact ? 'text-xs' : 'text-sm'}`}>${item.fob.toFixed(2)}</strong></div>
                    <div className="flex items-center justify-between text-rose-200"><span>CIF ({portShort}):</span><strong className={`text-rose-400 font-extrabold ${isCompact ? 'text-xs' : 'text-sm'}`}>${item.cif.toFixed(2)}</strong></div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Action Buttons */}
      <div className="glass-panel p-5 rounded-2xl border border-slate-800 flex flex-wrap gap-3">
        <button onClick={onPreviewPdf} className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-indigo-900/30 flex items-center justify-center gap-2"><Icon name="eye" className="w-5 h-5" /> Preview PDF</button>
        <button onClick={onGeneratePdf} className="flex-1 bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 flex items-center justify-center gap-2"><Icon name="download" className="w-5 h-5" /> Download PDF</button>
        <button onClick={onShareWhatsapp} className="flex-1 bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-emerald-900/30 flex items-center justify-center gap-2"><Icon name="share-2" className="w-5 h-5" /> Send via WhatsApp</button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// ERROR BOUNDARY
// ═══════════════════════════════════════════════════════════════
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { hasError: false, error: null }; }
  static getDerivedStateFromError(error) { return { hasError: true, error }; }
  componentDidCatch(error, errorInfo) { console.error("Caught component error:", error, errorInfo); }
  render() {
    if (this.state.hasError) {
      return (
        <div className="p-8 bg-slate-900/90 border border-rose-800 rounded-2xl text-center space-y-4 max-w-lg mx-auto my-8 glass-panel">
          <div className="text-4xl">⚠️</div>
          <h3 className="text-xl font-bold text-white">Section Render Notice</h3>
          <p className="text-xs text-rose-300 font-mono bg-slate-950 p-3 rounded-lg overflow-x-auto text-left">{this.state.error?.toString() || "Render Exception"}</p>
          <button onClick={() => this.setState({ hasError: false })} className="px-6 py-2 bg-rose-600 hover:bg-rose-700 text-white text-xs font-bold rounded-xl shadow-lg shadow-rose-900/30">🔄 Reload Section</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// ═══════════════════════════════════════════════════════════════
// ADMIN CENTER VIEW — Complete
// ═══════════════════════════════════════════════════════════════
function AdminCenterView({ isAdmin, unlocked, setUnlocked, accounts, setAccounts, settings, setSettings, auditLogs, suggestions, sentQuotations, theme, setTheme, handleSetTheme, customThemes, setCustomThemes, hikeUnlocked, setHikeUnlocked, userHikePct, currentUser, inactivityTimeout, setInactivityTimeout, speakTextWithHumanVoice, userLocation }) {
  const [pinInput, setPinInput] = useState("");
  const [activeAdminTab, setActiveAdminTab] = useState("users");
  const [pinErr, setPinErr] = useState("");
  const [showAddUserModal, setShowAddUserModal] = useState(false);
  const [newEmail, setNewEmail] = useState(""); const [newPassword, setNewPassword] = useState(""); const [newName, setNewName] = useState(""); const [newRole, setNewRole] = useState("User"); const [newDesignation, setNewDesignation] = useState("Sales Executive");
  const [gsheetConfig, setGsheetConfig] = useState(() => MiamoStore.getGoogleSheetConfig());
  const [syncState, setSyncState] = useState(() => MiamoStore.getSyncState());
  const [deletedUsers, setDeletedUsers] = useState(() => MiamoStore.getDeletedUsersArchive());
  const [catalog, setCatalog] = useState(() => ({ ...window.PRODUCT_CATALOG }));
  const [productSpecsList, setProductSpecsList] = useState(() => MiamoStore.getProductSpecs() || window.PRODUCT_CATALOG);
  const specKeys = Object.keys(productSpecsList);
  const [selectedSpecName, setSelectedSpecName] = useState(specKeys[0] || "");
  const currentSpecObj = productSpecsList[selectedSpecName] || {};
  const [specEditName, setSpecEditName] = useState(selectedSpecName);
  const [specEditOrigin, setSpecEditOrigin] = useState(currentSpecObj.origin || "INDIA");
  const [specEditPrice, setSpecEditPrice] = useState(currentSpecObj.default_price || 0);
  const [specEditCartons, setSpecEditCartons] = useState(currentSpecObj.cartons_per_20ft || 1000);
  const [specEditDetails, setSpecEditDetails] = useState((currentSpecObj.details || []).join("\n"));
  const [showPasswordMap, setShowPasswordMap] = useState({});
  const [auditSearchQuery, setAuditSearchQuery] = useState("");
  const [passwordSearchQuery, setPasswordSearchQuery] = useState("");
  const [mergedViewMode, setMergedViewMode] = useState(false);
  const [mergedSecondaryTab, setMergedSecondaryTab] = useState("audit");
  const [draggedTabIdx, setDraggedTabIdx] = useState(null);

  // Navigation & Scroll Refs
  const adminTabsRef = useRef(null);

  // Preview Modals State
  const [showPdfPreviewModal, setShowPdfPreviewModal] = useState(false);
  const [showCelebrationPreviewModal, setShowCelebrationPreviewModal] = useState(false);

  // Custom Theme Palette Manager & Live Theme Editor State
  const [deletedThemesHistory, setDeletedThemesHistory] = useState(() => MiamoStore.getDeletedThemesHistory() || []);
  const [deletedThemeKeys, setDeletedThemeKeys] = useState(() => MiamoStore.getDeletedThemeKeys() || []);
  const [newThemeName, setNewThemeName] = useState("");
  const [newPrimaryHex, setNewPrimaryHex] = useState("#f59e0b");
  const [newAccentHex, setNewAccentHex] = useState("#e11d48");
  const [newBgHex, setNewBgHex] = useState("#0f172a");
  const [newTextHex, setNewTextHex] = useState("#ffffff");
  const [themeToast, setThemeToast] = useState("");

  // Live Theme Palette Editor State — Complete Master Granular Control
  const [editingThemeObj, setEditingThemeObj] = useState(null);
  const [editThemeLabel, setEditThemeLabel] = useState("");
  const [editPrimaryHex, setEditPrimaryHex] = useState("#f59e0b");
  const [editAccentHex, setEditAccentHex] = useState("#e11d48");
  const [editBgHex, setEditBgHex] = useState("#0f172a");
  const [editSurfaceHex, setEditSurfaceHex] = useState("#1e293b");
  const [editTextHex, setEditTextHex] = useState("#ffffff");
  const [editSubtextHex, setEditSubtextHex] = useState("#94a3b8");
  const [editHighlightHex, setEditHighlightHex] = useState("#f59e0b");
  const [editBorderHex, setEditBorderHex] = useState("#334155");
  const [editSidebarHex, setEditSidebarHex] = useState("#0f172a");
  const [editTabHex, setEditTabHex] = useState("#e11d48");
  const [paletteUrlInput, setPaletteUrlInput] = useState("");

  const ALLOWED_BUILTIN_KEYS = ["dark", "light", "royal_pink", "emerald_forest", "cyberpunk_gold", "diamond_mint"];
  const allThemeOptions = useMemo(() => {
    return [...THEME_OPTIONS, ...customThemes].filter(t => {
      if (deletedThemeKeys.includes(t.value)) return false;
      if (t.isCustom) return true;
      return ALLOWED_BUILTIN_KEYS.includes(t.value);
    });
  }, [customThemes, deletedThemeKeys]);

  const pendingApprovalsCount = Object.values(accounts || {}).filter(a => a?.status === "Pending Approval").length;

  const defaultAdminTabs = useMemo(() => [
    { id: "users", label: `📩 Account Approvals (${pendingApprovalsCount})` },
    { id: "passwords", label: "🔑 Passwords Vault" },
    { id: "quotations_excel", label: `📊 Quotations (${(sentQuotations || []).length})` },
    { id: "deleted_users", label: `🗑️ Deleted (${(deletedUsers || []).length})` },
    { id: "photos", label: "🖼️ Photos" },
    { id: "product_specs", label: "📦 Products" },
    { id: "audit", label: `📊 Logs (${(Array.isArray(auditLogs) ? auditLogs : []).length})` },
    { id: "feedback", label: `💬 Feedback (${(Array.isArray(suggestions) ? suggestions : []).length})` },
    { id: "theme", label: "🎨 UI & Theme" },
    { id: "system_settings", label: "⚙️ Settings" },
  ], [accounts, sentQuotations, deletedUsers, auditLogs, suggestions]);

  const [adminTabOrder, setAdminTabOrder] = useState(() => {
    try {
      const saved = localStorage.getItem("miamo_admin_tab_order");
      return saved ? JSON.parse(saved) : ["users", "passwords", "quotations_excel", "deleted_users", "photos", "product_specs", "audit", "feedback", "theme", "system_settings"];
    } catch { return ["users", "passwords", "quotations_excel", "deleted_users", "photos", "product_specs", "audit", "feedback", "theme", "system_settings"]; }
  });

  const orderedTabList = useMemo(() => {
    const map = new Map(defaultAdminTabs.map(t => [t.id, t]));
    const list = adminTabOrder.map(id => map.get(id)).filter(Boolean);
    defaultAdminTabs.forEach(t => {
      if (!list.find(item => item.id === t.id)) list.push(t);
    });
    return list;
  }, [adminTabOrder, defaultAdminTabs]);

  const handleTabDrop = (targetIdx) => {
    if (draggedTabIdx === null || draggedTabIdx === targetIdx) return;
    const updated = [...orderedTabList.map(t => t.id)];
    const [moved] = updated.splice(draggedTabIdx, 1);
    updated.splice(targetIdx, 0, moved);
    setAdminTabOrder(updated);
    localStorage.setItem("miamo_admin_tab_order", JSON.stringify(updated));
    setDraggedTabIdx(null);
  };

  // Dynamically inject CSS for custom themes
  useEffect(() => {
    let styleEl = document.getElementById("custom-theme-styles");
    if (!styleEl) {
      styleEl = document.createElement("style");
      styleEl.id = "custom-theme-styles";
      document.head.appendChild(styleEl);
    }
    const cssRules = customThemes.map(t => `
      .${t.value}-theme {
        background-color: ${t.colors?.bg || '#0f172a'} !important;
        color: ${t.colors?.text || '#ffffff'} !important;
      }
    `).join("\n");
    styleEl.innerHTML = cssRules;
  }, [customThemes]);

  const handleAddCustomTheme = (e) => {
    if (e) e.preventDefault();
    const finalName = newThemeName.trim() || `New 5-Color Custom Palette #${customThemes.length + 1}`;
    const valKey = "custom_" + finalName.toLowerCase().replace(/[^a-z0-9]/g, '_') + "_" + Date.now().toString(36);
    
    // Auto-extract 5 hex colors if user pasted a Canva / Coolors / Website link
    let extracted = null;
    if (paletteUrlInput && paletteUrlInput.trim()) {
      extracted = parsePaletteUrlOrHex(paletteUrlInput.trim());
    }

    const pColor = extracted ? extracted.primary : newPrimaryHex;
    const aColor = extracted ? extracted.accent : newAccentHex;
    const bColor = extracted ? extracted.bg : newBgHex;
    const sColor = extracted ? extracted.surface : (newBgHex || "#1E293B");
    const tColor = extracted ? extracted.text : newTextHex;

    const newThemeObj = {
      value: valKey,
      label: `🎨 ${finalName}`,
      desc: `User Created Custom 5 Color Palette (${pColor}, ${aColor})`,
      isCustom: true,
      colors: { primary: pColor, accent: aColor, bg: bColor, surface: sColor, text: tColor }
    };
    const updatedCustom = [...customThemes, newThemeObj];
    setCustomThemes(updatedCustom);
    MiamoStore.saveCustomThemes(updatedCustom);
    handleSetTheme(valKey);
    setNewThemeName("");
    setPaletteUrlInput("");
    alert(`✅ Custom palette "${finalName}" generated & applied live!`);
  };

  const handleDeleteTheme = (t) => {
    if (allThemeOptions.length <= 1) return alert("Cannot delete the last remaining theme!");
    const confirmDel = confirm(`Are you sure you want to delete theme palette "${t.label}"?`);
    if (!confirmDel) return;

    // 1. Push to deleted history stack for Undo
    const historyItem = { theme: t, deletedAt: new Date().toLocaleString() };
    const updatedHistory = [historyItem, ...deletedThemesHistory];
    setDeletedThemesHistory(updatedHistory);
    MiamoStore.saveDeletedThemesHistory(updatedHistory);

    // 2. Add key to deletedThemeKeys and persist to localStorage
    const updatedKeys = [...deletedThemeKeys, t.value];
    setDeletedThemeKeys(updatedKeys);
    MiamoStore.saveDeletedThemeKeys(updatedKeys);

    // 3. If custom theme, also filter out of customThemes list
    if (t.isCustom) {
      const updatedCustom = customThemes.filter(ct => ct.value !== t.value);
      setCustomThemes(updatedCustom);
      MiamoStore.saveCustomThemes(updatedCustom);
    }

    if (theme === t.value) {
      handleSetTheme("dark");
    }
    setThemeToast(`🗑️ Theme "${t.label}" deleted.`);
    setTimeout(() => setThemeToast(""), 8000);
  };

  const handleUndoThemeDelete = () => {
    if (deletedThemesHistory.length === 0) return alert("No deleted themes to restore!");
    const [lastDeleted, ...remainingHistory] = deletedThemesHistory;
    setDeletedThemesHistory(remainingHistory);
    MiamoStore.saveDeletedThemesHistory(remainingHistory);

    const valKey = lastDeleted?.theme?.value;
    if (valKey) {
      const updatedKeys = deletedThemeKeys.filter(k => k !== valKey);
      setDeletedThemeKeys(updatedKeys);
      MiamoStore.saveDeletedThemeKeys(updatedKeys);

      if (lastDeleted?.theme?.isCustom) {
        const updatedCustom = [...customThemes, lastDeleted.theme];
        setCustomThemes(updatedCustom);
        MiamoStore.saveCustomThemes(updatedCustom);
      }
      handleSetTheme(valKey);
    }
    alert(`↩️ Theme "${lastDeleted?.theme?.label || 'Palette'}" restored successfully!`);
  };

  useEffect(() => {
    const obj = productSpecsList[selectedSpecName] || {};
    setSpecEditName(selectedSpecName);
    setSpecEditOrigin((obj.origin || "INDIA").toUpperCase());
    setSpecEditPrice(obj.default_price || 0);
    setSpecEditCartons(obj.cartons_per_20ft || 1000);
    setSpecEditDetails((obj.details || []).join("\n"));
  }, [selectedSpecName]);

  const safeAccounts = accounts || {};
  const safeLogs = Array.isArray(auditLogs) ? auditLogs : [];
  const safeSuggestions = Array.isArray(suggestions) ? suggestions : [];
  const expectedPin = settings?.admin_security_code || "282911";

  const toggleShowPassword = (email) => setShowPasswordMap(prev => ({ ...prev, [email]: !prev[email] }));

  const handleChangeUserPassword = (email, info) => {
    const newPass = prompt(`Enter new password for user: ${info?.display_name || email}`, info?.password || "");
    if (newPass === null) return;
    if (!newPass.trim()) return alert("Password cannot be empty!");
    const updated = { ...safeAccounts, [email]: { ...info, password: newPass.trim() } };
    MiamoStore.saveAccounts(updated);
    setAccounts(updated);
    alert(`✅ Password for ${info?.display_name || email} has been updated!`);
  };

  const handleCreateUserManually = (e) => {
    e.preventDefault();
    if (!newEmail || !newPassword || !newName) return alert("Please fill all required fields!");
    const memberCode = MiamoStore.getNextMemberCode();
    const updated = { ...safeAccounts, [newEmail.trim().toLowerCase()]: { display_name: newName, user_email: newEmail.trim().toLowerCase(), password: newPassword, role: newRole, designation: newDesignation, member_code: memberCode, status: "Active", registered_at: new Date().toLocaleString() } };
    MiamoStore.saveAccounts(updated);
    setAccounts(updated);
    setShowAddUserModal(false);
    setNewEmail(""); setNewPassword(""); setNewName("");
    alert(`✅ User Account Created! (Member Code: ${memberCode})`);
  };

  const handleDeleteUser = (email, info) => {
    if (!confirm(`Are you sure you want to delete user ${info?.display_name || email}?`)) return;
    MiamoStore.archiveDeletedUser(email, info);
    const updated = { ...safeAccounts };
    delete updated[email];
    MiamoStore.saveAccounts(updated);
    setAccounts(updated);
    setDeletedUsers(MiamoStore.getDeletedUsersArchive());
    alert(`🗑️ User ${info?.display_name || email} deleted.`);
  };

  const handleRestoreUser = (email) => {
    const restoredAccount = MiamoStore.restoreDeletedUser(email);
    if (restoredAccount) {
      setAccounts(MiamoStore.getAccounts());
      setDeletedUsers(MiamoStore.getDeletedUsersArchive());
      alert(`✅ Account restored for ${restoredAccount.display_name || email}!`);
    }
  };

  const handleTriggerSync = () => {
    const nextSync = Date.now() + 12 * 60 * 60 * 1000;
    const newState = { last_synced: new Date().toLocaleString(), last_synced_timestamp: Date.now(), next_sync_timestamp: nextSync, sync_status: "Active (12-Hour Auto Sync Enabled)" };
    MiamoStore.saveSyncState(newState);
    setSyncState(newState);
    alert("⚡ Google Sheets Product Base Prices & Freight Rates Synced Successfully!");
  };

  if (!isAdmin) {
    return (
      <div className="max-w-md mx-auto glass-panel p-8 rounded-2xl border border-rose-800/60 text-center space-y-4">
        <Icon name="shield-alert" className="w-12 h-12 text-rose-500 mx-auto" />
        <h3 className="text-xl font-bold text-white">Admin Privileges Required</h3>
        <p className="text-xs text-slate-400">Your account does not have Admin access.</p>
      </div>
    );
  }

  // ─── Admin PIN Gate — Backspace Fixed ───
  if (!unlocked) {
    return (
      <div className="max-w-md mx-auto glass-panel p-8 rounded-2xl border border-slate-800 text-center space-y-4">
        <div className="w-14 h-14 bg-rose-600/20 border border-rose-500 text-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-2"><Icon name="lock" className="w-7 h-7" /></div>
        <h3 className="text-xl font-bold text-white">Admin Security Lock</h3>
        <p className="text-xs text-slate-400">Enter Admin Security PIN:</p>
        {pinErr && <div className="p-2.5 bg-rose-950/80 border border-rose-800 text-rose-300 text-xs rounded-xl">{pinErr}</div>}
        <form onSubmit={(e) => { e.preventDefault(); setPinErr(""); if (pinInput.trim() === expectedPin.trim()) { setUnlocked(true); } else { setPinErr("❌ Incorrect Security PIN!"); setPinInput(""); } }} className="space-y-3">
          <input
            type="password"
            value={pinInput}
            onChange={e => setPinInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Backspace') { e.stopPropagation(); } }}
            placeholder="••••••••"
            className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-center text-xl tracking-widest text-white focus:outline-none focus:border-rose-500"
            required autoFocus
          />
          <button type="submit" className="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30 transition-all">🔓 Unlock Admin Center</button>
        </form>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between p-4 bg-emerald-950/60 border border-emerald-800/40 rounded-2xl text-emerald-300 text-sm">
        <span className="font-semibold flex items-center gap-2">🔓 Admin Access Unlocked</span>
        <button onClick={() => setUnlocked(false)} className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 text-slate-300 rounded-lg text-xs font-bold border border-slate-700">🔒 Lock Panel Now</button>
      </div>

      {/* Draggable & Reorderable Admin Tabs */}
      <div className="space-y-2">
        <div className="flex items-center justify-between gap-2 flex-wrap text-xs text-slate-400">
          <span className="text-[11px] font-semibold text-slate-400">💡 Drag tabs to reorder position anytime:</span>
          <button
            type="button"
            onClick={() => setMergedViewMode(!mergedViewMode)}
            className={`px-3 py-1 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 cursor-pointer ${
              mergedViewMode ? 'bg-rose-950/80 border-rose-600 text-rose-300' : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-white'
            }`}
          >
            <span>🧩</span> {mergedViewMode ? 'Exit Merged Dual View' : 'Merge / Side-by-Side Views'}
          </button>
        </div>

        <div className="relative flex items-center bg-slate-950/80 rounded-xl p-1 border border-slate-800">
          <button
            type="button"
            onClick={() => adminTabsRef.current?.scrollBy({ left: -200, behavior: 'smooth' })}
            className="px-2.5 py-2 bg-slate-900 hover:bg-rose-900/80 text-rose-300 rounded-l-lg border border-slate-800 shadow-md font-bold text-xs z-10 flex-shrink-0 cursor-pointer"
            title="Scroll tabs left"
          >
            ◀
          </button>

          <div ref={adminTabsRef} className="flex border-b border-slate-800 gap-1.5 overflow-x-auto pb-1 items-center scrollbar-none flex-1 px-1.5">
            {orderedTabList.map((tab, idx) => (
              <button
                key={tab.id}
                draggable={true}
                onDragStart={() => setDraggedTabIdx(idx)}
                onDragOver={(e) => e.preventDefault()}
                onDrop={() => handleTabDrop(idx)}
                onClick={() => setActiveAdminTab(tab.id)}
                className={`px-3.5 py-2 text-xs font-bold rounded-t-xl transition-all whitespace-nowrap cursor-grab active:cursor-grabbing border-t-2 ${
                  activeAdminTab === tab.id
                    ? "bg-slate-900 text-rose-400 border-rose-500 shadow-md"
                    : "bg-slate-950/60 text-slate-400 border-transparent hover:text-slate-200 hover:bg-slate-900/60"
                }`}
                title="Click to view tab, or drag to reorder"
              >
                <span className="opacity-40 mr-1 text-[10px]">⠿</span>
                {tab.label}
              </button>
            ))}
          </div>

          <button
            type="button"
            onClick={() => adminTabsRef.current?.scrollBy({ left: 200, behavior: 'smooth' })}
            className="px-2.5 py-2 bg-slate-900 hover:bg-rose-900/80 text-rose-300 rounded-r-lg border border-slate-800 shadow-md font-bold text-xs z-10 flex-shrink-0 cursor-pointer"
            title="Scroll tabs right"
          >
            ▶
          </button>
        </div>

        {/* Secondary Tab Selector in Merged Mode */}
        {mergedViewMode && (
          <div className="p-3 bg-slate-950 border border-slate-800 rounded-xl flex items-center gap-3 text-xs">
            <span className="font-bold text-amber-400 flex items-center gap-1">🧩 Combine Secondary Tab:</span>
            <select
              value={mergedSecondaryTab}
              onChange={e => setMergedSecondaryTab(e.target.value)}
              className="bg-slate-900 border border-slate-800 rounded-lg px-3 py-1.5 text-white font-bold"
            >
              {orderedTabList.filter(t => t.id !== activeAdminTab).map(t => (
                <option key={t.id} value={t.id}>{t.label}</option>
              ))}
            </select>
            <span className="text-[11px] text-slate-400">Viewing both tabs stacked simultaneously.</span>
          </div>
        )}
      </div>

      {/* Tab: Master Passwords & Credentials Vault */}
      {(activeAdminTab === "passwords" || (mergedViewMode && mergedSecondaryTab === "passwords")) && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-6 text-left">
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-4">
            <div>
              <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🔑</span> Master Passwords & Security Credentials Vault</h3>
              <p className="text-xs text-slate-400">Complete access desk showing all staff account passwords, admin security PIN, and system auth keys.</p>
            </div>
            {/* Password Search Bar */}
            <div className="w-full sm:w-64">
              <input
                type="text"
                value={passwordSearchQuery}
                onChange={e => setPasswordSearchQuery(e.target.value)}
                placeholder="🔍 Search name, email, role..."
                className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-rose-500"
              />
            </div>
          </div>

          {/* Section 1: Staff User Account Login & Hike Passwords */}
          <div className="space-y-3">
            <h4 className="font-bold text-amber-400 text-xs flex items-center gap-1.5"><span>👥</span> Staff Account Login & Hike Passwords ({Object.keys(safeAccounts).length}):</h4>
            <div className="divide-y divide-slate-800/60 bg-slate-900/60 rounded-xl border border-slate-800/80 overflow-hidden">
              {Object.entries(safeAccounts)
                .filter(([eStr, info]) => {
                  if (!passwordSearchQuery.trim()) return true;
                  const q = passwordSearchQuery.toLowerCase();
                  return eStr.toLowerCase().includes(q) || (info?.display_name || "").toLowerCase().includes(q) || (info?.designation || "").toLowerCase().includes(q);
                })
                .map(([userEmail, info]) => {
                  if (!info) return null;
                  const isShowPass = showPasswordMap["login_" + userEmail];
                  const isShowHike = showPasswordMap["hike_" + userEmail];
                  const hikePin = info.hike_pin || "282911";
                  const hikePct = info.hike_pct !== undefined ? info.hike_pct : 5.0;

                  return (
                    <div key={userEmail} className="p-4 flex flex-wrap items-center justify-between gap-4 hover:bg-slate-900/90 transition-colors">
                      {/* Left Side: Name, Unique ID, Role, Email, Designation & Hike PIN */}
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <span className="font-extrabold text-white text-sm">{info.display_name || userEmail}</span>
                          <span className="text-rose-400 font-mono text-xs font-bold">({info.member_code || 'MF-0000'})</span>
                          <span className="px-2 py-0.5 bg-slate-800 text-slate-300 text-[10px] font-bold rounded">{info.role || 'User'}</span>
                        </div>
                        <p className="text-xs text-slate-400">
                          {userEmail} • <span className="text-amber-300 font-semibold">{info.designation || 'Sales Executive'}</span>
                        </p>
                        <div className="flex items-center gap-2 pt-0.5">
                          <span className="text-[11px] font-bold text-rose-400">📈 Staff Hike PIN:</span>
                          <span className="font-mono text-xs font-bold text-white bg-slate-950 px-2 py-0.5 rounded border border-slate-800">
                            {isShowHike ? hikePin : "••••••••"}
                          </span>
                          <button
                            type="button"
                            onClick={() => setShowPasswordMap(prev => ({ ...prev, ["hike_" + userEmail]: !prev["hike_" + userEmail] }))}
                            className="text-[11px] text-slate-400 hover:text-white underline"
                          >
                            {isShowHike ? "🙈 Hide" : "👁️ View"}
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              const newPin = prompt(`Enter new Hike Security PIN for ${info.display_name || userEmail}:`, hikePin);
                              if (newPin === null) return;
                              if (!newPin.trim()) return alert("PIN cannot be empty!");
                              const updated = { ...safeAccounts, [userEmail]: { ...info, hike_pin: newPin.trim() } };
                              MiamoStore.saveAccounts(updated);
                              setAccounts(updated);
                              alert(`✅ Hike PIN updated for ${info.display_name || userEmail} to: ${newPin.trim()}`);
                            }}
                            className="text-[11px] text-amber-400 hover:underline font-bold"
                          >
                            ✏️ Edit PIN
                          </button>
                        </div>
                      </div>

                      {/* Right Side: Login Password Box & Hike Password Box & Margin Box */}
                      <div className="flex flex-wrap items-center gap-3">
                        {/* Account Login Password */}
                        <div className="flex items-center gap-2 bg-slate-950 px-3 py-2 rounded-xl border border-slate-800 font-mono text-xs">
                          <span className="text-slate-400 font-sans text-[11px]">Password:</span>
                          <span className="text-amber-300 font-bold tracking-wider">{isShowPass ? (info.password || "••••••••") : "••••••••"}</span>
                          <button
                            type="button"
                            onClick={() => setShowPasswordMap(prev => ({ ...prev, ["login_" + userEmail]: !prev["login_" + userEmail] }))}
                            className="text-slate-400 hover:text-white underline text-[11px] ml-1"
                          >
                            {isShowPass ? "🙈 Hide" : "👁️ View"}
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              navigator.clipboard.writeText(`Email: ${userEmail}\nPassword: ${info.password || ''}`);
                              alert(`📋 Login Credentials for ${info.display_name || userEmail} copied to clipboard!`);
                            }}
                            className="text-slate-300 hover:text-white underline text-[11px] ml-1"
                          >
                            📋 Copy
                          </button>
                          <button
                            type="button"
                            onClick={() => handleChangeUserPassword(userEmail, info)}
                            className="text-amber-400 hover:underline font-sans text-[11px] ml-1"
                          >
                            ✏️ Edit
                          </button>
                        </div>

                        {/* Hike Password Box */}
                        <div className="flex items-center gap-2 bg-slate-950 px-3 py-2 rounded-xl border border-slate-800 font-mono text-xs">
                          <span className="text-slate-400 font-sans text-[11px]">Hike Password:</span>
                          <span className="text-rose-400 font-bold tracking-wider">{isShowHike ? hikePin : "••••••••"}</span>
                          <button
                            type="button"
                            onClick={() => setShowPasswordMap(prev => ({ ...prev, ["hike_" + userEmail]: !prev["hike_" + userEmail] }))}
                            className="text-slate-400 hover:text-white underline text-[11px] ml-1"
                          >
                            {isShowHike ? "🙈 Hide" : "👁️ View"}
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              navigator.clipboard.writeText(`Email: ${userEmail}\nHike PIN: ${hikePin}`);
                              alert(`📋 Hike PIN for ${info.display_name || userEmail} copied to clipboard!`);
                            }}
                            className="text-slate-300 hover:text-white underline text-[11px] ml-1"
                          >
                            📋 Copy
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              const newPin = prompt(`Enter new Hike Security PIN for ${info.display_name || userEmail}:`, hikePin);
                              if (newPin === null) return;
                              if (!newPin.trim()) return alert("PIN cannot be empty!");
                              const updated = { ...safeAccounts, [userEmail]: { ...info, hike_pin: newPin.trim() } };
                              MiamoStore.saveAccounts(updated);
                              setAccounts(updated);
                              alert(`✅ Hike PIN updated for ${info.display_name || userEmail} to: ${newPin.trim()}`);
                            }}
                            className="text-rose-400 hover:underline font-sans text-[11px] ml-1"
                          >
                            ✏️ Edit PIN
                          </button>
                        </div>

                        {/* Hike Margin Box */}
                        <div className="flex items-center gap-2 bg-slate-950 px-3 py-2 rounded-xl border border-slate-800 font-mono text-xs">
                          <span className="text-slate-400 font-sans text-[11px]">Hike Margin:</span>
                          <span className="text-emerald-400 font-extrabold">+{hikePct}%</span>
                          <button
                            type="button"
                            onClick={() => {
                              const newPct = prompt(`Enter new Hike Margin % for ${info.display_name || userEmail}:`, hikePct);
                              if (newPct === null) return;
                              const val = parseFloat(newPct);
                              if (isNaN(val) || val < 0) return alert("Invalid percentage!");
                              const updated = { ...safeAccounts, [userEmail]: { ...info, hike_pct: val } };
                              MiamoStore.saveAccounts(updated);
                              setAccounts(updated);
                              alert(`✅ Hike Margin for ${info.display_name || userEmail} set to +${val}%`);
                            }}
                            className="text-amber-400 hover:underline font-sans text-[11px] ml-1"
                          >
                            ✏️ Edit %
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
            </div>
          </div>

          {/* Section 2: Master System Keys & PINs */}
          <div className="space-y-3 pt-4 border-t border-slate-800">
            <h4 className="font-bold text-emerald-400 text-xs flex items-center gap-1.5"><span>🛡️</span> System Master Security Keys & PINs:</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
              <div className="p-4 bg-slate-900/80 rounded-xl border border-slate-800 flex items-center justify-between">
                <div>
                  <span className="font-bold text-white block">🔒 Admin Panel Security Lock PIN</span>
                  <span className="text-slate-400 text-[11px]">Master code to unlock Admin Panel</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="bg-slate-950 px-3 py-1.5 rounded-lg border border-slate-800 text-emerald-300 font-mono font-bold text-sm">
                    {expectedPin}
                  </span>
                  <button
                    type="button"
                    onClick={() => {
                      const newCode = prompt("Enter new Admin Security PIN:", expectedPin);
                      if (!newCode || !newCode.trim()) return;
                      const updated = { ...settings, admin_security_code: newCode.trim() };
                      MiamoStore.saveSettings(updated);
                      setSettings(updated);
                      alert(`✅ Admin Security PIN updated to: ${newCode.trim()}`);
                    }}
                    className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 font-bold rounded-lg"
                  >
                    ✏️ Edit PIN
                  </button>
                </div>
              </div>

              <div className="p-4 bg-slate-900/80 rounded-xl border border-slate-800 flex items-center justify-between">
                <div>
                  <span className="font-bold text-white block">📈 Global Staff Hike Master Lock</span>
                  <span className="text-slate-400 text-[11px]">Master switch to unlock/lock Hike Calculator for all staff</span>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    const nextState = !hikeUnlocked;
                    setHikeUnlocked(nextState);
                    const updatedSettings = { ...settings, hike_unlocked: nextState };
                    MiamoStore.saveSettings(updatedSettings);
                    setSettings(updatedSettings);
                    alert(`✅ Global Staff Hike Status set to: ${nextState ? 'UNLOCKED (All staff can access Hike Calculator)' : 'RESTRICTED'}`);
                  }}
                  className={`px-3.5 py-2 rounded-xl border font-mono font-bold text-xs cursor-pointer shadow-md transition-all ${
                    hikeUnlocked ? 'bg-emerald-600 hover:bg-emerald-700 text-white border-emerald-500 shadow-emerald-950/40' : 'bg-rose-600 hover:bg-rose-700 text-white border-rose-500 shadow-rose-950/40 animate-pulse'
                  }`}
                >
                  {hikeUnlocked ? "🔓 UNLOCKED for All Staff" : "🔒 RESTRICTED (Click to Unlock All Staff)"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Tab: Account Approvals & New User Desk */}
      {activeAdminTab === "users" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-6">
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-4">
            <div>
              <h3 className="text-base font-bold text-white flex items-center gap-2"><span>📩</span> Account Approvals & New User Registration Desk</h3>
              <p className="text-xs text-slate-400">Review pending staff registration requests or generate new user accounts manually. (All active accounts are managed in Passwords Vault).</p>
            </div>
            <button onClick={() => setShowAddUserModal(true)} className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-rose-900/30 flex items-center gap-1.5 cursor-pointer">
              <span>➕</span> Create User Account Manually
            </button>
          </div>

          {/* Pending Registration Approval Requests Desk Only */}
          <div className="space-y-3">
            <h4 className="font-bold text-amber-400 text-xs flex items-center gap-1.5">
              <span>⏳</span> Pending Registration Approval Requests ({Object.values(safeAccounts).filter(a => a?.status === "Pending Approval").length}):
            </h4>

            {Object.values(safeAccounts).filter(a => a?.status === "Pending Approval").length === 0 ? (
              <div className="p-8 text-center bg-slate-900/40 rounded-2xl border border-slate-800 space-y-2">
                <span className="text-3xl">✅</span>
                <p className="text-sm font-bold text-white">No Pending Account Approvals</p>
                <p className="text-xs text-slate-400">All registered staff members are approved. Active user accounts & credentials are in 🔑 Passwords Vault.</p>
              </div>
            ) : (
              <div className="divide-y divide-slate-800/80 bg-slate-900/80 rounded-2xl border border-amber-800/40 overflow-hidden">
                {Object.entries(safeAccounts)
                  .filter(([_, info]) => info?.status === "Pending Approval")
                  .map(([userEmail, info]) => (
                    <div key={userEmail} className="p-4 flex flex-wrap items-center justify-between gap-4 bg-amber-950/20">
                      <div className="space-y-1">
                        <h4 className="font-bold text-white text-sm flex items-center gap-2">
                          {info.display_name || userEmail}
                          <span className="text-rose-400 font-mono text-xs">({info.member_code || 'MF-0000'})</span>
                          <span className="px-2 py-0.5 bg-amber-500/20 text-amber-300 border border-amber-500/40 text-[10px] font-black rounded-lg animate-pulse">⏳ Pending Approval</span>
                        </h4>
                        <p className="text-xs text-slate-400">
                          {userEmail} • <span className="text-amber-300 font-bold">Requested Role: {info.role || 'User'}</span>
                        </p>
                        <div className="flex items-center gap-2 pt-1 text-xs">
                          <span className="text-slate-400 font-semibold">Designation:</span>
                          <span className="text-white font-medium bg-slate-950 px-2 py-0.5 rounded border border-slate-800">{info.designation || 'Sales Executive'}</span>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-2">
                        <button
                          onClick={() => {
                            const updated = { ...safeAccounts, [userEmail]: { ...info, status: "Active" } };
                            MiamoStore.saveAccounts(updated);
                            setAccounts(updated);
                            alert(`✅ Account for ${info.display_name || userEmail} approved and activated!`);
                          }}
                          className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-black rounded-xl shadow-lg shadow-emerald-900/30 flex items-center gap-1 cursor-pointer"
                        >
                          <span>✅</span> Approve Account
                        </button>

                        <button
                          onClick={() => handleDeleteUser(userEmail, info)}
                          className="px-3 py-2 bg-rose-950 hover:bg-rose-900 text-rose-300 text-xs font-bold rounded-xl border border-rose-800/60 cursor-pointer"
                        >
                          ❌ Reject / Delete
                        </button>
                      </div>
                    </div>
                  ))}
              </div>
            )}
          </div>

          {/* Manual User Creation Modal */}
          {showAddUserModal && (
            <div className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4">
              <div className="max-w-md w-full bg-slate-900 rounded-2xl p-6 border border-slate-800 space-y-4">
                <div className="flex justify-between items-center border-b border-slate-800 pb-2"><h3 className="text-lg font-bold text-white">➕ Manual Account Generator</h3><button onClick={() => setShowAddUserModal(false)} className="text-slate-400 hover:text-white">✕</button></div>
                <form onSubmit={handleCreateUserManually} className="space-y-3 text-left text-xs">
                  <div><label className="text-slate-300 font-semibold block mb-1">User Email ID</label><input type="email" value={newEmail} onChange={e => setNewEmail(e.target.value)} placeholder="executive@miamo.com" className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white" required /></div>
                  <div><label className="text-slate-300 font-semibold block mb-1">Password</label><input type="text" value={newPassword} onChange={e => setNewPassword(e.target.value)} placeholder="Custom Password" className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white" required /></div>
                  <div><label className="text-slate-300 font-semibold block mb-1">Full Name</label><input type="text" value={newName} onChange={e => setNewName(e.target.value)} placeholder="Rahul Sharma" className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white" required /></div>
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">Designation / Role Title</label>
                    <input
                      type="text"
                      value={newDesignation}
                      onChange={e => setNewDesignation(e.target.value)}
                      placeholder="e.g. Export Logistics Manager"
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white font-medium"
                      required
                    />
                  </div>
                  <div><label className="text-slate-300 font-semibold block mb-1">Account Role</label><select value={newRole} onChange={e => setNewRole(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white"><option value="User">User (Standard Sales)</option><option value="Admin">Admin (Full Control)</option></select></div>
                  <div className="pt-2 flex gap-2">
                    <button type="submit" className="flex-1 bg-rose-600 hover:bg-rose-700 text-white font-bold py-2.5 rounded-xl">🚀 Create & Activate User</button>
                    <button type="button" onClick={() => setShowAddUserModal(false)} className="bg-slate-800 text-slate-300 py-2.5 px-4 rounded-xl font-bold">Cancel</button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Tab: Quotations Excel Records Vault (Admin Only) */}
      {activeAdminTab === "quotations_excel" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-5 text-left">
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-4">
            <div>
              <h3 className="text-base font-bold text-white">📊 Quotation Records Vault & Excel Exporter</h3>
              <p className="text-xs text-slate-400">Complete detailed logs of all quotations generated by staff members.</p>
            </div>
            <button
              onClick={() => {
                if (!sentQuotations || sentQuotations.length === 0) return alert("No quotation records found!");
                const excelData = sentQuotations.map((q, idx) => ({
                  "S.No": idx + 1,
                  "Ref No": q.ref_no || "N/A",
                  "Date & Time": q.timestamp || "N/A",
                  "Customer / Buyer Name": q.client_name || "VALUED CUSTOMER",
                  "Customer Phone": q.client_phone || "N/A",
                  "Destination Port": q.dest_port || "Cotonou, Benin",
                  "Sent By": q.sent_by || "Sales Executive"
                }));
                const worksheet = XLSX.utils.json_to_sheet(excelData);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, "Quotation_Log");
                XLSX.writeFile(workbook, `Miamo_Quotations_Export_${new Date().toISOString().slice(0,10)}.xlsx`);
              }}
              className="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-emerald-900/30 flex items-center gap-2"
            >
              📥 Export All Records to Excel (.xlsx)
            </button>
          </div>

          {/* Google Drive Link Config */}
          <div className="p-4 bg-slate-900/90 rounded-xl border border-slate-800 space-y-2 text-xs">
            <label className="text-amber-400 font-bold block flex items-center gap-1.5">
              <span>☁️</span> Google Drive Backup Folder Link (Monthly Auto-Sync)
            </label>
            <div className="flex gap-2">
              <input
                type="url"
                value={settings?.gdrive_folder_link || ""}
                onChange={e => {
                  const updated = { ...settings, gdrive_folder_link: e.target.value };
                  MiamoStore.saveSettings(updated);
                  setSettings(updated);
                }}
                placeholder="https://drive.google.com/drive/folders/your-folder-id"
                className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-mono text-xs focus:border-rose-500 focus:outline-none"
              />
              {settings?.gdrive_folder_link && (
                <a href={settings.gdrive_folder_link} target="_blank" rel="noopener noreferrer" className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl flex items-center gap-1">
                  🔗 Open Drive
                </a>
              )}
            </div>
            <p className="text-[11px] text-slate-400">Monthly backup reports can be directly accessed from this Google Drive link.</p>
          </div>

          {/* Records Table */}
          {sentQuotations.length === 0 ? (
            <p className="text-xs text-slate-500 italic py-6 text-center">No quotation records generated yet.</p>
          ) : (
            <div className="overflow-x-auto rounded-xl border border-slate-800">
              <table className="w-full text-left text-xs">
                <thead className="bg-slate-900 text-slate-400 font-bold border-b border-slate-800">
                  <tr>
                    <th className="p-3">Ref No</th>
                    <th className="p-3">Date / Time</th>
                    <th className="p-3">Customer Name</th>
                    <th className="p-3">Destination Port</th>
                    <th className="p-3">Sent By</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 font-mono text-slate-200">
                  {sentQuotations.map((q, idx) => (
                    <tr key={idx} className="hover:bg-slate-900/50">
                      <td className="p-3 font-bold text-rose-400">{q.ref_no}</td>
                      <td className="p-3 text-slate-400">{q.timestamp}</td>
                      <td className="p-3 font-sans font-bold text-white">{q.client_name}</td>
                      <td className="p-3 text-amber-300">{q.dest_port}</td>
                      <td className="p-3 font-sans">{q.sent_by}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* Tab: Deleted Users */}
      {activeAdminTab === "deleted_users" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
          <h3 className="text-base font-bold text-white">🗑️ Deleted Users Archive & Document Audit Vault</h3>
          <p className="text-xs text-slate-400">Complete historical records of deleted staff accounts.</p>
          {deletedUsers.length === 0 ? (
            <p className="text-xs text-slate-400 italic py-4">No deleted users in archive vault.</p>
          ) : (
            <div className="space-y-4">
              {deletedUsers.map((item, idx) => (
                <div key={idx} className="p-4 bg-slate-900/90 rounded-xl border border-slate-800 space-y-2 text-xs">
                  <div className="flex flex-wrap justify-between items-center text-white border-b border-slate-800 pb-2">
                    <div><span className="font-bold text-sm text-rose-400">{item.account?.display_name || item.email}</span><p className="text-slate-400 text-[11px]">{item.email} • Deleted: {item.deleted_at}</p></div>
                    <button onClick={() => handleRestoreUser(item.email)} className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl shadow-md flex items-center gap-1">🔄 Restore</button>
                  </div>
                  <h5 className="font-bold text-amber-400 mb-1 text-[11px]">📁 Document History ({item.sent_quotations?.length || 0} Quotations):</h5>
                  {(!item.sent_quotations || item.sent_quotations.length === 0) ? (
                    <p className="text-slate-500 italic text-[11px]">No quotation documents recorded.</p>
                  ) : (
                    <div className="space-y-1 pl-2">{item.sent_quotations.map((q, qidx) => (<div key={qidx} className="p-2 bg-slate-950 rounded border border-slate-800/60 flex justify-between text-[11px]"><span><strong>{q.ref_no}</strong> • Client: {q.client_name} ({q.dest_port})</span><span className="text-slate-400">{q.timestamp}</span></div>))}</div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Tab: Product Photos */}
      {activeAdminTab === "photos" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4 text-left">
          <h3 className="text-base font-bold text-white">🖼️ Product Photos & Catalog Image Manager</h3>
          <p className="text-xs text-slate-400">Upload custom product photos. Photos are saved permanently and persist through code updates.</p>
          <div className="space-y-4">
            {Object.entries(catalog).map(([pName, pSpec]) => (
              <div key={pName} className="p-4 bg-slate-900/80 rounded-xl border border-slate-800 flex flex-wrap items-center justify-between gap-4 text-xs">
                <div className="flex items-center gap-3">
                  <div className="w-14 h-14 bg-slate-950 rounded border border-slate-800 overflow-hidden flex items-center justify-center">
                    {pSpec.image ? <img src={pSpec.image} alt={pName} className="w-full h-full object-contain p-1" /> : <span className="text-2xl">📦</span>}
                  </div>
                  <div><h4 className="font-bold text-white">{pName}</h4><p className="text-slate-400 text-[11px]">Category: {pSpec.category} | Packaging: {pSpec.packaging}</p>{MiamoStore.getCatalogPhotos()[pName] && <p className="text-emerald-400 text-[10px] font-bold">✅ Custom Photo Uploaded</p>}</div>
                </div>
                <div className="flex items-center gap-2">
                  <label className="px-3 py-1.5 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl cursor-pointer shadow-lg shadow-rose-900/30">
                    📁 Upload Photo
                    <input type="file" accept="image/*" className="hidden" onChange={(e) => {
                      const file = e.target.files[0];
                      if (!file) return;
                      const reader = new FileReader();
                      reader.onload = (evt) => {
                        const img = new Image();
                        img.onload = () => {
                          const MAX_W = 600;
                          const ratio = Math.min(MAX_W / img.width, 1);
                          const canvas = document.createElement('canvas');
                          canvas.width = Math.round(img.width * ratio);
                          canvas.height = Math.round(img.height * ratio);
                          const ctx = canvas.getContext('2d');
                          ctx.clearRect(0, 0, canvas.width, canvas.height);
                          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                          // Auto-strip solid black background boxes from photos
                          try {
                            const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                            const d = imgData.data;
                            for (let i = 0; i < d.length; i += 4) {
                              if (d[i] < 20 && d[i + 1] < 20 && d[i + 2] < 20) {
                                d[i + 3] = 0; // Turn black background pixels 100% transparent!
                              }
                            }
                            ctx.putImageData(imgData, 0, 0);
                          } catch (err) {}

                          // MUST use image/png to preserve 100% transparency!
                          const compressed = canvas.toDataURL('image/png');
                          const updated = { ...catalog, [pName]: { ...pSpec, image: compressed } };
                          window.PRODUCT_CATALOG[pName].image = compressed;
                          MiamoStore.saveCatalogPhoto(pName, compressed);
                          setCatalog(updated);
                          alert(`✅ Transparent photo uploaded & saved for ${pName}!`);
                        };
                        img.src = evt.target.result;
                      };
                      reader.readAsDataURL(file);
                    }} />
                  </label>

                  {pSpec.image && (
                    <button
                      type="button"
                      onClick={() => {
                        const img = new Image();
                        img.crossOrigin = "anonymous";
                        img.onload = () => {
                          const canvas = document.createElement('canvas');
                          canvas.width = img.width;
                          canvas.height = img.height;
                          const ctx = canvas.getContext('2d');
                          ctx.clearRect(0, 0, canvas.width, canvas.height);
                          ctx.drawImage(img, 0, 0);
                          try {
                            const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                            const d = imgData.data;
                            for (let i = 0; i < d.length; i += 4) {
                              if (d[i] < 25 && d[i + 1] < 25 && d[i + 2] < 25) {
                                d[i + 3] = 0; // Make black background pixels 100% transparent!
                              }
                            }
                            ctx.putImageData(imgData, 0, 0);
                            const cleanedPng = canvas.toDataURL('image/png');
                            const updated = { ...catalog, [pName]: { ...pSpec, image: cleanedPng } };
                            window.PRODUCT_CATALOG[pName].image = cleanedPng;
                            MiamoStore.saveCatalogPhoto(pName, cleanedPng);
                            setCatalog(updated);
                            alert(`✨ Black background box removed for ${pName}! Photo is now 100% transparent.`);
                          } catch (e) {
                            alert("Please re-upload this PNG photo to strip the black background.");
                          }
                        };
                        img.src = pSpec.image;
                      }}
                      className="px-2.5 py-1.5 bg-amber-950 hover:bg-amber-900 text-amber-300 text-xs font-bold rounded-xl border border-amber-800/60"
                      title="Remove solid black background box from photo"
                    >
                      ✨ Remove Black BG
                    </button>
                  )}

                  {MiamoStore.getCatalogPhotos()[pName] && (
                    <button onClick={() => {
                      const saved = MiamoStore.getCatalogPhotos();
                      delete saved[pName];
                      localStorage.setItem("miamo_catalog_photos", JSON.stringify(saved));
                      const defaultImg = "https://images.unsplash.com/photo-1534483509719-3feaee7c30da?w=400&auto=format&fit=crop&q=80";
                      window.PRODUCT_CATALOG[pName].image = defaultImg;
                      setCatalog({ ...catalog, [pName]: { ...pSpec, image: defaultImg } });
                      alert(`↺ Photo reset to default for ${pName}`);
                    }} className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-bold rounded-xl">↺ Reset</button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Tab: Product Specs */}
      {activeAdminTab === "product_specs" && (
        <div className="space-y-6 text-left">
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
            <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-4">
              <div><h3 className="text-base font-bold text-white flex items-center gap-2"><span>📦</span> Export Product Specifications & Catalog Editor</h3><p className="text-xs text-slate-400">Edit, add, or delete product specifications, parameters, grades, and base prices.</p></div>
              <button type="button" onClick={() => {
                const newName = prompt("Enter new export product title / grade:", "FOXNUT (MAKHANA) - GRADE 6 SUTAR");
                if (!newName || !newName.trim()) return;
                const name = newName.trim();
                if (productSpecsList[name]) return alert("Product with this name already exists!");
                const newObj = { origin: "INDIA", default_price: 16.50, cartons_per_20ft: 1200, details: ["GRADE: 6 SUTAR EXPORT QUALITY", "MOISTURE: MAX 8%", "PACKAGING: 10KG CARTON"], image: "" };
                const updated = { ...productSpecsList, [name]: newObj };
                MiamoStore.saveProductSpecs(updated);
                window.PRODUCT_CATALOG = updated;
                setProductSpecsList(updated);
                setSelectedSpecName(name);
                alert(`✅ New product "${name}" added!`);
              }} className="px-4 py-2 bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-500 hover:to-emerald-600 text-white font-bold text-xs rounded-xl shadow-lg shadow-emerald-900/30 flex items-center gap-1.5 cursor-pointer">
                <span>➕</span> Create New Export Product
              </button>
            </div>
            <div className="space-y-2 text-xs">
              <label className="text-slate-300 font-semibold block">Select Product to Edit Specifications:</label>
              <div className="flex gap-3">
                <select value={selectedSpecName} onChange={e => setSelectedSpecName(e.target.value)} className="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-white font-bold text-sm focus:border-rose-500">{specKeys.map(key => <option key={key} value={key}>{key}</option>)}</select>
                <button type="button" onClick={() => {
                  if (!selectedSpecName) return;
                  if (!confirm(`Are you sure you want to delete "${selectedSpecName}"?`)) return;
                  const updated = { ...productSpecsList };
                  delete updated[selectedSpecName];
                  MiamoStore.saveProductSpecs(updated);
                  window.PRODUCT_CATALOG = updated;
                  setProductSpecsList(updated);
                  const remaining = Object.keys(updated);
                  setSelectedSpecName(remaining[0] || "");
                  alert(`🗑️ Product "${selectedSpecName}" deleted!`);
                }} className="px-4 py-2 bg-rose-950/80 hover:bg-rose-900 text-rose-300 font-bold text-xs rounded-xl border border-rose-800/60 cursor-pointer">🗑️ Delete</button>
              </div>
            </div>
            {selectedSpecName && (
              <form onSubmit={(e) => {
                e.preventDefault();
                if (!specEditName.trim()) return alert("Product title required!");
                const detailsArr = specEditDetails.split("\n").map(s => s.trim()).filter(Boolean);
                const currentPhoto = MiamoStore.getCatalogPhotos()[selectedSpecName] || productSpecsList[selectedSpecName]?.image || "";
                const updated = { ...productSpecsList, [specEditName.trim()]: { origin: (specEditOrigin || "INDIA").toUpperCase(), default_price: parseFloat(specEditPrice) || 0, cartons_per_20ft: parseInt(specEditCartons) || 1000, details: detailsArr, image: currentPhoto } };
                if (selectedSpecName !== specEditName.trim()) delete updated[selectedSpecName];
                MiamoStore.saveProductSpecs(updated);
                window.PRODUCT_CATALOG = updated;
                setProductSpecsList(updated);
                setSelectedSpecName(specEditName.trim());
                alert(`✅ Product Specifications for "${specEditName.trim()}" saved!`);
              }} className="space-y-4 pt-2 text-xs">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div><label className="text-slate-300 font-semibold block mb-1">Product Title & Grade Name</label><input type="text" value={specEditName} onChange={e => setSpecEditName(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2.5 text-white font-bold text-sm" required /></div>
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">Country of Origin</label>
                    <select
                      value={(specEditOrigin || "INDIA").toUpperCase()}
                      onChange={e => setSpecEditOrigin(e.target.value.toUpperCase())}
                      className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2.5 text-white font-semibold"
                    >
                      <option value="CHINA">CHINA</option>
                      <option value="MALAYSIA">MALAYSIA</option>
                      <option value="OMAN">OMAN</option>
                      <option value="INDIA">INDIA</option>
                      <option value="VIETNAM">VIETNAM</option>
                      <option value="BRAZIL">BRAZIL</option>
                    </select>
                  </div>
                  <div><label className="text-slate-300 font-semibold block mb-1">Default Base Purchase Price ($)</label><input type="number" step="0.01" value={specEditPrice} onChange={e => setSpecEditPrice(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2.5 text-amber-400 font-mono font-bold" required /></div>
                  <div><label className="text-slate-300 font-semibold block mb-1">Cartons per 20ft Container</label><input type="number" value={specEditCartons} onChange={e => setSpecEditCartons(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2.5 text-white font-mono font-semibold" required /></div>
                </div>
                <div><label className="text-slate-300 font-semibold block mb-1">Specification Detail Lines (1 per line)</label><textarea rows={5} value={specEditDetails} onChange={e => setSpecEditDetails(e.target.value)} className="w-full bg-slate-900 border border-slate-800 rounded-xl p-3 text-white font-mono text-xs focus:border-rose-500" /></div>
                <div className="pt-2 flex justify-end"><button type="submit" className="px-6 py-3 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-rose-900/40 flex items-center gap-2 cursor-pointer">💾 Save Product Specifications</button></div>
              </form>
            )}
          </div>
        </div>
      )}

      {/* Tab: Audit Logs — with Location & Filter */}
      {activeAdminTab === "audit" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4 text-left">
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-4">
            <div>
              <h3 className="text-base font-bold text-white">📊 System Security Audit Logs (Live Location & Activity Tracking)</h3>
              <p className="text-xs text-slate-400">Complete detailed logs of all user logins, session locations, quotation actions, and activity durations.</p>
            </div>
            <input
              type="text"
              value={auditSearchQuery}
              onChange={e => setAuditSearchQuery(e.target.value)}
              placeholder="🔍 Search by user, city, IP, action..."
              className="bg-slate-900 border border-slate-800 rounded-xl px-4 py-2 text-xs text-white placeholder-slate-500 w-64 focus:border-rose-500 focus:outline-none"
            />
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead className="bg-slate-900 text-slate-400 uppercase">
                <tr>
                  <th className="p-2.5">Timestamp</th>
                  <th className="p-2.5">User</th>
                  <th className="p-2.5">Action</th>
                  <th className="p-2.5">📍 Location & IP</th>
                  <th className="p-2.5">Customer & Port</th>
                  <th className="p-2.5">⏱️ Duration</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800 text-slate-300">
                {safeLogs
                  .filter(log => {
                    if (!auditSearchQuery.trim()) return true;
                    const q = auditSearchQuery.toLowerCase();
                    return (
                      (log?.['User Email'] || '').toLowerCase().includes(q) ||
                      (log?.Action || '').toLowerCase().includes(q) ||
                      (log?.Location || '').toLowerCase().includes(q) ||
                      (log?.['Real Client IP'] || '').toLowerCase().includes(q) ||
                      (log?.['Customer Name'] || '').toLowerCase().includes(q)
                    );
                  })
                  .map((log, idx) => (
                    <tr key={idx} className="hover:bg-slate-900/50">
                      <td className="p-2.5 font-mono text-[11px] whitespace-nowrap">{log?.Timestamp || 'N/A'}</td>
                      <td className="p-2.5 font-semibold text-white text-[11px] whitespace-nowrap">{log?.['User Email'] || 'N/A'}</td>
                      <td className="p-2.5 text-rose-400 font-bold text-[11px]">{log?.Action || 'N/A'}</td>
                      <td className="p-2.5 text-[11px]">
                        <span className="text-emerald-400 font-semibold">{log?.Location || '—'}</span>
                        {log?.['Real Client IP'] && <span className="block text-slate-500 text-[10px]">IP: {log['Real Client IP']}</span>}
                      </td>
                      <td className="p-2.5 text-[11px]">
                        {log?.['Customer Name'] && log['Customer Name'] !== 'N/A' ? (
                          <span>Client: <strong className="text-white">{log['Customer Name']}</strong> ({log?.['Destination Port'] || ''})</span>
                        ) : (
                          <span>Port: {log?.['Destination Port'] || 'N/A'}</span>
                        )}
                      </td>
                      <td className="p-2.5 text-[11px] font-mono text-amber-300 font-bold">{log?.Duration || 'Active'}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Tab: Feedback */}
      {activeAdminTab === "feedback" && (
        <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
          <h3 className="text-base font-bold text-white">💬 Team Feedback & Suggestions Desk</h3>
          {safeSuggestions.length === 0 ? <p className="text-xs text-slate-400 italic">No feedback submitted yet.</p> : (
            <div className="space-y-3">{safeSuggestions.map((s, idx) => (
              <div key={idx} className="p-4 bg-slate-900/80 rounded-xl border border-slate-800 text-xs space-y-1">
                <div className="flex items-center justify-between"><span className="font-bold text-rose-400">{s.type}</span><span className="text-slate-500 text-[11px]">{s.timestamp}</span></div>
                <p className="text-slate-300">{s.message}</p>
                <p className="text-slate-400 text-[11px]">From: {s.user_email}</p>
              </div>
            ))}</div>
          )}
        </div>
      )}

      {/* Tab: UI & Theme — Dropdown with 12 themes + 25 fonts */}
      {activeAdminTab === "theme" && (
        <div className="space-y-6 text-left">
          {/* Custom Canva Theme Palette Studio & Delete / Undo Manager */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-5 text-xs">
            <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-3">
              <div>
                <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🎨</span> Master Theme & 5-Color Custom Palette Studio</h3>
                <p className="text-xs text-slate-400">Create custom 5-color palettes, import palette links from Coolors / ColorHunt, edit colors, delete themes, or undo deletion.</p>
              </div>
              <div className="flex items-center gap-2 flex-wrap">
                <button
                  type="button"
                  onClick={() => {
                    if (confirm("Are you sure you want to reset all theme color overrides to defaults? This will clear any cached dark overrides.")) {
                      localStorage.removeItem("miamo_theme_color_overrides");
                      alert("✅ Theme color overrides reset! Reloading page...");
                      location.reload();
                    }
                  }}
                  className="px-3.5 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 font-bold text-xs rounded-xl flex items-center gap-1.5 cursor-pointer border border-slate-700"
                  title="Purge cached theme overrides from browser memory"
                >
                  <span>🧹</span> Reset Overrides
                </button>

                <button
                  type="button"
                  onClick={() => {
                    const newKey = `custom_${Date.now()}`;
                    setEditingThemeObj({
                      value: newKey,
                      label: "✨ New 5-Color Custom Palette",
                      desc: "User created custom 5-color palette",
                      isCustom: true
                    });
                    setEditPrimaryHex("#DA1C30");
                    setEditAccentHex("#F59E0B");
                    setEditBgHex("#0B0F17");
                    setEditSurfaceHex("#1E293B");
                    setEditTextHex("#FFFFFF");
                    setPaletteUrlInput("");
                  }}
                  className="px-4 py-2 bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-black text-xs rounded-xl shadow-lg shadow-rose-900/30 flex items-center gap-1.5 cursor-pointer"
                >
                  <span>➕</span> Create New 5-Color Palette
                </button>

                {deletedThemesHistory.length > 0 && (
                  <button
                    type="button"
                    onClick={handleUndoThemeDelete}
                    className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-black text-xs rounded-xl shadow-lg shadow-emerald-900/30 flex items-center gap-1.5 cursor-pointer animate-pulse"
                  >
                    <span>↩️</span> Undo Theme Delete ({deletedThemesHistory.length})
                  </button>
                )}
              </div>
            </div>

            {themeToast && (
              <div className="p-3 bg-rose-950/80 border border-rose-800 text-rose-300 font-bold rounded-xl flex items-center justify-between">
                <span>{themeToast}</span>
                <button type="button" onClick={handleUndoThemeDelete} className="underline text-amber-300 text-xs ml-3 font-black">↩️ Undo Now</button>
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="text-slate-300 font-semibold block mb-2">Active Theme (Select from dropdown):</label>
                <select
                  value={theme || localStorage.getItem("miamo_app_theme") || "dark"}
                  onChange={e => handleSetTheme(e.target.value)}
                  className="w-full bg-slate-900 border border-rose-500/40 rounded-xl px-4 py-3 text-white font-bold text-sm focus:border-rose-500 focus:outline-none"
                >
                  {allThemeOptions.map(t => (
                    <option key={t.value} value={t.value}>{t.label} — {t.desc}</option>
                  ))}
                </select>
                <div className="mt-3 p-3 bg-slate-900/80 rounded-xl border border-slate-800">
                  <p className="text-slate-300 text-xs"><strong>Currently Active:</strong> <span className="text-rose-400 font-bold">{allThemeOptions.find(t => t.value === (theme || localStorage.getItem("miamo_app_theme") || 'dark'))?.label || '🌙 Dark Obsidian'}</span></p>
                </div>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-2">Product Card Photo Background Style:</label>
                <select
                  value={settings?.product_card_img_bg || "pure_white"}
                  onChange={e => {
                    const updated = { ...settings, product_card_img_bg: e.target.value };
                    MiamoStore.saveSettings(updated);
                    setSettings(updated);
                  }}
                  className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-white font-bold text-sm focus:border-rose-500 focus:outline-none"
                >
                  <option value="pure_white">⚪ Pure Crisp White Badge (Default — Clean Image Look)</option>
                  <option value="dark_glass">🌙 Dark Glassmorphic Box</option>
                  <option value="transparent_3d">✨ 100% Transparent 3D Floating</option>
                </select>
                <p className="text-[11px] text-emerald-400 mt-2">✅ Product photo background displays clean white!</p>
              </div>
            </div>

            {/* Sleek Theme Dropdown Selection & Control Panel (NO grid of small boxes) */}
            <div className="p-4 bg-slate-950/80 rounded-2xl border border-slate-800 space-y-3">
              <label className="text-slate-300 font-bold text-xs flex items-center justify-between">
                <span className="flex items-center gap-1.5"><span>🎨</span> Select & Manage Theme (Dropdown Menu)</span>
                <span className="text-[11px] text-amber-400 font-mono">{allThemeOptions.length} Themes Available</span>
              </label>

              <div className="flex flex-col sm:flex-row gap-2.5 items-center">
                <select
                  value={theme || localStorage.getItem("miamo_app_theme") || "dark"}
                  onChange={e => handleSetTheme(e.target.value)}
                  className="flex-1 w-full bg-slate-900 border border-rose-500/50 rounded-xl px-4 py-2.5 text-white font-bold text-xs focus:border-rose-500 focus:outline-none cursor-pointer shadow-inner"
                >
                  <optgroup label="✨ Built-in System Themes">
                    {THEME_OPTIONS.filter(t => !deletedThemeKeys.includes(t.value)).map(t => (
                      <option key={t.value} value={t.value}>{t.label} — {t.desc}</option>
                    ))}
                  </optgroup>
                  {customThemes.filter(ct => !deletedThemeKeys.includes(ct.value)).length > 0 && (
                    <optgroup label="🎨 Your Custom Themes">
                      {customThemes.filter(ct => !deletedThemeKeys.includes(ct.value)).map(ct => (
                        <option key={ct.value} value={ct.value}>{ct.label} — Custom Palette</option>
                      ))}
                    </optgroup>
                  )}
                </select>

                <div className="flex items-center gap-2 w-full sm:w-auto flex-shrink-0">
                  <button
                    type="button"
                    onClick={() => {
                      const currentThemeObj = allThemeOptions.find(t => t.value === (theme || localStorage.getItem("miamo_app_theme") || "dark")) || allThemeOptions[0];
                      if (currentThemeObj) {
                        setEditingThemeObj(currentThemeObj);
                        setEditThemeLabel(currentThemeObj.label || currentThemeObj.value);
                        setEditPrimaryHex(currentThemeObj.colors?.primary || "#DA1C30");
                        setEditAccentHex(currentThemeObj.colors?.accent || "#F59E0B");
                        setEditBgHex(currentThemeObj.colors?.bg || "#0B0F17");
                        setEditSurfaceHex(currentThemeObj.colors?.surface || currentThemeObj.colors?.card || currentThemeObj.colors?.bg || "#1E293B");
                        setEditTextHex(currentThemeObj.colors?.text || "#FFFFFF");
                        setEditSubtextHex(currentThemeObj.colors?.subtext || "#94a3b8");
                        setEditHighlightHex(currentThemeObj.colors?.highlight || currentThemeObj.colors?.accent || "#F59E0B");
                        setEditBorderHex(currentThemeObj.colors?.border || "#334155");
                        setEditSidebarHex(currentThemeObj.colors?.sidebar || "#0f172a");
                        setEditTabHex(currentThemeObj.colors?.activeTab || "#e11d48");
                        setPaletteUrlInput("");
                      }
                    }}
                    className="px-3.5 py-2.5 bg-amber-600 hover:bg-amber-500 text-white font-bold text-xs rounded-xl shadow cursor-pointer flex items-center gap-1"
                    title="Edit Active Theme Name & Colors"
                  >
                    <span>✏️</span> Edit Active Theme
                  </button>

                  {customThemes.some(ct => ct.value === (theme || "dark")) && (
                    <button
                      type="button"
                      onClick={() => {
                        const currentThemeObj = allThemeOptions.find(t => t.value === (theme || "dark"));
                        if (currentThemeObj) handleDeleteTheme(currentThemeObj);
                      }}
                      className="px-3 py-2.5 bg-slate-800 hover:bg-rose-900/60 text-rose-400 font-bold text-xs rounded-xl border border-rose-800/40 cursor-pointer flex items-center gap-1"
                      title="Delete Custom Theme"
                    >
                      <span>🗑️</span> Delete
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* Add Custom Theme Form (Canva / Palette Link Auto-Generator) */}
            <form onSubmit={handleAddCustomTheme} className="border-t border-slate-800 pt-4 space-y-3">
              <h4 className="font-bold text-white text-xs flex items-center justify-between gap-1.5">
                <span className="flex items-center gap-1.5"><span>🔗</span> Auto-Generate Theme from Canva / Coolors / Palette Link</span>
                <span className="text-[10px] text-amber-400 font-mono">Paste link or choose manual hexes below</span>
              </h4>
              
              <div className="p-3 bg-slate-950 rounded-xl border border-slate-800 space-y-2">
                <div className="flex flex-col sm:flex-row gap-2">
                  <input
                    type="text"
                    value={paletteUrlInput}
                    onChange={e => setPaletteUrlInput(e.target.value)}
                    placeholder="Paste Canva / Coolors / ColorHunt / Website Palette Link (e.g. https://coolors.co/2b2d42-8d99ae-edf2f4-ef233c-d90429)"
                    className="flex-1 bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-xs text-white font-mono placeholder-slate-500 focus:border-amber-500 focus:outline-none"
                  />
                  <button
                    type="button"
                    onClick={() => {
                      const parsed = parsePaletteUrlOrHex(paletteUrlInput);
                      if (parsed) {
                        setNewPrimaryHex(parsed.primary);
                        setNewAccentHex(parsed.accent);
                        setNewBgHex(parsed.bg);
                        setNewTextHex(parsed.text);
                        alert("⚡ 5 Hex Colors extracted from link into color pickers!");
                      } else {
                        alert("⚠️ Could not extract colors from link. Please paste a valid Canva/Coolors link or raw hex codes!");
                      }
                    }}
                    className="px-3.5 py-2 bg-gradient-to-r from-amber-500 to-rose-600 hover:from-amber-400 hover:to-rose-500 text-white font-black text-xs rounded-xl cursor-pointer flex-shrink-0"
                  >
                    ⚡ Extract Colors
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
                <div>
                  <label className="text-slate-400 block mb-1">Theme Name</label>
                  <input
                    type="text"
                    value={newThemeName}
                    onChange={e => setNewThemeName(e.target.value)}
                    placeholder="e.g. Canva Sunset Gold"
                    className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white font-bold"
                    required
                  />
                </div>
                <div>
                  <label className="text-slate-400 block mb-1">Primary Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={newPrimaryHex} onChange={e => setNewPrimaryHex(e.target.value)} className="w-8 h-8 rounded cursor-pointer bg-slate-900 border border-slate-800" />
                    <input type="text" value={newPrimaryHex} onChange={e => setNewPrimaryHex(e.target.value)} className="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-2 py-1.5 font-mono text-[11px] text-white" />
                  </div>
                </div>
                <div>
                  <label className="text-slate-400 block mb-1">Accent Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={newAccentHex} onChange={e => setNewAccentHex(e.target.value)} className="w-8 h-8 rounded cursor-pointer bg-slate-900 border border-slate-800" />
                    <input type="text" value={newAccentHex} onChange={e => setNewAccentHex(e.target.value)} className="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-2 py-1.5 font-mono text-[11px] text-white" />
                  </div>
                </div>
                <div>
                  <label className="text-slate-400 block mb-1">Background Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={newBgHex} onChange={e => setNewBgHex(e.target.value)} className="w-8 h-8 rounded cursor-pointer bg-slate-900 border border-slate-800" />
                    <input type="text" value={newBgHex} onChange={e => setNewBgHex(e.target.value)} className="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-2 py-1.5 font-mono text-[11px] text-white" />
                  </div>
                </div>
                <div className="flex items-end">
                  <button
                    type="submit"
                    className="w-full py-2 px-3 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-rose-900/30 cursor-pointer"
                  >
                    ➕ Create Theme Palette
                  </button>
                </div>
              </div>
            </form>
          </div>

          {/* Brand Title, Logo & Typography */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
            <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🖼️</span> Brand Logo & Title Styling Studio</h3>
            <p className="text-xs text-slate-400">Customize the top-left portal brand text, logo photo, font family, font size, and color style.</p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Brand Title Text</label>
                <input type="text" value={settings?.brand_title_text || "MIAMO FOODS EXPORTS"} onChange={e => { const updated = { ...settings, brand_title_text: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-bold" placeholder="e.g. MIAMO FOODS EXPORTS" />
              </div>
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Brand Subtitle Text</label>
                <input type="text" value={settings?.brand_subtitle_text || "Price Quotation & Management Portal"} onChange={e => { const updated = { ...settings, brand_subtitle_text: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white" placeholder="e.g. Price Quotation & Management Portal" />
              </div>

              {/* 25+ Font Dropdown */}
              <div className="md:col-span-2">
                <label className="text-slate-300 font-semibold block mb-1">Brand Font Family Style (25 Premium Fonts)</label>
                <select
                  value={settings?.brand_font_family || "Inter"}
                  onChange={e => { const updated = { ...settings, brand_font_family: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }}
                  className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold"
                >
                  {FONT_OPTIONS.map(f => (
                    <option key={f.value} value={f.value}>{f.label}</option>
                  ))}
                </select>
                {/* Live Font Preview */}
                <div className="mt-2 p-3 bg-slate-900/60 rounded-xl border border-slate-800">
                  <p className="text-[11px] text-slate-400 mb-1">Live Font Preview:</p>
                  <p className="text-lg text-white font-bold" style={{ fontFamily: FONT_OPTIONS.find(f => f.value === (settings?.brand_font_family || 'Inter'))?.css || "'Inter', sans-serif" }}>
                    {settings?.brand_title_text || "MIAMO FOODS EXPORTS"}
                  </p>
                </div>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Brand Title Font Size</label>
                <select value={settings?.brand_font_size || "medium"} onChange={e => { const updated = { ...settings, brand_font_size: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="small">Small (14px)</option><option value="medium">Medium Standard (16px)</option><option value="large">Large Prominent (18px)</option><option value="xl">Extra Large Banner (20px)</option>
                </select>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Brand Title Color Gradient</label>
                <select value={settings?.brand_title_color || "rose_gradient"} onChange={e => { const updated = { ...settings, brand_title_color: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="rose_gradient">🔴 Rose & Red Gradient</option>
                  <option value="gold_luxury">👑 Luxury Gold & Amber</option>
                  <option value="emerald_glow">💚 Royal Emerald Glow</option>
                  <option value="cyber_cyan">💙 Cyber Cyan Gradient</option>
                  <option value="pure_white">⚪ Pure Crystal White</option>
                </select>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Brand Logo Photo / Image</label>
                <div className="flex items-center gap-3 pt-1">
                  <div className="w-12 h-12 bg-rose-600 rounded-xl flex items-center justify-center font-bold text-white text-xs overflow-hidden border border-rose-400 flex-shrink-0">
                    {settings?.brand_logo_url ? <img src={settings.brand_logo_url} alt="Logo" className="w-full h-full object-contain" /> : "MF"}
                  </div>
                  <label className="px-3.5 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl cursor-pointer shadow-lg shadow-rose-900/30">
                    📁 Upload Logo Photo
                    <input type="file" accept="image/*" className="hidden" onChange={(e) => {
                      const file = e.target.files[0];
                      if (!file) return;
                      const reader = new FileReader();
                      reader.onload = (evt) => { const updated = { ...settings, brand_logo_url: evt.target.result }; MiamoStore.saveSettings(updated); setSettings(updated); alert("✅ Brand Logo photo updated successfully!"); };
                      reader.readAsDataURL(file);
                    }} />
                  </label>
                  {settings?.brand_logo_url && (
                    <button onClick={() => { const updated = { ...settings, brand_logo_url: "" }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="text-xs text-rose-400 hover:underline">Remove Logo</button>
                  )}
                </div>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Logo Circle / Frame Size (Preset & Pixel Slider)</label>
                <div className="space-y-2">
                  <select
                    value={settings?.brand_logo_size || "medium"}
                    onChange={e => {
                      const val = e.target.value;
                      const pxMap = { small: 28, medium: 44, large: 60, xl: 76, jumbo: 96, giant: 120 };
                      const updated = { ...settings, brand_logo_size: val, brand_logo_size_px: pxMap[val] || 44 };
                      MiamoStore.saveSettings(updated);
                      setSettings(updated);
                    }}
                    className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold"
                  >
                    <option value="small">Small Circle (28px)</option>
                    <option value="medium">Medium Circle (44px Standard)</option>
                    <option value="large">Large Circle (60px)</option>
                    <option value="xl">Extra Large Circle (76px)</option>
                    <option value="jumbo">Jumbo Circle (96px)</option>
                    <option value="giant">Giant Circle (120px)</option>
                  </select>
                  
                  {/* Slider for exact pixel size adjustment */}
                  <div className="flex items-center gap-3 bg-slate-900/80 p-2 rounded-xl border border-slate-800">
                    <span className="text-[10px] text-slate-400 font-bold uppercase">Custom Size:</span>
                    <input
                      type="range"
                      min="24"
                      max="150"
                      value={settings?.brand_logo_size_px || 44}
                      onChange={e => {
                        const px = parseInt(e.target.value, 10);
                        const updated = { ...settings, brand_logo_size_px: px };
                        MiamoStore.saveSettings(updated);
                        setSettings(updated);
                      }}
                      className="flex-1 accent-rose-500 cursor-pointer"
                    />
                    <span className="text-xs font-mono font-bold text-amber-300">{settings?.brand_logo_size_px || 44}px</span>
                  </div>
                </div>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Logo Frame Shape Style</label>
                <select
                  value={settings?.brand_logo_shape || "rounded-full"}
                  onChange={e => { const updated = { ...settings, brand_logo_shape: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }}
                  className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold"
                >
                  <option value="rounded-full">🟢 Perfect Circle (Default)</option>
                  <option value="rounded-2xl">Rounded Smooth Box</option>
                  <option value="rounded-lg">Soft Square</option>
                  <option value="square">Sharp Square</option>
                </select>
              </div>
            </div>
          </div>

          {/* Header & Pills */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
            <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🛠️</span> Top Header Bar & Status Pills Studio</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Header Bar Color & Style</label>
                <select value={settings?.header_bg_style || "slate_dark"} onChange={e => { const updated = { ...settings, header_bg_style: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="slate_dark">Dark Obsidian Slate (Default)</option><option value="deep_navy">Deep Navy Blue Glass</option><option value="rose_glass">Rose Ruby Glass</option><option value="midnight_purple">Midnight Purple Glass</option><option value="emerald_dark">Royal Emerald Dark</option><option value="custom">Custom Color Picker (Hex)</option>
                </select>
              </div>
              {settings?.header_bg_style === "custom" && (
                <div><label className="text-slate-300 font-semibold block mb-1">Custom Header Hex Color</label><input type="color" value={settings?.header_custom_hex || "#0f172a"} onChange={e => { const updated = { ...settings, header_custom_hex: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full h-10 bg-slate-900 border border-slate-800 rounded-xl p-1 cursor-pointer" /></div>
              )}
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Status Pills Bar Alignment</label>
                <select value={settings?.pills_location || "right"} onChange={e => { const updated = { ...settings, pills_location: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="right">Align Right (Standard)</option><option value="center">Align Center</option><option value="left">Align Left</option>
                </select>
              </div>
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Status Pills Visual Style</label>
                <select value={settings?.pills_style || "glassmorphic"} onChange={e => { const updated = { ...settings, pills_style: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="glassmorphic">Glassmorphic Dark</option><option value="vibrant_gradient">Vibrant Red-Indigo Gradient</option><option value="neon_border">Neon Cyber Emerald Glow</option><option value="minimal">Minimalist Subtle Slate</option>
                </select>
              </div>
            </div>
          </div>

          {/* ElevenLabs + StreamElements Voice Studio */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
            <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-3">
              <div>
                <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🎙️</span> Natural Human Voice Greeting Studio</h3>
                <p className="text-xs text-slate-400">StreamElements TTS is FREE — no API key needed! Or use your own ElevenLabs API key for ultra-realistic voices.</p>
              </div>
              <button
                onClick={() => {
                  const sampleText = `Hello ${currentUser?.display_name || "Admin"}! Welcome back to Miamo Foods Exports. How can I help you today?`;
                  speakTextWithHumanVoice(sampleText, currentUser?.gender || "Male");
                }}
                className="px-4 py-2 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-slate-950 font-black text-xs rounded-xl shadow-lg shadow-amber-900/30 flex items-center gap-1.5 cursor-pointer"
              >
                <span>🔊</span> Test Human Voice
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Voice Engine Mode</label>
                <select value={settings?.voice_engine_mode || "streamelements"} onChange={e => { const updated = { ...settings, voice_engine_mode: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                  <option value="streamelements">🆓 StreamElements TTS (FREE — No API Key)</option>
                  <option value="natural_neural">🎙️ Natural Neural Browser Voice</option>
                  <option value="elevenlabs">✨ ElevenLabs AI Human Voice (API Key Required)</option>
                </select>
              </div>

              {/* StreamElements Voice Selection */}
              {(settings?.voice_engine_mode === "streamelements" || !settings?.voice_engine_mode) && (
                <div>
                  <label className="text-slate-300 font-semibold block mb-1">StreamElements Voice Character</label>
                  <select value={settings?.se_voice_id || "Brian"} onChange={e => { const updated = { ...settings, se_voice_id: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                    {SE_VOICE_OPTIONS.map(v => <option key={v.id} value={v.id}>{v.label}</option>)}
                  </select>
                  <p className="text-[10px] text-emerald-400 mt-1">✅ Completely FREE — powered by Amazon Polly via StreamElements</p>
                </div>
              )}

              {/* ElevenLabs fields */}
              {settings?.voice_engine_mode === "elevenlabs" && (
                <>
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">ElevenLabs API Key</label>
                    <input type="password" value={settings?.elevenlabs_api_key || ""} onChange={e => { const updated = { ...settings, elevenlabs_api_key: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} placeholder="sk_xxxxxxxxxxxxxxxx" className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-mono" />
                  </div>
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">ElevenLabs Voice Preset</label>
                    <select value={settings?.elevenlabs_voice_id || "21m00Tcm4TlvDq8ikWAM"} onChange={e => { const updated = { ...settings, elevenlabs_voice_id: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-semibold">
                      <option value="21m00Tcm4TlvDq8ikWAM">Rachel (Warm & Natural Female)</option>
                      <option value="ErXwobaYiN019PkySvjV">Antoni (Deep & Professional Male)</option>
                      <option value="EXAVITQu4vr4xnSDxMaL">Bella (Expressive Soft Female)</option>
                      <option value="pNInz6obpgDQGcFmaJgB">Adam (Dominant Executive Male)</option>
                    </select>
                  </div>
                </>
              )}

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Voice Pitch (Browser: 1.0)</label>
                <div className="flex items-center gap-3">
                  <input type="range" min="0.5" max="1.5" step="0.05" value={settings?.voice_pitch || 1.0} onChange={e => { const updated = { ...settings, voice_pitch: parseFloat(e.target.value) }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="flex-1" />
                  <span className="text-amber-400 font-mono font-bold">{settings?.voice_pitch || 1.0}x</span>
                </div>
              </div>

              <div>
                <label className="text-slate-300 font-semibold block mb-1">Voice Speed Rate (0.95 = Natural)</label>
                <div className="flex items-center gap-3">
                  <input type="range" min="0.7" max="1.3" step="0.05" value={settings?.voice_rate || 0.95} onChange={e => { const updated = { ...settings, voice_rate: parseFloat(e.target.value) }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="flex-1" />
                  <span className="text-amber-400 font-mono font-bold">{settings?.voice_rate || 0.95}x</span>
                </div>
              </div>
            </div>
          </div>

          {/* Security & Announcement */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
            <h3 className="text-base font-bold text-white flex items-center gap-2"><span>⚙️</span> Portal Security & Announcement Settings</h3>
            <div className="space-y-4 text-xs">
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Welcome Hub Announcement Banner</label>
                <input type="text" value={settings?.home_custom_announcement || ""} onChange={e => { const updated = { ...settings, home_custom_announcement: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500" />
              </div>
              <div>
                <label className="text-slate-300 font-semibold block mb-1">Admin Security Lock PIN</label>
                <input type="text" value={settings?.admin_security_code || "282911"} onChange={e => { const updated = { ...settings, admin_security_code: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }} className="w-full bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-sm text-white focus:border-rose-500 font-mono tracking-widest" />
              </div>
            </div>
          </div>
        </div>
      )}

          {/* Tab: System Settings — Cleaned Up (No Duplicate Freight Rates) */}
          {activeAdminTab === "system_settings" && (
            <div className="space-y-6 text-left">
              {/* Custom PDF Page Template & Letterhead Studio */}
              <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
                <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-3">
                  <div>
                    <h3 className="text-base font-bold text-white flex items-center gap-2"><span>📄</span> Custom PDF Quotation Page Template & Letterhead Studio</h3>
                    <p className="text-xs text-slate-400">Upload your company's official letterhead background image or custom page design. All generated product quote PDFs will print automatically on this fixed template page!</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setShowPdfPreviewModal(true)}
                    className="px-4 py-2 bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-black text-xs rounded-xl shadow-lg shadow-rose-900/30 flex items-center gap-1.5 cursor-pointer"
                  >
                    <span>👁️</span> Preview PDF on Custom Template
                  </button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">Upload Letterhead / PDF Background Image</label>
                    <div className="flex items-center gap-3 pt-1">
                      <div className="w-16 h-20 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center overflow-hidden flex-shrink-0 shadow-md">
                        {settings?.pdf_bg_template_url ? (
                          <img src={settings.pdf_bg_template_url} alt="PDF Template" className="w-full h-full object-cover" />
                        ) : (
                          <span className="text-2xl">📄</span>
                        )}
                      </div>
                      <div className="space-y-2">
                        <label className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl cursor-pointer shadow-lg shadow-rose-900/30 inline-block">
                          📁 Upload PDF Template Image
                          <input
                            type="file"
                            accept="image/*"
                            className="hidden"
                            onChange={e => {
                              const file = e.target.files[0];
                              if (!file) return;
                              const reader = new FileReader();
                              reader.onload = (evt) => {
                                const img = new Image();
                                img.onload = () => {
                                  const canvas = document.createElement('canvas');
                                  const MAX_W = 1200;
                                  const ratio = Math.min(MAX_W / img.width, 1);
                                  canvas.width = Math.round(img.width * ratio);
                                  canvas.height = Math.round(img.height * ratio);
                                  const ctx = canvas.getContext('2d');
                                  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                                  const compressed = canvas.toDataURL('image/jpeg', 0.85);
                                  const updated = { ...settings, pdf_bg_template_url: compressed };
                                  MiamoStore.saveSettings(updated);
                                  setSettings(updated);
                                  alert("✅ Custom PDF background template uploaded and saved!");
                                };
                                img.src = evt.target.result;
                              };
                              reader.readAsDataURL(file);
                            }}
                          />
                        </label>
                        {settings?.pdf_bg_template_url && (
                          <button
                            type="button"
                            onClick={() => {
                              const updated = { ...settings, pdf_bg_template_url: "" };
                              MiamoStore.saveSettings(updated);
                              setSettings(updated);
                            }}
                            className="block text-xs text-rose-400 hover:underline font-semibold"
                          >
                            Reset to Standard White PDF
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* PDF Elements Customizer Toggles */}
                <div className="pt-4 border-t border-slate-800 space-y-3">
                  <h4 className="font-bold text-rose-400 text-xs flex items-center gap-1.5">
                    <span>🎛️</span> PDF Template Elements Layout Customizer (Full Show/Hide Control)
                  </h4>
                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
                    <label className="flex items-center gap-2 p-2.5 bg-slate-900 rounded-xl border border-slate-800 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={settings?.pdf_show_top_header !== false}
                        onChange={e => {
                          const updated = { ...settings, pdf_show_top_header: e.target.checked };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                        }}
                        className="w-4 h-4 rounded text-rose-600 focus:ring-rose-500"
                      />
                      <span className="text-white font-bold text-xs">Top Ref No & Client Header</span>
                    </label>

                    <label className="flex items-center gap-2 p-2.5 bg-slate-900 rounded-xl border border-slate-800 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={settings?.pdf_show_top_logo === true}
                        onChange={e => {
                          const updated = { ...settings, pdf_show_top_logo: e.target.checked };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                        }}
                        className="w-4 h-4 rounded text-rose-600 focus:ring-rose-500"
                      />
                      <span className="text-white font-bold text-xs">Top Left Logo & Tagline</span>
                    </label>

                    <label className="flex items-center gap-2 p-2.5 bg-slate-900 rounded-xl border border-slate-800 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={settings?.pdf_show_price_list_badge === true}
                        onChange={e => {
                          const updated = { ...settings, pdf_show_price_list_badge: e.target.checked };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                        }}
                        className="w-4 h-4 rounded text-rose-600 focus:ring-rose-500"
                      />
                      <span className="text-white font-bold text-xs">". Price List ." Banner Box</span>
                    </label>

                    <label className="flex items-center gap-2 p-2.5 bg-slate-900 rounded-xl border border-slate-800 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={settings?.pdf_show_terms_box !== false}
                        onChange={e => {
                          const updated = { ...settings, pdf_show_terms_box: e.target.checked };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                        }}
                        className="w-4 h-4 rounded text-rose-600 focus:ring-rose-500"
                      />
                      <span className="text-white font-bold text-xs">Payment Terms & Certifications Box</span>
                    </label>

                    <label className="flex items-center gap-2 p-2.5 bg-slate-900 rounded-xl border border-slate-800 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={settings?.pdf_show_bottom_footer !== false}
                        onChange={e => {
                          const updated = { ...settings, pdf_show_bottom_footer: e.target.checked };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                        }}
                        className="w-4 h-4 rounded text-rose-600 focus:ring-rose-500"
                      />
                      <span className="text-white font-bold text-xs">Bottom Footer Bar</span>
                    </label>
                  </div>
                </div>
              </div>
              {/* First-Time User Celebration Fireworks Modal Customizer */}
              <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
                <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-800 pb-3">
                  <div>
                    <h3 className="text-base font-bold text-white flex items-center gap-2"><span>🎆</span> First-Time Login Celebration Popup & Fireworks Studio</h3>
                    <p className="text-xs text-slate-400">Customize the welcome headline, custom announcement, and test the 30-second celebration fireworks modal.</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setShowCelebrationPreviewModal(true)}
                    className="px-4 py-2 bg-gradient-to-r from-amber-500 to-rose-600 hover:from-amber-400 hover:to-rose-500 text-white font-black text-xs rounded-xl shadow-lg shadow-rose-900/30 flex items-center gap-1.5 cursor-pointer animate-pulse"
                  >
                    <span>🎉</span> Preview Celebration Modal (30s Fireworks)
                  </button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">First-Time Modal Title Banner</label>
                    <input
                      type="text"
                      value={settings?.first_time_modal_title || "MIAMO FOODS EXPORTS"}
                      onChange={e => { const updated = { ...settings, first_time_modal_title: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }}
                      className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-bold"
                      placeholder="e.g. MIAMO FOODS EXPORTS"
                    />
                  </div>
                  <div className="md:col-span-2">
                    <label className="text-slate-300 font-semibold block mb-1">First-Time User Welcome Announcement Text</label>
                    <textarea
                      rows={3}
                      value={settings?.first_time_modal_message || "Welcome to your official MIAMO EXPORTS portal! Wishing you immense prosperity, successful contracts, and global export growth."}
                      onChange={e => { const updated = { ...settings, first_time_modal_message: e.target.value }; MiamoStore.saveSettings(updated); setSettings(updated); }}
                      className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-medium focus:border-rose-500 focus:outline-none"
                      placeholder="Type custom first-time announcement text..."
                    />
                  </div>
                </div>
              </div>

              {/* Inactivity Security Auto-Logout */}
              <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
                <h3 className="text-base font-bold text-white flex items-center gap-2">⚙️ Security & Session Settings</h3>
                <div className="space-y-4 text-xs">
                  <div>
                    <label className="text-slate-300 font-semibold block mb-1">🌙 Inactivity Auto-Logout Timeout (5 Hours Default)</label>
                    <p className="text-slate-400 text-[11px] mb-2">Automatically logs out user and requires password re-entry after specified inactivity duration.</p>
                    <div className="flex items-center gap-3">
                      <select
                        value={inactivityTimeout}
                        onChange={e => {
                          const val = parseFloat(e.target.value);
                          setInactivityTimeout(val);
                          MiamoStore.saveInactivityTimeout(val);
                        }}
                        className="bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-white font-mono font-bold"
                      >
                        <option value="60">1 Hour</option>
                        <option value="120">2 Hours</option>
                        <option value="180">3 Hours</option>
                        <option value="300">5 Hours (Default Standard)</option>
                        <option value="480">8 Hours</option>
                        <option value="720">12 Hours</option>
                        <option value="1440">24 Hours</option>
                      </select>
                      <span className="text-emerald-400 font-semibold text-[11px]">✅ Active: {(inactivityTimeout/60).toFixed(1)} Hours ({inactivityTimeout} mins)</span>
                    </div>
                  </div>

              {/* Custom PWA App Icon Upload */}
              <div className="border-t border-slate-800 pt-4">
                <label className="text-slate-300 font-semibold block mb-1">📱 Custom PWA App Shortcut Icon (Shopping Bag / Logo)</label>
                <p className="text-slate-400 text-[11px] mb-2">Upload your custom shopping bag or brand icon for desktop/mobile app shortcuts.</p>
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 bg-slate-900 border border-slate-700 rounded-2xl flex items-center justify-center overflow-hidden flex-shrink-0">
                    {settings?.pwa_icon_url ? <img src={settings.pwa_icon_url} alt="App Icon" className="w-full h-full object-contain p-1" /> : <span className="text-2xl">🛍️</span>}
                  </div>
                  <label className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl cursor-pointer shadow-lg shadow-rose-900/30">
                    📁 Upload Custom App Icon
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={e => {
                        const file = e.target.files[0];
                        if (!file) return;
                        const reader = new FileReader();
                        reader.onload = (evt) => {
                          const iconData = evt.target.result;
                          const updated = { ...settings, pwa_icon_url: iconData };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                          const appleIcon = document.querySelector('link[rel="apple-touch-icon"]');
                          if (appleIcon) appleIcon.href = iconData;
                          alert("✅ Custom App Icon saved! Shortcut icon updated.");
                        };
                        reader.readAsDataURL(file);
                      }}
                    />
                  </label>
                </div>
              </div>

              {/* Custom Mobile App Splash Animation / GIF Upload */}
              <div className="border-t border-slate-800 pt-4">
                <label className="text-slate-300 font-semibold block mb-1">🎬 Custom Mobile App Opening Splash GIF / Animation Logo</label>
                <p className="text-slate-400 text-[11px] mb-2">Upload your custom animated GIF or logo that pops up for 2.5 seconds when opening the app on mobile.</p>
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 bg-slate-900 border border-slate-700 rounded-2xl flex items-center justify-center overflow-hidden flex-shrink-0">
                    {settings?.mobile_splash_gif_url || settings?.brand_logo_url ? (
                      <img src={settings.mobile_splash_gif_url || settings.brand_logo_url} alt="Splash GIF" className="w-full h-full object-contain p-1" />
                    ) : (
                      <span className="text-2xl">🎬</span>
                    )}
                  </div>
                  <label className="px-4 py-2 bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-bold text-xs rounded-xl cursor-pointer shadow-lg shadow-rose-900/30">
                    📁 Upload Custom Splash GIF / Image
                    <input
                      type="file"
                      accept="image/*,.gif"
                      className="hidden"
                      onChange={e => {
                        const file = e.target.files[0];
                        if (!file) return;
                        const reader = new FileReader();
                        reader.onload = (evt) => {
                          const gifData = evt.target.result;
                          const updated = { ...settings, mobile_splash_gif_url: gifData };
                          MiamoStore.saveSettings(updated);
                          setSettings(updated);
                          alert("✅ Mobile Splash GIF saved! Will animate on mobile app launch.");
                        };
                        reader.readAsDataURL(file);
                      }}
                    />
                  </label>
                </div>
              </div>

              {/* Live Location Display */}
              <div className="border-t border-slate-800 pt-4">
                <label className="text-slate-300 font-semibold block mb-2">📍 Your Current Live Location (Auto-detected)</label>
                <div className="p-4 bg-slate-900/60 rounded-xl border border-slate-800 flex items-center gap-4">
                  {userLocation.flag && <img src={userLocation.flag} alt="" className="w-8 h-6 rounded shadow" />}
                  <div>
                    <p className="text-white font-bold text-sm">{userLocation.city}{userLocation.region ? ', ' + userLocation.region : ''}, {userLocation.country}</p>
                    <p className="text-slate-400 text-xs font-mono">IP Address: {userLocation.ip}</p>
                  </div>
                  <span className="ml-auto px-2 py-1 bg-emerald-950/60 text-emerald-400 text-[10px] font-bold rounded border border-emerald-800/40 flex items-center gap-1">
                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span> Live
                  </span>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">This location is logged in the Audit Logs whenever you access the portal.</p>
              </div>
            </div>
          </div>

          {/* Google Sheets 12-Hour Sync */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4 text-left">
            <h3 className="text-base font-bold text-white flex items-center gap-2">⚡ Google Sheets 12-Hour Auto-Price Sync</h3>
            <p className="text-xs text-slate-400">Connect your master Google Sheet to auto-fetch Product Base Prices and Freight Rates every 12 hours.</p>
            <div className="p-4 bg-slate-900 border border-slate-800 rounded-xl space-y-3">
              <div>
                <label className="text-xs font-semibold text-slate-300 block mb-1">Google Sheet Published CSV URL</label>
                <input type="text" value={gsheetConfig.sheet_url} onChange={e => { const updated = { ...gsheetConfig, sheet_url: e.target.value }; setGsheetConfig(updated); MiamoStore.saveGoogleSheetConfig(updated); }} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2 text-xs text-white" />
              </div>
              <div className="flex flex-wrap items-center justify-between gap-4 pt-2">
                <div className="text-xs text-slate-300 space-y-0.5">
                  <p><strong>Status:</strong> <span className="text-emerald-400 font-bold">{syncState.sync_status}</span></p>
                  <p><strong>Last Synced:</strong> {syncState.last_synced}</p>
                </div>
                <button onClick={handleTriggerSync} className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl shadow-lg shadow-emerald-900/30">⚡ Trigger Instant Sync Now</button>
              </div>
            </div>
          </div>

          {/* Margin Controller */}
          <div className="glass-panel p-6 rounded-2xl border border-slate-800">
            <h3 className="text-base font-bold text-white flex items-center gap-2 mb-4">📈 Margin & Profit Controller (Admin)</h3>
            <MarginControllerView unlocked={hikeUnlocked} setUnlocked={setHikeUnlocked} currentUser={currentUser} accounts={accounts} setAccounts={setAccounts} userHikePct={userHikePct} />
          </div>
        </div>
      )}

      {/* 1. Live PDF Background Template Preview Modal */}
      {showPdfPreviewModal && (
        <div className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4">
          <div className="max-w-4xl w-full bg-slate-900 rounded-2xl p-6 border border-slate-800 space-y-4 max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center border-b border-slate-800 pb-3">
              <h3 className="text-base font-bold text-white flex items-center gap-2"><span>📄</span> Live Custom PDF Background Template Preview</h3>
              <button onClick={() => setShowPdfPreviewModal(false)} className="text-slate-400 hover:text-white font-bold text-lg">✕</button>
            </div>
            <div className="p-4 bg-white rounded-xl overflow-x-auto flex justify-center text-slate-900">
              <PdfTemplateRender
                refNo="MF-PREVIEW-2026"
                clientName="VALUED GLOBAL BUYER"
                destPort="DUBAI PORT, UAE"
                quoteLang="English"
                data={[
                  { name: Object.keys(window.PRODUCT_CATALOG)[0] || "Tomato Paste", cartons: 2080, origin: "China", fob: 19.43, cif: 21.50 },
                  { name: Object.keys(window.PRODUCT_CATALOG)[1] || "Sardines in Vegetable Oil", cartons: 3200, origin: "China", fob: 12.50, cif: 14.20 }
                ]}
                paymentTerms="30% T/T Advance, 70% against B/L copy"
                brandLogoUrl={settings?.brand_logo_url}
                pdfBgTemplateUrl={settings?.pdf_bg_template_url}
                pdfBgStyle={settings?.pdf_bg_style}
              />
            </div>
            <div className="flex justify-end">
              <button onClick={() => setShowPdfPreviewModal(false)} className="px-6 py-2.5 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-lg">Close Preview</button>
            </div>
          </div>
        </div>
      )}

      {/* 2. Live Celebration Fireworks Preview Modal */}
      {showCelebrationPreviewModal && (
        <div className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4">
          <div className="max-w-lg w-full bg-slate-900 rounded-3xl p-6 border-2 border-amber-500/60 shadow-2xl text-center space-y-4 animate-bounce-short">
            <div className="text-5xl animate-spin-slow">🎆🎉</div>
            <h3 className="text-2xl font-black text-transparent bg-clip-text bg-gradient-to-r from-amber-400 via-rose-400 to-amber-300">
              {settings?.first_time_modal_title || "MIAMO FOODS EXPORTS"}
            </h3>
            <p className="text-sm font-semibold text-rose-300">🎉 Welcome to the Executive Portal!</p>
            <p className="text-xs text-slate-300 p-3 bg-slate-950/80 rounded-2xl border border-slate-800">
              {settings?.first_time_modal_announcement || settings?.home_custom_announcement || "30-Second Fireworks Celebration Test Active!"}
            </p>
            <div className="w-20 h-20 mx-auto rounded-2xl bg-white border-2 border-amber-500 overflow-hidden flex items-center justify-center p-2 shadow-xl">
              {settings?.mobile_splash_gif_url || settings?.brand_logo_url ? (
                <img src={settings?.mobile_splash_gif_url || settings?.brand_logo_url} alt="Splash GIF" className="w-full h-full object-contain" />
              ) : (
                <span className="text-3xl">📦</span>
              )}
            </div>
            <button
              onClick={() => setShowCelebrationPreviewModal(false)}
              className="w-full py-3 bg-gradient-to-r from-amber-500 to-rose-600 hover:from-amber-400 hover:to-rose-500 text-white font-black text-sm rounded-2xl shadow-xl shadow-rose-900/40"
            >
              ✅ Complete 30s Celebration Preview
            </button>
          </div>
        </div>
      )}

      {/* 3. Live 5-Color Theme Palette Studio & URL Importer Modal */}
      {editingThemeObj && (
        <div className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4">
          <div className="max-w-lg w-full bg-slate-900 rounded-3xl p-6 border border-slate-800 space-y-4 shadow-2xl text-left">
            <div className="flex justify-between items-center border-b border-slate-800 pb-3">
              <h3 className="text-base font-bold text-white flex items-center gap-2">
                <span>🎨</span> 5-Color Palette Studio ({editingThemeObj.label})
              </h3>
              <button onClick={() => setEditingThemeObj(null)} className="text-slate-400 hover:text-white font-bold">✕</button>
            </div>

            {/* 1-Click Coolors / ColorHunt / Hexes URL Auto-Importer */}
            <div className="p-3.5 bg-slate-950 rounded-2xl border border-slate-800 space-y-2">
              <label className="text-amber-400 font-bold text-xs block flex items-center gap-1.5">
                <span>🔗</span> Import 5-Color Palette from Coolors / ColorHunt URL
              </label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={paletteUrlInput}
                  onChange={e => setPaletteUrlInput(e.target.value)}
                  placeholder="Paste e.g. https://coolors.co/2b2d42-8d99ae-edf2f4-ef233c-d90429 or colorhunt link..."
                  className="flex-1 bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-xs text-white font-mono placeholder-slate-500 focus:border-amber-500 focus:outline-none"
                />
                <button
                  type="button"
                  onClick={() => {
                    const parsed = parsePaletteUrlOrHex(paletteUrlInput);
                    if (parsed) {
                      setEditPrimaryHex(parsed.primary);
                      setEditAccentHex(parsed.accent);
                      setEditBgHex(parsed.bg);
                      setEditSurfaceHex(parsed.surface);
                      setEditTextHex(parsed.text);
                      alert("⚡ 5 Hex Colors extracted and loaded into pickers successfully!");
                    } else {
                      alert("⚠️ Could not extract hex colors. Please paste a valid Coolors/ColorHunt link or hex string!");
                    }
                  }}
                  className="px-3.5 py-2 bg-gradient-to-r from-amber-500 to-rose-600 hover:from-amber-400 hover:to-rose-500 text-white font-black text-xs rounded-xl shadow cursor-pointer flex-shrink-0"
                >
                  ⚡ Extract 5 Colors
                </button>
              </div>
            </div>

            <form
              onSubmit={(e) => {
                e.preventDefault();
                const valKey = editingThemeObj.value;
                const updatedLabel = editThemeLabel.trim() || editingThemeObj.label;
                const newColors = {
                  primary: editPrimaryHex,
                  accent: editAccentHex,
                  bg: editBgHex,
                  surface: editSurfaceHex,
                  text: editTextHex,
                  subtext: editSubtextHex,
                  highlight: editHighlightHex,
                  border: editBorderHex,
                  sidebar: editSidebarHex,
                  activeTab: editTabHex
                };
                const updatedObj = {
                  ...editingThemeObj,
                  label: updatedLabel,
                  desc: `Master Palette (${editPrimaryHex}, ${editAccentHex})`,
                  colors: newColors
                };

                // 1. Save in customThemes list
                const existingCustom = customThemes.filter(t => t.value !== valKey);
                const updatedCustom = [...existingCustom, updatedObj];
                setCustomThemes(updatedCustom);
                MiamoStore.saveCustomThemes(updatedCustom);

                // 2. Save in permanent theme color overrides map
                const currentOverrides = MiamoStore.getThemeColorOverrides() || {};
                const updatedOverrides = { ...currentOverrides, [valKey]: newColors };
                MiamoStore.saveThemeColorOverrides(updatedOverrides);

                handleSetTheme(valKey);
                handleThemeRevisionBump(); // Force CSS re-injection even if theme key didn't change
                setEditingThemeObj(null);
                alert(`✅ Master Theme "${editingThemeObj.label}" saved and applied live across all elements!`);
              }}
              className="space-y-3.5 text-xs text-left"
            >
              <div>
                <label className="text-amber-400 font-bold block mb-1">🏷️ Theme Palette Display Name (Editable)</label>
                <input
                  type="text"
                  value={editThemeLabel}
                  onChange={e => setEditThemeLabel(e.target.value)}
                  placeholder="e.g. Canva Sunset Gold"
                  className="w-full bg-slate-950 border border-slate-700 rounded-xl px-3.5 py-2 text-xs text-white font-bold focus:border-amber-500 focus:outline-none"
                  required
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="text-slate-300 font-semibold block mb-1">1. Primary Brand Color (Buttons & CTAs)</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editPrimaryHex} onChange={e => setEditPrimaryHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editPrimaryHex} onChange={e => setEditPrimaryHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white font-mono" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">2. Secondary / Accent Highlight Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editAccentHex} onChange={e => setEditAccentHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editAccentHex} onChange={e => setEditAccentHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white font-mono" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">3. Main App Background Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editBgHex} onChange={e => setEditBgHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editBgHex} onChange={e => setEditBgHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white font-mono" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">4. Surface / Card / Container Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editSurfaceHex} onChange={e => setEditSurfaceHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editSurfaceHex} onChange={e => setEditSurfaceHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-white font-mono" />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="text-slate-300 font-semibold block mb-1">5. Main Text / Headings Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editTextHex} onChange={e => setEditTextHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editTextHex} onChange={e => setEditTextHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">6. Subtitle & Helper Text Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editSubtextHex} onChange={e => setEditSubtextHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editSubtextHex} onChange={e => setEditSubtextHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">7. Status Badges & Icon Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editHighlightHex} onChange={e => setEditHighlightHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editHighlightHex} onChange={e => setEditHighlightHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="text-slate-300 font-semibold block mb-1">8. Card & Input Border Color</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editBorderHex} onChange={e => setEditBorderHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editBorderHex} onChange={e => setEditBorderHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">9. Sidebar & Navigation BG</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editSidebarHex} onChange={e => setEditSidebarHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editSidebarHex} onChange={e => setEditSidebarHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>

                <div>
                  <label className="text-slate-300 font-semibold block mb-1">10. Active Tab & Highlight</label>
                  <div className="flex items-center gap-2">
                    <input type="color" value={editTabHex} onChange={e => setEditTabHex(e.target.value)} className="w-10 h-10 rounded-xl cursor-pointer bg-slate-950 border border-slate-800 p-0.5" />
                    <input type="text" value={editTabHex} onChange={e => setEditTabHex(e.target.value)} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-2 py-1.5 text-white font-mono text-[11px]" />
                  </div>
                </div>
              </div>

              <div className="pt-3 flex gap-2">
                <button
                  type="submit"
                  className="flex-1 bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-black py-3 px-4 rounded-2xl shadow-xl shadow-rose-900/30 cursor-pointer transition-all active:scale-95"
                >
                  💾 Save & Apply 5-Color Palette
                </button>
                <button type="button" onClick={() => setEditingThemeObj(null)} className="bg-slate-800 text-slate-300 py-3 px-4 rounded-2xl font-bold cursor-pointer">Cancel</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// TEAM CHAT VIEW
// ═══════════════════════════════════════════════════════════════
function TeamChatView({ accounts, currentUser, chats, setChats }) {
  const [recipient, setRecipient] = useState(Object.keys(accounts)[0] || "");
  const [msgText, setMsgText] = useState("");
  const pairKey = [currentUser.user_email, recipient].sort().join("_AND_");
  const messageHistory = chats[pairKey] || [];

  const handleSendMessage = () => {
    if (!msgText.trim()) return;
    const newEntry = { sender_email: currentUser.user_email, sender_name: currentUser.display_name, timestamp: new Date().toLocaleTimeString(), message: msgText.trim() };
    const updatedChats = { ...chats, [pairKey]: [...messageHistory, newEntry] };
    MiamoStore.saveChats(updatedChats);
    setChats(updatedChats);
    setMsgText("");
  };

  const handleExportChatPdf = () => {
    if (messageHistory.length === 0) return alert("No chat messages to export!");
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    const recipientAcc = accounts[recipient] || {};
    
    doc.setFont("helvetica", "bold");
    doc.setFontSize(16);
    doc.setTextColor(218, 28, 48); // Miamo Red
    doc.text("MIAMO EXPORTS — SECURE CHAT TRANSCRIPT", 14, 20);

    doc.setFontSize(10);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(100, 100, 100);
    doc.text(`Participants: ${currentUser.display_name} <${currentUser.user_email}> & ${recipientAcc.display_name || recipient} <${recipient}>`, 14, 28);
    doc.text(`Security Level: End-to-End Encrypted Audit Record | Generated: ${new Date().toLocaleString()}`, 14, 34);

    doc.setDrawColor(200, 200, 200);
    doc.line(14, 38, 196, 38);

    let y = 46;
    messageHistory.forEach((m) => {
      if (y > 270) { doc.addPage(); y = 20; }
      doc.setFont("helvetica", "bold");
      doc.setFontSize(9);
      doc.setTextColor(40, 40, 40);
      doc.text(`${m.sender_name} [${m.timestamp}]:`, 14, y);
      y += 5;
      
      doc.setFont("helvetica", "normal");
      doc.setFontSize(10);
      doc.setTextColor(60, 60, 60);
      const splitMsg = doc.splitTextToSize(m.message, 175);
      doc.text(splitMsg, 18, y);
      y += (splitMsg.length * 5) + 4;
    });

    doc.save(`Chat_Transcript_${currentUser.display_name}_${recipientAcc.display_name || 'Member'}.pdf`);
  };

  return (
    <div className="glass-panel p-6 rounded-2xl border border-slate-800 h-[600px] flex flex-col text-left">
      <div className="mb-4 pb-4 border-b border-slate-800 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <h3 className="font-bold text-white text-base">💬 Team Chat</h3>
          <span className="px-2.5 py-0.5 bg-emerald-950/80 text-emerald-400 text-[10px] font-bold rounded-full border border-emerald-800/60 flex items-center gap-1">
            🔒 End-to-End Encrypted
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={handleExportChatPdf} className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-rose-300 font-bold text-xs rounded-xl border border-slate-700 flex items-center gap-1">
            📄 Export Chat PDF
          </button>
          <select value={recipient} onChange={e => setRecipient(e.target.value)} className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white font-medium">
            {Object.entries(accounts).map(([email, acc]) => (<option key={email} value={email}>{acc.display_name} ({acc.member_code})</option>))}
          </select>
        </div>
      </div>
      <div className="flex-1 overflow-y-auto space-y-3 p-2">
        {messageHistory.length === 0 ? (
          <div className="text-center text-slate-500 italic text-xs py-12">No previous messages in this chat conversation.</div>
        ) : (
          messageHistory.map((m, idx) => {
            const isMe = m.sender_email === currentUser.user_email;
            return (
              <div key={idx} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                <div className={`max-w-[75%] p-3 rounded-2xl text-xs ${isMe ? 'bg-rose-600 text-white rounded-br-none' : 'bg-slate-800 text-slate-200 rounded-bl-none'}`}>
                  <p className="font-bold mb-1">{m.sender_name} <span className="opacity-60 text-[10px] font-normal">{m.timestamp}</span></p>
                  <p className="whitespace-pre-wrap">{m.message}</p>
                </div>
              </div>
            );
          })
        )}
      </div>
      <div className="pt-4 border-t border-slate-800 flex gap-2">
        <input type="text" value={msgText} onChange={e => setMsgText(e.target.value)} placeholder="Type message..." className="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-2 text-sm text-white focus:border-rose-500 focus:outline-none" onKeyDown={e => e.key === 'Enter' && handleSendMessage()} />
        <button onClick={handleSendMessage} className="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl font-bold text-sm shadow-lg shadow-rose-900/30">Send</button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// CONTACT DESK VIEW
// ═══════════════════════════════════════════════════════════════
function ContactDeskView({ onSubmitFeedback }) {
  const [type, setType] = useState("⚠️ Problem / Bug Report");
  const [msg, setMsg] = useState("");
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4 text-left">
        <h3 className="text-xl font-bold text-white">📞 Contact Desk & Headquarters</h3>
        <p className="text-xs text-slate-400">MIAMO FOODS EXPORTS • Ludhiana, Punjab, India</p>
        <div className="space-y-2 text-sm text-slate-300">
          <p>📧 <strong>Email:</strong> Chiragpal2829@gmail.com</p>
          <p>📞 <strong>WhatsApp:</strong> +91 9888946517</p>
          <p>🌐 <strong>Brand Tagline:</strong> BONHEUR AVEC SANTE</p>
        </div>
      </div>
      <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
        <h3 className="text-base font-bold text-white">💬 Submit Feedback or Issue</h3>
        <div className="space-y-3">
          <button onClick={() => { if (!msg.trim()) return alert("Please type a description!"); onSubmitFeedback(type, msg); setMsg(""); }} className="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-rose-900/30">🚀 Submit Feedback</button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// PDF TEMPLATE — Logo Embedded + Custom Page Background Support
// ═══════════════════════════════════════════════════════════════
function PdfTemplateRender({ refNo, clientName, destPort, lang, data, brandLogoUrl, pdfBgTemplateUrl, pdfBgStyle, settings, captureId }) {
  const cleanPortName = (destPort || "TEMA").split(',')[0].trim().toUpperCase();
  const isArabic = lang === "العربية (Arabic)";

  const dict = {
    "English": { price_list_title: ". Price List .", cartons_per: "cartons per 20-foot container", product_type: "Product Type:", color: "Color:", packaging: "Packaging:", cans_per_carton: "Cans/carton:", shelf_life: "Shelf Life:", nutrition: "Nutrition:", origin: "Origin:", moq: "Minimum order quantity:", fob: "FOB", cif: "CIF", per_carton: "/carton", ref_no: "Ref No:", client: "Client:", dest_port: "Destination Port:", payment_terms: "Payment Terms:", payment_desc: "30% T/T Advance, 70% against B/L copy", validity: "Quotation Validity:", validity_desc: "14 Days from issuance", certifications: "Official Certifications:", certifications_desc: "HALAL, ISO 22000, HACCP & FDA Certified", for_company: "MIAMO FOODS EXPORTS", slogan: "bonheur avec sante" },
    "Français (French)": { price_list_title: ". Liste de Prix .", cartons_per: "cartons par conteneur de 20 pieds", product_type: "Type de produit:", color: "Couleur:", packaging: "Emballage:", cans_per_carton: "Boîtes/carton:", shelf_life: "Durée de conservation:", nutrition: "Valeur nutritionnelle:", origin: "Origine:", moq: "Quantité minimum de commande:", fob: "FOB", cif: "CAF", per_carton: "/carton", ref_no: "N° de Réf:", client: "Client:", dest_port: "Port de Destination:", payment_terms: "Conditions de Paiement:", payment_desc: "30% Acompte T/T, 70% contre copie du B/L", validity: "Validité de l'Offre:", validity_desc: "14 Jours à compter de l'émission", certifications: "Certifications Officielles:", certifications_desc: "Certifié HALAL, ISO 22000, HACCP et FDA", for_company: "MIAMO FOODS EXPORTS", slogan: "bonheur avec sante" },
    "العربية (Arabic)": { price_list_title: ". قائمة الأسعار .", cartons_per: "كرتونة في حاوية 20 قدم", product_type: "نوع المنتج:", color: "اللون:", packaging: "التعبئة والتغليف:", cans_per_carton: "علبة/كرتونة:", shelf_life: "مدة الصلاحية:", nutrition: "القيمة الغذائية:", origin: "بلد المنشأ:", moq: "الحد الأدنى للطلب:", fob: "فوب (FOB)", cif: "سيف (CIF)", per_carton: "/كرتونة", ref_no: "رقم المرجع:", client: "العميل:", dest_port: "ميناء الوصول:", payment_terms: "شروط الدفع:", payment_desc: "30% دفعة مقدمة T/T، 70% مقابل نسخة بوليصة الشحن B/L", validity: "صلاحية العرض:", validity_desc: "14 يوماً من تاريخ الإصدار", certifications: "الشهادات الرسمية:", certifications_desc: "شهادات حلال (HALAL)، ISO 22000، HACCP وموافقات FDA", for_company: "شركة ميامو للأغذية والتصدير", slogan: "bonheur avec sante" }
  }[lang] || { price_list_title: ". Price List .", cartons_per: "cartons per 20-foot container", product_type: "Product Type:", color: "Color:", packaging: "Packaging:", cans_per_carton: "Cans/carton:", shelf_life: "Shelf Life:", nutrition: "Nutrition:", origin: "Origin:", moq: "Minimum order quantity:", fob: "FOB", cif: "CIF", per_carton: "/carton", ref_no: "Ref No:", client: "Client:", dest_port: "Destination Port:", payment_terms: "Payment Terms:", payment_desc: "30% T/T Advance, 70% against B/L copy", validity: "Quotation Validity:", validity_desc: "14 Days from issuance", certifications: "Official Certifications:", certifications_desc: "HALAL, ISO 22000, HACCP & FDA Certified", for_company: "MIAMO FOODS EXPORTS", slogan: "bonheur avec sante" };

  // Read toggle settings with smart defaults
  const showTopHeader = settings?.pdf_show_top_header !== undefined ? settings.pdf_show_top_header : true;
  const showTopLogo = settings?.pdf_show_top_logo !== undefined ? settings.pdf_show_top_logo : !pdfBgTemplateUrl;
  const showPriceListBadge = settings?.pdf_show_price_list_badge !== undefined ? settings.pdf_show_price_list_badge : false;
  const showTermsBox = settings?.pdf_show_terms_box !== undefined ? settings.pdf_show_terms_box : true;
  const showFooter = settings?.pdf_show_bottom_footer !== undefined ? settings.pdf_show_bottom_footer : true;

  return (
    <div
      id={captureId || "pdf-render-template"}
      className={`w-[850px] min-h-[1100px] text-slate-900 p-8 space-y-6 font-sans border shadow-xl relative overflow-hidden ${isArabic ? 'text-right' : 'text-left'} ${pdfBgTemplateUrl ? 'bg-transparent' : 'bg-white'}`}
      style={{
        backgroundImage: pdfBgTemplateUrl ? `url(${pdfBgTemplateUrl})` : 'none',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}
      dir={isArabic ? 'rtl' : 'ltr'}
    >
      {/* 🌟 100% Full Crisp Opacity — NO white wash overlay dimming the uploaded template! */}

      <div className="relative z-10 space-y-6">
        {/* Header: Logo (Left) + Ref Badge (Right) */}
        {(showTopHeader || showTopLogo) && (
          <div className="flex justify-between items-center pb-3 border-b-2 border-slate-200">
            {showTopLogo ? (
              <div className="flex items-center gap-3">
                {brandLogoUrl ? (
                  <img src={brandLogoUrl} alt="Brand Logo" style={{ width: '64px', height: '64px', objectFit: 'contain', display: 'block' }} />
                ) : (
                  <div>
                    <h1 className="text-4xl font-black text-[#DA1C30] tracking-tight">MIAMO</h1>
                    <p className="text-xs font-bold text-[#DA1C30] uppercase tracking-wider">{dict.slogan}</p>
                  </div>
                )}
                {brandLogoUrl && <div><p className="text-xs font-bold text-[#DA1C30] uppercase tracking-wider">{dict.slogan}</p></div>}
              </div>
            ) : <div></div>}

            {showTopHeader && (
              <div className="text-right space-y-1">
                <span className="inline-block bg-slate-900 text-white font-mono text-xs font-bold px-3 py-1 rounded-lg">{dict.ref_no} {refNo}</span>
                <p className="text-xs font-bold text-slate-600">{dict.client} {clientName}</p>
              </div>
            )}
          </div>
        )}

        {/* Price List Banner — Optional Badge */}
        {showPriceListBadge && (
          <div className="text-center my-4">
            <div style={{ display: 'inline-block', backgroundColor: '#1e3a5f', color: '#ffffff', fontWeight: '800', fontSize: '18px', padding: '8px 32px', borderRadius: '6px', letterSpacing: '2px', boxShadow: '0 2px 8px rgba(0,0,0,0.15)' }}>
              {dict.price_list_title}
            </div>
          </div>
        )}

        {/* Product Cards */}
        <div className="space-y-8">
          {data.map(item => {
            const specs = window.PRODUCT_CATALOG[item.name] || {};
            const originName = (item.origin || "MALAYSIA").toUpperCase();
            const catalogPhotos = MiamoStore.getCatalogPhotos() || {};
            const pImage = catalogPhotos[item.name] || specs.image || "https://images.unsplash.com/photo-1550583724-b2692b85b150?w=400&auto=format&fit=crop&q=80";

            return (
              <div key={item.name} className="flex justify-between items-start border-b border-slate-200 pb-6">
                <div className="flex-1 pr-6 space-y-2 text-xs text-slate-800">
                  <h3 className="font-extrabold text-sm text-slate-900 mb-2">* {item.name} *</h3>
                  <ul className="space-y-1 list-disc pl-4 text-slate-700">
                    <li><strong>{specs.cartons_per_20ft || item.cartons || 1000}</strong> {dict.cartons_per}</li>
                    <li><strong>{dict.product_type}</strong> {specs.category || "Sweetened Condensed Milk"}</li>
                    <li><strong>{dict.color}</strong> {specs.color || "Light Cream"}</li>
                    <li><strong>{dict.packaging}</strong> {specs.packaging || "Can Packaging"}</li>
                    <li><strong>{dict.cans_per_carton}</strong> {specs.cans_per_carton || "24 cans/carton"}</li>
                    <li><strong>{dict.shelf_life}</strong> {specs.shelf_life || "12 to 18 months"}</li>
                    <li><strong>{dict.nutrition}</strong> {specs.protein_fat || "Protein: 1.3%, Fat: 10%"}</li>
                    <li><strong>{dict.origin}</strong> {item.origin}</li>
                    <li><strong>{dict.moq}</strong> {specs.moq || "1 x 20-foot container"}</li>
                  </ul>
                  {/* FOB & CIF Badges */}
                  <div className="pt-2 space-y-1.5 font-bold">
                    <div className="text-slate-900 text-sm">{dict.fob} {originName} <span className="font-extrabold text-[#1e293b]">${item.fob.toFixed(2)}{dict.per_carton}</span></div>
                    <div style={{ display: 'inline-block', backgroundColor: '#fff1f5', border: '1px solid #f472b6', color: '#9d174d', fontSize: '12px', fontWeight: '900', padding: '4px 12px', borderRadius: '6px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
                      {dict.cif} {cleanPortName} ${item.cif.toFixed(2)}{dict.per_carton}
                    </div>
                  </div>
                </div>
                {/* Product Photo */}
                <div className="w-44 flex-shrink-0 flex items-center justify-center p-2 border border-slate-100 bg-slate-50 rounded-xl">
                  <img src={pImage} alt={item.name} className="max-h-40 w-auto object-contain rounded" crossOrigin="anonymous" />
                </div>
              </div>
            );
          })}
        </div>

        {/* Terms & Certifications */}
        {showTermsBox && (
          <div className="p-4 bg-slate-50/90 rounded-xl border border-slate-200 text-xs space-y-2 text-slate-700">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="font-bold text-slate-900">{dict.payment_terms}</p><p className="text-[11px]">{dict.payment_desc}</p>
                <p className="font-bold text-slate-900 mt-2">{dict.validity}</p><p className="text-[11px]">{dict.validity_desc}</p>
              </div>
              <div>
                <p className="font-bold text-slate-900">{dict.certifications}</p><p className="text-[11px] text-emerald-700 font-semibold">{dict.certifications_desc}</p>
              </div>
            </div>
          </div>
        )}

        {/* Footer */}
        {showFooter && (
          <div className="border-t border-slate-300 pt-4 flex justify-between text-[11px] text-slate-500">
            <div><p><strong>{dict.ref_no}</strong> {refNo} | <strong>{dict.client}</strong> {clientName}</p><p><strong>{dict.dest_port}</strong> {destPort}</p></div>
            <div className="text-right"><p><strong>{dict.for_company}</strong></p><p>{dict.slogan} • Ludhiana, Punjab, India</p></div>
          </div>
        )}
      </div>
    </div>
  );
}

// Render React App safely
try {
  ReactDOM.createRoot(document.getElementById('root')).render(
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  );
} catch (err) {
  console.error("Fatal React Render Error:", err);
  const root = document.getElementById('root');
  if (root) {
    root.innerHTML = '<div style="padding:32px;background:#0f172a;color:#f87171;font-family:monospace;min-height:100vh;">' +
      '<h2 style="color:#fbbf24;margin-bottom:16px;">⚠️ Fatal App Render Exception</h2>' +
      '<pre style="white-space:pre-wrap;font-size:13px;">' + (err ? (err.stack || err.toString()) : 'Unknown Render Error') + '</pre>' +
      '<button onclick="localStorage.removeItem(\'miamo_app_theme\');localStorage.removeItem(\'miamo_theme\');location.reload()" style="margin-top:24px;padding:10px 20px;background:#DA1C30;color:white;border:none;border-radius:8px;cursor:pointer;">🔄 Reset Theme & Reload</button>' +
      '</div>';
  }
}

