// BookUno Web — Top nav, mobile drawer, footer, sidebar

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

/* ─── Top nav ─────────────────────────────────────────────── */
function TopNav({ active = 'discover', logoVariant = 'default', loggedIn = false, dark = false, onMenu }) {
  const [menuOpen, setMenuOpen] = useStateW(false);
  const _navSession = (() => { try { return JSON.parse(window.localStorage.getItem('bookuno.local_test_session') || 'null'); } catch { return null; } })();
  // Real Supabase session (sb-<ref>-auth-token) so live signed-in users get
  // their initials too, not just local test sessions.
  const _sbUser = (() => {
    try {
      const key = Object.keys(window.localStorage).find(k => /^sb-.+-auth-token$/.test(k));
      if (!key) return null;
      const v = JSON.parse(window.localStorage.getItem(key) || 'null');
      return v?.user || v?.currentSession?.user || null;
    } catch { return null; }
  })();
  const _navUser = _navSession?.user || _navSession?.session?.user || _sbUser;
  // Show logged-in chrome only when a real session exists — a hardcoded
  // loggedIn prop with no session used to render a "?" avatar for guests.
  const authed = !!_navUser;
  const _navName = _navUser?.user_metadata?.full_name || _navUser?.name || '';
  const _navEmail = _navUser?.email || '';
  const _navInitials = _navName ? _navName.split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase() : (_navEmail ? _navEmail[0].toUpperCase() : '?');
  const links = [
    { id: 'discover', label: 'Discover', href: '/#/discover' },
    { id: 'categories', label: 'Categories', href: '/#/categories' },
    { id: 'business', label: 'For business', href: '/#/business' },
    { id: 'help', label: 'Help', href: '/#/help' },
  ];
  // Lock body scroll while the drawer is open
  useEffectW(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const openMenu = () => { setMenuOpen(true); if (onMenu) onMenu(); };

  // Render drawer+scrim via portal so they escape the .web container-type:inline-size
  // context (which would otherwise constrain position:fixed to be relative to .web,
  // not the viewport).
  const drawer = ReactDOM.createPortal(
    <>
      <div className={`nav-drawer-scrim ${menuOpen ? 'open' : ''}`} onClick={() => setMenuOpen(false)}/>
      <div className={`nav-drawer ${menuOpen ? 'open' : ''}`} role="dialog" aria-modal="true" aria-hidden={!menuOpen}>
        <div className="nav-drawer-head">
          <BULogo variant={logoVariant} size={28}/>
          <button className="nav-drawer-close" onClick={() => setMenuOpen(false)} aria-label="Close menu">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
          </button>
        </div>
        <div className="nav-drawer-links">
          {links.map(l => (
            <a key={l.id} href={l.href} className={l.id === active ? 'act' : ''} onClick={() => setMenuOpen(false)}>{l.label}</a>
          ))}
        </div>
        <div className="nav-drawer-cta">
          {!authed && <a className="btn ghost lg" href="/#/auth" style={{ background: dark ? 'rgba(255,255,255,0.1)' : 'var(--chip)', color: dark ? '#fff' : undefined }}>Log in</a>}
          {authed
            ? <a className="btn primary lg" href="/app.html#/account">My account</a>
            : <a className="btn primary lg" href="/#/auth?mode=register">Sign up</a>}
        </div>
      </div>
    </>,
    document.body
  );

  return (
    <>
      <nav className={`nav ${dark ? 'dark' : ''}`} style={dark ? { background: 'rgba(15,14,30,0.6)', borderColor: 'rgba(255,255,255,0.08)' } : null}>
        <div className="nav-inner">
          <a href="/#/discover" className="nav-logo" style={{ display: 'inline-flex' }}><BULogo variant={logoVariant} size={28} dark={dark}/></a>
          <div className="nav-links">
            {links.map(l => (
              <a key={l.id} href={l.href} className={`nav-link ${l.id === active ? 'act' : ''}`} style={dark && l.id !== active ? { color: 'rgba(255,255,255,0.65)' } : null}>{l.label}</a>
            ))}
          </div>
          <a className="nav-search" href="/#/search" style={dark ? { background: 'rgba(255,255,255,0.08)', boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.1)' } : null}>
            <Ic.search style={{ width: 16, height: 16, color: dark ? 'rgba(255,255,255,0.6)' : 'var(--muted)' }}/>
            <input placeholder="Search businesses or services…" style={dark ? { color: '#fff' } : null} readOnly tabIndex={-1}/>
            <span className="kbd">⌘K</span>
          </a>
          <div className="nav-actions">
            {!authed ? (
              <>
                <a className="btn ghost sm desktop-only" href="/#/auth" style={dark ? { background: 'rgba(255,255,255,0.1)', color: '#fff' } : null}>Log in</a>
                <a className="btn primary sm" href="/#/auth?mode=register">Sign up</a>
              </>
            ) : (
              <>
                <a className="icon-btn" href="/app.html#/account" style={dark ? { background: 'rgba(255,255,255,0.1)', boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.1)', color: '#fff' } : null} aria-label="Notifications">
                  <Ic.bell style={{ width: 18, height: 18 }}/>
                  <span className="dot"/>
                </a>
                <a className="icon-btn" href="/app.html#/account" style={dark ? { background: 'rgba(255,255,255,0.1)', boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.1)', color: '#fff' } : null} aria-label="Messages">
                  <Ic.msg style={{ width: 18, height: 18 }}/>
                </a>
                <a href="/app.html#/account" aria-label="My account" style={{ width: 38, height: 38, borderRadius: 12, background: 'linear-gradient(135deg, #FFB4A2, #FF7B9C)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13, textDecoration: 'none' }}>{_navInitials}</a>
              </>
            )}
            <button className="nav-menu-btn" onClick={openMenu} aria-label="Open menu" style={dark ? { background: 'rgba(255,255,255,0.1)', boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.1)', color: '#fff' } : null}>
              <svg viewBox="0 0 24 24" width="20" height="20" fill="none"><path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>
            </button>
          </div>
        </div>
      </nav>
      {drawer}
    </>
  );
}

/* ─── Footer column (collapsible on mobile) ───────────────── */
function FooterCol({ title, links }) {
  const [open, setOpen] = useStateW(false);
  return (
    <div className={`footer-col ${open ? 'open' : ''}`}>
      <h5 onClick={() => setOpen(o => !o)}>
        {title}
        <svg className="footer-chev" viewBox="0 0 24 24" width="16" height="16" fill="none"><path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </h5>
      <div className="footer-col-body">
        {links.map(l => <a key={l.label} href={l.href}>{l.label}</a>)}
      </div>
    </div>
  );
}

/* ─── Footer ──────────────────────────────────────────────── */
function Footer({ logoVariant = 'default' }) {
  return (
    <footer className="footer">
      <div className="container">
        <div>
          <BULogo variant={logoVariant} size={28} dark/>
          <p style={{ marginTop: 14, fontSize: 13.5, color: 'rgba(255,255,255,0.7)', maxWidth: 280, lineHeight: 1.55 }}>
            All bookings. One platform. Find and book every kind of local service business.
          </p>
          <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
            <span className="btn sm" style={{ background: 'rgba(255,255,255,0.08)', color: 'rgba(255,255,255,0.7)', cursor: 'default' }}><Ic.apple style={{ width: 14, height: 14 }}/> iOS app soon</span>
            <span className="btn sm" style={{ background: 'rgba(255,255,255,0.08)', color: 'rgba(255,255,255,0.7)', cursor: 'default' }}><Ic.google style={{ width: 14, height: 14 }}/> Android soon</span>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
            <a href="https://twitter.com/bookuno" target="_blank" rel="noopener noreferrer" aria-label="Twitter / X"
              style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center', color: '#fff', textDecoration: 'none' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.746l7.737-8.835L1.254 2.25H8.08l4.259 5.631 5.905-5.631zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
            </a>
            <a href="https://instagram.com/bookuno" target="_blank" rel="noopener noreferrer" aria-label="Instagram"
              style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center', color: '#fff', textDecoration: 'none' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
            </a>
          </div>
        </div>
        <FooterCol title="Customers" links={[
          { label: 'Discover', href: '/#/discover' },
          { label: 'Search', href: '/#/search' },
          { label: 'Categories', href: '/#/categories' },
        ]}/>
        <FooterCol title="Business" links={[
          { label: 'For business', href: '/#/business' },
          { label: 'Pricing', href: '/app.html#/pricing' },
        ]}/>
        <FooterCol title="Company" links={[
          { label: 'Contact', href: '/#/help' },
        ]}/>
        <FooterCol title="Support" links={[
          { label: 'Help centre', href: '/#/help' },
          { label: 'Privacy', href: '/privacy.html' },
          { label: 'Terms', href: '/terms.html' },
        ]}/>
      </div>
      <div className="footer-bot">
        <div>© 2026 Bookuno · Made with ❤️ in the UK</div>
        <div style={{ display: 'flex', gap: 14 }}>
          <a href="/#/discover" style={{ display: 'inline' }}>English (UK)</a>
          <a href="/#/discover" style={{ display: 'inline' }}>GBP £</a>
          <a href="/privacy.html" style={{ display: 'inline' }}>Privacy</a>
          <a href="/terms.html" style={{ display: 'inline' }}>Terms</a>
          <a href="/privacy.html#cookies" style={{ display: 'inline' }}>Cookies</a>
        </div>
      </div>
    </footer>
  );
}

/* ─── Customer side nav (account) ─────────────────────────── */
function CustomerSide({ active = 'book', onNav }) {
  // Read session from localStorage
  const localSession = (() => {
    try { return JSON.parse(window.localStorage.getItem('bookuno.local_test_session') || 'null'); } catch { return null; }
  })();
  const sessionUser = localSession?.user || localSession?.session?.user;
  const userName = sessionUser?.user_metadata?.full_name || sessionUser?.name || '';
  const userEmail = sessionUser?.email || '';
  const initials = userName ? userName.split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase() : (userEmail ? userEmail[0].toUpperCase() : '?');

  const [showProfile, setShowProfile] = React.useState(active === 'profile');
  const [editName, setEditName] = React.useState(userName);
  const [editPhone, setEditPhone] = React.useState(sessionUser?.phone || '');
  const [saving, setSaving] = React.useState(false);
  const [saveMsg, setSaveMsg] = React.useState('');

  async function handleSave(e) {
    e.preventDefault();
    setSaving(true);
    setSaveMsg('');
    try {
      if (window.BOOKUNO_API?.updateProfile) {
        await window.BOOKUNO_API.updateProfile({ name: editName.trim(), phone: editPhone.trim() });
      }
      setSaveMsg('Saved.');
    } catch (err) {
      setSaveMsg(err?.message || 'Could not save. Please try again.');
    } finally {
      setSaving(false);
      setTimeout(() => setSaveMsg(''), 2500);
    }
  }

  async function handleSignOut() {
    try { await window.BOOKUNO_API?.signOut?.(); } catch {}
    window.localStorage.removeItem('bookuno.local_test_session');
    window.location.hash = '#/auth';
  }

  const nav = (id) => { onNav?.(id); };
  const groups = [
    { g: 'PERSONAL', items: [
      { id: 'home', i: Ic.home, l: 'Overview', onClick: () => nav('home') },
      { id: 'book', i: Ic.cal, l: 'My bookings', onClick: () => nav('book') },
      { id: 'saved', i: Ic.heart, l: 'Saved', href: '/app.html#/search' },
      { id: 'msg', i: Ic.msg, l: 'Messages', onClick: () => nav('msg') },
      { id: 'rev', i: Ic.star, l: 'Reviews', onClick: () => nav('rev') },
      { id: 'gift', i: Ic.gift, l: 'Offers', href: '/app.html#/search' },
    ]},
    { g: 'ACCOUNT', items: [
      { id: 'profile', i: Ic.user, l: 'Profile', onClick: () => { setShowProfile(p => !p); nav('profile'); } },
      { id: 'pay', i: Ic.card, l: 'Payments', onClick: () => nav('pay') },
      { id: 'privacy', i: Ic.shield, l: 'Privacy & data', onClick: () => nav('privacy') },
      { id: 'help', i: Ic.spark, l: 'Help', href: '/#/help' },
    ]},
  ];
  return (
    <aside className="side">
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px 14px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ width: 44, height: 44, borderRadius: 14, background: 'linear-gradient(135deg, #FFB4A2, #FF7B9C)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 15 }}>{initials}</div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: -0.01 }}>{userName || 'My account'}</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis' }}>{userEmail}</div>
        </div>
      </div>
      <div style={{ paddingTop: 6 }}>
        {groups.map((gr, gi) => (
          <div key={gi}>
            <div className="side-group">{gr.g}</div>
            {gr.items.map(it => {
              const Icon = it.i;
              const isAct = showProfile ? it.id === 'profile' : it.id === active;
              return (
                <button
                  key={it.id}
                  type="button"
                  className={`side-item ${isAct ? 'act' : ''}`}
                  onClick={() => { if (it.onClick) it.onClick(); else if (it.href) window.location.href = it.href; }}
                >
                  <Icon style={{ width: 18, height: 18 }}/>
                  <span style={{ flex: 1 }}>{it.l}</span>
                  {it.m && <span style={{ fontSize: 10.5, fontWeight: 800, padding: '2px 7px', borderRadius: 999, background: isAct ? 'rgba(255,255,255,0.22)' : 'var(--pri-50)', color: isAct ? '#fff' : 'var(--pri-700)' }}>{it.m}</span>}
                </button>
              );
            })}
          </div>
        ))}
      </div>

      {/* Profile inline section */}
      {showProfile && (
        <div style={{ margin: '12px 8px 0', padding: 14, borderRadius: 14, background: 'var(--bg)', border: '1px solid var(--line)' }}>
          <div className="side-group" style={{ padding: '0 0 8px' }}>PROFILE</div>
          <form onSubmit={handleSave} style={{ display: 'grid', gap: 10 }}>
            <div>
              <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', display: 'block', marginBottom: 4 }}>Name</label>
              <input
                value={editName}
                onChange={e => setEditName(e.target.value)}
                placeholder="Your name"
                style={{ width: '100%', border: '1.5px solid var(--line)', borderRadius: 10, padding: '8px 10px', fontSize: 13.5, fontWeight: 600, outline: 'none', background: '#fff' }}
              />
            </div>
            <div>
              <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', display: 'block', marginBottom: 4 }}>Email</label>
              <div style={{ fontSize: 13, color: 'var(--muted)', padding: '8px 10px', background: 'var(--chip)', borderRadius: 10 }}>{userEmail || '—'}</div>
            </div>
            <div>
              <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', display: 'block', marginBottom: 4 }}>Phone</label>
              <input
                value={editPhone}
                onChange={e => setEditPhone(e.target.value)}
                placeholder="07123 456789"
                inputMode="tel"
                style={{ width: '100%', border: '1.5px solid var(--line)', borderRadius: 10, padding: '8px 10px', fontSize: 13.5, fontWeight: 600, outline: 'none', background: '#fff' }}
              />
            </div>
            <button type="submit" className="btn primary sm block" disabled={saving} style={{ marginTop: 2 }}>{saving ? 'Saving…' : 'Save changes'}</button>
            {saveMsg && <div style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>{saveMsg}</div>}
          </form>
          <button
            type="button"
            onClick={handleSignOut}
            style={{ marginTop: 12, width: '100%', padding: '9px 12px', borderRadius: 10, border: '1.5px solid var(--line)', background: 'transparent', fontSize: 13, fontWeight: 700, color: 'var(--muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Sign out
          </button>
        </div>
      )}
    </aside>
  );
}

/* ─── Business side nav (dashboard) ───────────────────────── */
function BusinessSide({ active = 'today' }) {
  const groups = [
    { g: 'WORKSPACE', items: [
      { id: 'today', i: Ic.home, l: 'Today', m: 8, href: '/business-app/app.html#today' },
      { id: 'cal', i: Ic.cal, l: 'Calendar', href: '/business-app/app.html#today' },
      { id: 'bookings', i: Ic.clock, l: 'Bookings', href: '/business-app/app.html#bookings' },
      { id: 'customers', i: Ic.user, l: 'Customers', href: '/business-app/app.html#customers' },
      { id: 'msg', i: Ic.msg, l: 'Messages', m: 3, href: '/business-app/app.html#messages' },
    ]},
    { g: 'BUSINESS', items: [
      { id: 'storefront', i: Ic.globe, l: 'Storefront', href: '/app.html#/public?business=north-street-barbers' },
      { id: 'svc', i: Ic.tag, l: 'Services', href: '/business-app/app.html#services' },
      { id: 'staff', i: Ic.user, l: 'Staff', href: '/business-app/app.html#staff' },
      { id: 'offers', i: Ic.gift, l: 'Offers & marketing', href: '/business-app/app.html#offers' },
      { id: 'insight', i: Ic.spark, l: 'Insights', href: '/business-app/app.html#insights' },
      { id: 'pay', i: Ic.card, l: 'Payouts', href: '/business-app/app.html#payouts' },
    ]},
    { g: 'SETTINGS', items: [
      { id: 'set', i: Ic.shield, l: 'Settings', href: '/business-app/app.html#settings' },
      { id: 'help', i: Ic.msg, l: 'Help', href: '/#/help' },
    ]},
  ];
  return (
    <aside className="side">
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px 14px', borderBottom: '1px solid var(--line)' }}>
        <Cover seed={0} h={44} r={12} style={{ width: 44, padding: 0, alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <span style={{ color: '#fff', fontWeight: 900, fontSize: 18 }}>K</span>
        </Cover>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: -0.01 }}>Knot &amp; Comb</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Barber · Pro plan</div>
        </div>
        <Ic.chevDn style={{ width: 14, height: 14, color: 'var(--muted)' }}/>
      </div>
      <div style={{ paddingTop: 6 }}>
        {groups.map((gr, gi) => (
          <div key={gi}>
            <div className="side-group">{gr.g}</div>
            {gr.items.map(it => {
              const Icon = it.i;
              const isAct = it.id === active;
              return (
                <button
                  key={it.id}
                  type="button"
                  className={`side-item ${isAct ? 'act' : ''}`}
                  onClick={() => { if (it.href) window.location.href = it.href; }}
                >
                  <Icon style={{ width: 18, height: 18 }}/>
                  <span style={{ flex: 1 }}>{it.l}</span>
                  {it.m && <span style={{ fontSize: 10.5, fontWeight: 800, padding: '2px 7px', borderRadius: 999, background: isAct ? 'rgba(255,255,255,0.22)' : 'var(--pri-50)', color: isAct ? '#fff' : 'var(--pri-700)' }}>{it.m}</span>}
                </button>
              );
            })}
          </div>
        ))}
      </div>
    </aside>
  );
}

Object.assign(window, { TopNav, Footer, FooterCol, CustomerSide, BusinessSide });
