// The Kape — App shell + routing + Home page
// All other page components live in pages.jsx and attach to window.

const { useState, useEffect, useMemo, useRef } = React;

// ── tiny router (hash-free, history.pushState) ──────────────────
function useRoute() {
  const [route, setRoute] = useState(() => parseRoute(window.location.pathname + window.location.search));
  useEffect(() => {
    const onPop = () => setRoute(parseRoute(window.location.pathname + window.location.search));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);
  const navigate = (path) => {
    window.history.pushState({}, "", path);
    setRoute(parseRoute(path));
    window.scrollTo({ top: 0, behavior: "instant" });
  };
  return [route, navigate];
}
function parseRoute(path) {
  // strip leading slash, allow query
  const [p, q] = path.split("?");
  const parts = p.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
  if (parts.length === 0) return { name: "home" };
  const [a, b] = parts;
  if (a === "collections" && !b) return { name: "collections" };
  if (a === "collections" && b) return { name: "collection", id: b };
  if (a === "product" && b) return { name: "product", id: b };
  if (a === "craft") return { name: "craft" };
  if (a === "the-house") return { name: "house" };
  if (a === "appointments") return { name: "appointments" };
  if (a === "locate-us" || a === "contact") return { name: "locate" };
  return { name: "home" };
}
window.navigate = null; // set below

const fmtAED = (n) => `AED ${n.toLocaleString("en-US")}`;

// ── Nav ────────────────────────────────────────────────────────
function Nav({ route, navigate }) {
  const links = [
    { label: "Collections", route: "/collections", match: ["collections", "collection", "product"] },
    { label: "Craft", route: "/craft", match: ["craft"] },
    { label: "The House", route: "/the-house", match: ["house"] },
    { label: "Locate Us", route: "/locate-us", match: ["locate"] },
  ];
  return (
    <header className="nav">
      <div className="container">
        <div className="nav-bar">
          <nav className="nav-links" aria-label="Primary">
            {links.map(l => (
              <a
                key={l.label}
                href={l.route}
                className="nav-link"
                aria-current={l.match.includes(route.name) ? "page" : undefined}
                onClick={(e) => { e.preventDefault(); navigate(l.route); }}
              >{l.label}</a>
            ))}
          </nav>
          <a href="/" className="nav-wordmark" onClick={(e) => { e.preventDefault(); navigate("/"); }}>
            THE KAPE
          </a>
          <div className="nav-right">
            <a className="nav-utility" href="#" onClick={(e) => e.preventDefault()}>EN · AR</a>
            <a className="nav-utility" href="#" onClick={(e) => e.preventDefault()}>AED</a>
            <a
              className="btn btn--sm"
              href="/appointments"
              onClick={(e) => { e.preventDefault(); navigate("/appointments"); }}
            >Book Appointment</a>
          </div>
        </div>
      </div>
    </header>
  );
}

// ── Footer ─────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="footer-wm">THE KAPE</div>
            <p>A contemporary modest-fashion house in Dubai Design District. The Kape is a modern interpretation of tailoring, luxury fabrics, and treatments — with a playful use of digital prints and embroidery.</p>
          </div>
          <div className="footer-col">
            <h5>Collections</h5>
            <ul>
              <li><a href="/collections/louis-barthelemy" onClick={(e) => { e.preventDefault(); navigate("/collections/louis-barthelemy"); }}>Louis Barthélemy</a></li>
              <li><a href="/collections/aw-25" onClick={(e) => { e.preventDefault(); navigate("/collections/aw-25"); }}>AW 25</a></li>
              <li><a href="/collections/resort-26" onClick={(e) => { e.preventDefault(); navigate("/collections/resort-26"); }}>Resort 26</a></li>
              <li><a href="/collections/ramadan-26" onClick={(e) => { e.preventDefault(); navigate("/collections/ramadan-26"); }}>Ramadan 26</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>The House</h5>
            <ul>
              <li><a href="/craft" onClick={(e) => { e.preventDefault(); navigate("/craft"); }}>Craft</a></li>
              <li><a href="/the-house" onClick={(e) => { e.preventDefault(); navigate("/the-house"); }}>The House</a></li>
              <li><a href="/appointments" onClick={(e) => { e.preventDefault(); navigate("/appointments"); }}>Appointments</a></li>
              <li><a href="/locate-us" onClick={(e) => { e.preventDefault(); navigate("/locate-us"); }}>Locate Us</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Showroom</h5>
            <ul>
              <li style={{color: "var(--muted)", fontSize: "13px", lineHeight: 1.7}}>Showroom A208<br/>Building 7, Dubai Design District<br/>Dubai, UAE</li>
              <li><a href="tel:+971504371111">+971 50 437 1111</a></li>
              <li><a href="tel:+97142763333">+971 4 276 3333</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Follow</h5>
            <ul>
              <li><a href="https://instagram.com/the_kape" target="_blank" rel="noopener">Instagram</a></li>
              <li><a href="https://facebook.com/The-Kape-684275191707993" target="_blank" rel="noopener">Facebook</a></li>
              <li><a href="https://wa.me/971504371111" target="_blank" rel="noopener">WhatsApp</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 The Kape · Made in UAE</span>
          <span>Prices in AED · By appointment in d3</span>
        </div>
      </div>
    </footer>
  );
}

