/* ==========================================================================
   Aurelia Books - Shared UI Components (Light Mode Standard E-Commerce)
   Header, Footer, Pagination, BookCard, CartDrawer, AuthModal, DemoModal, Toast, StatusBadge
   ========================================================================== */
(function () {
  const { useState, useEffect, useCallback, useRef, useContext, useMemo } = React;

  /* ══════════════════════════════════════════════════════════════════════
     LOADING SPINNER
     ══════════════════════════════════════════════════════════════════════ */
  function LoadingSpinner({ size = 'md', text }) {
    const sizeMap = { sm: 'w-5 h-5', md: 'w-8 h-8', lg: 'w-12 h-12' };
    return (
      <div className="flex flex-col items-center justify-center py-12 gap-3">
        <div className={`${sizeMap[size]} border-3 border-stone-200 border-t-amber-600 rounded-full animate-spin`}></div>
        {text && <span className="text-xs font-semibold text-stone-500">{text}</span>}
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     GENERIC MODAL
     ══════════════════════════════════════════════════════════════════════ */
  function Modal({ isOpen, onClose, title, maxWidth = 'max-w-md', children }) {
    if (!isOpen) return null;

    return (
      <div className="fixed inset-0 z-50 bg-stone-900/60 backdrop-blur-sm flex items-center justify-center p-4"
           onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className={`bg-white border border-stone-200 rounded-3xl w-full ${maxWidth} p-6 sm:p-8 shadow-2xl relative animate-modal-in`}>
          <button onClick={onClose}
                  className="absolute top-4 right-4 w-8 h-8 rounded-full bg-stone-100 text-stone-500 hover:text-stone-900 hover:bg-stone-200 flex items-center justify-center transition-colors">
            <i className="fa-solid fa-xmark text-sm"></i>
          </button>
          {title && (
            <h2 className="font-serif text-2xl font-bold text-stone-900 mb-4">{title}</h2>
          )}
          {children}
        </div>
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     DEMO ACCOUNTS PORTFOLIO MODAL & FLOATING BADGE
     ══════════════════════════════════════════════════════════════════════ */
  function DemoAccountModal({ isOpen, onClose }) {
    const { setUser, showToast, fetchCart } = window.useApp();
    const [loadingRole, setLoadingRole] = useState(null);

    if (!isOpen) return null;

    const handleOneClickLogin = async (email, password, roleName) => {
      setLoadingRole(roleName);
      try {
        const res = await ApiClient.login(email, password);
        setUser(res.data.user);
        showToast(`Signed in successfully as ${res.data.user.fullName} (${roleName})!`, 'success');
        fetchCart();
        onClose();
      } catch (err) {
        showToast(err.message || 'Login failed', 'error');
      } finally {
        setLoadingRole(null);
      }
    };

    return (
      <div className="fixed inset-0 z-[80] bg-stone-900/70 backdrop-blur-md flex items-center justify-center p-4"
           onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="bg-white border border-amber-300 rounded-3xl w-full max-w-lg p-6 sm:p-8 shadow-2xl relative animate-modal-in space-y-6">
          <button onClick={onClose}
                  className="absolute top-4 right-4 w-8 h-8 rounded-full bg-stone-100 text-stone-500 hover:text-stone-900 flex items-center justify-center">
            <i className="fa-solid fa-xmark text-sm"></i>
          </button>

          {/* Header */}
          <div className="text-center space-y-2">
            <div className="w-12 h-12 bg-amber-100 border border-amber-300 rounded-2xl flex items-center justify-center mx-auto text-amber-700 text-xl font-bold shadow-sm">
              <i className="fa-solid fa-key"></i>
            </div>
            <span className="text-[10px] font-extrabold uppercase tracking-widest text-amber-700 bg-amber-50 px-3 py-1 rounded-full border border-amber-200 inline-block">
              Portfolio & Demo Preview Mode
            </span>
            <h2 className="font-serif text-2xl font-bold text-stone-900">Explore Aurelia Books Demo Accounts</h2>
            <p className="text-xs text-stone-600 max-w-sm mx-auto">
              Welcome to the portfolio live demo! Click below to automatically sign in as an Administrator or Customer to test full functionality.
            </p>
          </div>

          {/* Accounts Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {/* Admin Account Card */}
            <div className="p-5 rounded-2xl bg-indigo-50/70 border border-indigo-200 text-left space-y-3 relative hover:border-indigo-400 transition-all shadow-sm">
              <div className="flex items-center justify-between">
                <span className="text-[10px] font-extrabold uppercase tracking-wider text-indigo-700 bg-white px-2 py-0.5 rounded border border-indigo-200">
                  <i className="fa-solid fa-shield-halved mr-1"></i>Admin Role
                </span>
                <i className="fa-solid fa-chart-pie text-indigo-400"></i>
              </div>
              <div>
                <h4 className="font-serif font-bold text-sm text-stone-900">System Administrator</h4>
                <p className="text-[11px] text-stone-500 font-mono mt-0.5">admin@bookstore.com</p>
                <p className="text-[10px] text-stone-400 font-mono">Password: Admin@123456</p>
              </div>
              <p className="text-[10px] text-stone-600 leading-tight">Access full Admin Portal, Revenue Charts, Books CRUD & Orders.</p>
              <button
                disabled={loadingRole === 'Admin'}
                onClick={() => handleOneClickLogin('admin@bookstore.com', 'Admin@123456', 'Admin')}
                className="w-full py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs shadow-md transition-all flex items-center justify-center gap-1.5 disabled:opacity-50"
              >
                {loadingRole === 'Admin' ? 'Signing In...' : '1-Click Login as Admin'}
                <i className="fa-solid fa-arrow-right text-[10px]"></i>
              </button>
            </div>

            {/* Customer Account Card */}
            <div className="p-5 rounded-2xl bg-amber-50/70 border border-amber-200 text-left space-y-3 relative hover:border-amber-400 transition-all shadow-sm">
              <div className="flex items-center justify-between">
                <span className="text-[10px] font-extrabold uppercase tracking-wider text-amber-800 bg-white px-2 py-0.5 rounded border border-amber-200">
                  <i className="fa-solid fa-user mr-1"></i>Customer Role
                </span>
                <i className="fa-solid fa-cart-shopping text-amber-400"></i>
              </div>
              <div>
                <h4 className="font-serif font-bold text-sm text-stone-900">John Alexander</h4>
                <p className="text-[11px] text-stone-500 font-mono mt-0.5">customer@example.com</p>
                <p className="text-[10px] text-stone-400 font-mono">Password: Password@123</p>
              </div>
              <p className="text-[10px] text-stone-600 leading-tight">Test Cart, Checkout, Address Selector, Coupons & Order History.</p>
              <button
                disabled={loadingRole === 'Customer'}
                onClick={() => handleOneClickLogin('customer@example.com', 'Password@123', 'Customer')}
                className="w-full py-2.5 rounded-xl bg-amber-600 hover:bg-amber-700 text-white font-bold text-xs shadow-md transition-all flex items-center justify-center gap-1.5 disabled:opacity-50"
              >
                {loadingRole === 'Customer' ? 'Signing In...' : '1-Click Login as Customer'}
                <i className="fa-solid fa-arrow-right text-[10px]"></i>
              </button>
            </div>
          </div>

          {/* Swagger API Docs Banner */}
          <div className="p-4 rounded-2xl bg-emerald-50/80 border border-emerald-200 text-left flex items-start gap-3.5 hover:border-emerald-300 transition-all">
            <div className="w-9 h-9 rounded-xl bg-emerald-600 text-white flex items-center justify-center shrink-0 font-bold shadow-md shadow-emerald-600/20 text-sm">
              <i className="fa-solid fa-code"></i>
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between gap-2">
                <h4 className="font-serif font-bold text-xs text-stone-900">OpenAPI 3.0 / Swagger Interactive API Docs</h4>
                <span className="text-[9px] font-extrabold uppercase tracking-wider bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full border border-emerald-300">
                  REST API
                </span>
              </div>
              <p className="text-[11px] text-stone-600 mt-0.5 leading-tight">
                Inspect 30+ backend endpoints for Spring Security JWT, Book Filtering, Orders, & Admin Dashboard.
              </p>
              <a
                href="/swagger-ui/index.html"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1.5 text-xs font-bold text-emerald-700 hover:text-emerald-800 hover:underline mt-2"
              >
                <span>Explore Swagger UI</span>
                <i className="fa-solid fa-arrow-up-right-from-square text-[10px]"></i>
              </a>
            </div>
          </div>

          <div className="text-center pt-1">
            <button onClick={onClose} className="text-xs font-semibold text-stone-500 hover:text-stone-900 underline">
              Continue Browsing as Guest
            </button>
          </div>
        </div>
      </div>
    );
  }

  function DemoFloatingBadge({ onOpenDemoModal }) {
    const { user } = window.useApp();
    return (
      <div className="fixed bottom-6 left-6 z-40">
        <button
          onClick={onOpenDemoModal}
          className="px-4 py-2.5 rounded-full bg-stone-900/90 backdrop-blur-md text-amber-400 border border-amber-500/40 font-bold text-xs shadow-2xl hover:scale-105 hover:bg-stone-900 transition-all flex items-center gap-2"
        >
          <i className="fa-solid fa-key text-amber-400"></i>
          <span>Demo Accounts</span>
          {user && <span className="text-[10px] bg-amber-500/20 text-amber-300 px-2 py-0.5 rounded-full border border-amber-400/30">Active: {user.fullName}</span>}
        </button>
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     CONFIRM DIALOG
     ══════════════════════════════════════════════════════════════════════ */
  function ConfirmDialog({ isOpen, onClose, onConfirm, title, message }) {
    if (!isOpen) return null;
    return (
      <div className="fixed inset-0 z-[60] bg-stone-900/60 backdrop-blur-sm flex items-center justify-center p-4"
           onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="bg-white border border-stone-200 rounded-3xl w-full max-w-sm p-6 shadow-2xl animate-modal-in text-center">
          <div className="w-14 h-14 bg-rose-100 rounded-full flex items-center justify-center mx-auto mb-4 text-rose-600 text-2xl">
            <i className="fa-solid fa-triangle-exclamation"></i>
          </div>
          <h3 className="font-serif text-lg font-bold text-stone-900 mb-2">{title || 'Confirm Action'}</h3>
          <p className="text-xs text-stone-600 mb-6">{message || 'Are you sure you want to proceed with this action?'}</p>
          <div className="flex gap-3">
            <button onClick={onClose}
                    className="flex-1 py-2.5 bg-stone-100 hover:bg-stone-200 text-stone-700 font-semibold rounded-xl transition-all text-xs">
              Cancel
            </button>
            <button onClick={() => { onConfirm(); onClose(); }}
                    className="flex-1 py-2.5 bg-rose-600 hover:bg-rose-700 text-white font-semibold rounded-xl shadow-lg shadow-rose-600/20 transition-all text-xs">
              Confirm
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     PAGINATION
     ══════════════════════════════════════════════════════════════════════ */
  function Pagination({ currentPage, totalPages, totalElements, onPageChange }) {
    if (!totalPages || totalPages <= 1) return null;

    const pages = [];
    const maxVisible = 5;
    let start = Math.max(0, currentPage - Math.floor(maxVisible / 2));
    let end = Math.min(totalPages - 1, start + maxVisible - 1);
    start = Math.max(0, end - maxVisible + 1);

    if (start > 0) pages.push(0);
    if (start > 1) pages.push('..._start');

    for (let i = start; i <= end; i++) pages.push(i);

    if (end < totalPages - 2) pages.push('..._end');
    if (end < totalPages - 1) pages.push(totalPages - 1);

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between mt-10 gap-4 pt-6 border-t border-stone-200">
        <span className="text-xs font-medium text-stone-500">
          Page <span className="font-bold text-stone-900">{currentPage + 1}</span> of {totalPages}
          {totalElements != null && <span className="ml-1">— {totalElements} Total Titles</span>}
        </span>
        <div className="flex items-center gap-1.5">
          <button
            onClick={() => onPageChange(currentPage - 1)}
            disabled={currentPage === 0}
            className="pagination-btn"
            aria-label="Previous page"
          >
            <i className="fa-solid fa-chevron-left text-xs"></i>
          </button>

          {pages.map((p, i) =>
            typeof p === 'string' ? (
              <span key={p} className="px-2 text-stone-400 text-xs select-none">…</span>
            ) : (
              <button
                key={p}
                onClick={() => onPageChange(p)}
                className={`pagination-btn ${p === currentPage ? 'active' : ''}`}
              >
                {p + 1}
              </button>
            )
          )}

          <button
            onClick={() => onPageChange(currentPage + 1)}
            disabled={currentPage >= totalPages - 1}
            className="pagination-btn"
            aria-label="Next page"
          >
            <i className="fa-solid fa-chevron-right text-xs"></i>
          </button>
        </div>
      </div>
    );
  }
  /* ══════════════════════════════════════════════════════════════════════
     BOOK CARD
     ══════════════════════════════════════════════════════════════════════ */
  function BookCard({ book, onAddToCart, onViewDetail }) {
    const formatCurrency = window.formatCurrency;
    const hasDiscount = book.discountPrice && Number(book.discountPrice) < Number(book.price);
    const discountPercent = hasDiscount
      ? Math.round((1 - Number(book.discountPrice) / Number(book.price)) * 100)
      : 0;

    return (
      <article className="book-card bg-white border border-stone-200/80 rounded-3xl overflow-hidden
                      hover:border-amber-500/50 hover:shadow-xl hover:shadow-amber-500/10
                      hover:-translate-y-1.5 transition-all duration-300 flex flex-col group relative">
        {/* Cover Image Container */}
        <div className="book-card-media h-64 bg-stone-50 relative overflow-hidden flex items-center justify-center cursor-pointer p-4"
             onClick={() => onViewDetail && onViewDetail(book)}>
          <span className="book-card-glow"></span>
          <img
            src={book.coverImage || 'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?auto=format&fit=crop&w=400&q=80'}
            alt={book.title}
            className="book-cover h-full max-h-56 object-contain rounded-lg shadow-md group-hover:scale-105 transition-transform duration-500"
          />

          {/* Wishlist Button Top Right */}
          <div className="absolute top-3 right-3 z-10">
            <WishlistButton bookId={book.id} />
          </div>

          {/* Discount Badge */}
          {hasDiscount && (
            <span className="book-sale-badge absolute top-3 left-3 text-white text-[10px] font-extrabold px-2.5 py-1 rounded-full shadow-md uppercase tracking-wider">
              Save {discountPercent}%
            </span>
          )}

          {/* Average Rating Badge */}
          <div className="book-rating absolute bottom-3 right-3 bg-white/90 backdrop-blur-md border border-stone-200 px-2 py-0.5 rounded-full text-[11px] font-bold text-amber-600 flex items-center gap-1 shadow-sm">
            <i className="fa-solid fa-star text-[10px] text-amber-500"></i>
            <span>{book.averageRating || '4.9'}</span>
          </div>
        </div>

        {/* Info */}
        <div className="book-card-body p-5 flex-1 flex flex-col justify-between space-y-3">
          <div>
            <span className="book-category text-[10px] font-bold uppercase tracking-wider text-amber-700 bg-amber-50 px-2.5 py-1 rounded-md border border-amber-200/60 inline-block mb-2">
              {book.categoryName || 'Literature'}
            </span>

            <h3 className="book-title font-serif font-bold text-stone-900 text-base leading-snug line-clamp-2 cursor-pointer hover:text-amber-600 transition-colors"
                onClick={() => onViewDetail && onViewDetail(book)}>
              {book.title}
            </h3>

            <p className="book-author text-xs text-stone-500 mt-1 font-medium line-clamp-1">
              By {book.authorNames ? book.authorNames.join(', ') : 'Unknown Author'}
            </p>
          </div>

          <div className="book-card-footer pt-3 border-t border-stone-100 flex items-center justify-between">
            <div className="book-price-wrap">
              <span className="book-price text-lg font-extrabold text-amber-700">
                {formatCurrency(book.discountPrice || book.price)}
              </span>
              {hasDiscount && (
                <span className="text-xs text-stone-400 line-through ml-2">
                  {formatCurrency(book.price)}
                </span>
              )}
            </div>

            <button
              onClick={(e) => { e.stopPropagation(); onAddToCart && onAddToCart(book.id); }}
              className="book-add-button p-2.5 bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-600 hover:text-white hover:border-amber-600 rounded-xl transition-all shadow-sm"
              title="Add to Cart"
            >
              <i className="fa-solid fa-bag-shopping text-sm"></i><span>Add</span>
            </button>
          </div>
        </div>
      </article>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     TOAST CONTAINER
     ══════════════════════════════════════════════════════════════════════ */
  function ToastContainer() {
    const { toasts } = window.useApp();
    return (
      <div className="fixed bottom-6 right-6 z-[70] space-y-2 pointer-events-none">
        {toasts.map(t => (
          <div key={t.id}
               className={`pointer-events-auto px-4 py-3 rounded-2xl border shadow-xl text-xs font-semibold
                          flex items-center gap-3 animate-toast-in
                          ${t.type === 'success'
                            ? 'bg-emerald-50 border-emerald-300 text-emerald-900 shadow-emerald-500/10'
                            : t.type === 'error'
                            ? 'bg-rose-50 border-rose-300 text-rose-900 shadow-rose-500/10'
                            : 'bg-white border-stone-200 text-stone-900 shadow-stone-500/10'}`}>
            <i className={`fa-solid text-sm ${
              t.type === 'success' ? 'fa-circle-check text-emerald-600'
              : t.type === 'error' ? 'fa-circle-exclamation text-rose-600'
              : 'fa-circle-info text-amber-600'}`}></i>
            <span>{t.message}</span>
          </div>
        ))}
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     HEADER / NAVBAR WITH STOREFRONT LINKS
     ══════════════════════════════════════════════════════════════════════ */
  function Header({ onOpenDemoModal }) {
    const { navigate, currentPath } = window.useRouter();
    const { user, cart, setIsCartOpen, setIsAuthOpen, setAuthMode, handleLogout, searchQuery, setSearchQuery } = window.useApp();
    const [isMenuOpen, setIsMenuOpen] = useState(false);

    return (
      <nav className="store-header sticky top-0 z-40 bg-white/95 backdrop-blur-md border-b border-stone-200/80 shadow-sm">
        <div className="max-w-7xl mx-auto flex items-center justify-between gap-4 px-4 sm:px-6 py-2.5">
          
          {/* 1. Brand Logo */}
          <div className="flex items-center gap-2.5 cursor-pointer shrink-0 group" onClick={() => navigate('/')}>
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-600 to-amber-800 flex items-center justify-center text-white shadow-md shadow-amber-700/20 group-hover:scale-105 transition-transform">
              <i className="fa-solid fa-book-open text-base"></i>
            </div>
            <div>
              <span className="font-serif text-xl font-bold tracking-tight text-stone-900 leading-none block">Aurelia</span>
              <span className="text-[9px] font-sans font-bold text-amber-700 tracking-[0.2em] uppercase block mt-0.5">Book house</span>
            </div>
          </div>

          {/* 2. Main Navigation Links */}
          <div className="hidden md:flex items-center gap-5 text-xs font-bold text-stone-700 shrink-0">
            <button onClick={() => navigate('/')}
                    className={`transition-colors py-1 ${currentPath === '/' ? 'text-amber-800 border-b-2 border-amber-700' : 'hover:text-amber-800'}`}>
              Home
            </button>
            <button onClick={() => navigate('/catalog')}
                    className={`transition-colors py-1 ${currentPath.startsWith('/catalog') ? 'text-amber-800 border-b-2 border-amber-700' : 'hover:text-amber-800'}`}>
              Book Catalog
            </button>
            <button onClick={() => navigate('/catalog?sort=price,asc')}
                    className="hover:text-amber-800 transition-colors text-amber-800 font-bold flex items-center gap-1">
              <i className="fa-solid fa-tags text-[10px]"></i>Deals
            </button>
          </div>

          {/* 3. Search Bar */}
          <div className="flex-1 max-w-xs sm:max-w-sm relative hidden sm:block">
            <i className="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-stone-400 text-xs"></i>
            <input
              type="text"
              placeholder="Search by title, author..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') navigate('/catalog'); }}
              className="w-full bg-stone-100/80 border border-stone-200 rounded-full pl-9 pr-3.5 py-1.5 text-xs text-stone-900 placeholder-stone-400 focus:bg-white focus:outline-none focus:border-amber-600 focus:ring-2 focus:ring-amber-500/15 transition-all"
            />
          </div>

          {/* 4. Action Controls */}
          <div className="flex items-center gap-2.5 shrink-0">
            
            {/* Quick Demo Button */}
            <button onClick={onOpenDemoModal}
                    className="px-3 py-1.5 bg-amber-100/80 border border-amber-300 rounded-full text-[11px] font-extrabold text-amber-900 hover:bg-amber-200/80 transition-all flex items-center gap-1.5 shadow-2xs">
              <i className="fa-solid fa-key text-[10px]"></i>
              <span className="hidden xs:inline">Demo Accounts</span>
            </button>

            {/* Cart Icon Button */}
            <button
              onClick={() => setIsCartOpen(true)}
              className="relative p-2 bg-stone-100 hover:bg-amber-50 border border-stone-200 text-stone-800 rounded-full transition-all shrink-0"
              title="Shopping Cart"
            >
              <i className="fa-solid fa-cart-shopping text-sm"></i>
              {cart && cart.totalItems > 0 && (
                <span className="absolute -top-1 -right-1 bg-amber-700 text-white text-[10px] font-extrabold px-1.5 py-0.2 rounded-full shadow-sm">
                  {cart.totalItems}
                </span>
              )}
            </button>

            {/* User Dropdown / Sign In */}
            {user ? (
              <div className="relative">
                <button
                  onClick={() => setIsMenuOpen(!isMenuOpen)}
                  className="flex items-center gap-2 px-3 py-1.5 bg-white border border-stone-200 hover:border-amber-400 rounded-full text-xs font-semibold text-stone-800 transition-all shadow-xs"
                >
                  <div className="w-6 h-6 rounded-full bg-amber-100 text-amber-800 font-extrabold flex items-center justify-center text-[11px]">
                    {(user.fullName || user.email || 'U').charAt(0).toUpperCase()}
                  </div>
                  <span className="hidden md:inline max-w-[110px] truncate font-bold">
                    {user.fullName || user.email}
                  </span>
                  <i className={`fa-solid fa-chevron-down text-[10px] text-stone-400 transition-transform ${isMenuOpen ? 'rotate-180' : ''}`}></i>
                </button>

                {/* Dropdown Menu */}
                {isMenuOpen && (
                  <>
                    <div className="fixed inset-0 z-10" onClick={() => setIsMenuOpen(false)}></div>
                    <div className="absolute right-0 mt-2 w-56 bg-white rounded-2xl border border-stone-200 shadow-xl py-2 z-20 space-y-1">
                      <div className="px-4 py-2 border-b border-stone-100">
                        <p className="text-xs font-bold text-stone-900 truncate">{user.fullName || 'Valued User'}</p>
                        <p className="text-[10px] text-stone-500 truncate">{user.email}</p>
                      </div>

                      <button
                        onClick={() => { setIsMenuOpen(false); navigate('/orders'); }}
                        className="w-full px-4 py-2 text-left text-xs font-semibold text-stone-700 hover:bg-amber-50 hover:text-amber-800 flex items-center gap-2.5 transition-colors"
                      >
                        <i className="fa-solid fa-receipt text-amber-600 text-xs w-4"></i>
                        <span>My Orders</span>
                      </button>

                      {user.roles && user.roles.includes('ROLE_ADMIN') && (
                        <button
                          onClick={() => { setIsMenuOpen(false); navigate('/admin'); }}
                          className="w-full px-4 py-2 text-left text-xs font-semibold text-indigo-700 hover:bg-indigo-50 flex items-center gap-2.5 transition-colors"
                        >
                          <i className="fa-solid fa-chart-pie text-indigo-600 text-xs w-4"></i>
                          <span>Admin Portal</span>
                        </button>
                      )}

                      <a
                        href="/swagger-ui/index.html"
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() => setIsMenuOpen(false)}
                        className="w-full px-4 py-2 text-left text-xs font-semibold text-emerald-700 hover:bg-emerald-50 flex items-center gap-2.5 transition-colors"
                      >
                        <i className="fa-solid fa-code text-emerald-600 text-xs w-4"></i>
                        <span>Swagger API Docs</span>
                        <i className="fa-solid fa-arrow-up-right-from-square text-[9px] ml-auto text-emerald-500"></i>
                      </a>

                      <button
                        onClick={() => { setIsMenuOpen(false); onOpenDemoModal(); }}
                        className="w-full px-4 py-2 text-left text-xs font-semibold text-amber-900 hover:bg-amber-50 flex items-center gap-2.5 transition-colors"
                      >
                        <i className="fa-solid fa-key text-amber-600 text-xs w-4"></i>
                        <span>Switch Demo Account</span>
                      </button>

                      <div className="border-t border-stone-100 pt-1">
                        <button
                          onClick={() => { setIsMenuOpen(false); handleLogout(); }}
                          className="w-full px-4 py-2 text-left text-xs font-semibold text-rose-600 hover:bg-rose-50 flex items-center gap-2.5 transition-colors"
                        >
                          <i className="fa-solid fa-right-from-bracket text-rose-500 text-xs w-4"></i>
                          <span>Sign Out</span>
                        </button>
                      </div>
                    </div>
                  </>
                )}
              </div>
            ) : (
              <button
                onClick={() => { setAuthMode('login'); setIsAuthOpen(true); }}
                className="px-4 py-1.5 rounded-full bg-gradient-to-r from-amber-600 to-amber-700 hover:from-amber-500 hover:to-amber-600 text-white font-bold text-xs shadow-md shadow-amber-600/20 transition-all flex items-center gap-1.5"
              >
                <i className="fa-solid fa-user text-xs"></i>
                <span>Sign In</span>
              </button>
            )}
          </div>
        </div>
      </nav>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     FOOTER
     ══════════════════════════════════════════════════════════════════════ */
  function Footer() {
    return (
      <footer className="store-footer bg-white border-t border-stone-200 mt-auto pt-14 pb-10">
        <div className="max-w-7xl mx-auto px-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-10 pb-10 border-b border-stone-200">
            {/* Brand */}
            <div className="md:col-span-2 space-y-4">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-2xl bg-amber-600 flex items-center justify-center text-white font-bold">
                  <i className="fa-solid fa-book-open"></i>
                </div>
                <span className="font-serif text-2xl font-bold text-stone-900">Aurelia Books</span>
              </div>
              <p className="text-xs text-stone-500 leading-relaxed max-w-sm">
                Curating timeless literature, academic excellence, and bestselling stories. Enjoy fast nationwide delivery and personal reader assistance.
              </p>
              <div className="flex gap-3">
                {['facebook-f', 'instagram', 'twitter', 'goodreads'].map((icon) => (
                  <a key={icon} href="#" className="w-8 h-8 rounded-full bg-stone-100 hover:bg-amber-100 hover:text-amber-700 flex items-center justify-center text-stone-500 text-xs transition-colors">
                    <i className={`fa-brands fa-${icon}`}></i>
                  </a>
                ))}
              </div>
            </div>

            {/* Links */}
            <div>
              <h4 className="font-serif text-xs font-bold uppercase tracking-wider text-stone-900 mb-3">Store Navigation</h4>
              <ul className="space-y-2 text-xs text-stone-500">
                <li><a href="#/" className="hover:text-amber-700 transition-colors">Storefront Home</a></li>
                <li><a href="#/catalog" className="hover:text-amber-700 transition-colors">Full Book Catalog</a></li>
                <li><a href="#/orders" className="hover:text-amber-700 transition-colors">My Order History</a></li>
                <li><a href="#" className="hover:text-amber-700 transition-colors">Shipping & Returns</a></li>
              </ul>
            </div>

            {/* Newsletter */}
            <div>
              <h4 className="font-serif text-xs font-bold uppercase tracking-wider text-stone-900 mb-3">Literary Newsletter</h4>
              <p className="text-xs text-stone-500 mb-3">Subscribe for monthly curated reading lists and exclusive book launch discounts.</p>
              <form onSubmit={(e) => { e.preventDefault(); alert('Thank you for subscribing to Aurelia Books newsletter!'); }} className="space-y-2">
                <input type="email" required placeholder="Enter your email..." className="warm-light-input py-2 text-xs" />
                <button type="submit" className="w-full py-2 bg-amber-600 hover:bg-amber-700 text-white font-bold text-xs rounded-xl shadow transition-all">
                  Subscribe
                </button>
              </form>
            </div>
          </div>

          <div className="pt-6 flex flex-col sm:flex-row items-center justify-between text-[11px] text-stone-400">
            <span>© 2026 Aurelia Books Press. All Rights Reserved.</span>
            <span>Portfolio Demo Mode Enabled</span>
          </div>
        </div>
      </footer>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     CART DRAWER
     ══════════════════════════════════════════════════════════════════════ */
  function CartDrawer() {
    const { navigate } = window.useRouter();
    const { cart, isCartOpen, setIsCartOpen, handleUpdateCartQty, handleRemoveCartItem, showToast } = window.useApp();
    const formatCurrency = window.formatCurrency;

    if (!isCartOpen) return null;

    const handleCheckout = () => {
      if (!cart || !cart.items || cart.items.length === 0) {
        showToast('Your shopping cart is empty!', 'error');
        return;
      }
      setIsCartOpen(false);
      navigate('/checkout');
    };

    return (
      <div className="fixed inset-0 z-50 overflow-hidden">
        <div className="absolute inset-0 bg-stone-900/50 backdrop-blur-sm animate-fade-in"
             onClick={() => setIsCartOpen(false)}></div>
        <div className="absolute inset-y-0 right-0 max-w-full flex pl-10">
          <div className="w-screen max-w-md bg-white border-l border-stone-200 p-6 flex flex-col justify-between shadow-2xl animate-slide-in-right">
            <div>
              <div className="flex items-center justify-between pb-4 border-b border-stone-200">
                <h3 className="font-serif text-lg font-bold flex items-center text-stone-900">
                  <i className="fa-solid fa-cart-shopping text-amber-600 mr-2"></i>
                  Your Shopping Cart
                </h3>
                <button onClick={() => setIsCartOpen(false)}
                        className="text-stone-400 hover:text-stone-900 transition-colors">
                  <i className="fa-solid fa-xmark text-lg"></i>
                </button>
              </div>

              <div className="py-4 space-y-4 max-h-[65vh] overflow-y-auto custom-scrollbar">
                {!cart || !cart.items || cart.items.length === 0 ? (
                  <div className="text-center py-12">
                    <i className="fa-solid fa-book-open text-4xl text-stone-300 mb-3"></i>
                    <p className="text-xs text-stone-500">Your shopping cart is empty.</p>
                  </div>
                ) : (
                  cart.items.map(item => (
                    <div key={item.id}
                         className="flex gap-3 bg-stone-50 p-3 rounded-2xl border border-stone-200 hover:border-amber-300 transition-all">
                      <img src={item.bookCoverImage || 'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?auto=format&fit=crop&w=100&q=80'}
                           className="w-14 h-18 object-cover rounded-lg shadow-sm" alt="" />
                      <div className="flex-1 min-w-0">
                        <h4 className="font-serif font-bold text-xs line-clamp-1 text-stone-900">{item.bookTitle}</h4>
                        <span className="text-xs font-bold text-amber-700">{formatCurrency(item.unitPrice)}</span>
                        <div className="flex items-center gap-2 mt-2">
                          <button onClick={() => handleUpdateCartQty(item.id, item.quantity - 1)}
                                  className="w-6 h-6 bg-white border border-stone-300 rounded flex items-center justify-center text-xs text-stone-600 hover:border-amber-600">
                            −
                          </button>
                          <span className="text-xs font-bold text-stone-900 w-5 text-center">{item.quantity}</span>
                          <button onClick={() => handleUpdateCartQty(item.id, item.quantity + 1)}
                                  className="w-6 h-6 bg-white border border-stone-300 rounded flex items-center justify-center text-xs text-stone-600 hover:border-amber-600">
                            +
                          </button>
                          <button onClick={() => handleRemoveCartItem(item.id)}
                                  className="ml-auto text-rose-500 hover:text-rose-700 text-xs p-1">
                            <i className="fa-solid fa-trash"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>

            {cart && cart.items && cart.items.length > 0 && (
              <div className="pt-4 border-t border-stone-200">
                <div className="flex justify-between items-center mb-4">
                  <span className="text-stone-500 text-xs font-medium">Subtotal ({cart.totalItems} items):</span>
                  <span className="text-lg font-extrabold text-amber-700">{formatCurrency(cart.totalPrice)}</span>
                </div>
                <button onClick={handleCheckout}
                        className="w-full py-3 bg-gradient-to-r from-amber-600 to-amber-700 hover:from-amber-500 hover:to-amber-600 text-white font-bold rounded-2xl shadow-lg shadow-amber-600/20 transition-all text-xs flex items-center justify-center gap-2">
                  <span>Proceed to Checkout</span>
                  <i className="fa-solid fa-arrow-right"></i>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     AUTH MODAL
     ══════════════════════════════════════════════════════════════════════ */
  function AuthModal() {
    const { isAuthOpen, setIsAuthOpen, authMode, setAuthMode, showToast, setUser, fetchCart } = window.useApp();

    if (!isAuthOpen) return null;

    const handleSubmit = async (e) => {
      e.preventDefault();
      const email = e.target.email.value;
      const password = e.target.password.value;

      try {
        if (authMode === 'login') {
          const res = await ApiClient.login(email, password);
          setUser(res.data.user);
          showToast('Welcome back! Signed in successfully.', 'success');
          setIsAuthOpen(false);
          fetchCart();
        } else {
          const fullName = e.target.fullName.value;
          const phone = e.target.phone.value;
          await ApiClient.register({ fullName, email, password, phone });
          showToast('Account created successfully! Please sign in.', 'success');
          setAuthMode('login');
        }
      } catch (err) {
        showToast(err.message, 'error');
      }
    };

    return (
      <div className="fixed inset-0 z-50 bg-stone-900/60 backdrop-blur-sm flex items-center justify-center p-4"
           onClick={(e) => { if (e.target === e.currentTarget) setIsAuthOpen(false); }}>
        <div className="bg-white border border-stone-200 rounded-3xl w-full max-w-md p-6 sm:p-8 shadow-2xl relative animate-modal-in">
          <button onClick={() => setIsAuthOpen(false)}
                  className="absolute top-4 right-4 text-stone-400 hover:text-stone-900 transition-colors">
            <i className="fa-solid fa-xmark text-lg"></i>
          </button>

          <div className="text-center mb-6">
            <div className="w-12 h-12 bg-amber-100 rounded-2xl flex items-center justify-center mx-auto mb-2 text-amber-700 text-xl font-bold">
              <i className="fa-solid fa-book-reader"></i>
            </div>
            <h2 className="font-serif text-2xl font-bold text-stone-900">
              {authMode === 'login' ? 'Sign In to Aurelia Books' : 'Create Your Reader Account'}
            </h2>
            <p className="text-xs text-stone-500 mt-1">Unlock member perks and order tracking</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {authMode === 'register' && (
              <>
                <div>
                  <label className="block text-xs font-bold text-stone-700 mb-1">Full Name</label>
                  <input name="fullName" required placeholder="Jane Doe" className="warm-light-input" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-stone-700 mb-1">Phone Number</label>
                  <input name="phone" required placeholder="+1 (555) 234-5678" className="warm-light-input" />
                </div>
              </>
            )}
            <div>
              <label className="block text-xs font-bold text-stone-700 mb-1">Email Address</label>
              <input name="email" type="email" required placeholder="reader@example.com" className="warm-light-input" />
            </div>
            <div>
              <label className="block text-xs font-bold text-stone-700 mb-1">Password</label>
              <input name="password" type="password" required placeholder="••••••••" className="warm-light-input" />
            </div>
            <button type="submit"
                    className="w-full py-3 bg-gradient-to-r from-amber-600 to-amber-700 hover:from-amber-500 hover:to-amber-600 text-white font-bold rounded-2xl shadow-md transition-all text-xs">
              {authMode === 'login' ? 'Sign In' : 'Register Account'}
            </button>
          </form>

          <div className="text-center text-xs text-stone-500 mt-6 pt-4 border-t border-stone-200">
            <span>{authMode === 'login' ? "Don't have an account?" : "Already registered?"} </span>
            <button onClick={() => setAuthMode(authMode === 'login' ? 'register' : 'login')}
                    className="text-amber-700 font-bold hover:underline">
              {authMode === 'login' ? 'Register now' : 'Sign in now'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     STATUS BADGE
     ══════════════════════════════════════════════════════════════════════ */
  function StatusBadge({ status }) {
    const colors = {
      PENDING:    'bg-amber-100 text-amber-800 border-amber-300',
      CONFIRMED:  'bg-blue-100 text-blue-800 border-blue-300',
      PROCESSING: 'bg-indigo-100 text-indigo-800 border-indigo-300',
      SHIPPING:   'bg-purple-100 text-purple-800 border-purple-300',
      DELIVERED:  'bg-emerald-100 text-emerald-800 border-emerald-300',
      CANCELLED:  'bg-rose-100 text-rose-800 border-rose-300',
    };
    return (
      <span className={`text-[10px] font-extrabold px-2.5 py-0.5 rounded-full border uppercase tracking-wider ${colors[status] || 'bg-stone-100 text-stone-700 border-stone-300'}`}>
        {status}
      </span>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
   WISHLIST BUTTON
   ══════════════════════════════════════════════════════════════════════ */
  function WishlistButton({ bookId }) {
    const { user, showToast, setIsAuthOpen } = window.useApp();
    const [isLiked, setIsLiked] = useState(false);

    useEffect(() => {
      if (!user) return;
      ApiClient.getWishlist()
        .then(res => {
          if (res && res.data && res.data.content) {
            const exists = res.data.content.some(item => item.bookId == bookId || item.id == bookId);
            setIsLiked(exists);
          }
        })
        .catch(() => {});
    }, [user, bookId]);

    const handleToggle = async (e) => {
      e.stopPropagation();
      if (!user) {
        setIsAuthOpen(true);
        return;
      }
      try {
        if (isLiked) {
          await ApiClient.removeFromWishlist(bookId);
          setIsLiked(false);
          showToast('Removed from Wishlist', 'info');
        } else {
          await ApiClient.addToWishlist(bookId);
          setIsLiked(true);
          showToast('Added to Wishlist!', 'success');
        }
      } catch (err) {
        showToast(err.message || 'Wishlist action failed', 'error');
      }
    };

    return (
      <button
        onClick={handleToggle}
        className={`p-2 rounded-full border shadow-sm transition-all ${
          isLiked
            ? 'bg-rose-50 border-rose-200 text-rose-600 hover:bg-rose-100'
            : 'bg-white/95 backdrop-blur-md border-stone-200 text-stone-400 hover:text-rose-600 hover:border-rose-300'
        }`}
        title="Add to Wishlist"
      >
        <i className={`fa-solid fa-heart text-xs ${isLiked ? 'text-rose-600' : ''}`}></i>
      </button>
    );
  }


  /* ── Export ──────────────────────────────────────────────────────────── */
  Object.assign(window, {
    LoadingSpinner, Modal, ConfirmDialog, Pagination, BookCard,
    ToastContainer, Header, Footer, CartDrawer, AuthModal, StatusBadge,
    DemoAccountModal, DemoFloatingBadge
  });
})();
