'use client';

import { useEffect, useState } from 'react';
import { useAppStore, hydrateStoreFromStorage, type AppSection } from '@/lib/store';
import { t } from '@/lib/i18n';
import Header from '@/components/layout/Header';
import BottomNav from '@/components/layout/BottomNav';
import Sidebar from '@/components/layout/Sidebar';
import AuthModule from '@/components/modules/AuthModule';
import AdminModule from '@/components/modules/AdminModule';
import ProfileModule from '@/components/modules/ProfileModule';
import OrdersModule from '@/components/modules/OrdersModule';
import CommunityModule from '@/components/modules/CommunityModule';
import SettingsModule from '@/components/modules/SettingsModule';
import EducationModule from '@/components/modules/EducationModule';
import HouseRentalModule from '@/components/modules/HouseRentalModule';
import ShopRentalModule from '@/components/modules/ShopRentalModule';
import OwnerDashboardModule from '@/components/modules/OwnerDashboardModule';
import MessagesModule from '@/components/modules/MessagesModule';
import FavouritesModule from '@/components/modules/FavouritesModule';
import HomeModule from '@/components/modules/HomeModule';
import ExploreModule from '@/components/modules/ExploreModule';
import MarketplaceModule from '@/components/modules/MarketplaceModule';
import MedicineModule from '@/components/modules/MedicineModule';
import CheckoutModule from '@/components/modules/CheckoutModule';
import FloatingCartButton from '@/components/layout/FloatingCartButton';
import {
  Home as HomeIcon,
  Compass,
  MessageCircle,
  Heart,
  User,
  Building2,
  Store,
  ShoppingBag,
  Pill,
  GraduationCap,
  Package,
  Users,
  Settings,
  Shield,
  Upload,
} from 'lucide-react';

const sectionConfig: Record<
  AppSection,
  { icon: React.ElementType; titleKey: string; descriptionKey: string }
> = {
  home: {
    icon: HomeIcon,
    titleKey: 'nav.home',
    descriptionKey: 'app.tagline',
  },
  explore: {
    icon: Compass,
    titleKey: 'nav.explore',
    descriptionKey: 'app.tagline',
  },
  messages: {
    icon: MessageCircle,
    titleKey: 'msg.title',
    descriptionKey: 'app.tagline',
  },
  favourites: {
    icon: Heart,
    titleKey: 'fav.title',
    descriptionKey: 'fav.empty',
  },
  profile: {
    icon: User,
    titleKey: 'profile.title',
    descriptionKey: 'app.tagline',
  },
  'house-rental': {
    icon: Building2,
    titleKey: 'house.title',
    descriptionKey: 'house.search',
  },
  'shop-rental': {
    icon: Store,
    titleKey: 'shop.title',
    descriptionKey: 'shop.search',
  },
  marketplace: {
    icon: ShoppingBag,
    titleKey: 'market.title',
    descriptionKey: 'market.search',
  },
  medicine: {
    icon: Pill,
    titleKey: 'medicine.title',
    descriptionKey: 'medicine.search',
  },
  education: {
    icon: GraduationCap,
    titleKey: 'edu.title',
    descriptionKey: 'app.tagline',
  },
  community: {
    icon: Users,
    titleKey: 'community.title',
    descriptionKey: 'app.tagline',
  },
  orders: {
    icon: Package,
    titleKey: 'order.title',
    descriptionKey: 'app.tagline',
  },
  settings: {
    icon: Settings,
    titleKey: 'settings.title',
    descriptionKey: 'app.tagline',
  },
  auth: {
    icon: User,
    titleKey: 'auth.login',
    descriptionKey: 'app.tagline',
  },
  admin: {
    icon: Shield,
    titleKey: 'admin.title',
    descriptionKey: 'admin.signIn',
  },

  'owner-dashboard': {
    icon: Upload,
    titleKey: 'owner.title',
    descriptionKey: 'owner.subtitle',
  },
  checkout: {
    icon: ShoppingBag,
    titleKey: 'market.cart',
    descriptionKey: 'market.search',
  },
};