// ── WhatsApp FAB ───────────────────────────────────────────────
function WhatsAppFab() {
  return (
    <a
      className="wa-fab"
      href="https://wa.me/971504371111?text=Hi%20The%20Kape%2C%20I%27d%20like%20to%20enquire%20about%20a%20piece."
      target="_blank" rel="noopener"
      aria-label="Chat on WhatsApp"
    >
      <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M20.5 3.5A11.4 11.4 0 0 0 12.05 0C5.6 0 .35 5.25.35 11.7c0 2.06.54 4.07 1.57 5.85L.25 24l6.6-1.73a11.66 11.66 0 0 0 5.2 1.32h.01c6.45 0 11.7-5.25 11.7-11.7a11.6 11.6 0 0 0-3.26-8.39ZM12.06 21.62h-.01a9.7 9.7 0 0 1-4.95-1.35l-.36-.21-3.92 1.03 1.05-3.82-.24-.39a9.7 9.7 0 0 1-1.49-5.18c0-5.36 4.37-9.72 9.73-9.72 2.6 0 5.04 1.01 6.88 2.85a9.66 9.66 0 0 1 2.84 6.88c0 5.36-4.37 9.72-9.72 9.72Zm5.34-7.28c-.29-.15-1.74-.86-2.01-.96-.27-.1-.47-.15-.66.15-.2.29-.76.96-.94 1.16-.17.2-.34.22-.64.07-.29-.15-1.24-.46-2.36-1.46-.87-.78-1.46-1.74-1.63-2.03-.17-.29-.02-.45.13-.6.13-.13.29-.34.44-.51.15-.17.2-.29.29-.49.1-.2.05-.37-.02-.51-.07-.15-.66-1.59-.9-2.18-.24-.57-.48-.49-.66-.5l-.56-.01a1.07 1.07 0 0 0-.78.37c-.27.29-1.02 1-1.02 2.44s1.05 2.83 1.2 3.03c.15.2 2.06 3.14 4.99 4.4.7.3 1.24.48 1.66.62.7.22 1.33.19 1.83.12.56-.08 1.74-.71 1.99-1.4.25-.69.25-1.27.17-1.4-.07-.13-.27-.2-.56-.34Z"/>
      </svg>
    </a>
  );
}

