// Nav.jsx — cursive wordmark + single "Collections" pill that reveals a
// mega-menu on hover. AI Studio / icons / CTA remain visible at all times.
const { useState, useEffect, useRef } = React;

// The mega-menu now mirrors the new four-axis Collections hub: customers
// pick HOW they want to shop (Room / Colour / Style / Shape & Size) rather
// than picking a cat-bucket (old Bath / Wall / Floor / Outdoor / Decor).
// Each card opens the matching axis sub-page; "View everything" goes to
// the Hub itself. The OLD NAV_CATEGORIES list is kept below the new one
// because the mobile drawer + a couple of legacy callers still reference
// it (we'll prune those once the new mobile layout lands).
const NAV_AXES = [
  {
    axis: 'room',
    label: 'By Room',
    subtitle: 'Bathroom · Kitchen · Outdoor',
    desc: 'Start with where the tile will live.',
    img:      '/assets/generated/category-hero-bath.jpg',
    fallback: '/assets/generated/hero-main.jpg',
    color:    'oklch(90% 0.008 220)',
  },
  {
    axis: 'colour',
    label: 'By Colour',
    subtitle: 'White · Beige · Green · Metallic',
    desc: 'Pick a palette and narrow from there.',
    img:      '/assets/categories/style-frozen-up.jpg',
    fallback: '/assets/generated/lifestyle-wall-texture.jpg',
    color:    'oklch(88% 0.01 75)',
  },
  {
    axis: 'style',
    label: 'By Style',
    subtitle: 'Marble · Onyx · Stone · Wood',
    desc: 'The material your tile aspires to be.',
    img:      '/assets/categories/luxury-meteorite.jpg',
    fallback: '/assets/generated/lifestyle-floor-wide.jpg',
    color:    'oklch(85% 0.012 80)',
  },
  {
    axis: 'shape',
    label: 'By Shape & Size',
    subtitle: 'Mosaic · Subway · Large Format',
    desc: 'From small accents to floor-spanning planks.',
    img:      '/assets/categories/heritage.jpg',
    fallback: '/assets/generated/category-hero-decor.jpg',
    color:    'oklch(88% 0.03 50)',
  },
  {
    // The Luxury tab is `direct: true` — clicking/hovering it doesn't
    // open a panel of sub-options, it navigates straight to the
    // filtered Luxury listing. CollectionsHub treats it the same way.
    // Rendered as the rightmost tab so it reads as a curated pick
    // distinct from the four "Shop by …" axes.
    axis: 'luxury',
    direct: true,
    label: 'Luxury',
    subtitle: 'The curated edit',
    desc: 'A small, deliberate selection.',
    img:      '/assets/categories/luxury-meteorite.jpg',
    fallback: '/assets/generated/lifestyle-floor-wide.jpg',
    color:    'oklch(86% 0.02 60)',
  },
];

// Legacy list — still referenced by the mobile drawer below. Tiles in
// the new browse model are reached via the four axes, but the mobile
// menu still surfaces the old cat names as quick-jump shortcuts.
const NAV_CATEGORIES = [
  { label: 'Bath',    id: 'bath',    subtitle: 'Mosaic · Subway · Large Format',    desc: 'From sleek large-format porcelain to handmade subway glazes.',   img: '/assets/generated/category-hero-bath.jpg',    fallback: '/assets/generated/hero-main.jpg',              color: 'oklch(90% 0.008 220)' },
  { label: 'Wall',    id: 'wall',    subtitle: 'Glazed · Textured · Handmade',      desc: 'Expressive glazes and rich textures.',                           img: '/assets/generated/category-hero-wall.jpg',    fallback: '/assets/generated/lifestyle-wall-texture.jpg', color: 'oklch(88% 0.01 75)' },
  { label: 'Floor',   id: 'floor',   subtitle: 'Porcelain · Stone · Anti-slip',     desc: "Hardwearing surfaces that don't date.",                          img: '/assets/generated/category-hero-floor.jpg',   fallback: '/assets/generated/lifestyle-floor-wide.jpg',   color: 'oklch(85% 0.012 80)' },
  { label: 'Outdoor', id: 'outdoor', subtitle: 'Frost-resistant · Non-slip',        desc: 'Built for the elements.',                                        img: '/assets/generated/category-hero-outdoor.jpg', fallback: '/assets/generated/hero-outdoor.jpg',           color: 'oklch(82% 0.02 100)' },
  { label: 'Decor',   id: 'decor',   subtitle: 'Patterned · Feature · Handcrafted', desc: 'Statement tiles for feature walls.',                             img: '/assets/generated/category-hero-decor.jpg',   fallback: '/assets/generated/lifestyle-decor-feature.jpg',color: 'oklch(88% 0.03 50)' },
];

