'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { supabase } from '@/src/supabaseClient';

export interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  category: 'digital_products' | 'graphic_design' | 'video_editing';
  tags: string[];
  mediaUrl: string;
  deliveryTime: string;
  isDigital: boolean;
  inStock?: boolean;
}

export interface CartItem {
  product: Product;
  quantity: number;
  customInstructions: string;
}

export interface Order {
  id: string;
  clientName: string;
  clientEmail: string;
  clientContact: string; // e.g. Telegram or WhatsApp
  items: CartItem[];
  totalPrice: number;
  status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
  createdAt: string;
  reference: string;
  adminNotes?: string;
}

export interface PortfolioItem {
  id: string;
  title: string;
  category: 'graphic_design' | 'video_editing';
  mediaUrl: string;
  videoSrc?: string; // Simulated link
  aspectRatio: 'aspect-square' | 'aspect-[3/4]' | 'aspect-[4/5]' | 'aspect-[16/9]' | 'aspect-[4/3]';
  tags: string[];
  description: string;
}

export interface SimulatedEmail {
  id: string;
  toEmail: string;
  subject: string;
  body: string;
  timestamp: string;
  read: boolean;
  referenceCode: string;
  newStatus: string;
}

export interface AdminMember {
  id: string;
  email: string;
  name: string;
  role: 'Owner' | 'Super Admin' | 'Editor' | 'Viewer' | 'SLA Operator';
  status: 'pending' | 'joined';
  joinedAt?: string;
}

