import React, { ReactNode, useState } from 'react';
import { Link } from 'react-router-dom';
import { Search, ShoppingCart, User, Menu, X, Heart } from 'lucide-react';
import { useCartStore } from '../lib/cart/store';
import { useHeaderSettings, useFooterSettings, useMenuSettings } from '../hooks/useAppearanceSettings';
import { SearchModal } from '../components/SearchModal';
import { NewsletterForm } from '../components/NewsletterForm';
import { LayoutWrapper } from './LayoutWrapper';
import { useModules } from '../hooks/useModules';
import { useModuleSettings } from '../hooks/useModuleSettings';
import { CouponURLHandler } from '../components/CouponURLHandler';

interface BaseLayoutProps {
  children: ReactNode;
}

/**
 * Base Layout Component
 * 
 * Renders the appropriate layout based on header style from appearance settings
 */
export function BaseLayout({ children }: BaseLayoutProps) {
  const headerSettings = useHeaderSettings();

  return (
    <>
      <CouponURLHandler />
      {/* Map header styles to layouts */}
      {headerSettings.style === 'classic' && <ClassicLayout>{children}</ClassicLayout>}
      {headerSettings.style === 'centered' && <ModernLayout>{children}</ModernLayout>}
      {headerSettings.style === 'minimal' && <LaunchLayout>{children}</LaunchLayout>}
      {headerSettings.style === 'split' && <BoutiqueLayout>{children}</BoutiqueLayout>}
    </>
  );
}

// Temporary internal switch function removed to allow fragment wrapping above.
// Re-implementing logic directly in return for cleaner wrapping.
/**
 * Classic Layout - Traditional ecommerce
 */