function SectionPlaceholder({
  section,
}: {
  section: AppSection;
}) {
  const { language } = useAppStore();
  const config = sectionConfig[section];
  const Icon = config.icon;

  return (
    <div className="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-16">
      <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-primary/10">
        <Icon className="h-10 w-10 text-primary" strokeWidth={1.5} />
      </div>
      <div className="text-center">
        <h2 className="text-xl font-bold text-foreground">
          {t(config.titleKey, language)}
        </h2>
        <p className="mt-1 text-sm text-muted-foreground">
          {t(config.descriptionKey, language)}
        </p>
      </div>
      <p className="text-xs text-muted-foreground/60">
        Coming soon
      </p>
    </div>
  );
}

export default function Home() {
  const { currentSection } = useAppStore();
  const [mounted, setMounted] = useState(false);

  // Single consolidated hydration effect:
  // 1. Hydrate ALL state from localStorage (admin, user, section, language)
  // 2. Apply admin customizations (CSS variables)
  // 3. Then set mounted=true to reveal content
  useEffect(() => {
    // Step 1: Hydrate store from localStorage
    hydrateStoreFromStorage();

    // Step 2: Apply customizations from localStorage (set by admin customizer)
    try {
      const stored = localStorage.getItem('needyfy_customizations');
      if (stored) {
        const c = JSON.parse(stored);
        const root = document.documentElement;
        // Theme & Colors
        if (c.primaryColor) {
          root.style.setProperty('--primary', c.primaryColor);
          root.style.setProperty('--ring', c.primaryColor);
          root.style.setProperty('--sidebar-primary', c.primaryColor);
          root.style.setProperty('--sidebar-ring', c.primaryColor);
        }
        if (c.accentColor) root.style.setProperty('--accent', c.accentColor);
        if (c.buttonColor) root.style.setProperty('--button-color', c.buttonColor);
        if (c.cardBgColor) root.style.setProperty('--card-bg', c.cardBgColor);
        if (c.sidebarColor) root.style.setProperty('--sidebar-bg', c.sidebarColor);
        if (c.headerColor) root.style.setProperty('--header-bg', c.headerColor);
        if (c.gradientStart) root.style.setProperty('--gradient-start', c.gradientStart);
        if (c.gradientEnd) root.style.setProperty('--gradient-end', c.gradientEnd);
        // Font Settings
        if (c.fontFamily) {
          root.style.setProperty('--font-family', c.fontFamily);
          root.style.fontFamily = c.fontFamily;
        }
        if (c.headingFontFamily) root.style.setProperty('--heading-font-family', c.headingFontFamily);
        if (c.baseFontSize) root.style.setProperty('--base-font-size', c.baseFontSize);
        if (c.headingFontWeight) root.style.setProperty('--heading-font-weight', c.headingFontWeight);
        // Text Colors
        if (c.textColor) root.style.setProperty('--text-color', c.textColor);
        if (c.mutedTextColor) root.style.setProperty('--muted-text-color', c.mutedTextColor);
        if (c.headingColor) root.style.setProperty('--heading-color', c.headingColor);
        if (c.linkColor) root.style.setProperty('--link-color', c.linkColor);
        // Dark Mode Colors
        if (c.darkBgColor) root.style.setProperty('--dark-bg-color', c.darkBgColor);
        if (c.darkCardColor) root.style.setProperty('--dark-card-color', c.darkCardColor);
        if (c.darkTextColor) root.style.setProperty('--dark-text-color', c.darkTextColor);
        if (c.darkAccentColor) root.style.setProperty('--dark-accent-color', c.darkAccentColor);
        // UI Effects - Shadow intensity
        const shadowMap: Record<string, string> = {
          none: '0 0 0 0 transparent',
          light: '0 1px 2px 0 rgba(0,0,0,0.05)',
          medium: '0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)',
          heavy: '0 10px 15px -3px rgba(0,0,0,0.15), 0 4px 6px -4px rgba(0,0,0,0.1)',
        };
        if (c.shadowIntensity) root.style.setProperty('--shadow-intensity', shadowMap[c.shadowIntensity] || shadowMap.medium);
        // Border radius
        const radiusMap: Record<string, string> = {
          'rounded-none': '0px', 'rounded-sm': '2px', 'rounded-md': '6px',
          'rounded-lg': '8px', 'rounded-xl': '12px', 'rounded-2xl': '16px',
        };
        if (c.buttonBorderRadius) root.style.setProperty('--button-radius', radiusMap[c.buttonBorderRadius] || '12px');
        if (c.cardBorderRadius) root.style.setProperty('--card-radius', radiusMap[c.cardBorderRadius] || '12px');
        if (c.inputBorderRadius) root.style.setProperty('--input-radius', radiusMap[c.inputBorderRadius] || '8px');
        // Animations
        root.style.setProperty('--animation-duration', c.enableAnimations === false ? '0ms' : '150ms');
        // Bottom Nav Colors
        if (c.bottomNavBgColor) root.style.setProperty('--bottom-nav-bg', c.bottomNavBgColor);
        if (c.bottomNavActiveColor) root.style.setProperty('--bottom-nav-active', c.bottomNavActiveColor);
        if (c.bottomNavInactiveColor) root.style.setProperty('--bottom-nav-inactive', c.bottomNavInactiveColor);
        // Sidebar
        if (c.sidebarWidth) root.style.setProperty('--sidebar-width', c.sidebarWidth);
        if (c.sidebarBgOpacity) root.style.setProperty('--sidebar-bg-opacity', c.sidebarBgOpacity + '%');
        // Notification
        if (c.notificationPosition) root.style.setProperty('--notification-position', c.notificationPosition);
        // Custom CSS
        if (c.customCSS && c.customCSS.trim()) {
          let customStyleEl = document.getElementById('needyfy-custom-css');
          if (!customStyleEl) {
            customStyleEl = document.createElement('style');
            customStyleEl.id = 'needyfy-custom-css';
            document.head.appendChild(customStyleEl);
          }
          customStyleEl.textContent = c.customCSS;
        }
      }
    } catch { /* ignore invalid JSON */ }

    // Step 3: Reveal content (hydration complete)
    // Use requestAnimationFrame to avoid synchronous setState in effect
    // which can trigger cascading renders
    requestAnimationFrame(() => setMounted(true));
  }, []);

  // Show loading state during SSR/hydration to avoid mismatch
  if (!mounted) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  // If on admin section, render full-screen admin portal (no app chrome)
  if (currentSection === 'admin') {
    return (
      <div className="min-h-screen bg-background">
        <AdminModule />
      </div>
    );
  }

  const renderSection = () => {
    if (currentSection === 'auth') {
      return <AuthModule />;
    }

    if (currentSection === 'home') {
      return <HomeModule />;
    }

    if (currentSection === 'explore') {
      return <ExploreModule />;
    }

    if (currentSection === 'messages') {
      return <MessagesModule />;
    }

    if (currentSection === 'favourites') {
      return <FavouritesModule />;
    }

    if (currentSection === 'marketplace') {
      return <MarketplaceModule />;
    }

    if (currentSection === 'medicine') {
      return <MedicineModule />;
    }

    if (currentSection === 'house-rental') {
      return <HouseRentalModule />;
    }

    if (currentSection === 'shop-rental') {
      return <ShopRentalModule />;
    }

    if (currentSection === 'education') {
      return <EducationModule />;
    }

    if (currentSection === 'profile') {
      return <ProfileModule />;
    }

    if (currentSection === 'orders') {
      return <OrdersModule />;
    }

    if (currentSection === 'community') {
      return <CommunityModule />;
    }

    if (currentSection === 'settings') {
      return <SettingsModule />;
    }


    if (currentSection === 'owner-dashboard') {
      return <OwnerDashboardModule />;
    }

    if (currentSection === 'checkout') {
      return <CheckoutModule />;
    }

    return <SectionPlaceholder section={currentSection} />;
  };

  return (
    <div className="flex min-h-screen flex-col bg-background">
      <Header />
      <Sidebar />
      <main className="flex flex-1 flex-col overflow-y-auto">{renderSection()}</main>
      <FloatingCartButton />
      <BottomNav />
    </div>
  );
}