function Nav({ currentPage, navigate, onOpenCart, onOpenSearch }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  // Active tab inside the mega-menu (room | colour | style). The mega
  // menu is now a Porcelain-Superstore-style flyout with text-only
  // columns under three tabs, not picture cards.
  const [megaTab, setMegaTab] = useState('room');
  const megaTimer = useRef(null);
  const { cart, favourites } = useAccount();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Escape closes mega + mobile menu
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') { setMegaOpen(false); setMenuOpen(false); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Touch-device detection — drives mega-menu behaviour. On touch
  // (iPad / Surface / phone-in-desktop-mode), hover events are unreliable
  // (iOS fires hover-on-first-tap → click-on-second). We disable hover
  // open/close entirely and let TAP toggle the panel instead.
  const [isTouch, setIsTouch] = useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(pointer: coarse)').matches
  );
  useEffect(() => {
    const mql = window.matchMedia('(pointer: coarse)');
    const on = () => setIsTouch(mql.matches);
    mql.addEventListener?.('change', on);
    return () => mql.removeEventListener?.('change', on);
  }, []);

  const openMega = () => {
    if (megaTimer.current) clearTimeout(megaTimer.current);
    setMegaOpen(true);
  };
  const scheduleCloseMega = () => {
    if (megaTimer.current) clearTimeout(megaTimer.current);
    megaTimer.current = setTimeout(() => setMegaOpen(false), 160);
  };
  // Old: jumped straight into a cat-filtered list. New: opens the axis
  // sub-page so the customer picks WHICH room / colour / style / shape
  // they want to browse before seeing tiles.
  const goToAxis = (a) => {
    setMegaOpen(false);
    navigate('collections-axis', a.axis);
  };
  // Legacy alias — the mobile drawer below still calls this with a cat
  // object. New CollectionDetail handles the legacy `{id, label}` shape
  // via its resolveFilter() fallback, so this keeps working unchanged.
  const goToCollection = (l) => {
    setMegaOpen(false);
    navigate('collection', { id: l.id, label: `${l.label} Tiles`, ...l });
  };

  const isHome = currentPage === 'home';
  // The product page (clicked into a specific tile) has a full-screen
  // ambience image as its hero — same as the home hero — so the nav
  // should sit transparently over it with the white logo, then fade
  // in its white background as the user scrolls past the hero.
  const isProduct = currentPage === 'product';
  const heroLikePage = isHome || isProduct;
  // isStudio used to gate the dark-bg nav variant for the AI Studio
  // page. Studio is removed; we leave the constant as `false` so any
  // remaining `|| isStudio` guards still compile and behave like the
  // home/normal route.
  const isStudio = false;
  const isCollectionPage = currentPage === 'collection' || currentPage === 'collections';
  const transparent = heroLikePage && !scrolled && !menuOpen && !megaOpen;

  // Scrolled-state nav background was warm cream — switched to a
  // neutral semi-opaque white to match the new site-wide white theme.
  const navBg = transparent ? 'transparent' : 'rgba(255,255,255,0.94)';
  const navBorder = (transparent && !megaOpen) ? 'transparent' : 'var(--cream-deep)';
  const fg = transparent ? 'white' : 'var(--dark)';
  const fgMid = transparent ? 'rgba(255,255,255,0.78)' : 'var(--dark-mid)';

  const cartCount = cart?.length || 0;
  const pillActive = megaOpen || isCollectionPage;

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
        height: 'var(--nav-h)',
        // Three-column grid (1fr auto 1fr) so the centre group sits
        // mathematically in the middle of the nav, regardless of how
        // wide the left lockup or right icon stack is. Previously the
        // nav used flex `justify-content: space-between` which makes
        // the centre group drift toward whichever side has less
        // content — and after removing the Account + Cart icons the
        // right side was much smaller, so the centre group was no
        // longer actually centred. Grid fixes this for good.
        display: 'grid',
        gridTemplateColumns: '1fr auto 1fr',
        alignItems: 'center',
        padding: '0 36px',
        background: navBg,
        backdropFilter: transparent || isStudio ? 'none' : 'saturate(140%) blur(18px)',
        WebkitBackdropFilter: transparent || isStudio ? 'none' : 'saturate(140%) blur(18px)',
        borderBottom: `1px solid ${navBorder}`,
        transition: 'background 0.5s ease, backdrop-filter 0.5s ease',
      }}>
        {/* Brand lockup — ALWAYS visible. Two visual modes:
              · over the hero (transparent nav): the three disks stay
                in their native colours; the wordmark text flips to
                white. Achieved by swapping in a "white-text" variant
                of the SVG where only the text-class fills are #FFFFFF.
              · everywhere else (opaque nav: home post-scroll, every
                non-hero page): the full original logo (disks + dark-
                purple wordmark) shows. */}
        <button onClick={() => navigate('home')} aria-label="Venoraa home"
          style={{
            // justifySelf: 'start' so the button shrinks to its content
            // (the logo image only) and clicks on empty nav space don't
            // accidentally navigate to home.
            justifySelf: 'start',
            background: 'none', border: 'none', cursor: 'pointer', padding: 0,
            display: 'flex', alignItems: 'center', height: '60px',
          }}>
          <img
            src={transparent
              ? '/assets/brand/venoraa-logo-white-text.svg'
              : '/assets/brand/venoraa-logo.svg'}
            alt="Venoraa"
            style={{
              height: '54px',
              width: 'auto',
              display: 'block',
              transition: 'opacity 0.4s ease',
            }}
          />
        </button>

        {/* Desktop centre — Collections pill + Journal, locked to the
            page's vertical centre via a 1fr/auto/1fr inner grid. The
            two outer 1fr columns are equal width (because the group
            has an explicit width), Collections is justified to the
            END of its column (flush right, kissing the divider),
            Journal to the START of its column (flush left). The 1px
            divider sits exactly between them — and the whole group
            is centred in the nav by the OUTER grid (1fr auto 1fr).
            Net: the divider lands on the page's vertical centre with
            Collections and Journal symmetric around it. */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1fr auto 1fr',
          alignItems: 'center',
          columnGap: '14px',
          /* Back to 340 px now that AI Studio is archived (was widened
             to 460 to fit both Journal + AI Studio in column 3). */
          width: '340px',
        }} className="nav-desktop">
          <button
            onMouseEnter={isTouch ? undefined : openMega}
            onMouseLeave={isTouch ? undefined : scheduleCloseMega}
            onFocus={isTouch ? undefined : openMega}
            onClick={() => {
              // Touch: first tap opens the mega-menu (don't navigate
              // yet). Tap a menu item — or close — to navigate. Mouse:
              // hover already opens, so a click goes straight to the
              // listing page like before.
              if (isTouch && !megaOpen) { openMega(); return; }
              setMegaOpen(false);
              navigate('collections');
            }}
            aria-haspopup="true"
            aria-expanded={megaOpen}
            style={{
              justifySelf: 'end',
              display: 'inline-flex', alignItems: 'center', gap: '10px',
              background: pillActive
                ? ((transparent || isStudio) ? 'rgba(255,255,255,0.14)' : 'var(--dark)')
                : ((transparent || isStudio) ? 'rgba(255,255,255,0.08)' : 'rgba(20,16,12,0.05)'),
              border: `1px solid ${pillActive
                ? ((transparent || isStudio) ? 'rgba(255,255,255,0.45)' : 'var(--dark)')
                : ((transparent || isStudio) ? 'rgba(255,255,255,0.22)' : 'var(--cream-deep)')}`,
              color: pillActive
                ? ((transparent || isStudio) ? 'white' : 'white')
                : fg,
              padding: '9px 18px', borderRadius: '999px', cursor: 'pointer',
              fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: 500,
              letterSpacing: '0.16em', textTransform: 'uppercase',
              transition: 'all 0.25s var(--ease-out)',
            }}
          >
            <span>Collections</span>
            <span style={{
              display: 'inline-block', width: '8px', height: '8px',
              borderRight: '1.5px solid currentColor',
              borderBottom: '1.5px solid currentColor',
              transform: megaOpen ? 'rotate(-135deg) translate(-1px,-1px)' : 'rotate(45deg)',
              transition: 'transform 0.3s var(--ease-out)',
              marginTop: megaOpen ? '2px' : '-3px',
            }}/>
          </button>
          <div style={{ width: '1px', height: '16px', background: (transparent || isStudio) ? 'rgba(255,255,255,0.18)' : 'var(--cream-deep)' }}/>
          {/* Column 3 — Journal only. (AI Studio was archived; see
              _archived/ai-studio/. To restore: add a second button
              here matching Journal's styling that navigates to 'studio'.) */}
          <button onClick={() => navigate('journal')} style={{
            justifySelf: 'start',
            background: 'none', border: 'none', cursor: 'pointer', padding: '9px 4px',
            fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: 400,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            color: currentPage === 'journal' ? fg : fgMid, transition: 'color 0.25s',
          }}
          onMouseEnter={e => e.currentTarget.style.color = fg}
          onMouseLeave={e => e.currentTarget.style.color = currentPage === 'journal' ? fg : fgMid}
          >Journal</button>
        </div>

        {/* Right — Icons + CTA. justifySelf:end pushes this group
            to the right edge of its 1fr grid cell so it doesn't
            sit at the cell's left side (which would visually
            unbalance the centred middle group). */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '18px', justifySelf: 'end' }} className="nav-desktop">
          <IconBtn label="Search" fg={fg} onClick={onOpenSearch} svg={IconSearch}/>
          {/* Favourites / selection drawer — opens the same drawer
              on every page so users can review every tile they've
              hearted and send the whole selection to the studio
              for a quote in one tap. Badge counts current favourites. */}
          <IconBtn label="Favourites" fg={fg} onClick={onOpenCart} svg={IconHeart} badge={favourites?.length || 0}/>
        </div>

        <button onClick={() => setMenuOpen(v => !v)} style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer', color: fg, fontSize: '22px' }} className="nav-hamburger">
          {menuOpen ? '✕' : '☰'}
        </button>

        {/* Mobile drawer — mirrors the new four-axis hub. Tap an axis →
            the matching axis sub-page; everything below is secondary nav
            (search / journal / quote). */}
        {menuOpen && (
          <div style={{ position: 'fixed', top: 'var(--nav-h)', left: 0, right: 0, bottom: 0, background: 'var(--cream)', zIndex: 99, display: 'flex', flexDirection: 'column', padding: '40px', gap: '20px', overflowY: 'auto' }}>
            {NAV_AXES.map(a => (
              <button
                key={a.axis}
                onClick={() => {
                  setMenuOpen(false);
                  if (a.direct) {
                    // Luxury — skip the axis sub-page, go straight
                    // to the filtered listing.
                    navigate('collection', { axis: a.axis, value: 'true', label: a.label });
                  } else {
                    navigate('collections-axis', a.axis);
                  }
                }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--serif)', fontSize: '34px', fontWeight: 300, color: 'var(--dark)' }}
              >{a.label}</button>
            ))}
            <div style={{ height: '1px', background: 'var(--cream-deep)', margin: '10px 0' }}/>
            <button onClick={() => { onOpenSearch(); setMenuOpen(false); }} style={mobileSub}>Search</button>
            <button onClick={() => { onOpenCart(); setMenuOpen(false); }} style={mobileSub}>Selection ({favourites?.length || 0})</button>
            <button onClick={() => { navigate('journal'); setMenuOpen(false); }} style={mobileSub}>Journal</button>
            <button onClick={() => { navigate('quote'); setMenuOpen(false); }} style={mobileSub}>Request a quote</button>
          </div>
        )}

        <style>{`
          @media(max-width:1020px){.nav-desktop{display:none!important;}.nav-hamburger{display:block!important;}}
        `}</style>
      </nav>

      {/* Tap-outside-to-close backdrop. Touch devices need this since
          they can't rely on the mouse-leave timer to close the panel. */}
      {isTouch && megaOpen && (
        <div
          aria-hidden
          onClick={() => setMegaOpen(false)}
          style={{
            position: 'fixed', top: 'var(--nav-h)', left: 0, right: 0, bottom: 0,
            background: 'transparent', zIndex: 98,
          }}
        />
      )}

      {/* MEGA-MENU — full-width band under the nav. Outer wrapper is
           edge-to-edge with a white background + bottom border so it
           reads as a horizontal "shelf" extending the nav. Inner content
           is constrained to a max width and centred so the layout still
           feels editorial. */}
      <div
        onMouseEnter={isTouch ? undefined : openMega}
        onMouseLeave={isTouch ? undefined : scheduleCloseMega}
        aria-hidden={!megaOpen}
        style={{
          position: 'fixed', top: 'var(--nav-h)', left: 0, right: 0, zIndex: 99,
          pointerEvents: megaOpen ? 'auto' : 'none',
          background: 'rgba(255,255,255,0.99)',
          backdropFilter: 'saturate(140%) blur(22px)',
          WebkitBackdropFilter: 'saturate(140%) blur(22px)',
          borderBottom: megaOpen ? '1px solid var(--cream-deep)' : '1px solid transparent',
          boxShadow: megaOpen ? '0 24px 48px rgba(20,16,12,0.10)' : 'none',
          transform: megaOpen ? 'translateY(0)' : 'translateY(-12px)',
          opacity: megaOpen ? 1 : 0,
          transition: 'opacity 0.32s var(--ease-out), transform 0.32s var(--ease-out), box-shadow 0.32s',
          overflow: 'hidden',
        }}
      >
        <div style={{
          maxWidth: '1440px',
          margin: '0 auto',
          padding: '0',
        }} className="mega-body">
          {/* ── Tab strip ─────────────────────────────────────────────
               Serif tabs with a sliding underline. The underline is one
               element transformed via CSS, not a per-tab border, so the
               transition reads as a single line gliding between labels —
               more refined than a hard swap. */}
          <div className="mega-tabs" style={{
            position: 'relative',
            display: 'flex', alignItems: 'center', gap: '40px',
            padding: '4px 56px 0',
            borderBottom: '1px solid var(--cream-deep)',
          }}>
            {NAV_AXES.map((a, i) => (
              <button
                key={a.axis}
                onMouseEnter={a.direct ? undefined : () => setMegaTab(a.axis)}
                onFocus={a.direct ? undefined : () => setMegaTab(a.axis)}
                onClick={() => {
                  if (a.direct) {
                    // Luxury — go straight to the listing. Don't
                    // route through the tab-content panel because
                    // there are no sub-options to choose between.
                    setMegaOpen(false);
                    navigate('collection', { axis: a.axis, value: 'true', label: a.label });
                  } else {
                    setMegaTab(a.axis);
                  }
                }}
                aria-selected={!a.direct && megaTab === a.axis}
                style={{
                  position: 'relative',
                  background: 'none', border: 'none', cursor: 'pointer',
                  padding: '22px 0 20px',
                  fontFamily: 'var(--serif)',
                  fontSize: '17px',
                  fontWeight: 400,
                  // Luxury reads as italic always — it's the curated
                  // pick, given a different visual weight from the
                  // four "Shop by …" tabs and tinted terracotta to
                  // mark it as the feature link.
                  fontStyle: a.direct ? 'italic' : (megaTab === a.axis ? 'italic' : 'normal'),
                  color: a.direct
                    ? 'var(--terracotta)'
                    : (megaTab === a.axis ? 'var(--dark)' : 'var(--dark-mid)'),
                  letterSpacing: '-0.005em',
                  transition: 'color 0.3s ease, font-style 0.3s ease',
                }}
              >
                {a.direct ? a.label : `Shop ${a.label.replace('By ', 'by ')}`}
                {/* Per-tab underline that animates width on activate */}
                <span aria-hidden style={{
                  position: 'absolute', left: 0, right: 0, bottom: '-1px',
                  height: 1,
                  background: 'var(--dark)',
                  transform: megaTab === a.axis ? 'scaleX(1)' : 'scaleX(0)',
                  transformOrigin: 'left center',
                  transition: 'transform 0.4s var(--ease-out)',
                }}/>
              </button>
            ))}
            <span style={{ flex: 1 }}/>
            <button onClick={() => { setMegaOpen(false); navigate('collections'); }} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              padding: '22px 0 20px',
              fontFamily: 'var(--sans)', fontSize: '11px',
              letterSpacing: '0.22em', textTransform: 'uppercase',
              color: 'var(--dark-mid)',
              transition: 'color 0.2s',
            }}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--dark)'}
            onMouseLeave={e => e.currentTarget.style.color = 'var(--dark-mid)'}
            >Browse all tiles &nbsp;→</button>
          </div>

          {/* ── Active tab content ───────────────────────────── */}
          <div key={megaTab} style={{ padding: '36px 56px 44px', animation: 'megaFadeIn 0.4s var(--ease-out)' }}>
            <MegaTabContent
              tab={megaTab}
              onPick={(value, label) => {
                setMegaOpen(false);
                navigate('collection', { axis: megaTab, value, label });
              }}
              onPickAll={() => {
                setMegaOpen(false);
                navigate('collections');
              }}
            />
          </div>
        </div>

        <style>{`
          /* ── Mega-menu open / tab-switch fade ────────────────── */
          @keyframes megaFadeIn {
            from { opacity: 0; transform: translateY(6px); }
            to   { opacity: 1; transform: translateY(0);   }
          }
          @keyframes megaLinkIn {
            from { opacity: 0; transform: translateY(4px); }
            to   { opacity: 1; transform: translateY(0);   }
          }
          @keyframes megaPickIn {
            from { opacity: 0; transform: translateY(8px); }
            to   { opacity: 1; transform: translateY(0);   }
          }

          /* ── Link hover: italic shift + arrow reveal ─────────── */
          .mega-link .mega-link-arrow {
            opacity: 0;
            transform: translateX(-6px);
            color: var(--terracotta);
            font-family: var(--sans);
            font-size: 12px;
            transition: opacity 0.25s var(--ease-out), transform 0.25s var(--ease-out);
            margin-left: auto;
            padding-left: 10px;
          }
          .mega-link .mega-link-suffix {
            color: var(--dark-mid);
            font-style: normal;
            transition: color 0.25s, font-style 0.25s;
          }
          .mega-link:hover .mega-link-label {
            font-style: italic;
          }
          .mega-link:hover .mega-link-suffix {
            color: var(--dark);
          }
          .mega-link:hover .mega-link-arrow {
            opacity: 1;
            transform: translateX(0);
          }

          /* ── Pick thumbs: ken-burns + caption underline ──────── */
          .mega-pick:hover .mega-pick-img {
            transform: scale(1.05);
          }
          .mega-pick .mega-pick-label {
            position: relative;
            display: inline-block;
            transition: font-style 0.25s;
          }
          .mega-pick .mega-pick-label::after {
            content: '';
            position: absolute; left: 0; right: 0; bottom: -2px;
            height: 1px;
            background: var(--dark);
            transform: scaleX(0);
            transform-origin: left center;
            transition: transform 0.4s var(--ease-out);
          }
          .mega-pick:hover .mega-pick-label {
            font-style: italic;
          }
          .mega-pick:hover .mega-pick-label::after {
            transform: scaleX(1);
          }
          .mega-pick .mega-pick-cta {
            transition: color 0.25s;
          }
          .mega-pick:hover .mega-pick-cta {
            color: var(--terracotta);
          }

          /* ── Responsive ──────────────────────────────────────── */
          @media(max-width:980px){
            .mega-content { grid-template-columns: 1fr !important; gap: 28px !important; }
          }
          @media(max-width:1020px){
            .mega-body{display:none;}
          }
        `}</style>
      </div>
    </>
  );
}