// ── Home ───────────────────────────────────────────────────────
function Home({ navigate }) {
  const products = window.PRODUCTS;
  const collections = window.COLLECTIONS;
  const featured = [
    "nara-silk-jader",
    "ayala-sapphire",
    "shouq-midnight",
    "gaida-deep-moss",
    "elaris",
    "rosalie",
    "nara-cupro-amber",
    "aurelia-beige",
  ].map(id => products.find(p => p.id === id)).filter(Boolean);

  return (
    <main data-screen-label="01 Home">
      {/* Hero */}
      <section className="hero">
        <div className="hero-image">
          <img src="media/product-01-nara-silk-jader.webp" alt="Nara Silk Jader — The Kape × Louis Barthélemy" />
        </div>
        <div className="hero-text">
          <span className="eyebrow">Resort 26 · Now in showroom</span>
          <h1 className="display">
            The Kape <em>×</em><br/>
            <span className="roman">Louis</span> <em>Barthélemy</em>
          </h1>
          <p>Painterly prints drift across silk, velvet and cupro — palms, stars and stories carried as memory. A contemporary kape, made in the UAE.</p>
          <div className="hero-cta">
            <a href="/collections/louis-barthelemy" className="btn" onClick={(e) => { e.preventDefault(); navigate("/collections/louis-barthelemy"); }}>
              Shop the collection <span className="arrow">→</span>
            </a>
            <a href="/appointments" className="btn btn--ghost" onClick={(e) => { e.preventDefault(); navigate("/appointments"); }}>
              Book an appointment
            </a>
          </div>
          <div className="hero-meta">
            <span>No. 01 / Painterly Prints</span>
            <span className="hero-meta-r">Silk · Velvet · Cupro<br/>AED 3,400 — 3,990</span>
          </div>
        </div>
      </section>

      {/* Current collections strip */}
      <section className="strip">
        <div className="strip-grid">
          {collections.map(c => (
            <a key={c.id} className="strip-card" href={`/collections/${c.id}`} onClick={(e) => { e.preventDefault(); navigate(`/collections/${c.id}`); }}>
              <img src={c.cover} alt={c.name} loading="lazy" />
              <div className="strip-card-inner">
                <span className="eyebrow">{c.eyebrow}</span>
                <h3>{c.name}</h3>
              </div>
            </a>
          ))}
        </div>
      </section>

      {/* Featured products */}
      <section className="section container">
        <div className="section-head">
          <div>
            <span className="eyebrow">The Edit</span>
            <h2>The Kapes,<br/><em>this season</em>.</h2>
          </div>
          <div className="right">
            <a className="linkish" href="/collections" onClick={(e) => { e.preventDefault(); navigate("/collections"); }}>
              View all collections →
            </a>
          </div>
        </div>
        <div className="products-grid">
          {featured.map(p => <ProductCard key={p.id} p={p} navigate={navigate} />)}
        </div>
      </section>

      {/* Craft teaser */}
      <section className="section container" style={{borderTop: "1px solid var(--border)"}}>
        <div className="craft-teaser">
          <div className="craft-teaser-img">
            <img src="media/product-20-ayala-sapphire.webp" alt="Hand embroidery on Ayala Sapphire" loading="lazy" />
          </div>
          <div>
            <span className="eyebrow">The Craft</span>
            <h2 className="display" style={{fontSize: "clamp(40px, 4.4vw, 64px)", lineHeight: 1.05, margin: "16px 0 20px"}}>
              A modern <em>interpretation</em><br/>of tailoring.
            </h2>
            <p style={{color: "var(--secondary)", maxWidth: 480, fontSize: 16}}>
              Every Kape is cut and finished in our Dubai atelier — across luxury fabrics, digital prints and the embroidery practices we hold to. Tailoring leads; ornament follows.
            </p>
            <div className="craft-pillars">
              <div className="craft-pillar"><span className="num">01</span><h4>Tailoring</h4><p>Considered cuts and proportions, finished by hand.</p></div>
              <div className="craft-pillar"><span className="num">02</span><h4>Luxury Fabrics</h4><p>Silk, velvet, cupro, jacquard — sourced with intent.</p></div>
              <div className="craft-pillar"><span className="num">03</span><h4>Digital Prints</h4><p>Commissioned artworks translated onto cloth.</p></div>
              <div className="craft-pillar"><span className="num">04</span><h4>Embroidery</h4><p>Hand-beaded panels, restraint over excess.</p></div>
            </div>
            <div style={{marginTop: 36}}>
              <a className="linkish" href="/craft" onClick={(e) => { e.preventDefault(); navigate("/craft"); }}>
                Inside the atelier →
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* Showroom band */}
      <section className="showroom">
        <div className="showroom-left">
          <span className="eyebrow" style={{color: "rgba(250,246,239,0.6)"}}>By appointment</span>
          <h2 style={{marginTop: 16}}>
            Step into the <em>showroom</em><br/>at d3.
          </h2>
          <p>Our boutique sits in Dubai Design District — travertine stone, epoxy resin, prefabricated cement. Try the collection, meet the team, fit your kape.</p>
          <div className="showroom-meta">
            <strong>Address</strong>
            Showroom A208, Building 7<br/>Dubai Design District, Dubai
            <br/><br/>
            <strong>By phone</strong>
            +971 50 437 1111 · +971 4 276 3333
          </div>
          <div className="showroom-cta">
            <a className="btn btn--inv" href="/appointments" onClick={(e) => { e.preventDefault(); window.navigate("/appointments"); }}>
              Book a fitting <span className="arrow">→</span>
            </a>
            <a className="btn btn--inv-ghost" href="https://wa.me/971504371111" target="_blank" rel="noopener">
              WhatsApp
            </a>
          </div>
        </div>
        <div className="showroom-right">
          <div className="map">
            <div className="map-label">DUBAI DESIGN DISTRICT</div>
            <div className="map-pin" />
          </div>
        </div>
      </section>

      {/* Press band */}
      <section className="press-band">
        <div className="container press-row">
          <span className="eyebrow">As covered in</span>
          <div className="press-logos">
            <span className="press-logo">SUPERFUTUREDESIGN*</span>
            <span className="press-logo">Architonic</span>
            <span className="press-logo">Commercial Interior Design</span>
            <span className="press-logo">Archilovers</span>
            <span className="press-logo">RECKLI</span>
          </div>
        </div>
      </section>
    </main>
  );
}