function ClassicLayout({ children }: BaseLayoutProps) {
  const { cart } = useCartStore();
  const itemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0);
  const storeLogo = (window as any).woonoowCustomer?.storeLogo;
  const storeName = (window as any).woonoowCustomer?.storeName || (window as any).woonoowCustomer?.siteTitle || 'Store Title';
  const user = (window as any).woonoowCustomer?.user;
  const headerSettings = useHeaderSettings();
  const { isEnabled } = useModules();
  const { settings: wishlistSettings } = useModuleSettings('wishlist');
  const footerSettings = useFooterSettings();
  const { primary: primaryMenu, mobile: mobileMenu } = useMenuSettings();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  const heightClass = headerSettings.height === 'compact' ? 'h-16' : headerSettings.height === 'tall' ? 'h-24' : 'h-20';
  const hasActions = headerSettings.elements.search || headerSettings.elements.account || headerSettings.elements.cart || headerSettings.elements.wishlist;

  const footerColsClass: Record<string, string> = {
    '1': 'grid-cols-1',
    '2': 'grid-cols-1 md:grid-cols-2',
    '3': 'grid-cols-1 md:grid-cols-3',
    '4': 'grid-cols-1 md:grid-cols-4',
  };
  const footerGridClass = footerColsClass[footerSettings.columns] || 'grid-cols-1 md:grid-cols-4';

  const headerContent = (
    <>
      <SearchModal isOpen={searchOpen} onClose={() => setSearchOpen(false)} />
      <header className="classic-header bg-white border-b sticky top-0 z-50 shadow-sm">
        <div className="container mx-auto px-4">
          <div className={`flex items-center ${headerSettings.mobile_logo === 'center' ? 'max-md:justify-center' : 'justify-between'} ${heightClass}`}>
            {/* Logo */}
            {headerSettings.elements.logo && (
              <div className={`flex-shrink-0 ${headerSettings.mobile_logo === 'center' ? 'max-md:mx-auto' : ''}`}>
                <Link to="/" className="flex items-center gap-3 group">
                  {storeLogo ? (
                    <img
                      src={storeLogo}
                      alt={storeName}
                      className="object-contain"
                      style={{
                        width: headerSettings.logo_width,
                        height: headerSettings.logo_height,
                        maxWidth: '100%'
                      }}
                    />
                  ) : (
                    <>
                      <div className="w-10 h-10 bg-gray-900 rounded-lg flex items-center justify-center">
                        <span className="text-white font-bold text-xl">W</span>
                      </div>
                      <span className="text-2xl font-serif font-light text-gray-900 hidden sm:block group-hover:text-gray-600 transition-colors">
                        {storeName}
                      </span>
                    </>
                  )}
                </Link>
              </div>
            )}

            {/* Navigation */}
            {headerSettings.elements.navigation && (
              <nav className="hidden md:flex items-center space-x-8">
                {primaryMenu.length > 0 ? (
                  primaryMenu.map(item => (
                    item.type === 'page' ? (
                      <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</Link>
                    ) : (
                      <a key={item.id} href={item.value} target={item.target} className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</a>
                    )
                  ))
                ) : (
                  <>
                    {(window as any).woonoowCustomer?.frontPageSlug && (
                      <Link to="/" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Home</Link>
                    )}
                    <Link to="/shop" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Shop</Link>
                    <a href="/about" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">About</a>
                    <a href="/contact" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Contact</a>
                  </>
                )}
              </nav>
            )}

            {/* Actions - Hidden on mobile when using bottom-nav */}
            {hasActions && (
              <div className={`flex items-center gap-3 ${headerSettings.mobile_menu === 'bottom-nav' ? 'max-md:hidden' : ''}`}>
                {/* Search */}
                {headerSettings.elements.search && (
                  <button
                    onClick={() => setSearchOpen(true)}
                    className="font-[inherit] flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors"
                  >
                    <Search className="h-5 w-5 text-gray-600" />
                  </button>
                )}
                {/* Account */}
                {headerSettings.elements.account && (user?.isLoggedIn ? (
                  <Link to="/my-account" className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <User className="h-5 w-5" />
                    <span className="hidden lg:block">Account</span>
                  </Link>
                ) : (
                  <Link to="/login" className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <User className="h-5 w-5" />
                    <span className="hidden lg:block">Account</span>
                  </Link>
                ))}

                {/* Wishlist - Only for guests (logged-in users use /my-account/wishlist) */}
                {headerSettings.elements.wishlist && isEnabled('wishlist') && (wishlistSettings.show_in_header ?? true) && !user?.isLoggedIn && (
                  <Link to="/wishlist" className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <Heart className="h-5 w-5" />
                    <span className="hidden lg:block">Wishlist</span>
                  </Link>
                )}

                {/* Cart */}
                {headerSettings.elements.cart && (
                  <Link to="/cart" className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <div className="relative">
                      <ShoppingCart className="h-5 w-5" />
                      {itemCount > 0 && (
                        <span className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-gray-900 text-white text-xs flex items-center justify-center font-medium">
                          {itemCount}
                        </span>
                      )}
                    </div>
                    <span className="hidden lg:block">
                      Cart ({itemCount})
                    </span>
                  </Link>
                )}

                {/* Mobile Menu Toggle - Only for hamburger and slide-in */}
                {(headerSettings.mobile_menu === 'hamburger' || headerSettings.mobile_menu === 'slide-in') && (
                  <button
                    className="font-[inherit] md:hidden flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors"
                    onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                  >
                    {mobileMenuOpen ? <X className="h-5 w-5 text-gray-600" /> : <Menu className="h-5 w-5 text-gray-600" />}
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Mobile Menu - Hamburger Dropdown */}
          {headerSettings.mobile_menu === 'hamburger' && mobileMenuOpen && (
            <div className="md:hidden border-t py-4">
              {headerSettings.elements.navigation && (
                <nav className="flex flex-col space-y-2 mb-4">
                  {(mobileMenu.length > 0 ? mobileMenu : primaryMenu).map(item => (
                    item.type === 'page' ? (
                      <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</Link>
                    ) : (
                      <a key={item.id} href={item.value} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</a>
                    )
                  ))}
                </nav>
              )}
            </div>
          )}

          {/* Mobile Menu - Slide-in Drawer */}
          {headerSettings.mobile_menu === 'slide-in' && mobileMenuOpen && (
            <>
              <div className="fixed inset-0 bg-black/50 z-40 md:hidden" onClick={() => setMobileMenuOpen(false)} />
              <div className="fixed top-0 left-0 h-full w-64 bg-white shadow-xl z-50 md:hidden transform transition-transform">
                <div className="p-4 border-b flex justify-between items-center">
                  <span className="font-semibold">Menu</span>
                  <button onClick={() => setMobileMenuOpen(false)} className="font-[inherit]">
                    <X className="h-5 w-5 text-gray-600" />
                  </button>
                </div>
                {headerSettings.elements.navigation && (
                  <nav className="flex flex-col p-4">
                    {(mobileMenu.length > 0 ? mobileMenu : primaryMenu).map(item => (
                      item.type === 'page' ? (
                        <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} onClick={() => setMobileMenuOpen(false)} target={item.target} className="px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded no-underline">{item.label}</Link>
                      ) : (
                        <a key={item.id} href={item.value} onClick={() => setMobileMenuOpen(false)} target={item.target} className="px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded no-underline">{item.label}</a>
                      )
                    ))}
                  </nav>
                )}
              </div>
            </>
          )}
        </div>
      </header>
    </>
  );

  const footerContent = (
    <>
      {/* Mobile Menu - Bottom Navigation */}
      {headerSettings.mobile_menu === 'bottom-nav' && (
        <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t shadow-lg z-50">
          <div className="flex justify-around items-center py-3">
            <Link to="/shop" className="flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 no-underline">
              <ShoppingCart className="h-5 w-5" />
              <span>Shop</span>
            </Link>
            {headerSettings.elements.search && (
              <button
                onClick={() => setSearchOpen(true)}
                className="font-[inherit] flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900"
              >
                <Search className="h-5 w-5" />
                <span>Search</span>
              </button>
            )}
            {headerSettings.elements.cart && (
              <Link to="/cart" className="flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 no-underline relative">
                <ShoppingCart className="h-5 w-5" />
                {itemCount > 0 && (
                  <span className="absolute top-1 right-2 h-4 w-4 rounded-full bg-gray-900 text-white text-xs flex items-center justify-center">
                    {itemCount}
                  </span>
                )}
                <span>Cart</span>
              </Link>
            )}
            {headerSettings.elements.account && (
              user?.isLoggedIn ? (
                <Link to="/my-account" className="flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 no-underline">
                  <User className="h-5 w-5" />
                  <span>Account</span>
                </Link>
              ) : (
                <Link to="/login" className="flex flex-col items-center gap-1 px-4 py-2 text-xs font-medium text-gray-700 hover:text-gray-900 no-underline">
                  <User className="h-5 w-5" />
                  <span>Login</span>
                </Link>
              )
            )}
          </div>
        </nav>
      )}

      <footer className="classic-footer bg-gray-100 border-t mt-auto">
        <div className="container mx-auto px-4 py-12">
          <div className={`grid ${footerGridClass} gap-8`}>
            {/* Render all sections dynamically */}
            {footerSettings.sections
              .filter((s: any) => s.visible)
              .filter((s: any) => {
                // Filter out newsletter section if module is disabled
                if (s.type === 'newsletter' && !isEnabled('newsletter')) {
                  return false;
                }
                return true;
              })
              .map((section: any) => (
                <div key={section.id}>
                  <h3 className="font-semibold mb-4">{section.title}</h3>

                  {/* Contact Section */}
                  {section.type === 'contact' && (
                    <div className="space-y-1 text-sm text-gray-600">
                      {footerSettings.contact_data?.show_email && footerSettings.contact_data?.email && (
                        <p>Email: {footerSettings.contact_data.email}</p>
                      )}
                      {footerSettings.contact_data?.show_phone && footerSettings.contact_data?.phone && (
                        <p>Phone: {footerSettings.contact_data.phone}</p>
                      )}
                      {footerSettings.contact_data?.show_address && footerSettings.contact_data?.address && (
                        <p>{footerSettings.contact_data.address}</p>
                      )}
                    </div>
                  )}

                  {/* Menu Section */}
                  {section.type === 'menu' && (
                    <ul className="space-y-2 text-sm">
                      <li><Link to="/shop" className="text-gray-600 hover:text-primary no-underline">Shop</Link></li>
                      <li><a href="/about" className="text-gray-600 hover:text-primary no-underline">About</a></li>
                      <li><a href="/contact" className="text-gray-600 hover:text-primary no-underline">Contact</a></li>
                    </ul>
                  )}

                  {/* Social Section */}
                  {section.type === 'social' && footerSettings.social_links?.length > 0 && (
                    <ul className="space-y-2 text-sm">
                      {footerSettings.social_links.map((link: any) => (
                        <li key={link.id}>
                          <a href={link.url} target="_blank" rel="noopener noreferrer" className="text-gray-600 hover:text-primary no-underline">
                            {link.platform}
                          </a>
                        </li>
                      ))}
                    </ul>
                  )}

                  {/* Newsletter Section */}
                  {section.type === 'newsletter' && (
                    <NewsletterForm description={footerSettings.labels?.newsletter_description} />
                  )}

                  {/* Custom HTML Section */}
                  {section.type === 'custom' && (
                    <div className="text-sm text-gray-600" dangerouslySetInnerHTML={{ __html: section.content }} />
                  )}
                </div>
              ))}
          </div>

          {/* Payment Icons */}
          {(footerSettings.payment ? footerSettings.payment.enabled : footerSettings.elements.payment) && (
            <div className="mt-8 pt-8 border-t">
              <p className="text-xs text-gray-500 text-center mb-4">
                {footerSettings.payment?.title || 'We accept'}
              </p>
              <div className="flex justify-center gap-4 text-gray-400 items-center">
                {footerSettings.payment?.methods && footerSettings.payment.methods.length > 0 ? (
                  footerSettings.payment.methods.map((method: any) => (
                    <div key={method.id} title={method.label}>
                      {method.url ? (
                        <img src={method.url} alt={method.label} className="h-6 w-auto object-contain" />
                      ) : (
                        <span className="text-xs">💳 {method.label}</span>
                      )}
                    </div>
                  ))
                ) : (
                  // Fallback for legacy or empty methods
                  <>
                    <span className="text-xs">💳 Visa</span>
                    <span className="text-xs">💳 Mastercard</span>
                    <span className="text-xs">💳 PayPal</span>
                  </>
                )}
              </div>
            </div>
          )}

          {/* Copyright */}
          {(footerSettings.copyright ? footerSettings.copyright.enabled : footerSettings.elements.copyright) && (
            <div className="border-t mt-8 pt-8 text-center text-sm text-gray-600">
              {footerSettings.copyright?.text || footerSettings.copyright_text}
            </div>
          )}
        </div>
      </footer>
    </>
  );

  return (
    <LayoutWrapper header={headerContent} footer={footerContent}>
      {children}
    </LayoutWrapper>
  );
}

/**
 * Modern Layout - Minimalist, clean
 */
function ModernLayout({ children }: BaseLayoutProps) {
  const { cart } = useCartStore();
  const itemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0);
  const storeLogo = (window as any).woonoowCustomer?.storeLogo;
  const storeName = (window as any).woonoowCustomer?.storeName || (window as any).woonoowCustomer?.siteTitle || 'Store Title';
  const user = (window as any).woonoowCustomer?.user;
  const headerSettings = useHeaderSettings();
  const { isEnabled } = useModules();
  const { settings: wishlistSettings } = useModuleSettings('wishlist');
  const { primary: primaryMenu, mobile: mobileMenu } = useMenuSettings();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  const paddingClass = headerSettings.height === 'compact' ? 'py-4' : headerSettings.height === 'tall' ? 'py-8' : 'py-6';
  const hasActions = headerSettings.elements.search || headerSettings.elements.account || headerSettings.elements.cart || headerSettings.elements.wishlist;

  return (
    <div className="modern-layout min-h-screen flex flex-col">
      <SearchModal isOpen={searchOpen} onClose={() => setSearchOpen(false)} />
      <header className="modern-header bg-white border-b sticky top-0 z-50">
        <div className="container mx-auto px-4">
          <div className={`flex flex-col items-center ${paddingClass}`}>
            {/* Logo - Centered */}
            {headerSettings.elements.logo && (
              <Link to="/" className="mb-4">
                {storeLogo ? (
                  <img
                    src={storeLogo}
                    alt={storeName}
                    className="object-contain"
                    style={{
                      width: headerSettings.logo_width,
                      height: headerSettings.logo_height,
                      maxWidth: '100%'
                    }}
                  />
                ) : (
                  <span className="text-3xl font-bold text-gray-900">{storeName}</span>
                )}
              </Link>
            )}

            {/* Navigation & Actions - Centered */}
            {(headerSettings.elements.navigation || hasActions) && (
              <nav className="hidden md:flex items-center space-x-8">
                {headerSettings.elements.navigation && (
                  <>
                    {primaryMenu.length > 0 ? (
                      primaryMenu.map(item => (
                        item.type === 'page' ? (
                          <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</Link>
                        ) : (
                          <a key={item.id} href={item.value} target={item.target} className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</a>
                        )
                      ))
                    ) : (
                      <>
                        {(window as any).woonoowCustomer?.frontPageSlug && (
                          <Link to="/" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Home</Link>
                        )}
                        <Link to="/shop" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Shop</Link>
                        <a href="/about" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">About</a>
                        <a href="/contact" className="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">Contact</a>
                      </>
                    )}
                  </>
                )}
                {headerSettings.elements.search && (
                  <button
                    onClick={() => setSearchOpen(true)}
                    className="font-[inherit] flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"
                  >
                    <Search className="h-4 w-4" />
                  </button>
                )}
                {headerSettings.elements.account && (
                  user?.isLoggedIn ? (
                    <Link to="/my-account" className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <User className="h-4 w-4" /> Account
                    </Link>
                  ) : (
                    <Link to="/login" className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <User className="h-4 w-4" /> Account
                    </Link>
                  )
                )}
                {/* Wishlist - Only for guests */}
                {headerSettings.elements.wishlist && isEnabled('wishlist') && (wishlistSettings.show_in_header ?? true) && !user?.isLoggedIn && (
                  <Link to="/wishlist" className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <Heart className="h-4 w-4" /> Wishlist
                  </Link>
                )}
                {headerSettings.elements.cart && (
                  <Link to="/cart" className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors no-underline">
                    <ShoppingCart className="h-4 w-4" /> Cart ({itemCount})
                  </Link>
                )}
              </nav>
            )}

            {/* Mobile Menu Toggle */}
            <button
              className="md:hidden mt-4 flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            >
              {mobileMenuOpen ? <X className="h-5 w-5 text-gray-600" /> : <Menu className="h-5 w-5 text-gray-600" />}
            </button>
          </div>

          {/* Mobile Menu */}
          {mobileMenuOpen && (
            <div className="md:hidden border-t py-4">
              {headerSettings.elements.navigation && (
                <nav className="flex flex-col space-y-2 mb-4">
                  {(mobileMenu.length > 0 ? mobileMenu : primaryMenu).map(item => (
                    item.type === 'page' ? (
                      <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</Link>
                    ) : (
                      <a key={item.id} href={item.value} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</a>
                    )
                  ))}
                </nav>
              )}
            </div>
          )}
        </div>
      </header>

      <main className="modern-main flex-1">
        {children}
      </main>

      <footer className="modern-footer bg-white border-t mt-auto">
        <div className="container mx-auto px-4 py-12 text-center">
          <div className="mb-6">
            <a href="/" className="text-2xl font-bold" style={{ color: 'var(--color-primary)' }}>
              Store Logo
            </a>
          </div>
          <nav className="flex justify-center space-x-6 mb-6">
            <a href="/shop" className="text-sm text-gray-600 hover:text-primary">Shop</a>
            <a href="/about" className="text-sm text-gray-600 hover:text-primary">About</a>
            <a href="/contact" className="text-sm text-gray-600 hover:text-primary">Contact</a>
          </nav>
          <p className="text-sm text-gray-600">
            © 2024 Your Store. All rights reserved.
          </p>
        </div>
      </footer>
    </div>
  );
}