// Three small editorial picks per tab. Sit side-by-side on the right of
// the mega-menu — each is a clickable thumbnail + caption. Hand-curated
// (vs auto-derived) because the "right" three to surface is an editorial
// call. All paths point at existing assets so no extra image gen needed.
const TAB_PICKS = {
  room: [
    { value: 'bathroom', label: 'Bathroom',  img: '/assets/generated/category-hero-bath.jpg',     fallback: '/assets/generated/hero-main.jpg' },
    { value: 'kitchen',  label: 'Kitchen',   img: '/assets/generated/category-hero-floor.jpg',    fallback: '/assets/generated/lifestyle-floor-wide.jpg' },
    { value: 'outdoor',  label: 'Outdoor',   img: '/assets/categories/outdoor.jpg',               fallback: '/assets/generated/hero-outdoor.jpg' },
  ],
  colour: [
    { value: 'white',    label: 'White',     img: '/assets/categories/style-frozen-up.jpg',       fallback: '/assets/generated/lifestyle-wall-texture.jpg' },
    { value: 'beige',    label: 'Beige',     img: '/assets/journal/swan.webp',                    fallback: '/assets/generated/category-hero-floor.jpg' },
    { value: 'metallic', label: 'Metallic',  img: '/assets/categories/luxury-meteorite.jpg',      fallback: '/assets/generated/category-hero-decor.jpg' },
  ],
  style: [
    { value: 'marble',    label: 'Marble',   img: '/assets/categories/luxury-meteorite.jpg',      fallback: '/assets/generated/lifestyle-floor-wide.jpg' },
    { value: 'stone',     label: 'Stone',    img: '/assets/categories/heritage.jpg',              fallback: '/assets/generated/category-hero-floor.jpg' },
    { value: 'patterned', label: 'Patterned',img: '/assets/categories/statement.jpg',             fallback: '/assets/generated/category-hero-decor.jpg' },
  ],
  shape: [
    { value: 'subway',    label: 'Subway',   sub: '30 × 60', img: '/assets/categories/style-frozen-up.jpg',  fallback: '/assets/generated/category-hero-wall.jpg' },
    { value: 'square-60', label: 'Square',   sub: '60 × 60', img: '/assets/categories/heritage.jpg',         fallback: '/assets/generated/category-hero-floor.jpg' },
    { value: 'mosaic',    label: 'Mosaic',   sub: '20 × 20', img: '/assets/categories/style-frozen-up.jpg',  fallback: '/assets/generated/category-hero-decor.jpg' },
  ],
};