// ── Product card (used across pages) ──────────────────────────
function ProductCard({ p, navigate }) {
  return (
    <a
      className="product-card"
      href={`/product/${p.id}`}
      onClick={(e) => { e.preventDefault(); navigate(`/product/${p.id}`); }}
    >
      <div className="ph"><img src={p.img} alt={p.title} loading="lazy" /></div>
      <div className="title">{p.title}</div>
      <div className="meta">{p.family} · {p.fabric}</div>
      <div className="price">{fmtAED(p.price)}</div>
    </a>
  );
}
window.ProductCard = ProductCard;
window.fmtAED = fmtAED;

// ── App ───────────────────────────────────────────────────────
function App() {
  const [route, navigate] = useRoute();
  window.navigate = navigate;

  let page;
  switch (route.name) {
    case "home":         page = <Home navigate={navigate} />; break;
    case "collections":  page = <window.Collections navigate={navigate} />; break;
    case "collection":   page = <window.CollectionDetail id={route.id} navigate={navigate} />; break;
    case "product":      page = <window.ProductDetail id={route.id} navigate={navigate} />; break;
    case "craft":        page = <window.Craft navigate={navigate} />; break;
    case "house":        page = <window.House navigate={navigate} />; break;
    case "appointments": page = <window.Appointments navigate={navigate} />; break;
    case "locate":       page = <window.Locate navigate={navigate} />; break;
    default:             page = <Home navigate={navigate} />;
  }

  return (
    <>
      <Nav route={route} navigate={navigate} />
      {page}
      <Footer navigate={navigate} />
      <WhatsAppFab />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