interface AppContextType {
  products: Product[];
  orders: Order[];
  cart: CartItem[];
  portfolio: PortfolioItem[];
  activeView: 'storefront' | 'portfolio' | 'admin' | 'profile';
  cartOpen: boolean;
  theme: 'light' | 'dark';
  currency: 'USD' | 'MMK';
  language: 'EN' | 'MM';
  setLanguage: (lang: 'EN' | 'MM') => void;
  currentUser: { id: string; name: string; email: string; contact?: string; supabaseId?: string } | null;
  isLoggedIn: boolean;
  sessionStatus: 'loading' | 'authenticated' | 'unauthenticated';
  searchQuery: string;
  setSearchQuery: (query: string) => void;
  setCartOpen: (open: boolean) => void;
  setActiveView: (view: 'storefront' | 'portfolio' | 'admin' | 'profile') => void;
  addToCart: (product: Product, quantity: number, customInstructions: string) => void;
  removeFromCart: (productId: string) => void;
  updateCartQty: (productId: string, qty: number) => void;
  clearCart: () => void;
  checkoutCart: (clientName: string, clientEmail: string, clientContact: string) => Order;
  updateOrderStatus: (orderId: string, status: Order['status']) => void;
  updateOrderNotes: (orderId: string, notes: string) => void;
  deleteOrder: (orderId: string) => void;
  sendSimulatedEmail: (toEmail: string, subject: string, body: string, referenceCode?: string) => void;
  addProduct: (product: Omit<Product, 'id'>) => void;
  updateProduct: (productId: string, updatedProduct: Omit<Product, 'id'>) => void;
  deleteProduct: (productId: string) => void;
  addPortfolioItem: (item: Omit<PortfolioItem, 'id'>) => void;
  updatePortfolioItem: (itemId: string, updatedItem: Omit<PortfolioItem, 'id'>) => void;
  deletePortfolioItem: (itemId: string) => void;
  toggleTheme: () => void;
  setCurrency: (c: 'USD' | 'MMK') => void;
  formatPrice: (priceUSD: number) => string;
  registerUser: (name: string, email: string, contact?: string) => boolean;
  loginUser: (email: string) => boolean;
  logoutUser: () => void;
  updateUserProfile: (name: string, contact?: string, email?: string, id?: string) => Promise<void> | void;
  deleteUserProfile: () => void;
  authModalOpen: boolean;
  setAuthModalOpen: (open: boolean) => void;
  authModalTab: 'register' | 'login';
  setAuthModalTab: (tab: 'register' | 'login') => void;
  simulatedEmails: SimulatedEmail[];
  deleteSimulatedEmail: (id: string) => void;
  markEmailAsRead: (id: string) => void;
  clearAllEmails: () => void;
  activeNotification: SimulatedEmail | null;
  setActiveNotification: (notification: SimulatedEmail | null) => void;
  adminTeam: AdminMember[];
  inviteAdminMember: (email: string, role: AdminMember['role']) => void;
  updateAdminRole: (memberId: string, role: AdminMember['role']) => void;
  removeAdminMember: (memberId: string) => void;
  acceptAdminInvite: (memberId: string) => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

// Initial Products Data
const initialProducts: Product[] = [
  // Digital Products
  {
    id: 'prod-1',
    name: 'Bulk Pack Aged Google Accounts (10x Verified)',
    description: '10 super stable, phone-verified aged Gmail accounts with high trust scores. Completely clean IP history, great for ad networks, cold emails, and developers.',
    price: 29.99,
    category: 'digital_products',
    tags: ['Aged Gmail', 'Verified', 'Bulk Accounts'],
    mediaUrl: 'https://picsum.photos/seed/google/600/400',
    deliveryTime: 'Instant Access',
    isDigital: true,
  },
  {
    id: 'prod-2',
    name: 'Aged FB Page & YT Channel Package',
    description: 'Dual bundle containing a 2021 aged Facebook Business Page and a YouTube channel with monetization review eligibility. Rebuilt IP health indices.',
    price: 149.99,
    category: 'digital_products',
    tags: ['Social Bundle', 'Monetization Ready', 'Organic History'],
    mediaUrl: 'https://picsum.photos/seed/social/600/400',
    deliveryTime: 'Within 2 hours',
    isDigital: true,
  },
  {
    id: 'prod-3',
    name: 'TikTok Creator Rewards Program Account',
    description: 'Fully unlocked US-configured TikTok account. Configured directly for Creator Rewards Program system rewards, ready for faceless or active monetization posting.',
    price: 45.00,
    category: 'digital_products',
    tags: ['TikTok Creator', 'US Geo-Targeted', 'Monetization'],
    mediaUrl: 'https://picsum.photos/seed/tiktok/600/400',
    deliveryTime: 'Super Fast (15 min)',
    isDigital: true,
  },
  {
    id: 'prod-4',
    name: 'Premium Canva & CapCut Pro Bundle',
    description: 'Get combined annual developer/team configurations for both Canva Pro and CapCut Pro editing suites. Accelerate graphic designing and video processing workflows.',
    price: 39.00,
    category: 'digital_products',
    tags: ['Canva Pro', 'CapCut Pro', 'License Bundle'],
    mediaUrl: 'https://picsum.photos/seed/canva/600/400',
    deliveryTime: 'Instant Token',
    isDigital: true,
  },
  {
    id: 'prod-5',
    name: 'Visa/MasterCard Multi-Currency Wallet Setup',
    description: 'Assisted creation of high-tier virtual global wallets supporting instant debit issuance. Verified gateway compatibility with key global storefront platforms.',
    price: 59.99,
    category: 'digital_products',
    tags: ['Fintech Wallet', 'VCC Virtual Cards', 'Global Transact'],
    mediaUrl: 'https://picsum.photos/seed/wallet/600/400',
    deliveryTime: 'Within 4 hours',
    isDigital: true,
  },
  {
    id: 'prod-6',
    name: 'Organic Social Media Boost Package (10k)',
    description: 'High-retention social media amplification. Safely boost platform algorithms (YouTube/TikTok/Instagram Views or Likes) to spark viral indexing.',
    price: 19.99,
    category: 'digital_products',
    tags: ['Growth Boost', 'Social Proof', 'High Retention'],
    mediaUrl: 'https://picsum.photos/seed/boost/600/400',
    deliveryTime: 'Delivery over 24 hrs',
    isDigital: true,
  },

  // Graphic Design
  {
    id: 'prod-7',
    name: 'Neon Brand Identity & Vector Logo Design',
    description: 'Completely custom master logo suite crafted by senior creative engineers. Visual packages including multiple vector layouts, high-res dark/light transparent pngs, and font files.',
    price: 99.00,
    category: 'graphic_design',
    tags: ['Logo Design', 'Branding Guide', 'Vector Asset SVG'],
    mediaUrl: 'https://picsum.photos/seed/logoart/600/400',
    deliveryTime: '3-4 Days Delivery',
    isDigital: false,
  },
  {
    id: 'prod-8',
    name: 'Music Album Cover & Movie Poster Suite',
    description: 'High-vibe, editorial typography poster or music album sleeve designed for absolute impact. Delivered as high-definition digital outputs and print-ready formats.',
    price: 69.00,
    category: 'graphic_design',
    tags: ['Album CoverArt', 'High Contrast Print', 'Poster Concept'],
    mediaUrl: 'https://picsum.photos/seed/albumcover/600/400',
    deliveryTime: '2 Days Delivery',
    isDigital: false,
  },
  {
    id: 'prod-9',
    name: 'Aesthetic Wedding Invitation Set',
    description: 'Ultra-refined luxurious wedding suite template including RSVP cards, matching save-the-dates, and gold-trimmed layout options tailored to your color schemes.',
    price: 49.00,
    category: 'graphic_design',
    tags: ['Wedding Invitation', 'Elegant Typo', 'Print Suite'],
    mediaUrl: 'https://picsum.photos/seed/weddinginv/600/400',
    deliveryTime: '3 Days Delivery',
    isDigital: false,
  },

  // Video Editing
  {
    id: 'prod-10',
    name: 'Ultra-Sync Aesthetic Lyrics Overlay Video',
    description: 'Full lyrics animation matched to your audio track. Clean typography, dynamic glass backgrounds, custom sound reactions, and cinematic particle triggers.',
    price: 120.00,
    category: 'video_editing',
    tags: ['Lyrics Overlays', 'Sound Reactive', 'Vibe Visuals'],
    mediaUrl: 'https://picsum.photos/seed/musicvideo/600/400',
    deliveryTime: '4 Days Delivery',
    isDigital: false,
  },
  {
    id: 'prod-11',
    name: 'Cinematic DaVinci Color Grading Studio',
    description: 'Make your smartphone or log footage look like Hollywood features with master LUT balancing, custom skin correction tracking, and ambient atmosphere masks.',
    price: 80.00,
    category: 'video_editing',
    tags: ['DaVinci Resolve', 'LUT Correction', 'Skin Grading'],
    mediaUrl: 'https://picsum.photos/seed/grading/600/400',
    deliveryTime: '2 Days Delivery',
    isDigital: false,
  },
  {
    id: 'prod-12',
    name: 'Wedding & Event Cinematic Highlights Film',
    description: 'Stitch multi-cam event raw footages into an emotionally gripping cinematic highlights masterpiece. Includes premium licensed scores, titles, and cinematic color correction.',
    price: 249.00,
    category: 'video_editing',
    tags: ['Event Highlights', 'Transition FX', 'Wedding Masterpiece'],
    mediaUrl: 'https://picsum.photos/seed/weddingfilm/600/400',
    deliveryTime: '5-7 Days Delivery',
    isDigital: false,
  }
];

// Initial Portfolio Data to feed sleek Masonry and video player
const initialPortfolio: PortfolioItem[] = [
  // Graphic Design
  {
    id: 'port-1',
    title: 'Retro-Futurism Album Cover Art',
    category: 'graphic_design',
    mediaUrl: 'https://picsum.photos/seed/retrowave/600/800', // tall
    aspectRatio: 'aspect-[3/4]',
    tags: ['Typography', 'Retro Wave', 'Illustration'],
    description: 'Synergized retro-vibe synthwave covers featuring neon-glow wireframe mountains and modern liquid typography.',
  },
  {
    id: 'port-2',
    title: 'Neon Catalyst Gaming Brand Logo',
    category: 'graphic_design',
    mediaUrl: 'https://picsum.photos/seed/gaminglogo/600/600', // square
    aspectRatio: 'aspect-square',
    tags: ['Brand Identity', 'Vector SVG', 'eSports Logo'],
    description: 'A glowing cybernetic phoenix identity designed for an integrated streaming and content group.',
  },
  {
    id: 'port-3',
    title: 'Cyberpunk Agency Street Billboard',
    category: 'graphic_design',
    mediaUrl: 'https://picsum.photos/seed/billboardart/800/450', // widescreen
    aspectRatio: 'aspect-[16/9]',
    tags: ['Outdoor Ad', 'Neon Gradients', 'Digital Billboard'],
    description: 'Scale vector layouts with integrated glow-tubing simulations for heavy-ambient city deployments.',
  },
  {
    id: 'port-4',
    title: 'Minimalist Editorial Monogram Identity',
    category: 'graphic_design',
    mediaUrl: 'https://picsum.photos/seed/monotype/600/800', // tall
    aspectRatio: 'aspect-[3/4]',
    tags: ['Luxury Branding', 'Serif Typo', 'Minimalist'],
    description: 'A quiet, high-society lifestyle logo and packaging visual centered on elegant negative space.',
  },

  // Video Editing
  {
    id: 'port-5',
    title: 'Dreamy Ambient Music Video Visualizer',
    category: 'video_editing',
    mediaUrl: 'https://picsum.photos/seed/visualmusic/800/450',
    videoSrc: 'https://assets.mixkit.co/videos/preview/mixkit-nebula-of-purple-and-blue-light-42217-large.mp4',
    aspectRatio: 'aspect-[16/9]',
    tags: ['Sync Lyrics', 'Vaporwave FX', 'After Effects'],
    description: 'A completely hand-keyed sound-reactive lyric integration styled in liquid chrome textures.',
  },
  {
    id: 'port-6',
    title: 'High-Society Country Estate Wedding Highlights',
    category: 'video_editing',
    mediaUrl: 'https://picsum.photos/seed/weddingport/800/450',
    videoSrc: 'https://assets.mixkit.co/videos/preview/mixkit-bride-and-groom-walks-on-the-pier-of-the-lake-34358-large.mp4',
    aspectRatio: 'aspect-[16/9]',
    tags: ['Event Cut', 'Cinematic LUT', 'Slow Motion'],
    description: 'A 4K multi-camera highlight edit seamlessly timed with orchestral orchestral beats and intimate logs.',
  },
  {
    id: 'port-7',
    title: 'Automotive Kinetic Motion Commercial',
    category: 'video_editing',
    mediaUrl: 'https://picsum.photos/seed/sportscar/800/450',
    videoSrc: 'https://assets.mixkit.co/videos/preview/mixkit-sports-car-drifting-on-a-curved-mountain-road-41865-large.mp4',
    aspectRatio: 'aspect-[16/9]',
    tags: ['DaVinci Resolve', 'Speed Ramps', 'Sound Design'],
    description: 'Furious speed ramping and deep rumbling audio matching for a prototype electric vehicle launch video.',
  }
];

// Initial Orders Seeding
const initialOrders: Order[] = [
  {
    id: 'ord-1',
    clientName: 'Sarah Jenkins',
    clientEmail: 'sarah.j@example.com',
    clientContact: '@sarahj_creative',
    totalPrice: 149.99,
    status: 'completed',
    createdAt: '2026-05-24T18:30:22Z',
    reference: 'VBG-4822',
    items: [
      {
        product: initialProducts[1], // Aged FB/YT package
        quantity: 1,
        customInstructions: 'Please configure primary owner email to sarah.j@example.com before transferring credentials.'
      }
    ]
  },
  {
    id: 'ord-2',
    clientName: 'Alex Thorne',
    clientEmail: 'alex.thorne@techflow.io',
    clientContact: 't.me/alex_thorne_dev',
    totalPrice: 39.00,
    status: 'in_progress',
    createdAt: '2026-05-25T09:12:44Z',
    reference: 'VBG-9411',
    items: [
      {
        product: initialProducts[3], // Canva + CapCut Bundle
        quantity: 1,
        customInstructions: 'Need instant email invites. Highly urgent for editing sprints.'
      }
    ]
  },
  {
    id: 'ord-3',
    clientName: 'Dimitri Leon',
    clientEmail: 'dimitrisounds@soundscape.com',
    clientContact: 'WhatsApp: +1829377488',
    totalPrice: 120.00,
    status: 'pending',
    createdAt: '2026-05-26T04:45:10Z',
    reference: 'VBG-1329',
    items: [
      {
        product: initialProducts[9], // Lyrics video overlay
        quantity: 1,
        customInstructions: 'Track file name is ambientwave_vibe_rev2.wav. Audio aspect is cinematic 16:9. Visual mood needs to be deep purple water and glowing stars.'
      }
    ]
  }
];

const initialAdminTeam: AdminMember[] = [
  {
    id: 'adm-1',
    email: 'labawkjohn@gmail.com',
    name: 'John Labawk',
    role: 'Owner',
    status: 'joined',
    joinedAt: '2026-05-01T08:00:00Z',
  },
  {
    id: 'adm-2',
    email: 'sarah.j@example.com',
    name: 'Sarah Jenkins',
    role: 'Super Admin',
    status: 'joined',
    joinedAt: '2026-05-15T09:30:00Z',
  },
  {
    id: 'adm-3',
    email: 'alex.thorne@techflow.io',
    name: 'Alex Thorne',
    role: 'Editor',
    status: 'joined',
    joinedAt: '2026-05-20T11:45:00Z',
  },
  {
    id: 'adm-4',
    email: 'dimitrisounds@soundscape.com',
    name: 'Dimitri Leon',
    role: 'SLA Operator',
    status: 'pending',
  }
];

export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [products, setProducts] = useState<Product[]>([]);
  const [orders, setOrders] = useState<Order[]>([]);
  const [cart, setCart] = useState<CartItem[]>([]);
  const [portfolio, setPortfolio] = useState<PortfolioItem[]>([]);
  const [adminTeam, setAdminTeam] = useState<AdminMember[]>([]);
  const [activeView, setActiveView] = useState<'storefront' | 'portfolio' | 'admin' | 'profile'>('storefront');
  const [cartOpen, setCartOpen] = useState<boolean>(false);
  const [theme, setTheme] = useState<'light' | 'dark'>('dark');
  const [currency, setCurrencyState] = useState<'USD' | 'MMK'>('USD');
  const [language, setLanguageState] = useState<'EN' | 'MM'>('EN');
  const [currentUser, setCurrentUser] = useState<{ id: string; name: string; email: string; contact?: string; supabaseId?: string } | null>(null);
  const [sessionStatus, setSessionStatus] = useState<'loading' | 'authenticated' | 'unauthenticated'>('loading');
  const isLoggedIn = currentUser !== null;
  const [searchQuery, setSearchQuery] = useState<string>('');
  