// Mega-menu tab body — text-link list on the left, three small editorial
// thumbnails side-by-side on the right. Compact, premium, contained.
// Reads window.AXES (exposed by Collections.jsx) for the link list and
// TAB_PICKS for the imagery.
function MegaTabContent({ tab, onPick, onPickAll }) {
  const fallback = {
    room:   { eyebrow: 'Where will it live?', options: [{id:'bathroom',label:'Bathroom'},{id:'kitchen',label:'Kitchen'},{id:'living',label:'Living Room'}] },
    colour: { eyebrow: 'Pick a palette',      options: [{id:'white',label:'White'},{id:'beige',label:'Beige & Cream'}] },
    style:  { eyebrow: 'A look in mind?',     options: [{id:'marble',label:'Marble Effect'},{id:'stone',label:'Stone Effect'}] },
    shape:  { eyebrow: 'Format & dimension',  options: [{id:'subway',label:'Subway · 30 × 60 cm'},{id:'mosaic',label:'Mosaic · 20 × 20 cm'}] },
  };
  const cfg = (window.AXES && window.AXES[tab]) || fallback[tab];
  const picks = TAB_PICKS[tab] || [];
  if (!cfg) return null;

  // 50/50 split: link list (2 cols inside) on the left, image picks on
  // the right. With the panel now full-width, both sides get room to
  // breathe — links are 17px serif, picks are larger 4:5 thumbs.
  const linkCols = tab === 'colour' ? 2 : 2;
  // Per-tab "View all" copy, scoped to the tab's vocabulary so it
  // reads naturally: "View all rooms" / "View all colours" / etc.
  const allLabel = ({
    room:   'View all tiles',
    colour: 'View all tiles',
    style:  'View all tiles',
    shape:  'View all tiles',
  })[tab] || 'View all tiles';

  return (
    <div className="mega-content" style={{
      display: 'grid',
      gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)',
      gap: '64px',
      alignItems: 'start',
    }}>
      {/* ── Left: eyebrow + link columns ───────────────────────── */}
      <div>
        {cfg.eyebrow && (
          <p style={{
            fontFamily: 'var(--sans)', fontSize: '10px',
            letterSpacing: '0.28em', textTransform: 'uppercase',
            color: 'var(--terracotta)',
            marginBottom: '22px',
          }}>{cfg.eyebrow}</p>
        )}

        {/* "View all" entry — sits ABOVE the specific options so the
            customer can land on the full catalogue without picking a
            filter. Distinguished from the rest with a thin divider
            below it. */}
        {onPickAll && (
          <div style={{ marginBottom: '14px', paddingBottom: '12px', borderBottom: '1px solid var(--cream-deep)' }}>
            <button
              onClick={onPickAll}
              className="mega-link mega-link-all"
              style={{
                display: 'flex', alignItems: 'center', gap: '14px',
                background: 'none', border: 'none', cursor: 'pointer',
                padding: '6px 0', textAlign: 'left', width: '100%',
                fontFamily: 'var(--serif)', fontSize: '18px', fontWeight: 400,
                fontStyle: 'italic',
                color: 'var(--terracotta)', letterSpacing: '-0.005em',
                animation: 'megaLinkIn 0.5s 0.04s both var(--ease-out)',
              }}
            >
              <span className="mega-link-label">{allLabel}</span>
              <span aria-hidden className="mega-link-arrow">→</span>
            </button>
          </div>
        )}

        <div style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${linkCols}, minmax(0, 1fr))`,
          columnGap: '40px', rowGap: '0',
        }}>
          {cfg.options.map((opt, i) => (
            <button
              key={opt.id}
              onClick={() => onPick(opt.id, opt.label)}
              className="mega-link"
              style={{
                display: 'flex', alignItems: 'center', gap: '14px',
                background: 'none', border: 'none', cursor: 'pointer',
                padding: '10px 0', textAlign: 'left',
                fontFamily: 'var(--serif)', fontSize: '17px', fontWeight: 400,
                color: 'var(--dark)', letterSpacing: '-0.005em',
                animation: `megaLinkIn 0.5s ${0.08 + i * 0.025}s both var(--ease-out)`,
              }}
            >
              {opt.swatch && (
                <span aria-hidden style={{
                  width: 16, height: 16, flex: '0 0 auto',
                  background: opt.swatch,
                  border: '1px solid var(--cream-deep)',
                  borderRadius: 1,
                }}/>
              )}
              <span className="mega-link-label">
                {opt.label} <span className="mega-link-suffix">Tiles</span>
              </span>
              <span aria-hidden className="mega-link-arrow">→</span>
            </button>
          ))}
        </div>
      </div>

      {/* ── Right: 3 picks side-by-side ───────────────────────── */}
      {picks.length > 0 && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${picks.length}, minmax(0, 1fr))`,
          gap: '16px',
        }}>
          {picks.map((p, i) => (
            <PickThumb
              key={p.value}
              pick={p}
              index={i}
              onClick={() => onPick(p.value, p.label)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// Small clickable picture-card on the right of the mega-menu. Image +
// caption + arrow. Subtle ken-burns on hover, caption underline draws.
function PickThumb({ pick, index, onClick }) {
  const [src, setSrc] = useState(pick.img);
  useEffect(() => { setSrc(pick.img); }, [pick.img]);
  return (
    <button
      onClick={onClick}
      className="mega-pick"
      style={{
        background: 'none', border: 'none', cursor: 'pointer',
        padding: 0, textAlign: 'left', display: 'block',
        animation: `megaPickIn 0.5s ${0.08 + index * 0.06}s both var(--ease-out)`,
      }}
    >
      <div style={{
        position: 'relative', overflow: 'hidden',
        aspectRatio: '4 / 5',
        background: 'var(--cream-mid)',
      }}>
        <img
          src={src}
          alt={pick.label}
          onError={() => { if (src !== pick.fallback) setSrc(pick.fallback); }}
          className="mega-pick-img"
          style={{
            width: '100%', height: '100%', objectFit: 'cover',
            display: 'block',
            transition: 'transform 1.0s var(--ease-out)',
          }}
        />
      </div>
      <div style={{ padding: '14px 0 0' }}>
        <p style={{
          fontFamily: 'var(--serif)', fontWeight: 400, fontSize: '17px',
          color: 'var(--dark)', letterSpacing: '-0.005em',
          marginBottom: '4px',
        }}>
          <span className="mega-pick-label">{pick.label}</span>
          {pick.sub && (
            <span style={{
              fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: 400,
              color: 'var(--dark-mid)', letterSpacing: '0.04em',
              marginLeft: '10px',
            }}>{pick.sub}</span>
          )}
        </p>
        <span className="mega-pick-cta" style={{
          fontFamily: 'var(--sans)', fontSize: '10px',
          letterSpacing: '0.2em', textTransform: 'uppercase',
          color: 'var(--dark-mid)',
        }}>Shop &nbsp;→</span>
      </div>
    </button>
  );
}

function MegaCard({ cat, index, visible, onClick }) {
  const [hover, setHover] = useState(false);
  const [src, setSrc] = useState(cat.img);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative', overflow: 'hidden', cursor: 'pointer',
        aspectRatio: '3/4', background: cat.color,
        border: 'none', padding: 0, textAlign: 'left',
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(14px)',
        transition: `opacity 0.5s ${index * 0.05}s var(--ease-out), transform 0.5s ${index * 0.05}s var(--ease-out)`,
      }}
    >
      <img
        src={src}
        alt={cat.label}
        onError={() => { if (src !== cat.fallback) setSrc(cat.fallback); }}
        style={{
          width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          transform: hover ? 'scale(1.07)' : 'scale(1)',
          transition: 'transform 0.9s var(--ease-out)',
        }}
      />
      <div style={{
        position: 'absolute', inset: 0,
        background: hover
          ? 'linear-gradient(to top, rgba(20,16,12,0.82) 0%, rgba(20,16,12,0.15) 55%)'
          : 'linear-gradient(to top, rgba(20,16,12,0.55) 0%, transparent 55%)',
        transition: 'background 0.35s',
      }}/>
      <div style={{ position: 'absolute', top: '14px', left: '14px', fontFamily: 'var(--sans)', fontSize: '9px', letterSpacing: '0.22em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.75)' }}>
        N° {String(index + 1).padStart(2, '0')}
      </div>
      <div style={{ position: 'absolute', left: '18px', right: '18px', bottom: '18px' }}>
        {/* New axis cards already self-label ("By Room", "By Colour", …);
            the legacy cat cards don't, so we still append "Tiles" for those. */}
        <p style={{ fontFamily: 'var(--serif)', fontSize: '24px', fontWeight: 300, color: 'white', lineHeight: 1.05, letterSpacing: '-0.01em', marginBottom: '4px' }}>
          {/^By\s/i.test(cat.label) ? cat.label : `${cat.label} Tiles`}
        </p>
        <p style={{ fontFamily: 'var(--sans)', fontSize: '10px', color: 'rgba(255,255,255,0.72)', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: '10px' }}>{cat.subtitle}</p>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: '6px',
          fontFamily: 'var(--sans)', fontSize: '10px', letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'white',
          borderBottom: '1px solid rgba(255,255,255,0.6)', paddingBottom: '2px',
          transform: hover ? 'translateX(4px)' : 'translateX(0)',
          transition: 'transform 0.25s',
        }}>Explore &nbsp;→</span>
      </div>
    </button>
  );
}

