/* ==========================================================================
   Aurelia Books - Customer Pages (Standard E-Commerce Architecture)
   HomePage, CatalogPage, BookDetailPage, CheckoutPage, OrdersPage
   ========================================================================== */
(function () {
  const { useState, useEffect, useCallback, useMemo } = React;

  /* ══════════════════════════════════════════════════════════════════════
     HOME PAGE — Standard E-Commerce Storefront Landing
     ══════════════════════════════════════════════════════════════════════ */
  function LegacyHomePage() {
    const { navigate } = window.useRouter();
    const { showToast, handleAddToCart } = window.useApp();
    const formatCurrency = window.formatCurrency;
    const BookCard = window.BookCard;
    const LoadingSpinner = window.LoadingSpinner;

    const [bestsellers, setBestsellers] = useState([]);
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      Promise.all([
        ApiClient.getBooks({ page: 0, size: 6, sortBy: 'createdAt', sortDir: 'desc' }),
        ApiClient.getCategories()
      ])
        .then(([booksRes, catRes]) => {
          if (booksRes && booksRes.data) setBestsellers(booksRes.data.content || (Array.isArray(booksRes.data) ? booksRes.data : []));
          if (catRes && catRes.data) setCategories(Array.isArray(catRes.data) ? catRes.data : []);
        })
        .catch((err) => console.warn('Home page load notice:', err))
        .finally(() => setLoading(false));
    }, []);

    const valueProps = [
      { icon: 'fa-truck-fast', title: 'Express Dispatch', desc: 'Free worldwide delivery on orders over $50' },
      { icon: 'fa-shield-halved', title: 'Authentic Editions', desc: '100% original publisher guaranteed prints' },
      { icon: 'fa-rotate-left', title: '30-Day Returns', desc: 'Hassle-free replacement & return policy' },
      { icon: 'fa-headset', title: '24/7 Reader Support', desc: 'Dedicated literary advisors & assistance' }
    ];

    const categoryIcons = {
      'Literature & Fiction': 'fa-book-bookmark',
      'Business & Economics': 'fa-chart-line',
      'Computer Science & AI': 'fa-code',
      'Personal Development': 'fa-brain',
      "Children's & Young Adult": 'fa-face-smile'
    };

    return (
      <main className="flex-1 w-full space-y-16 pb-16">
        {/* 1. Hero Showcase Banner */}
        <section className="relative brand-hero-bg border-b border-amber-200/80 overflow-hidden pt-12 pb-20 px-6">
          <div className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-12 items-center">
            {/* Left Content */}
            <div className="lg:col-span-7 space-y-6">
              <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-amber-500/20 border border-amber-600/30 text-amber-900 text-xs font-bold uppercase tracking-wider">
                <i className="fa-solid fa-crown text-amber-600"></i>
                <span>Literary Excellence • 2026 Season</span>
              </div>

              <h1 className="font-serif text-4xl sm:text-6xl font-bold text-stone-900 leading-[1.15]">
                Curated Books for <span className="gold-text-gradient block sm:inline">Discerning Readers</span>
              </h1>

              <p className="text-stone-700 text-base sm:text-lg font-medium leading-relaxed max-w-xl">
                Explore thousands of handpicked titles ranging from world classics to cutting-edge technology & business masterclasses. Use code <code className="bg-white/80 px-2 py-0.5 rounded text-amber-900 font-bold border border-amber-300">WELCOME10</code> for 10% off.
              </p>

              {/* Action Buttons */}
              <div className="flex flex-col sm:flex-row items-center gap-4 pt-2">
                <button
                  onClick={() => navigate('/catalog')}
                  className="w-full sm:w-auto px-8 py-4 rounded-2xl bg-gradient-to-r from-amber-600 to-amber-700 hover:from-amber-500 hover:to-amber-600 text-white font-bold text-sm shadow-xl shadow-amber-600/25 transition-all flex items-center justify-center gap-3"
                >
                  <i className="fa-solid fa-store"></i>
                  <span>Browse Full Catalog</span>
                </button>

                <button
                  onClick={() => navigate('/catalog?sort=price,asc')}
                  className="w-full sm:w-auto px-8 py-4 rounded-2xl bg-white/90 hover:bg-white border border-stone-200 text-stone-900 font-bold text-sm transition-all shadow-sm flex items-center justify-center gap-2"
                >
                  <i className="fa-solid fa-tags text-amber-600"></i>
                  <span>View Special Deals</span>
                </button>
              </div>

              {/* Customer Rating Badge */}
              <div className="flex items-center gap-4 pt-4 border-t border-amber-200/60">
                <div className="flex -space-x-2">
                  {['photo-1534528741775-53994a69daeb', 'photo-1507003211169-0a1dd7228f2d', 'photo-1517841905240-472988babdf9'].map((img, i) => (
                    <img key={i} src={`https://images.unsplash.com/${img}?auto=format&fit=crop&w=100&q=80`} className="w-9 h-9 rounded-full border-2 border-white object-cover" alt="" />
                  ))}
                </div>
                <div className="text-xs">
                  <div className="flex gap-1 text-amber-500 font-bold">
                    {[...Array(5)].map((_, i) => <i key={i} className="fa-solid fa-star text-xs"></i>)}
                    <span className="text-stone-900 font-extrabold ml-1">4.9 / 5.0</span>
                  </div>
                  <span className="text-stone-600 font-medium">Loved by over 12,000+ avid readers worldwide</span>
                </div>
              </div>
            </div>

            {/* Right Featured Image Stack */}
            <div className="lg:col-span-5 relative flex justify-center">
              <div className="relative w-full max-w-md">
                <img
                  src="https://images.unsplash.com/photo-1512820790803-83ca734da794?auto=format&fit=crop&w=600&q=80"
                  alt="Featured Book"
                  className="w-full h-[420px] object-cover rounded-3xl shadow-2xl border-4 border-white transform -rotate-2 hover:rotate-0 transition-transform duration-500"
                />
                <div className="absolute -bottom-6 -left-6 bg-white p-5 rounded-3xl border border-stone-200 shadow-xl max-w-xs space-y-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-amber-700 block">Staff Pick of the Month</span>
                  <h4 className="font-serif font-bold text-sm text-stone-900">How to Win Friends & Influence People</h4>
                  <span className="text-xs font-extrabold text-amber-700 block">$7.96 <span className="line-through text-stone-400 font-normal text-[10px]">$10.00</span></span>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* 2. Value Props Bar */}
        <section className="max-w-7xl mx-auto px-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {valueProps.map((prop, i) => (
              <div key={i} className="bg-white border border-stone-200/80 p-6 rounded-3xl shadow-sm flex items-start gap-4 hover:border-amber-300 transition-all">
                <div className="w-12 h-12 rounded-2xl bg-amber-50 border border-amber-200 text-amber-700 flex items-center justify-center text-xl shrink-0">
                  <i className={`fa-solid ${prop.icon}`}></i>
                </div>
                <div>
                  <h4 className="font-serif font-bold text-sm text-stone-900 mb-1">{prop.title}</h4>
                  <p className="text-xs text-stone-500 font-medium leading-relaxed">{prop.desc}</p>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* 3. Shop By Genre / Category Cards */}
        <section className="max-w-7xl mx-auto px-6 space-y-8">
          <div className="flex items-center justify-between">
            <div>
              <span className="text-xs font-bold uppercase tracking-wider text-amber-700 block mb-1">Curated Selections</span>
              <h2 className="font-serif text-3xl font-bold text-stone-900">Browse by Genre & Category</h2>
            </div>
            <button onClick={() => navigate('/catalog')} className="text-xs font-bold text-amber-700 hover:underline flex items-center gap-1.5">
              <span>View All Categories</span>
              <i className="fa-solid fa-arrow-right"></i>
            </button>
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
            {categories.map((cat) => (
              <div
                key={cat.id}
                onClick={() => navigate(`/catalog?category=${cat.id}`)}
                className="bg-white border border-stone-200 rounded-3xl p-6 text-center cursor-pointer hover:border-amber-500 hover:shadow-xl hover:-translate-y-1 transition-all group"
              >
                <div className="w-14 h-14 rounded-2xl bg-amber-50 border border-amber-200 text-amber-700 flex items-center justify-center text-2xl mx-auto mb-4 group-hover:bg-amber-600 group-hover:text-white transition-colors shadow-sm">
                  <i className={`fa-solid ${categoryIcons[cat.name] || 'fa-book'}`}></i>
                </div>
                <h3 className="font-serif font-bold text-sm text-stone-900 mb-1 line-clamp-1 group-hover:text-amber-700 transition-colors">{cat.name}</h3>
                <span className="text-[11px] text-stone-400 font-semibold block">Explore Titles →</span>
              </div>
            ))}
          </div>
        </section>

        {/* 4. Trending & Bestselling Books Grid */}
        <section className="max-w-7xl mx-auto px-6 space-y-8">
          <div className="flex items-center justify-between">
            <div>
              <span className="text-xs font-bold uppercase tracking-wider text-amber-700 block mb-1">Popular Demand</span>
              <h2 className="font-serif text-3xl font-bold text-stone-900">Trending Bestsellers</h2>
            </div>
            <button onClick={() => navigate('/catalog')} className="px-5 py-2.5 rounded-full bg-stone-100 hover:bg-stone-200 text-stone-800 font-bold text-xs transition-all">
              Explore All Books
            </button>
          </div>

          {loading ? (
            <LoadingSpinner text="Loading bestsellers..." />
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {bestsellers.map((book) => (
                <BookCard
                  key={book.id}
                  book={book}
                  onAddToCart={handleAddToCart}
                  onViewDetail={(b) => navigate(`/book/${b.slug || b.id}`)}
                />
              ))}
            </div>
          )}
        </section>

        {/* 5. Author Spotlight / Literary Inspiration Section */}
        <section className="max-w-7xl mx-auto px-6">
          <div className="bg-white border border-stone-200 rounded-3xl p-8 sm:p-12 grid grid-cols-1 lg:grid-cols-12 gap-8 items-center shadow-sm">
            <div className="lg:col-span-5 relative">
              <img
                src="https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?auto=format&fit=crop&w=600&q=80"
                alt="Author Spotlight"
                className="w-full h-80 object-cover rounded-2xl shadow-lg border border-stone-200"
              />
            </div>
            <div className="lg:col-span-7 space-y-4">
              <span className="text-xs font-bold uppercase tracking-wider text-amber-700 bg-amber-50 px-3 py-1 rounded-md border border-amber-200 inline-block">
                Author Spotlight of the Month
              </span>
              <h3 className="font-serif text-3xl font-bold text-stone-900">George Orwell & The Dystopian Legacy</h3>
              <p className="text-xs sm:text-sm text-stone-600 leading-relaxed font-medium">
                "In a time of deceit telling the truth is a revolutionary act." Revisit Orwell’s seminal masterpiece <strong>1984</strong> in our collector's edition printing.
              </p>
              <blockquote className="p-4 bg-amber-50/60 border-l-4 border-amber-600 rounded-r-2xl italic font-serif text-stone-800 text-sm">
                "Perhaps one did not want to be loved so much as to be understood."
              </blockquote>
              <button
                onClick={() => navigate('/catalog')}
                className="px-6 py-3 rounded-2xl bg-amber-600 hover:bg-amber-700 text-white font-bold text-xs transition-all shadow-md"
              >
                Browse Dystopian Classics
              </button>
            </div>
          </div>
        </section>

        {/* 6. Newsletter Sign-up Box */}
        <section className="max-w-7xl mx-auto px-6">
          <div className="brand-hero-bg rounded-3xl p-8 sm:p-12 border border-amber-300 text-center max-w-3xl mx-auto space-y-4 shadow-lg">
            <div className="w-14 h-14 bg-white rounded-2xl flex items-center justify-center text-amber-700 text-2xl mx-auto shadow-md">
              <i className="fa-regular fa-envelope"></i>
            </div>
            <h3 className="font-serif text-2xl sm:text-3xl font-bold text-stone-900">Join the Aurelia Literary Club</h3>
            <p className="text-xs sm:text-sm text-stone-700 font-medium max-w-lg mx-auto">
              Receive curated monthly reading lists, exclusive author interviews, and a $10 discount voucher directly to your inbox.
            </p>
            <form onSubmit={(e) => { e.preventDefault(); alert('Thank you for subscribing to Aurelia Literary Club!'); }} className="flex flex-col sm:flex-row gap-3 max-w-md mx-auto pt-2">
              <input type="email" required placeholder="Enter your email address..." className="warm-light-input py-3 text-xs flex-1" />
              <button type="submit" className="px-6 py-3 bg-amber-700 hover:bg-amber-800 text-white font-bold text-xs rounded-xl shadow-md transition-all">
                Subscribe
              </button>
            </form>
          </div>
        </section>
      </main>
    );
  }

  function HomePage() {
    const { navigate } = window.useRouter();
    const { showToast, handleAddToCart } = window.useApp();
    const BookCard = window.BookCard;
    const LoadingSpinner = window.LoadingSpinner;
    const [bestsellers, setBestsellers] = useState([]);
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      Promise.all([
        ApiClient.getBooks({ page: 0, size: 6, sortBy: 'createdAt', sortDir: 'desc' }),
        ApiClient.getCategories()
      ])
        .then(([booksRes, catRes]) => {
          if (booksRes && booksRes.data) setBestsellers(booksRes.data.content || (Array.isArray(booksRes.data) ? booksRes.data : []));
          if (catRes && catRes.data) setCategories(Array.isArray(catRes.data) ? catRes.data : []);
        })
        .catch((err) => console.warn('Home page load notice:', err))
        .finally(() => setLoading(false));
    }, []);

    const categoryIcons = ['fa-wand-magic-sparkles', 'fa-chart-line', 'fa-laptop-code', 'fa-brain', 'fa-face-smile-beam'];

    return (
      <main className="redex-home flex-1 w-full pb-20">
        <section className="redex-hero-wrap">
          <div className="redex-hero">
            <span className="hero-orb hero-orb-one"></span>
            <span className="hero-orb hero-orb-two"></span>
            <span className="hero-float hero-float-book"><i className="fa-solid fa-book-open"></i></span>
            <span className="hero-float hero-float-pen"><i className="fa-solid fa-pen-nib"></i></span>
            <div className="redex-hero-copy">
              <span className="redex-kicker"><i className="fa-solid fa-sparkles"></i> Your next chapter starts here</span>
              <h1>Expand your mind,<br />one book at a time.</h1>
              <p>Books connect ideas, people, and possibilities. Discover stories worth keeping and knowledge that moves you forward.</p>
              <div className="redex-hero-actions">
                <button onClick={() => navigate('/catalog')} className="redex-btn redex-btn-light">Explore the library <i className="fa-solid fa-arrow-right"></i></button>
                <button onClick={() => navigate('/catalog?sort=price,asc')} className="redex-btn redex-btn-ghost">View special deals</button>
              </div>
              <div className="redex-proof">
                <span><strong>12k+</strong> happy readers</span>
                <span><strong>4.9</strong> average rating</span>
              </div>
            </div>
            <div className="redex-hero-art">
              <div className="hero-art-fallback" aria-hidden="true" style={{ display: 'none' }}>
                <div className="fallback-rays"><i className="fa-solid fa-lightbulb"></i></div>
                <div className="fallback-book-stack">
                  <span></span><span></span><span></span>
                </div>
                <div className="fallback-open-book">
                  <span className="fallback-page fallback-page-left"></span>
                  <span className="fallback-page fallback-page-right"></span>
                  <i className="fa-solid fa-book-open"></i>
                </div>
              </div>
              <img
                src="/images/aurelia-hero-3d.png"
                alt="An open book, a stack of books and a glowing idea"
                onLoad={(e) => { e.currentTarget.style.display = 'block'; }}
                onError={(e) => { e.currentTarget.style.display = 'none'; if(e.currentTarget.previousElementSibling) e.currentTarget.previousElementSibling.style.display = 'block'; }}
              />
            </div>
          </div>
        </section>

        <section className="redex-section redex-intro">
          <div>
            <span className="redex-eyebrow">About our library</span>
            <h2>Books chosen for<br />curious minds.</h2>
          </div>
          <div className="redex-intro-copy">
            <p>From timeless fiction to practical ideas for work and life, Aurelia brings thoughtful books together in one calm, inspiring place.</p>
            <button onClick={() => navigate('/catalog')} className="redex-text-link">Discover our collection <i className="fa-solid fa-arrow-right"></i></button>
          </div>
          <div className="redex-mini-illustration"><i className="fa-solid fa-feather-pointed"></i></div>
        </section>

        <section className="redex-section redex-category-section">
          <div className="redex-heading-row">
            <div><span className="redex-eyebrow">Find your favorite corner</span><h2>Explore by category</h2></div>
            <button onClick={() => navigate('/catalog')} className="redex-circle-arrow"><i className="fa-solid fa-arrow-right"></i></button>
          </div>
          <div className="redex-category-grid">
            {categories.slice(0, 5).map((cat, i) => (
              <button key={cat.id} onClick={() => navigate(`/catalog?category=${cat.id}`)} className={`redex-category-card redex-category-${i % 5}`}>
                <span className="category-icon"><i className={`fa-solid ${categoryIcons[i % categoryIcons.length]}`}></i></span>
                <span className="category-name">{cat.name}</span>
                <span className="category-link">Browse books <i className="fa-solid fa-arrow-right"></i></span>
              </button>
            ))}
          </div>
        </section>

        <section className="redex-section redex-arrivals">
          <div className="redex-heading-row">
            <div><span className="redex-eyebrow">Fresh from the shelf</span><h2>New arrivals</h2></div>
            <button onClick={() => navigate('/catalog')} className="redex-text-link">See all books <i className="fa-solid fa-arrow-right"></i></button>
          </div>
          {loading ? <LoadingSpinner text="Loading new arrivals..." /> : (
            <div className="redex-book-grid">
              {bestsellers.map(book => <BookCard key={book.id} book={book} onAddToCart={handleAddToCart} onViewDetail={(b) => navigate(`/book/${b.slug || b.id}`)} />)}
            </div>
          )}
        </section>

        <section className="redex-section redex-story">
          <div className="redex-story-art">
            <span className="story-circle"></span>
            <i className="fa-solid fa-book-open-reader"></i>
          </div>
          <div className="redex-story-copy">
            <span className="redex-eyebrow">Reader stories</span>
            <h2>What people say about Aurelia</h2>
            <blockquote>“A beautifully calm place to find my next read. Every recommendation feels considered, and checkout takes only a moment.”</blockquote>
            <div className="redex-story-person"><span>JM</span><div><strong>Julia Morgan</strong><small>Verified reader</small></div></div>
          </div>
        </section>

        <section className="redex-section redex-cta">
          <span className="cta-dot cta-dot-one"></span><span className="cta-dot cta-dot-two"></span>
          <i className="fa-solid fa-bookmark cta-icon"></i>
          <span className="redex-kicker">A world of ideas awaits</span>
          <h2>Ready to find your next<br />favorite book?</h2>
          <button onClick={() => navigate('/catalog')} className="redex-btn redex-btn-light">Start exploring <i className="fa-solid fa-arrow-right"></i></button>
        </section>
      </main>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     CATALOG PAGE — Dedicated Search, Filter & Pagination Catalog
     ══════════════════════════════════════════════════════════════════════ */
  function CatalogPage() {
    const { navigate } = window.useRouter();
    const { searchQuery, showToast, handleAddToCart } = window.useApp();
    const formatCurrency = window.formatCurrency;
    const Pagination = window.Pagination;
    const BookCard = window.BookCard;
    const LoadingSpinner = window.LoadingSpinner;

    const [books, setBooks] = useState([]);
    const [categories, setCategories] = useState([]);
    const [selectedCategory, setSelectedCategory] = useState(null);
    const [sortBy, setSortBy] = useState('createdAt,desc');
    const [loading, setLoading] = useState(true);

    // Read URL query params e.g. ?category=3 or ?sort=price,asc
    useEffect(() => {
      const hash = window.location.hash;
      if (hash.includes('?')) {
        const queryStr = hash.split('?')[1];
        const params = new URLSearchParams(queryStr);
        const cat = params.get('category');
        const sort = params.get('sort');
        if (cat) setSelectedCategory(parseInt(cat));
        if (sort) setSortBy(sort);
      }
    }, []);

    const [page, setPage] = useState(0);
    const [pageData, setPageData] = useState({ totalPages: 0, totalElements: 0 });
    const pageSize = 12;

    const fetchCategories = useCallback(async () => {
      try {
        const res = await ApiClient.getCategories();
        if (res.data) setCategories(res.data);
      } catch (err) { console.error(err); }
    }, []);

    const fetchBooks = useCallback(async () => {
      setLoading(true);
      const params = { page, size: pageSize };
      if (selectedCategory) params.categoryId = selectedCategory;
      if (searchQuery) params.keyword = searchQuery;
      if (sortBy) {
        const [by, dir] = sortBy.split(',');
        params.sortBy = by;
        params.sortDir = dir;
      }
      try {
        const res = await ApiClient.getBooks(params);
        if (res.data) {
          setBooks(res.data.content || []);
          setPageData({
            totalPages: res.data.totalPages || 0,
            totalElements: res.data.totalElements || 0
          });
        }
      } catch (err) {
        showToast('Error loading catalog books', 'error');
      } finally {
        setLoading(false);
      }
    }, [page, selectedCategory, searchQuery, sortBy]);

    useEffect(() => { fetchCategories(); }, [fetchCategories]);
    useEffect(() => { setPage(0); }, [selectedCategory, searchQuery, sortBy]);
    useEffect(() => { fetchBooks(); }, [fetchBooks]);

    return (
      <main className="catalog-page max-w-7xl mx-auto px-6 py-8 flex-1 w-full space-y-8">
        {/* Breadcrumb */}
        <nav className="catalog-breadcrumb flex items-center gap-2 text-xs text-stone-500">
          <a href="#/" className="hover:text-amber-700 font-medium">Home</a>
          <i className="fa-solid fa-chevron-right text-[10px] text-stone-400"></i>
          <span className="text-stone-900 font-bold">Book Catalog</span>
        </nav>

        {/* Catalog Banner */}
        <div className="catalog-banner flex flex-col md:flex-row md:items-center justify-between gap-4 pb-4 border-b border-stone-200">
          <div>
            <span className="catalog-kicker"><i className="fa-solid fa-sparkles"></i> Curated for every reader</span>
            <h1 className="font-serif text-3xl font-bold text-stone-900">Explore All Books</h1>
            <p className="text-xs text-stone-500 font-medium mt-1">Find a story to get lost in or an idea to grow with.</p>
          </div>
          <span className="catalog-count text-xs font-semibold text-stone-600 bg-white px-4 py-2 rounded-full border border-stone-200 shadow-sm">
            <strong>{pageData.totalElements}</strong> books available
          </span>
        </div>

        {/* Catalog Grid & Filters */}
        <div className="catalog-layout grid grid-cols-1 md:grid-cols-4 gap-8">
          {/* Sidebar */}
          <aside className="catalog-sidebar bg-white border border-stone-200 rounded-3xl p-6 h-fit sticky top-24 shadow-sm">
            <div className="flex items-center justify-between mb-5 pb-3 border-b border-stone-100">
              <h3 className="font-serif font-bold text-base text-stone-900 flex items-center">
                <i className="fa-solid fa-sliders text-amber-600 mr-2"></i> Refine Search
              </h3>
              <button onClick={() => { setSelectedCategory(null); }} className="text-xs text-amber-700 hover:underline font-semibold">
                Reset
              </button>
            </div>

            {/* Categories */}
            <div className="mb-6">
              <label className="block text-[11px] font-bold text-stone-400 uppercase tracking-wider mb-2.5">Category</label>
              <div className="space-y-1 max-h-64 overflow-y-auto custom-scrollbar">
                <button
                  onClick={() => setSelectedCategory(null)}
                  className={`w-full text-left px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                    selectedCategory === null ? 'bg-amber-100/80 text-amber-900 border border-amber-300' : 'text-stone-600 hover:bg-stone-100'
                  }`}
                >
                  <i className="fa-solid fa-layer-group mr-2 text-stone-400"></i>All Genres
                </button>
                {categories.map(c => (
                  <button
                    key={c.id}
                    onClick={() => setSelectedCategory(c.id)}
                    className={`w-full text-left px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                      selectedCategory === c.id ? 'bg-amber-100/80 text-amber-900 border border-amber-300' : 'text-stone-600 hover:bg-stone-100'
                    }`}
                  >
                    <i className="fa-solid fa-bookmark mr-2 text-stone-400"></i>{c.name}
                  </button>
                ))}
              </div>
            </div>

            {/* Sort */}
            <div>
              <label className="block text-[11px] font-bold text-stone-400 uppercase tracking-wider mb-2.5">Sort Order</label>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="warm-light-input py-2 text-xs"
              >
                <option value="createdAt,desc">Newest Arrivals</option>
                <option value="price,asc">Price: Low to High</option>
                <option value="price,desc">Price: High to Low</option>
                <option value="title,asc">Title: A to Z</option>
              </select>
            </div>
          </aside>

          {/* Main Book Grid */}
          <div className="catalog-results md:col-span-3">
            {loading ? (
              <LoadingSpinner text="Fetching books..." />
            ) : books.length === 0 ? (
              <div className="text-center py-16 bg-white rounded-3xl border border-stone-200 p-8">
                <i className="fa-solid fa-book-open text-5xl text-stone-300 mb-4"></i>
                <h3 className="font-serif text-lg font-bold text-stone-700 mb-1">No Titles Match Your Filters</h3>
                <p className="text-xs text-stone-500">Try choosing another genre or resetting your search term.</p>
              </div>
            ) : (
              <>
                <div className="catalog-book-grid grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                  {books.map(book => (
                    <BookCard
                      key={book.id}
                      book={book}
                      onAddToCart={handleAddToCart}
                      onViewDetail={(b) => navigate(`/book/${b.slug || b.id}`)}
                    />
                  ))}
                </div>
                <Pagination
                  currentPage={page}
                  totalPages={pageData.totalPages}
                  totalElements={pageData.totalElements}
                  onPageChange={setPage}
                />
              </>
            )}
          </div>
        </div>
      </main>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     BOOK DETAIL PAGE
     ══════════════════════════════════════════════════════════════════════ */
  function BookDetailPage() {
    const { currentPath, navigate } = window.useRouter();
    const { showToast, handleAddToCart } = window.useApp();
    const formatCurrency = window.formatCurrency;
    const LoadingSpinner = window.LoadingSpinner;

    const [book, setBook] = useState(null);
    const [loading, setLoading] = useState(true);
    const [quantity, setQuantity] = useState(1);

    const slugMatch = window.matchRoute('/book/:slug', currentPath);
    const slug = slugMatch ? slugMatch.slug : null;

    useEffect(() => {
      if (!slug) return;
      setLoading(true);
      ApiClient.getBookBySlug(slug)
        .then(res => { if (res.data) setBook(res.data); })
        .catch(err => { showToast('Book not found', 'error'); navigate('/'); })
        .finally(() => setLoading(false));
    }, [slug]);

    if (loading) return <main className="max-w-7xl mx-auto px-6 py-12"><LoadingSpinner text="Fetching book details..." /></main>;
    if (!book) return null;

    return (
      <main className="max-w-7xl mx-auto px-6 py-8 flex-1">
        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-xs text-stone-500 mb-6">
          <a href="#/" className="hover:text-amber-700 font-medium">Home</a>
          <i className="fa-solid fa-chevron-right text-[10px] text-stone-400"></i>
          <a href="#/catalog" className="hover:text-amber-700 font-medium">Catalog</a>
          <i className="fa-solid fa-chevron-right text-[10px] text-stone-400"></i>
          <span className="text-stone-900 font-bold line-clamp-1">{book.title}</span>
        </nav>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10 bg-white border border-stone-200 rounded-3xl p-6 sm:p-10 shadow-sm">
          {/* Book Image */}
          <div className="bg-stone-50 border border-stone-200/80 rounded-2xl p-8 flex items-center justify-center">
            <img
              src={book.coverImage || 'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?auto=format&fit=crop&w=600&q=80'}
              alt={book.title}
              className="max-h-[480px] object-contain rounded-xl shadow-lg"
            />
          </div>

          {/* Book Info */}
          <div className="space-y-6">
            <div>
              <span className="text-xs font-bold uppercase tracking-wider text-amber-700 bg-amber-50 px-3 py-1 rounded-md border border-amber-200 inline-block mb-3">
                {book.categoryName || 'Literature'}
              </span>
              <h1 className="font-serif text-3xl sm:text-4xl font-bold text-stone-900 leading-tight">{book.title}</h1>
              <p className="text-sm font-semibold text-stone-600 mt-2">
                Author: <span className="text-stone-900">{book.authorNames ? book.authorNames.join(', ') : 'Unknown'}</span>
              </p>
              {book.publisherName && (
                <p className="text-xs text-stone-500 mt-1">
                  Publisher: <span className="text-stone-700 font-medium">{book.publisherName}</span>
                </p>
              )}
              <p className="text-xs text-stone-400 mt-1">ISBN: {book.isbn || 'N/A'}</p>
            </div>

            {/* Price Box */}
            <div className="p-4 rounded-2xl bg-amber-50/60 border border-amber-200 space-y-1">
              <div className="flex items-baseline gap-3">
                <span className="font-serif text-3xl font-extrabold text-amber-800">
                  {formatCurrency(book.discountPrice || book.price)}
                </span>
                {book.discountPrice && (
                  <>
                    <span className="text-base text-stone-400 line-through">{formatCurrency(book.price)}</span>
                    <span className="text-xs bg-rose-100 text-rose-800 font-bold px-2.5 py-0.5 rounded-full">
                      Save {Math.round((1 - book.discountPrice / book.price) * 100)}%
                    </span>
                  </>
                )}
              </div>
              {book.stockQuantity != null && (
                <p className="text-xs text-stone-600 font-medium pt-1">
                  <i className="fa-solid fa-boxes-stacked mr-1 text-amber-600"></i>
                  In Stock: {book.stockQuantity} Copies Available
                </p>
              )}
            </div>

            {/* Quantity + Add to Cart */}
            <div className="flex items-center gap-4">
              <div className="flex items-center border border-stone-300 rounded-xl overflow-hidden bg-stone-50">
                <button onClick={() => setQuantity(q => Math.max(1, q - 1))}
                        className="px-4 py-2.5 text-stone-700 hover:bg-stone-200 transition-all font-bold">−</button>
                <span className="px-5 py-2.5 font-bold text-stone-900 text-sm">{quantity}</span>
                <button onClick={() => setQuantity(q => q + 1)}
                        className="px-4 py-2.5 text-stone-700 hover:bg-stone-200 transition-all font-bold">+</button>
              </div>
              <button onClick={() => { handleAddToCart(book.id); }}
                      className="flex-1 py-3.5 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">
                <i className="fa-solid fa-cart-plus"></i>
                <span>Add to Shopping Cart</span>
              </button>
            </div>

            {/* Overview / Description */}
            <div className="border-t border-stone-200 pt-5 space-y-2">
              <h3 className="font-serif font-bold text-stone-900 text-base flex items-center gap-2">
                <i className="fa-solid fa-align-left text-amber-600"></i> Book Synopsis
              </h3>
              <p className="text-xs text-stone-600 leading-relaxed whitespace-pre-line">
                {book.description || 'No detailed description available for this title.'}
              </p>
            </div>
          </div>
        </div>
      </main>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     CHECKOUT PAGE
     ══════════════════════════════════════════════════════════════════════ */
  function CheckoutPage() {
    const { navigate } = window.useRouter();
    const { user, cart, showToast, fetchCart, setIsAuthOpen, setAuthMode } = window.useApp();
    const formatCurrency = window.formatCurrency;
    const LoadingSpinner = window.LoadingSpinner;

    const [addresses, setAddresses] = useState([]);
    const [selectedAddressId, setSelectedAddressId] = useState('');
    const [couponCode, setCouponCode] = useState('');
    const [appliedCoupon, setAppliedCoupon] = useState(null);
    const [paymentMethod, setPaymentMethod] = useState('COD');
    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [showNewAddressForm, setShowNewAddressForm] = useState(false);
    const [newAddress, setNewAddress] = useState({
      receiverName: user ? (user.fullName || '') : '',
      receiverPhone: user ? (user.phone || '') : '',
      province: 'New York',
      district: 'Manhattan',
      ward: 'Broadway',
      street: '',
      note: ''
    });

    const handleSaveNewAddress = async (e) => {
      e.preventDefault();
      if (!newAddress.receiverName.trim() || !newAddress.receiverPhone.trim() || !newAddress.street.trim()) {
        showToast('Please fill in Receiver Name, Phone, and Street Address!', 'error');
        return;
      }
      try {
        const res = await ApiClient.addAddress({ ...newAddress, defaultAddress: true });
        const saved = res.data || { id: Date.now(), ...newAddress };
        setAddresses(prev => [saved, ...prev]);
        setSelectedAddressId(saved.id);
        setShowNewAddressForm(false);
        showToast('New shipping address saved and selected!', 'success');
      } catch (err) {
        showToast(err.message, 'error');
      }
    };

    useEffect(() => {
      if (!user) {
        setIsAuthOpen(true);
        setAuthMode('login');
        navigate('/');
        return;
      }
      loadAddresses();
    }, [user]);

    const loadAddresses = async () => {
      setLoading(true);
      try {
        const res = await ApiClient.getUserAddresses();
        if (res.data && res.data.length > 0) {
          setAddresses(res.data);
          setSelectedAddressId(res.data[0].id);
        } else {
          const sample = await ApiClient.addAddress({
            receiverName: user ? (user.fullName || 'Valued Reader') : 'Valued Reader',
            receiverPhone: '+1 (555) 234-5678',
            province: 'New York', district: 'Manhattan', ward: 'Broadway',
            street: '123 Broadway Ave', defaultAddress: true
          });
          setAddresses([sample.data]);
          setSelectedAddressId(sample.data.id);
        }
      } catch (err) { showToast(err.message, 'error'); }
      finally { setLoading(false); }
    };

    const handleApplyCoupon = async () => {
      if (!couponCode.trim()) return;
      try {
        const res = await ApiClient.validateCoupon(couponCode, cart.totalPrice);
        if (res.data && res.data.valid) {
          setAppliedCoupon(res.data);
          showToast(`Coupon ${couponCode} applied successfully!`, 'success');
        } else {
          setAppliedCoupon(null);
          showToast(res.data ? res.data.message : 'Invalid coupon code', 'error');
        }
      } catch (err) { showToast(err.message, 'error'); }
    };

    const handleCreateOrder = async (e) => {
      e.preventDefault();
      if (!selectedAddressId || isNaN(parseInt(selectedAddressId))) {
        showToast('Please select or add a shipping address before placing order!', 'error');
        return;
      }
      setSubmitting(true);
      try {
        const res = await ApiClient.createOrder({
          addressId: parseInt(selectedAddressId),
          paymentMethod,
          couponCode: appliedCoupon ? appliedCoupon.code : null
        });
        showToast(`Order placed successfully! Order Code: ${res.data ? res.data.orderCode : ''}`, 'success');
        fetchCart();
        navigate('/orders');
      } catch (err) { showToast(err.message, 'error'); }
      finally { setSubmitting(false); }
    };

    if (!cart || !cart.items || cart.items.length === 0) {
      return (
        <main className="max-w-7xl mx-auto px-6 py-16 text-center">
          <i className="fa-solid fa-cart-shopping text-5xl text-stone-300 mb-4"></i>
          <h2 className="font-serif text-xl font-bold text-stone-800 mb-2">Your Cart is Empty</h2>
          <p className="text-xs text-stone-500 mb-6">Explore our catalog to add books before checking out</p>
          <button onClick={() => navigate('/catalog')}
                  className="px-6 py-2.5 bg-amber-600 hover:bg-amber-700 text-white font-semibold rounded-2xl transition-all text-xs">
            Browse Catalog
          </button>
        </main>
      );
    }

    if (loading) return <main className="max-w-7xl mx-auto px-6 py-12"><LoadingSpinner text="Preparing checkout..." /></main>;

    const subtotal = cart.totalPrice || 0;
    const discount = appliedCoupon ? appliedCoupon.discountAmount : 0;
    const shippingFee = 30000;
    const grandTotal = Math.max(0, subtotal - discount + shippingFee);

    return (
      <main className="max-w-4xl mx-auto px-6 py-8 flex-1">
        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-xs text-stone-500 mb-6">
          <a href="#/" className="hover:text-amber-700 font-medium">Home</a>
          <i className="fa-solid fa-chevron-right text-[10px] text-stone-400"></i>
          <span className="text-stone-900 font-bold">Order Checkout</span>
        </nav>

        <h1 className="font-serif text-3xl font-bold text-stone-900 mb-6 flex items-center gap-2">
          <i className="fa-solid fa-credit-card text-amber-600"></i>
          Complete Your Order
        </h1>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* Order Form */}
          <form onSubmit={handleCreateOrder} className="md:col-span-2 space-y-5">
            {/* Address */}
            <div className="bg-white border border-stone-200 rounded-3xl p-6 shadow-sm space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="font-serif font-bold text-stone-900 text-base flex items-center gap-2">
                  <i className="fa-solid fa-location-dot text-amber-600"></i>
                  Delivery Shipping Address
                </h3>
                <button type="button" onClick={() => setShowNewAddressForm(!showNewAddressForm)}
                        className="text-xs font-bold text-amber-700 hover:text-amber-800 flex items-center gap-1 bg-amber-50 hover:bg-amber-100 px-3 py-1.5 rounded-xl border border-amber-200/60 transition-all">
                  <i className={`fa-solid ${showNewAddressForm ? 'fa-minus' : 'fa-plus'}`}></i>
                  {showNewAddressForm ? 'Cancel' : 'Add New Address'}
                </button>
              </div>

              {!showNewAddressForm ? (
                <select value={selectedAddressId} onChange={e => setSelectedAddressId(e.target.value)}
                        className="warm-light-input py-2.5 text-xs font-medium">
                  {addresses.map(a => (
                    <option key={a.id} value={a.id}>
                      {a.receiverName} — {a.street}, {a.ward}, {a.district}, {a.province} ({a.receiverPhone})
                    </option>
                  ))}
                </select>
              ) : (
                <div className="p-4 bg-stone-50 border border-amber-200/60 rounded-2xl space-y-3 animate-fade-in">
                  <h4 className="text-xs font-bold text-amber-900 uppercase tracking-wider">New Recipient Details</h4>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="text-[11px] font-semibold text-stone-600 mb-1 block">Recipient Name *</label>
                      <input value={newAddress.receiverName} onChange={e => setNewAddress({...newAddress, receiverName: e.target.value})}
                             placeholder="Full name" className="warm-light-input py-2 text-xs" required />
                    </div>
                    <div>
                      <label className="text-[11px] font-semibold text-stone-600 mb-1 block">Phone Number *</label>
                      <input value={newAddress.receiverPhone} onChange={e => setNewAddress({...newAddress, receiverPhone: e.target.value})}
                             placeholder="Phone number" className="warm-light-input py-2 text-xs" required />
                    </div>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <div>
                      <label className="text-[11px] font-semibold text-stone-600 mb-1 block">Province / City</label>
                      <input value={newAddress.province} onChange={e => setNewAddress({...newAddress, province: e.target.value})}
                             className="warm-light-input py-2 text-xs" />
                    </div>
                    <div>
                      <label className="text-[11px] font-semibold text-stone-600 mb-1 block">District</label>
                      <input value={newAddress.district} onChange={e => setNewAddress({...newAddress, district: e.target.value})}
                             className="warm-light-input py-2 text-xs" />
                    </div>
                    <div>
                      <label className="text-[11px] font-semibold text-stone-600 mb-1 block">Ward</label>
                      <input value={newAddress.ward} onChange={e => setNewAddress({...newAddress, ward: e.target.value})}
                             className="warm-light-input py-2 text-xs" />
                    </div>
                  </div>
                  <div>
                    <label className="text-[11px] font-semibold text-stone-600 mb-1 block">Street Address *</label>
                    <input value={newAddress.street} onChange={e => setNewAddress({...newAddress, street: e.target.value})}
                           placeholder="House number, street name" className="warm-light-input py-2 text-xs" required />
                  </div>
                  <div className="flex justify-end gap-2 pt-2">
                    <button type="button" onClick={() => setShowNewAddressForm(false)}
                            className="px-4 py-1.5 text-xs font-semibold text-stone-600 hover:text-stone-900 border border-stone-300 rounded-xl">
                      Cancel
                    </button>
                    <button type="button" onClick={handleSaveNewAddress}
                            className="px-5 py-1.5 text-xs font-bold text-white bg-amber-600 hover:bg-amber-700 rounded-xl shadow-md transition-all">
                      Save & Use Address
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Coupon */}
            <div className="bg-white border border-stone-200 rounded-3xl p-6 shadow-sm space-y-3">
              <h3 className="font-serif font-bold text-stone-900 text-base flex items-center gap-2">
                <i className="fa-solid fa-ticket text-amber-600"></i>
                Discount Coupon Code
              </h3>
              <div className="flex gap-2">
                <input value={couponCode} onChange={e => setCouponCode(e.target.value)}
                       placeholder="Try WELCOME10..."
                       className="flex-1 warm-light-input py-2 text-xs" />
                <button type="button" onClick={handleApplyCoupon}
                        className="px-5 py-2 bg-stone-100 border border-stone-300 hover:border-amber-600 text-xs font-semibold rounded-xl text-stone-800 transition-all">
                  Apply
                </button>
              </div>
              {appliedCoupon && (
                <p className="text-xs text-emerald-700 font-bold mt-2">
                  <i className="fa-solid fa-circle-check mr-1"></i>
                  Discount Applied: -{formatCurrency(appliedCoupon.discountAmount)}
                </p>
              )}
            </div>

            {/* Payment Method */}
            <div className="bg-white border border-stone-200 rounded-3xl p-6 shadow-sm space-y-3">
              <h3 className="font-serif font-bold text-stone-900 text-base flex items-center gap-2">
                <i className="fa-solid fa-wallet text-amber-600"></i>
                Payment Method
              </h3>
              <div className="grid grid-cols-2 gap-3">
                <label className={`flex items-center gap-3 p-3 rounded-2xl border cursor-pointer transition-all ${
                  paymentMethod === 'COD' ? 'border-amber-600 bg-amber-50/60' : 'border-stone-200 bg-stone-50'
                }`}>
                  <input type="radio" name="payment" value="COD" checked={paymentMethod === 'COD'}
                         onChange={e => setPaymentMethod(e.target.value)} className="accent-amber-600" />
                  <div>
                    <p className="text-xs font-bold text-stone-900">Cash on Delivery (COD)</p>
                    <p className="text-[10px] text-stone-500">Pay upon doorstep receipt</p>
                  </div>
                </label>

                <label className={`flex items-center gap-3 p-3 rounded-2xl border cursor-pointer transition-all ${
                  paymentMethod === 'BANK_TRANSFER' ? 'border-amber-600 bg-amber-50/60' : 'border-stone-200 bg-stone-50'
                }`}>
                  <input type="radio" name="payment" value="BANK_TRANSFER" checked={paymentMethod === 'BANK_TRANSFER'}
                         onChange={e => setPaymentMethod(e.target.value)} className="accent-amber-600" />
                  <div>
                    <p className="text-xs font-bold text-stone-900">Bank Transfer</p>
                    <p className="text-[10px] text-stone-500">Instant QR code transfer</p>
                  </div>
                </label>
              </div>
            </div>

            <button type="submit" disabled={submitting}
                    className="w-full py-3.5 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 disabled:opacity-50">
              {submitting ? 'Processing Order...' : 'Confirm & Place Order'}
            </button>
          </form>

          {/* Order Summary Sidebar */}
          <div className="bg-white border border-stone-200 rounded-3xl p-6 shadow-sm h-fit sticky top-24 space-y-4">
            <h3 className="font-serif font-bold text-stone-900 text-base pb-3 border-b border-stone-100 flex items-center gap-2">
              <i className="fa-solid fa-list-check text-amber-600"></i>
              Order Summary
            </h3>
            <div className="space-y-3 max-h-64 overflow-y-auto custom-scrollbar">
              {cart.items.map(item => (
                <div key={item.id} className="flex gap-2.5 text-xs">
                  <img src={item.bookCoverImage || 'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?auto=format&fit=crop&w=100&q=80'}
                       className="w-10 h-13 object-cover rounded-lg shadow-sm" alt="" />
                  <div className="flex-1 min-w-0">
                    <p className="line-clamp-1 text-stone-900 font-bold">{item.bookTitle}</p>
                    <p className="text-[10px] text-stone-500">Qty: {item.quantity}</p>
                  </div>
                  <span className="font-bold text-amber-800">
                    {formatCurrency(item.unitPrice * item.quantity)}
                  </span>
                </div>
              ))}
            </div>
            <div className="border-t border-stone-200 pt-4 space-y-2 text-xs">
              <div className="flex justify-between text-stone-600">
                <span>Subtotal:</span><span>{formatCurrency(subtotal)}</span>
              </div>
              <div className="flex justify-between text-emerald-700 font-semibold">
                <span>Discount:</span><span>-{formatCurrency(discount)}</span>
              </div>
              <div className="flex justify-between text-stone-600">
                <span>Shipping Fee:</span><span>{formatCurrency(shippingFee)}</span>
              </div>
              <div className="pt-3 border-t border-stone-200 flex justify-between font-serif font-bold text-base text-stone-900">
                <span>Total Amount:</span>
                <span className="text-amber-800">{formatCurrency(grandTotal)}</span>
              </div>
            </div>
          </div>
        </div>
      </main>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     ORDERS PAGE
     ══════════════════════════════════════════════════════════════════════ */
  function OrdersPage() {
    const { navigate } = window.useRouter();
    const { user, showToast, setIsAuthOpen, setAuthMode } = window.useApp();
    const formatCurrency = window.formatCurrency;
    const Pagination = window.Pagination;
    const StatusBadge = window.StatusBadge;
    const LoadingSpinner = window.LoadingSpinner;

    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(0);
    const [pageData, setPageData] = useState({ totalPages: 0, totalElements: 0 });

    useEffect(() => {
      if (!user) {
        setIsAuthOpen(true);
        setAuthMode('login');
        navigate('/');
        return;
      }
      fetchOrders();
    }, [user, page]);

    const fetchOrders = async () => {
      setLoading(true);
      try {
        const res = await ApiClient.getUserOrders({ page, size: 10 });
        if (res.data) {
          setOrders(res.data.content || []);
          setPageData({ totalPages: res.data.totalPages || 0, totalElements: res.data.totalElements || 0 });
        }
      } catch (err) { showToast(err.message, 'error'); }
      finally { setLoading(false); }
    };

    return (
      <main className="max-w-4xl mx-auto px-6 py-8 flex-1">
        <nav className="flex items-center gap-2 text-xs text-stone-500 mb-6">
          <a href="#/" className="hover:text-amber-700 font-medium">Home</a>
          <i className="fa-solid fa-chevron-right text-[10px] text-stone-400"></i>
          <span className="text-stone-900 font-bold">My Orders</span>
        </nav>

        <h1 className="font-serif text-3xl font-bold text-stone-900 mb-6 flex items-center gap-2">
          <i className="fa-solid fa-receipt text-amber-600"></i>
          My Order History
        </h1>

        {loading ? (
          <LoadingSpinner text="Fetching your orders..." />
        ) : orders.length === 0 ? (
          <div className="text-center py-16 bg-white rounded-3xl border border-stone-200 p-8">
            <i className="fa-solid fa-box-open text-5xl text-stone-300 mb-4"></i>
            <h3 className="font-serif text-lg font-bold text-stone-700 mb-1">No Orders Found</h3>
            <p className="text-xs text-stone-500 mb-6">Start exploring our catalog to place your first book order</p>
            <button onClick={() => navigate('/catalog')}
                    className="px-6 py-2.5 bg-amber-600 hover:bg-amber-700 text-white font-semibold rounded-2xl transition-all text-xs">
              Explore Catalog
            </button>
          </div>
        ) : (
          <>
            <div className="space-y-4">
              {orders.map(o => (
                <div key={o.id} className="bg-white border border-stone-200 rounded-3xl p-6 shadow-sm hover:border-amber-300 transition-all">
                  <div className="flex flex-wrap items-center justify-between gap-3 pb-3 mb-3 border-b border-stone-100">
                    <div className="flex items-center gap-3">
                      <span className="font-mono font-bold text-amber-800 text-xs">{o.orderCode}</span>
                      <StatusBadge status={o.orderStatus} />
                    </div>
                    <span className="text-xs text-stone-400 font-medium">
                      {o.createdAt ? new Date(o.createdAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : ''}
                    </span>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-stone-600">
                    <p>
                      <i className="fa-solid fa-user text-stone-400 mr-2"></i>
                      Recipient: <span className="text-stone-900 font-semibold">{o.receiverName} ({o.receiverPhone})</span>
                    </p>
                    <p className="text-stone-500">
                      <i className="fa-solid fa-location-dot text-stone-400 mr-2"></i>
                      Address: {o.shippingAddress}
                    </p>
                  </div>
                  <div className="flex items-center justify-between mt-4 pt-3 border-t border-stone-100">
                    <span className="text-xs text-stone-500">
                      Payment Method: <span className="font-semibold text-stone-800">{o.paymentMethod}</span>
                    </span>
                    <span className="font-serif text-lg font-bold text-amber-800">{formatCurrency(o.totalAmount)}</span>
                  </div>
                </div>
              ))}
            </div>
            <Pagination
              currentPage={page}
              totalPages={pageData.totalPages}
              totalElements={pageData.totalElements}
              onPageChange={setPage}
            />
          </>
        )}
      </main>
    );
  }

  /* ── Export All 5 Customer Components ───────────────────────────────── */
  Object.assign(window, {
    HomePage,
    CatalogPage,
    BookDetailPage,
    CheckoutPage,
    OrdersPage
  });
})();