  // Globally unified auth modal active state control
  const [authModalOpen, setAuthModalOpen] = useState<boolean>(false);
  const [authModalTab, setAuthModalTab] = useState<'register' | 'login'>('register');

  // Simulated Email Notification states
  const [simulatedEmails, setSimulatedEmails] = useState<SimulatedEmail[]>([]);
  const [activeNotification, setActiveNotification] = useState<SimulatedEmail | null>(null);

  // Initialize and load from localStorage if available, else seed initial
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const storedProds = localStorage.getItem('vgb_products');
      const storedOrders = localStorage.getItem('vgb_orders');
      const storedCart = localStorage.getItem('vgb_cart');
      const storedTheme = localStorage.getItem('vgb_theme') as 'light' | 'dark' | null;
      const storedCurrency = localStorage.getItem('vgb_currency') as 'USD' | 'MMK' | null;
      const storedLanguage = localStorage.getItem('vgb_language') as 'EN' | 'MM' | null;
      const rememberMe = localStorage.getItem('vgb_remember_me') !== 'false'; // default to true
      const storedUser = rememberMe 
        ? localStorage.getItem('vgb_current_user') 
        : sessionStorage.getItem('vgb_current_user');
      const storedPortfolio = localStorage.getItem('vgb_portfolio');
      const storedEmails = localStorage.getItem('vgb_emails');
      const storedAdminTeam = localStorage.getItem('vgb_admin_team');
      