/**
 * Boutique Layout - Luxury, elegant
 */
function BoutiqueLayout({ children }: BaseLayoutProps) {
  const { cart } = useCartStore();
  const itemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0);
  const storeLogo = (window as any).woonoowCustomer?.storeLogo;
  const storeName = (window as any).woonoowCustomer?.storeName || (window as any).woonoowCustomer?.siteTitle || 'BOUTIQUE';
  const user = (window as any).woonoowCustomer?.user;
  const headerSettings = useHeaderSettings();
  const { isEnabled } = useModules();
  const { settings: wishlistSettings } = useModuleSettings('wishlist');
  const { primary: primaryMenu, mobile: mobileMenu } = useMenuSettings();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  const heightClass = headerSettings.height === 'compact' ? 'h-20' : headerSettings.height === 'tall' ? 'h-28' : 'h-24';
  const hasActions = headerSettings.elements.search || headerSettings.elements.account || headerSettings.elements.cart || headerSettings.elements.wishlist;

  return (
    <div className="boutique-layout min-h-screen flex flex-col font-serif">
      <SearchModal isOpen={searchOpen} onClose={() => setSearchOpen(false)} />
      <header className="boutique-header bg-white border-b sticky top-0 z-50">
        <div className="container mx-auto px-4">
          <div className={`flex items-center justify-between ${heightClass}`}>
            {/* Logo */}
            <div className="flex-1"></div>

            {headerSettings.elements.logo && (
              <div className="flex-shrink-0">
                <Link to="/">
                  {storeLogo ? (
                    <img
                      src={storeLogo}
                      alt={storeName}
                      className="object-contain"
                      style={{
                        width: headerSettings.logo_width,
                        height: headerSettings.logo_height,
                        maxWidth: '100%'
                      }}
                    />
                  ) : (
                    <span className="text-3xl font-bold tracking-wide text-gray-900">{storeName}</span>
                  )}
                </Link>
              </div>
            )}

            <div className="flex-1 flex justify-end">
              {(headerSettings.elements.navigation || hasActions) && (
                <nav className="hidden md:flex items-center space-x-8">
                  {headerSettings.elements.navigation && (
                    <>
                      {primaryMenu.length > 0 ? (
                        primaryMenu.map(item => (
                          item.type === 'page' ? (
                            <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</Link>
                          ) : (
                            <a key={item.id} href={item.value} target={item.target} className="text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">{item.label}</a>
                          )
                        ))
                      ) : (
                        <>
                          {(window as any).woonoowCustomer?.frontPageSlug && (
                            <Link to="/" className="text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">Home</Link>
                          )}
                          <Link to="/shop" className="text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">Shop</Link>
                        </>
                      )}
                    </>
                  )}
                  {headerSettings.elements.search && (
                    <button
                      onClick={() => setSearchOpen(true)}
                      className="font-[inherit] flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors"
                    >
                      <Search className="h-4 w-4" />
                    </button>
                  )}
                  {headerSettings.elements.account && (user?.isLoggedIn ? (
                    <Link to="/my-account" className="flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <User className="h-4 w-4" /> Account
                    </Link>
                  ) : (
                    <Link to="/login" className="flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <User className="h-4 w-4" /> Account
                    </Link>
                  ))}
                  {/* Wishlist - Only for guests */}
                  {headerSettings.elements.wishlist && isEnabled('wishlist') && (wishlistSettings.show_in_header ?? true) && !user?.isLoggedIn && (
                    <Link to="/wishlist" className="flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <Heart className="h-4 w-4" /> Wishlist
                    </Link>
                  )}
                  {headerSettings.elements.cart && (
                    <Link to="/cart" className="flex items-center gap-1 text-sm uppercase tracking-wider text-gray-700 hover:text-gray-900 transition-colors no-underline">
                      <ShoppingCart className="h-4 w-4" /> Cart ({itemCount})
                    </Link>
                  )}
                </nav>
              )}

              {/* Mobile Menu Toggle */}
              <button
                className="font-[inherit] md:hidden flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors"
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              >
                {mobileMenuOpen ? <X className="h-5 w-5 text-gray-600" /> : <Menu className="h-5 w-5 text-gray-600" />}
              </button>
            </div>
          </div>

          {/* Mobile Menu */}
          {mobileMenuOpen && (
            <div className="md:hidden border-t py-4">
              {headerSettings.elements.navigation && (
                <nav className="flex flex-col space-y-2 mb-4">
                  {(mobileMenu.length > 0 ? mobileMenu : primaryMenu).map(item => (
                    item.type === 'page' ? (
                      <Link key={item.id} to={`/${item.value.replace(/^\/+/, '')}`} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</Link>
                    ) : (
                      <a key={item.id} href={item.value} target={item.target} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 no-underline">{item.label}</a>
                    )
                  ))}
                </nav>
              )}
            </div>
          )}
        </div>
      </header>

      <main className="boutique-main flex-1">
        {children}
      </main>

      <footer className="boutique-footer bg-gray-50 border-t mt-auto">
        <div className="container mx-auto px-4 py-16 text-center">
          <div className="mb-8">
            <a href="/" className="text-3xl font-bold tracking-wide" style={{ color: 'var(--color-primary)' }}>
              BOUTIQUE
            </a>
          </div>
          <nav className="flex justify-center space-x-8 mb-8">
            <a href="/shop" className="text-sm uppercase tracking-wider text-gray-600 hover:text-primary">Shop</a>
            <a href="/about" className="text-sm uppercase tracking-wider text-gray-600 hover:text-primary">About</a>
            <a href="/contact" className="text-sm uppercase tracking-wider text-gray-600 hover:text-primary">Contact</a>
          </nav>
          <p className="text-sm text-gray-600 tracking-wide">
            © 2024 BOUTIQUE. ALL RIGHTS RESERVED.
          </p>
        </div>
      </footer>
    </div>
  );
}