const megaLink = { background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'var(--sans)', fontSize: '12px', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--dark)' };

const mobileSub = { background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--sans)', fontSize: '14px', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--dark-mid)' };

function IconBtn({ label, fg, onClick, svg, badge, active }) {
  return (
    <button onClick={onClick} aria-label={label} style={{
      background: 'none', border: 'none', cursor: 'pointer', padding: '6px',
      position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: active ? 'var(--terracotta)' : fg, transition: 'color 0.2s',
    }}
    onMouseEnter={e => !active && (e.currentTarget.style.color = 'var(--terracotta)')}
    onMouseLeave={e => !active && (e.currentTarget.style.color = fg)}>
      {svg}
      {badge > 0 && (
        <span style={{
          position: 'absolute', top: '-2px', right: '-4px',
          background: 'var(--terracotta)', color: 'white',
          minWidth: '16px', height: '16px', borderRadius: '8px',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--sans)', fontSize: '10px', fontWeight: 500, padding: '0 4px',
        }}>{badge}</span>
      )}
    </button>
  );
}

const IconSearch = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>;
const IconUser   = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>;
const IconBag    = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 7h12l-1 13H7L6 7z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>;
const IconHeart  = <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 21s-7-4.35-7-10a4 4 0 0 1 7-2.65A4 4 0 0 1 19 11c0 5.65-7 10-7 10z"/></svg>;

function DesignAssistant() { return null; }

Object.assign(window, { Nav, DesignAssistant, NAV_AXES, NAV_CATEGORIES });