      setTimeout(() => {
        setProducts(storedProds ? JSON.parse(storedProds) : initialProducts);
        setOrders(storedOrders ? JSON.parse(storedOrders) : initialOrders);
        setCart(storedCart ? JSON.parse(storedCart) : []);
        setPortfolio(storedPortfolio ? JSON.parse(storedPortfolio) : initialPortfolio);
        setAdminTeam(storedAdminTeam ? JSON.parse(storedAdminTeam) : initialAdminTeam);
        setSimulatedEmails(storedEmails ? JSON.parse(storedEmails) : [
          {
            id: 'email-init-1',
            toEmail: 'guest@masterdigital.agency',
            subject: 'Welcome to MASTER DIGITAL Creative Suites',
            body: 'Greetings Creative,\n\nWelcome to your securing digital ledger at MASTER DIGITAL. We specialize in instant-delivery premium products, social program monetizations, virtual wallet setups, and bespoke design & cinematic video editing.\n\nAll future design/video SLA progress updates, license code delivery, and simulated SMTP communication will be mirrored in this real-time alert log for instant auditing.',
            timestamp: new Date(Date.now() - 3600000 * 24).toISOString(),
            read: false,
            referenceCode: 'SYSTEM',
            newStatus: 'info'
          }
        ]);
        if (storedTheme) {
          setTheme(storedTheme);
        }
        if (storedCurrency) {
          setCurrencyState(storedCurrency);
        }
        if (storedLanguage) {
          setLanguageState(storedLanguage);
        }
        if (typeof window !== 'undefined') {
          const params = new URLSearchParams(window.location.search);
          const viewParam = params.get('view') || params.get('tab');
          if (viewParam === 'storefront' || viewParam === 'portfolio' || viewParam === 'admin' || viewParam === 'profile') {
            setActiveView(viewParam as any);
          }
        }
        if (storedUser) {
          try {
            setCurrentUser(JSON.parse(storedUser));
            setSessionStatus('authenticated');
          } catch (e) {
            console.error('Failed to parse stored user', e);
            setSessionStatus('unauthenticated');
          }
        } else {
          setSessionStatus('unauthenticated');
        }

        const syncSupabaseAndLocal = async () => {
          try {
            const { data: { session } } = await supabase.auth.getSession();
            const rememberMePref = localStorage.getItem('vgb_remember_me') !== 'false';
            
            // If remember_me is deactivated and there is no active session storage user (new tab/window closing event), sign out of supabase session
            if (!rememberMePref && !sessionStorage.getItem('vgb_current_user')) {
              if (session) {
                await supabase.auth.signOut();
              }
              setCurrentUser(null);
              setSessionStatus('unauthenticated');
              localStorage.removeItem('vgb_current_user');
              return;
            }

            if (session?.user) {
              const email = session.user.email;
              if (email) {
                const storedUsers = localStorage.getItem('vgb_registered_users');
                const userList = storedUsers ? JSON.parse(storedUsers) : [];
                let matched = userList.find((u: any) => 
                  (u.supabaseId && u.supabaseId === session.user.id) ||
                  u.id === session.user.id ||
                  u.email.toLowerCase() === email.toLowerCase()
                );
                if (!matched) {
                  const defaultName = email.split('@')[0];
                  matched = {
                    id: session.user.id || `usr-${Date.now()}`,
                    name: defaultName,
                    email: email,
                    supabaseId: session.user.id
                  };
                  userList.push(matched);
                  localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
                } else {
                  if (!matched.supabaseId) {
                    matched.supabaseId = session.user.id;
                    localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
                  }
                }
                setCurrentUser(matched);
                setSessionStatus('authenticated');
                if (rememberMePref) {
                  localStorage.setItem('vgb_current_user', JSON.stringify(matched));
                } else {
                  sessionStorage.setItem('vgb_current_user', JSON.stringify(matched));
                  localStorage.removeItem('vgb_current_user');
                }
              }
            }
          } catch (e) {
            console.error('Error syncing Supabase session', e);
          }
        };

        syncSupabaseAndLocal();
      }, 0);
    }

    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      const rememberMePref = localStorage.getItem('vgb_remember_me') !== 'false';
      if (session?.user) {
        const email = session.user.email;
        if (email) {
          const storedUsers = localStorage.getItem('vgb_registered_users');
          const userList = storedUsers ? JSON.parse(storedUsers) : [];
          let matched = userList.find((u: any) => 
            (u.supabaseId && u.supabaseId === session.user.id) ||
            u.id === session.user.id ||
            u.email.toLowerCase() === email.toLowerCase()
          );
          if (!matched) {
            const defaultName = email.split('@')[0];
            matched = {
              id: session.user.id || `usr-${Date.now()}`,
              name: defaultName,
              email: email,
              supabaseId: session.user.id
            };
            userList.push(matched);
            localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
          } else {
            if (!matched.supabaseId) {
              matched.supabaseId = session.user.id;
              localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
            }
          }
          setCurrentUser(matched);
          setSessionStatus('authenticated');
          if (rememberMePref) {
            localStorage.setItem('vgb_current_user', JSON.stringify(matched));
          } else {
            sessionStorage.setItem('vgb_current_user', JSON.stringify(matched));
            localStorage.removeItem('vgb_current_user');
          }
        }
      } else if (event === 'SIGNED_OUT') {
        setCurrentUser(null);
        setSessionStatus('unauthenticated');
        localStorage.removeItem('vgb_current_user');
        sessionStorage.removeItem('vgb_current_user');
      }
    });

    return () => {
      subscription.unsubscribe();
    };
  }, []);

  const toggleTheme = () => {
    const nextTheme = theme === 'dark' ? 'light' : 'dark';
    setTheme(nextTheme);
    localStorage.setItem('vgb_theme', nextTheme);
  };

  // Synchronize theme with html element class list for Tailwind support
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const root = window.document.documentElement;
      if (theme === 'dark') {
        root.classList.add('dark');
        root.classList.remove('light');
      } else {
        root.classList.add('light');
        root.classList.remove('dark');
      }
    }
  }, [theme]);

  const setCurrency = (c: 'USD' | 'MMK') => {
    setCurrencyState(c);
    localStorage.setItem('vgb_currency', c);
  };

  const setLanguage = (lang: 'EN' | 'MM') => {
    setLanguageState(lang);
    if (typeof window !== 'undefined') {
      localStorage.setItem('vgb_language', lang);
    }
  };

  const formatPrice = (priceUSD: number) => {
    if (currency === 'MMK') {
      return (Math.round(priceUSD * 4000)).toLocaleString() + ' MMK';
    }
    return '$' + priceUSD.toFixed(2);
  };

  const registerUser = (name: string, email: string, contact?: string): boolean => {
    if (typeof window === 'undefined') return false;
    const storedUsers = localStorage.getItem('vgb_registered_users');
    const userList = storedUsers ? JSON.parse(storedUsers) : [];
    
    // Check if user already exists
    const exists = userList.find((u: any) => u.email.toLowerCase() === email.toLowerCase());
    if (exists) {
      // Login if they already registered
      const matched = { id: exists.id, name: exists.name, email: exists.email, contact: exists.contact || contact };
      setCurrentUser(matched);
      setSessionStatus('authenticated');
      localStorage.setItem('vgb_current_user', JSON.stringify(matched));
      return true;
    }

    const newUser = {
      id: `usr-${Date.now()}`,
      name,
      email,
      contact,
    };
    userList.push(newUser);
    localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
    setCurrentUser(newUser);
    setSessionStatus('authenticated');
    localStorage.setItem('vgb_current_user', JSON.stringify(newUser));
    return true;
  };

  const loginUser = (email: string): boolean => {
    if (typeof window === 'undefined') return false;
    const storedUsers = localStorage.getItem('vgb_registered_users');
    const userList = storedUsers ? JSON.parse(storedUsers) : [];
    
    const matched = userList.find((u: any) => u.email.toLowerCase() === email.toLowerCase());
    if (matched) {
      setCurrentUser(matched);
      setSessionStatus('authenticated');
      localStorage.setItem('vgb_current_user', JSON.stringify(matched));
      return true;
    }
    return false;
  };

  const logoutUser = async () => {
    try {
      await supabase.auth.signOut();
    } catch (e) {
      console.error('Error signing out of Supabase', e);
    }
    setCurrentUser(null);
    setSessionStatus('unauthenticated');
    localStorage.removeItem('vgb_current_user');
    sessionStorage.removeItem('vgb_current_user');
  };

  const updateUserProfile = async (name: string, contact?: string, email?: string, id?: string) => {
    if (!currentUser || typeof window === 'undefined') return;
    const targetEmail = email || currentUser.email;
    const targetId = id || currentUser.id;
    const updated = { ...currentUser, id: targetId, name, email: targetEmail, contact };
    
    // Update in Supabase first
    try {
      const updateData: any = {
        data: {
          name,
          contact,
          user_id: targetId
        }
      };
      if (email && email.toLowerCase() !== currentUser.email.toLowerCase()) {
        updateData.email = email;
      }
      const { error } = await supabase.auth.updateUser(updateData);
      if (error) {
        console.error('Supabase auth update user error:', error.message);
      }
    } catch (e) {
      console.error('Failed to update credentials in Supabase Auth:', e);
    }

    setCurrentUser(updated);

    // Save current user
    localStorage.setItem('vgb_current_user', JSON.stringify(updated));
    if (sessionStorage.getItem('vgb_current_user')) {
      sessionStorage.setItem('vgb_current_user', JSON.stringify(updated));
    }

    // Update in registered list
    const storedUsers = localStorage.getItem('vgb_registered_users');
    if (storedUsers) {
      try {
        const userList = JSON.parse(storedUsers);
        const idx = userList.findIndex((u: any) => 
          (currentUser.supabaseId && u.supabaseId === currentUser.supabaseId) ||
          u.email.toLowerCase() === currentUser.email.toLowerCase() || 
          u.id === currentUser.id
        );
        if (idx !== -1) {
          userList[idx] = { ...userList[idx], ...updated };
          localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
        } else {
          userList.push(updated);
          localStorage.setItem('vgb_registered_users', JSON.stringify(userList));
        }
      } catch (e) {
        console.error('Failed to update registered user lists', e);
      }
    }
  };

  const deleteUserProfile = async () => {
    if (!currentUser || typeof window === 'undefined') return;
    const emailToDelete = currentUser.email;
    
    // Sign out of everything first
    await logoutUser();

    // Remove from registered users list
    const storedUsers = localStorage.getItem('vgb_registered_users');
    if (storedUsers) {
      try {
        const userList = JSON.parse(storedUsers);
        const filteredList = userList.filter((u: any) => u.email.toLowerCase() !== emailToDelete.toLowerCase());
        localStorage.setItem('vgb_registered_users', JSON.stringify(filteredList));
      } catch (e) {
        console.error('Failed to delete registered user', e);
      }
    }
  };

  // Sync back state modifications to localStorage
  const syncProducts = (newProds: Product[]) => {
    setProducts(newProds);
    localStorage.setItem('vgb_products', JSON.stringify(newProds));
  };

  const syncOrders = (newOrders: Order[]) => {
    setOrders(newOrders);
    localStorage.setItem('vgb_orders', JSON.stringify(newOrders));
  };

  const syncPortfolio = (newPortfolio: PortfolioItem[]) => {
    setPortfolio(newPortfolio);
    localStorage.setItem('vgb_portfolio', JSON.stringify(newPortfolio));
  };

  const syncCart = (newCart: CartItem[]) => {
    setCart(newCart);
    localStorage.setItem('vgb_cart', JSON.stringify(newCart));
  };

  const syncEmails = (newEmails: SimulatedEmail[]) => {
    setSimulatedEmails(newEmails);
    localStorage.setItem('vgb_emails', JSON.stringify(newEmails));
  };

  const deleteSimulatedEmail = (id: string) => {
    const updated = simulatedEmails.filter(e => e.id !== id);
    syncEmails(updated);
  };

  const markEmailAsRead = (id: string) => {
    const updated = simulatedEmails.map(e => e.id === id ? { ...e, read: true } : e);
    syncEmails(updated);
  };

  const clearAllEmails = () => {
    syncEmails([]);
  };

  // Cart operations
  const addToCart = (product: Product, quantity: number, customInstructions: string) => {
    const existingIndex = cart.findIndex((item) => item.product.id === product.id);
    let updatedCart = [...cart];
    
    if (existingIndex > -1) {
      updatedCart[existingIndex] = {
        ...updatedCart[existingIndex],
        quantity: updatedCart[existingIndex].quantity + quantity,
        customInstructions: customInstructions || updatedCart[existingIndex].customInstructions,
      };
    } else {
      updatedCart.push({ product, quantity, customInstructions });
    }
    
    syncCart(updatedCart);
    setCartOpen(true);
  };

  const removeFromCart = (productId: string) => {
    const updatedCart = cart.filter((item) => item.product.id !== productId);
    syncCart(updatedCart);
  };

  const updateCartQty = (productId: string, qty: number) => {
    if (qty <= 0) {
      removeFromCart(productId);
      return;
    }
    const updatedCart = cart.map((item) => 
      item.product.id === productId ? { ...item, quantity: qty } : item
    );
    syncCart(updatedCart);
  };

  const clearCart = () => {
    syncCart([]);
  };

  const checkoutCart = (clientName: string, clientEmail: string, clientContact: string) => {
    const totalSum = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
    const orderRef = `VBG-${Math.floor(1000 + Math.random() * 9000)}`;
    const newOrder: Order = {
      id: `ord-${Date.now()}`,
      clientName,
      clientEmail,
      clientContact,
      items: [...cart],
      totalPrice: totalSum,
      status: 'pending',
      createdAt: new Date().toISOString(),
      reference: orderRef,
    };

    const updatedOrders = [newOrder, ...orders];
    syncOrders(updatedOrders);

    // Create immediate Order Receipt Simulated Email
    const itemDetails = cart.map(item => `- ${item.product.name} (Qty: ${item.quantity}) - $${(item.product.price * item.quantity).toFixed(2)}`).join('\n');
    const newEmail: SimulatedEmail = {
      id: `email-${Date.now()}`,
      toEmail: clientEmail || 'client@masterdigital.agency',
      subject: `[MASTER DIGITAL] Secure Invoice & Order Placed: ${orderRef}`,
      body: `Dear ${clientName},\n\nThank you for your creative design & cinematic video request!\n\nYour order is officially PLACED with reference code ${orderRef}.\n\n--- ORDER OVERVIEW ---\n${itemDetails}\n\nTotal Estimated Amount: $${totalSum.toFixed(2)} USD\nEstimated Delivery: Instant-delivery / Custom SLA (under 24h)\n\nAn administrator will review your custom files and instructions shortly. You can track progress in real-time within your Secured Ledger under 'My Profile & Ledger'.\n\nBest regards,\nSMTP Automated Billing Node`,
      timestamp: new Date().toISOString(),
      read: false,
      referenceCode: orderRef,
      newStatus: 'pending'
    };

    const updatedEmails = [newEmail, ...simulatedEmails];
    syncEmails(updatedEmails);
    setActiveNotification(newEmail);
    
    syncCart([]);
    setCartOpen(false);
    return newOrder;
  };

  // Admin operational controls
  const updateOrderStatus = (orderId: string, status: Order['status']) => {
    const order = orders.find(o => o.id === orderId);
    
    const updatedOrders = orders.map((o) => 
      o.id === orderId ? { ...o, status } : o
    );
    syncOrders(updatedOrders);

    if (order) {
      // Create simulated email notification
      const statusLabels: Record<string, string> = {
        'pending': 'PENDING APPROVAL',
        'in_progress': 'PROCESSING PIPELINE',
        'completed': 'FULLY DELIVERED',
        'cancelled': 'CANCELLED / VOIDED'
      };

      const friendlyStatus = statusLabels[status] || status.toUpperCase();
      
      const newEmail: SimulatedEmail = {
        id: `email-${Date.now()}`,
        toEmail: order.clientEmail || 'client@masterdigital.agency',
        subject: `[MASTER DIGITAL] SLA Priority Update: ${order.reference} ${status.toUpperCase()}`,
        body: `Dear ${order.clientName || 'Creative Partner'},\n\nYour creative design & cinematic video production project SLA status has been updated!\n\nOrder Index: ${order.reference}\nUpdated Pipeline Phase: ${friendlyStatus}\nTotal Value: $${order.totalPrice.toFixed(2)} USD\nTimestamp: ${new Date().toLocaleString()}\n\nOur specialized graphic designers and cinematic editors have prioritized your queue logs. Fully rendered materials and access keys will display directly inside your Profile Ledger once finalized.\n\nThank you for choosing MASTER DIGITAL. If you have active inquiries, please provide our executive support team your original Telegram/WhatsApp detail: ${order.clientContact || 'N/A'}.\n\nBest regards,\nMASTER DIGITAL Automated Notification Dispatch Engine\n(SMTP Simulation Node)`,
        timestamp: new Date().toISOString(),
        read: false,
        referenceCode: order.reference,
        newStatus: status
      };

      const updatedEmails = [newEmail, ...simulatedEmails];
      syncEmails(updatedEmails);
      
      // Auto-popup notification toast at the top/bottom of the screen
      setActiveNotification(newEmail);
    }
  };

  const updateOrderNotes = (orderId: string, notes: string) => {
    const updatedOrders = orders.map((order) => 
      order.id === orderId ? { ...order, adminNotes: notes } : order
    );
    syncOrders(updatedOrders);
  };

  const deleteOrder = (orderId: string) => {
    const updatedOrders = orders.filter((o) => o.id !== orderId);
    syncOrders(updatedOrders);
  };

  const sendSimulatedEmail = (toEmail: string, subject: string, body: string, referenceCode?: string) => {
    const newEmail: SimulatedEmail = {
      id: `email-${Date.now()}`,
      toEmail,
      subject,
      body,
      timestamp: new Date().toISOString(),
      read: false,
      referenceCode: referenceCode || 'CUSTOM',
      newStatus: 'notification'
    };
    const updatedEmails = [newEmail, ...simulatedEmails];
    syncEmails(updatedEmails);
    setActiveNotification(newEmail);
  };

  const addProduct = (prodData: Omit<Product, 'id'>) => {
    const newProduct: Product = {
      ...prodData,
      id: `prod-${Date.now()}`,
    };
    const updatedProducts = [newProduct, ...products];
    syncProducts(updatedProducts);
  };

  const updateProduct = (productId: string, updatedProduct: Omit<Product, 'id'>) => {
    const updatedProducts = products.map((prod) =>
      prod.id === productId ? { ...updatedProduct, id: productId } : prod
    );
    syncProducts(updatedProducts);
  };

  const deleteProduct = (productId: string) => {
    const updatedProducts = products.filter((prod) => prod.id !== productId);
    syncProducts(updatedProducts);
  };

  const addPortfolioItem = (itemData: Omit<PortfolioItem, 'id'>) => {
    const newItem: PortfolioItem = {
      ...itemData,
      id: `port-${Date.now()}`,
    };
    const updatedPortfolio = [newItem, ...portfolio];
    syncPortfolio(updatedPortfolio);
  };

  const updatePortfolioItem = (itemId: string, updatedItem: Omit<PortfolioItem, 'id'>) => {
    const updatedPortfolio = portfolio.map((item) =>
      item.id === itemId ? { ...updatedItem, id: itemId } : item
    );
    syncPortfolio(updatedPortfolio);
  };

  const deletePortfolioItem = (itemId: string) => {
    const updatedPortfolio = portfolio.filter((item) => item.id !== itemId);
    syncPortfolio(updatedPortfolio);
  };

  const syncAdminTeam = (newTeam: AdminMember[]) => {
    setAdminTeam(newTeam);
    localStorage.setItem('vgb_admin_team', JSON.stringify(newTeam));
  };

  const inviteAdminMember = async (email: string, role: AdminMember['role']) => {
    const storedUsers = localStorage.getItem('vgb_registered_users');
    const userList = storedUsers ? JSON.parse(storedUsers) : [];
    const matchedUser = userList.find((u: any) => u.email.toLowerCase() === email.toLowerCase());

    const memberId = `adm-${Date.now()}`;
    const newMember: AdminMember = {
      id: memberId,
      email: email.trim(),
      name: matchedUser ? matchedUser.name : email.split('@')[0],
      role: role,
      status: 'pending',
    };

    const updatedTeam = [...adminTeam, newMember];
    syncAdminTeam(updatedTeam);

    // Build the authentic redirect link targeting the login page with the state payload
    const redirectUrl = `${window.location.origin}/login?invite_id=${memberId}`;

    try {
      // 1. Trigger Supabase client-side Sign-Up to populate credentials with random temporary passkey
      const tempPassword = 'AuthAdmin' + Math.random().toString(36).slice(-8) + '26#!';
      const { data, error } = await supabase.auth.signUp({
        email: email.trim(),
        password: tempPassword,
        options: {
          emailRedirectTo: redirectUrl,
        }
      });

      if (error) {
        // If they are already registered in Supabase, we send them a reset password email to set their credentials.
        if (error.message?.toLowerCase().includes('already registered') || error.status === 400) {
          const { error: resetError } = await supabase.auth.resetPasswordForEmail(email.trim(), {
            redirectTo: redirectUrl,
          });
          if (resetError) {
            console.error('Database reset password error', resetError);
          }
        } else {
          console.error('Supabase registration error', error);
        }
      }
    } catch (e) {
      console.error('SMTP Invitation dispatch exception', e);
    }

    // Still trigger local simulated email log for in-app history tracking
    const subject = `[MASTER DIGITAL] Security Clearance Key: SLA Team Invitation`;
    const body = `Dear Creative,\n\nYou have been officially invited to join the MASTER DIGITAL Operator & SLA Technical Team!\n\nRole assigned: ${role}\nInvited Email: ${email}\nSecurity clearance: Active Pipeline Controls\n\nA real invitation has been successfully sent to your email. Please check your inbox / spam folder to verify and set your account password.\n\nBest regards,\nMaster Digital SLA Audited Operations`;
    
    sendSimulatedEmail(email.trim(), subject, body, 'INVITE');
  };

  const updateAdminRole = (memberId: string, role: AdminMember['role']) => {
    const updatedTeam = adminTeam.map((mem) => 
      mem.id === memberId ? { ...mem, role: role } : mem
    );
    syncAdminTeam(updatedTeam);

    const member = adminTeam.find((m) => m.id === memberId);
    if (member) {
      const subject = `[MASTER DIGITAL] Role Modification Notification`;
      const body = `Dear ${member.name || 'Creative Operator'},\n\nYour security clearance and team position role on MASTER DIGITAL has been successfully adjusted.\n\nNew Role Assigned: ${role}\nModified on: ${new Date().toLocaleString()}\n\nBest regards,\nMaster Digital Team Directory Service`;
      sendSimulatedEmail(member.email, subject, body, 'ROLE_CHANGE');
    }
  };

  const removeAdminMember = (memberId: string) => {
    const member = adminTeam.find((m) => m.id === memberId);
    const updatedTeam = adminTeam.filter((mem) => mem.id !== memberId);
    syncAdminTeam(updatedTeam);

    if (member) {
      const subject = `[MASTER DIGITAL] Team Revocation Notice`;
      const body = `Dear ${member.name || 'Creative'},\n\nWe regret to inform you that your secure access and operator authorization key for the MASTER DIGITAL Control Hub has been revoked.\n\nIf you believe this was an error, please get in touch with your primary System Supervisor.\n\nBest regards,\nMASTER DIGITAL Access Operations Node`;
      sendSimulatedEmail(member.email, subject, body, 'REVOKED');
    }
  };

  const acceptAdminInvite = (memberId: string) => {
    const updatedTeam = adminTeam.map((mem) => 
      mem.id === memberId ? { ...mem, status: 'joined' as const, joinedAt: new Date().toISOString() } : mem
    );
    syncAdminTeam(updatedTeam);

    const member = adminTeam.find((m) => m.id === memberId);
    if (member) {
      const subject = `[MASTER DIGITAL] Welcome to the Operator Team Directory`;
      const body = `Dear ${member.name || 'Creative Operator'},\n\nYour security clearance acceptance key has been approved and registered.\n\nStatus: Joined\nTimestamp: ${new Date().toLocaleString()}\n\nYou can now log in and access restricted administrative nodes inside the core dashboard.\n\nBest regards,\nMaster Digital SLA Audited Operations`;
      sendSimulatedEmail(member.email, subject, body, 'WELCOME_TEAM');
    }
  };

  return (
    <AppContext.Provider
      value={{
        products,
        orders,
        cart,
        portfolio,
        activeView,
        cartOpen,
        theme,
        currency,
        currentUser,
        isLoggedIn,
        sessionStatus,
        searchQuery,
        setSearchQuery,
        setCartOpen,
        setActiveView,
        addToCart,
        removeFromCart,
        updateCartQty,
        clearCart,
        checkoutCart,
        updateOrderStatus,
        updateOrderNotes,
        deleteOrder,
        sendSimulatedEmail,
        addProduct,
        updateProduct,
        deleteProduct,
        addPortfolioItem,
        updatePortfolioItem,
        deletePortfolioItem,
        toggleTheme,
        setCurrency,
        setLanguage,
        language,
        formatPrice,
        registerUser,
        loginUser,
        logoutUser,
        updateUserProfile,
        deleteUserProfile,
        authModalOpen,
        setAuthModalOpen,
        authModalTab,
        setAuthModalTab,
        simulatedEmails,
        deleteSimulatedEmail,
        markEmailAsRead,
        clearAllEmails,
        activeNotification,
        setActiveNotification,
        adminTeam,
        inviteAdminMember,
        updateAdminRole,
        removeAdminMember,
        acceptAdminInvite,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useApp = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
};