/**
 * Launch Layout - Single product funnel
 * Note: Landing page is custom (user's page builder)
 * WooNooW only takes over from checkout onwards
 */
function LaunchLayout({ children }: BaseLayoutProps) {
  const isCheckoutFlow = window.location.pathname.includes('/checkout') ||
    window.location.pathname.includes('/my-account') ||
    window.location.pathname.includes('/order-received');

  const storeName = (window as any).woonoowCustomer?.storeName || (window as any).woonoowCustomer?.siteTitle || 'Store Title';
  const storeLogo = (window as any).woonoowCustomer?.storeLogo;
  const headerSettings = useHeaderSettings();

  if (!isCheckoutFlow) {
    // For non-checkout pages, use minimal layout
    return (
      <div className="launch-layout min-h-screen flex flex-col">
        {children}
      </div>
    );
  }

  // For checkout flow: minimal header, no footer
  const heightClass = headerSettings.height === 'compact' ? 'h-12' : headerSettings.height === 'tall' ? 'h-20' : 'h-16';

  return (
    <div className="launch-layout min-h-screen flex flex-col bg-gray-50">
      <header className="launch-header bg-white border-b">
        <div className="container mx-auto px-4">
          <div className={`flex items-center justify-center ${heightClass}`}>
            {headerSettings.elements.logo && (
              <Link to="/">
                {storeLogo ? (
                  <img
                    src={storeLogo}
                    alt={storeName}
                    className="object-contain"
                    style={{
                      width: headerSettings.logo_width,
                      height: headerSettings.logo_height,
                      maxWidth: '100%'
                    }}
                  />
                ) : (
                  <span className="text-xl font-bold text-gray-900">{storeName}</span>
                )}
              </Link>
            )}
          </div>
        </div>
      </header>

      <main className="launch-main flex-1 py-8">
        <div className="container mx-auto px-4 max-w-2xl">
          {children}
        </div>
      </main>

      {/* Minimal footer for checkout */}
      <footer className="launch-footer bg-white border-t py-4">
        <div className="container mx-auto px-4 text-center text-sm text-gray-600">
          © 2024 Your Store. Secure Checkout.
        </div>
      </footer>
    </div>
  );
}
