// topbar.jsx — Ryoko · Canonical top bar (Discover style)
// Self-mounting nothing — exposes window.RyokoTopBar({ active, member, scrolled }).
// Use:
//   <window.RyokoTopBar active="trips" member={MEMBER} scrolled={scrolled} />
// active values: "discover" | "trips" | null
// Path prefix is auto-detected so links work from any subfolder.

(function () {
  const { useState, useEffect, useRef } = React;

  // Resolve relative path back to root from the current page.
  // E.g. /onboarding/Welcome.html → "../"; a page two folders deep → "../../"
  function rootPrefix() {
    try {
      const path = window.location.pathname;
      const parts = path.split("/").filter(Boolean);
      // last segment is the file (e.g. Trips.html); drop it.
      const dirs = parts.slice(0, -1);
      // depth is the number of subdirs we are inside relative to project root.
      // Heuristic: project pages live one level deep (e.g. /trips/), so depth = dirs.length.
      const depth = dirs.length;
      if (depth <= 0) return "./";
      return "../".repeat(depth);
    } catch (e) { return "../"; }
  }

  // Root-absolute hrefs ("/trips") are unified-app SPA routes and are used
  // as-is; relative hrefs are legacy pages and get the depth prefix.
  function resolveHref(prefix, target) {
    return target && target.charAt(0) === "/" ? target : prefix + target;
  }

  const NAV = [
    { id: "discover",  label: "Discover",     href: "landing/Landing.html" },
    { id: "trips",     label: "Trips",         href: "/trips" },
  ];

  const MAIN_MENU = [
    { id: "profile",       label: "Your file · Profile",        href: "/profile",      glyph: "·" },
    { id: "beafile",       label: "Bea's file · the second principal", href: "/profile/file/bea-aldercott", glyph: "·" },
    { id: "henryfile",     label: "Henry's file · the third principal", href: "/profile/file/henry-aldercott", glyph: "·" },
    { id: "homefile",      label: "Home file · between trips",    href: "/profile/home",   glyph: "·" },
    { id: "vault",         label: "Document vault",              href: "landing/Landing.html",      glyph: "·" },
    { id: "settings",      label: "Settings & privacy",          href: "profile/Settings.html",     glyph: "·" },
  ];

  const QUICK_MENU = [];

  // Default demo data — pages can override via props.
  const DEFAULT_TODAY = [
    { k: "Active", v: "5 trips" },
    { k: "Unread", v: "5 new" },
    { k: "Voucher", v: "€504" },
  ];

  const DEFAULT_RECENT = [
    { id: "n1", when: "32 min ago", who: "Camille Okafor", avatar: "CO",
      title: "A note on Wednesday's wine library", href: "landing/Landing.html" },
    { id: "n2", when: "1 h ago", who: "Pedro Castro · Pousada", avatar: "PC",
      title: "Late check-out confirmed for 18 Sept", href: "landing/Landing.html" },
  ];

  function AvatarMenu({ open, onClose, member, prefix, todayStats, recentNotifs, actingAs }) {
    const [snoozed, setSnoozed] = useState(false);
    const [discreetOn, setDiscreetOn] = useState(
      typeof window !== "undefined" && window.RyokoDiscreet ? window.RyokoDiscreet.isOn() : false
    );
    const [activePrincipal, setActivePrincipal] = useState(
      typeof window !== "undefined" && window.RyokoPrincipal ? window.RyokoPrincipal.current() : "ea"
    );
    useEffect(() => {
      if (!window.RyokoDiscreet) return;
      const unsub = window.RyokoDiscreet.subscribe(setDiscreetOn);
      setDiscreetOn(window.RyokoDiscreet.isOn());
      return unsub;
    }, []);
    useEffect(() => {
      if (!window.RyokoPrincipal) return;
      const unsub = window.RyokoPrincipal.subscribe(setActivePrincipal);
      setActivePrincipal(window.RyokoPrincipal.current());
      return unsub;
    }, []);
    if (!open) return null;
    const today = todayStats || DEFAULT_TODAY;
    const recent = recentNotifs || DEFAULT_RECENT;

    return (
      <>
        <div className="rk-tb-menu-veil" onClick={onClose} />
        <div className="rk-tb-menu rich" data-screen-label="Avatar menu">
          {/* Header */}
          <div className="rk-tb-menu-head">
            <div className="rk-tb-menu-av">{member.avatar}</div>
            <div>
              <div className="rk-tb-menu-name">{member.fullName || member.party || member.name || "Mr. Aldercott"}</div>
              <div className="rk-tb-menu-no">{member.status || "Member · No. 0418"}</div>
            </div>
          </div>

          {/* Acting-for strip (if applicable) */}
          {actingAs && (
            <div className="rk-tb-menu-acting">
              <span className="rk-tb-menu-acting-eye">👁</span>
              <span><b>{actingAs.who}</b> acting on the file · {actingAs.scope}</span>
              <a href="/profile/home" className="rk-tb-menu-acting-switch">Switch →</a>
            </div>
          )}

          {/* Principal switcher · multi-principal household */}
          {window.RyokoPrincipal && (
            <>
              <div className="rk-tb-menu-section-head">
                Switch principal · view as
                <a href="/profile/home" className="rk-tb-menu-section-link">Authority chain →</a>
              </div>
              <div className="rk-tb-menu-principals">
                {window.RyokoPrincipal.list().map(p => (
                  <button key={p.id}
                          className={`rk-tb-menu-principal-row ${activePrincipal === p.id ? "active" : ""}`}
                          onClick={(e) => { e.preventDefault(); window.RyokoPrincipal.set(p.id); }}>
                    <span className="rk-tb-menu-principal-av">{p.avatar}</span>
                    <span>
                      <div className="rk-tb-menu-principal-name">{p.short} <span style={{ color: "rgba(42,38,32,.55)", fontSize: 12 }}>· {p.name.replace(p.short, "").replace(p.short.replace(".", ""), "").trim()}</span></div>
                      <div className="rk-tb-menu-principal-role">{p.role}</div>
                    </span>
                    {activePrincipal === p.id && <span className="rk-tb-menu-principal-tick">●</span>}
                  </button>
                ))}
              </div>
            </>
          )}

          {/* Today at a glance */}
          <div className="rk-tb-menu-section-head">Today, at a glance</div>
          <div className="rk-tb-menu-stats">
            {today.map((s, i) => (
              <div key={i} className="rk-tb-menu-stat">
                <div className="rk-tb-menu-stat-k">{s.k}</div>
                <div className="rk-tb-menu-stat-v">{s.v}</div>
              </div>
            ))}
          </div>

          {/* Off-book ledger · only visible when discreet is on or has been used in session */}
          {discreetOn && window.RyokoDiscreet && window.RyokoDiscreet.getLedger().length > 0 && (
            <>
              <div className="rk-tb-menu-section-head">
                Off-book ledger · this session
                <span className="rk-tb-menu-section-link" style={{ color: "#d6a55e" }}>private to you</span>
              </div>
              <div className="rk-tb-menu-offbook">
                {window.RyokoDiscreet.getLedger().slice(0, 4).map((n, i) => (
                  <div key={i} className="rk-tb-menu-offbook-row">
                    <span className="rk-tb-menu-offbook-when">{n.when}</span>
                    <span className="rk-tb-menu-offbook-what">{n.what}</span>
                    <span className="rk-tb-menu-offbook-where">{n.surface}</span>
                  </div>
                ))}
                <div className="rk-tb-menu-offbook-foot">
                  Writes only to your off-book ledger · not in your file · purges in 30 days.
                </div>
              </div>
            </>
          )}

          {/* Recent correspondence · human messages */}
          <div className="rk-tb-menu-section-head">
            Recent correspondence
            <a href={prefix + "landing/Landing.html"} className="rk-tb-menu-section-link">All threads →</a>
          </div>
          <div className="rk-tb-menu-recent">
            {recent.slice(0, 2).map(n => (
              <a key={n.id} href={prefix + n.href} className="rk-tb-menu-recent-row">
                <span className="rk-tb-menu-recent-av">{n.avatar}</span>
                <div className="rk-tb-menu-recent-body">
                  <div className="rk-tb-menu-recent-meta">{n.who} · {n.when}</div>
                  <div className="rk-tb-menu-recent-title">{n.title}</div>
                </div>
              </a>
            ))}
          </div>

          {/* Inbox preview · system signals */}
          <div className="rk-tb-menu-section-head">
            Inbox · system signals
            <a href={prefix + "landing/Landing.html"} className="rk-tb-menu-section-link">All signals →</a>
          </div>
          <div className="rk-tb-menu-recent">
            <a href={prefix + "landing/Landing.html"} className="rk-tb-menu-recent-row system">
              <span className="rk-tb-menu-recent-av system" aria-hidden="true">·</span>
              <div className="rk-tb-menu-recent-body">
                <div className="rk-tb-menu-recent-meta">Inbox · {m.unread || 0} unread</div>
                <div className="rk-tb-menu-recent-title">Approvals · doc expiries · supplier changes · debriefs</div>
              </div>
            </a>
          </div>

          {/* Main menu */}
          <div className="rk-tb-menu-divider" />
          <div className="rk-tb-menu-section-head">Your file</div>
          <div className="rk-tb-menu-list">
            {MAIN_MENU.map((m) => (
              <a key={m.id} href={resolveHref(prefix, m.href)} className="rk-tb-menu-link">
                <span className="rk-tb-menu-row">
                  {m.label}
                  <span className="rk-tb-menu-row-arrow">→</span>
                </span>
              </a>
            ))}
          </div>

          {/* Quick actions: longform / sketch / brief */}
          <div className="rk-tb-menu-divider" />
          <div className="rk-tb-menu-quick">
            {QUICK_MENU.map(q => (
              <a key={q.id} href={prefix + q.href} className="rk-tb-menu-quick-btn">
                {q.label}
              </a>
            ))}
          </div>

          {/* Footer · toggles + sign out */}
          <div className="rk-tb-menu-divider" />
          <div className="rk-tb-menu-foot">
            <button className="rk-discreet-toggle-row"
                    onClick={(e) => {
                      e.preventDefault();
                      if (window.RyokoDiscreet) window.RyokoDiscreet.toggle();
                      else setDiscreetOn(d => !d);
                    }}
                    aria-pressed={discreetOn}>
              <span className={`rk-discreet-toggle-track ${discreetOn ? "on" : ""}`}>
                <span className="rk-discreet-toggle-thumb" />
              </span>
              <span className="rk-discreet-toggle-label">
                <span>{discreetOn ? "Off-book · 4h timer running" : "Browse off-book · 4h"}</span>
                <span className="rk-discreet-toggle-sub">
                  {discreetOn
                    ? "Saves & views are not in your file"
                    : "Hidden from household, architect & spouse"}
                </span>
              </span>
            </button>
            <button className="rk-tb-menu-toggle"
                    onClick={(e) => { e.preventDefault(); setSnoozed(s => !s); }}>
              <span className={`rk-tb-menu-toggle-track ${snoozed ? "on" : ""}`}>
                <span className="rk-tb-menu-toggle-thumb" />
              </span>
              <span className="rk-tb-menu-toggle-label">
                {snoozed ? "Notifications snoozed · 4h" : "Snooze notifications · 4h"}
              </span>
            </button>
            <a href="#" onClick={(e) => e.preventDefault()} className="rk-tb-menu-signout">
              Sign out · the file is held
            </a>
          </div>
        </div>
      </>
    );
  }

  function RyokoTopBar({ active, member, scrolled, unreadBell, todayStats, recentNotifs, actingAs }) {
    const [menuOpen, setMenuOpen] = useState(false);
    const prefix = rootPrefix();
    const baseMember = member || { avatar: "EA", status: "Member · No. 0418", unread: 0 };

    // Active principal · the topbar avatar reflects whoever is currently
    // signed-in-as. For founder principals this is invisible (matches the
    // member prop). For trial-tier (Bea, Henry), the avatar swaps and the
    // "view as" status line appears in the menu header.
    const [activePrincipalId, setActivePrincipalId] = useState(
      typeof window !== "undefined" && window.RyokoPrincipal ? window.RyokoPrincipal.current() : "ea"
    );
    useEffect(() => {
      if (!window.RyokoPrincipal) return;
      const unsub = window.RyokoPrincipal.subscribe(setActivePrincipalId);
      setActivePrincipalId(window.RyokoPrincipal.current());
      return unsub;
    }, []);
    const principalRecord = window.RyokoPrincipal
      ? window.RyokoPrincipal.list().find(p => p.id === activePrincipalId)
      : null;
    const m = principalRecord && activePrincipalId !== "ea"
      ? {
          ...baseMember,
          avatar: principalRecord.avatar,
          fullName: principalRecord.name,
          status: `${principalRecord.role} · viewing as`,
          principalActive: true,
          principalRecord,
        }
      : baseMember;

    const onSearchClick = () => {
      if (window.RyokoCmdk && window.RyokoCmdk.open) window.RyokoCmdk.open();
    };

    return (
      <header className={`rk-topbar ${scrolled ? "scrolled" : ""}`} data-screen-label="Top bar">
        <div className="rk-tb-left">
          <a href={prefix + "landing/Landing.html"} className="rk-tb-brand">RYOKO</a>
          <span className="rk-tb-brand-tag">Lifestyle &amp; Bespoke Travel</span>
        </div>
        <nav className="rk-tb-nav">
          {NAV.map(n => {
            const isActive = active === n.id;
            const cls = isActive ? "active" : "";
            if (n.href) {
              return <a key={n.id} className={cls} href={resolveHref(prefix, n.href)}>{n.label}</a>;
            }
            return <a key={n.id} className={cls}>{n.label}</a>;
          })}
        </nav>
        <div className="rk-tb-right">
          <div className="rk-tb-search-wrap">
            <svg className="rk-tb-search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="11" cy="11" r="7"/>
              <path d="m20 20-3.5-3.5"/>
            </svg>
            <button className="rk-tb-search" onClick={onSearchClick}>
              Search trips, references, or destinations
            </button>
            <span className="rk-tb-search-kbd">⌘ K</span>
          </div>
          <a className="rk-tb-msg"
             href={prefix + "landing/Landing.html"}
             aria-label="Messages · correspondence with the desk"
             title="Messages · correspondence with the desk">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M4 6h16v11a1 1 0 0 1-1 1H8l-4 3z"/>
            </svg>
            {(m.msgUnread && m.msgUnread > 0) && <span className="rk-tb-bell-pip" />}
          </a>
          <a className="rk-tb-bell"
             href={prefix + "landing/Landing.html"}
             aria-label="Inbox · system signals (approvals, expiries, supplier changes)"
             title="Inbox · system signals">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/>
              <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>
            </svg>
            {(unreadBell > 0 || (m.unread && m.unread > 0)) && <span className="rk-tb-bell-pip" />}
          </a>
          <button className={`rk-tb-avatar-trigger ${menuOpen ? "open" : ""} ${m.principalActive ? "viewing-as" : ""}`}
                  onClick={() => setMenuOpen(o => !o)}
                  title={m.principalActive ? `Viewing as ${m.fullName}` : m.status}>
            <span className="rk-tb-avatar">{m.avatar}</span>
          </button>
          <AvatarMenu open={menuOpen} onClose={() => setMenuOpen(false)} member={m} prefix={prefix}
                      todayStats={todayStats} recentNotifs={recentNotifs} actingAs={actingAs} />
        </div>
      </header>
    );
  }

  window.RyokoTopBar = RyokoTopBar;
})();
