// ============================================================
// shell.jsx — the app frame from the approved mockup: top bar,
// left menu (a pill row on phones), bottom tab bar on phones,
// and the hash router. Every page is an empty state in Phase 1.
// ============================================================
const R = window.AreteRoutes;

// ---- router ----
function useRoute() {
  // state always holds the fixed (canonical) hash, so every bad hash is
  // fixed, even two in a row
  const [hash, setHash] = React.useState(() => R.normalize(window.location, window.history).href);
  React.useEffect(() => {
    const onHash = () => setHash(R.normalize(window.location, window.history).href);
    window.addEventListener("hashchange", onHash);
    onHash();   // catch a change between first render and this effect
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return R.parse(hash);
}

// ---- top bar ----
function initials(email) {
  const name = (email || "").split("@")[0].replace(/[^a-z]/gi, " ").trim();
  if (!name) return "?";
  const parts = name.split(/\s+/);
  return (parts.length > 1 ? parts[0][0] + parts[1][0] : name.slice(0, 2)).toUpperCase();
}
function firstName(email) {
  const n = (email || "").split("@")[0].replace(/[^a-z]+.*$/i, "");
  return n ? n[0].toUpperCase() + n.slice(1).toLowerCase() : "";
}
// The display name comes from the sign-in account (Google sets full_name),
// never from a list of emails: this file is public on GitHub Pages.
function displayName(fullName, email) {
  const parts = String(fullName || "").trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return [firstName(email), initials(email)];
  return [parts[0], (parts.length > 1 ? parts[0][0] + parts[parts.length - 1][0] : parts[0].slice(0, 2)).toUpperCase()];
}

function AccountMenu({ email, fullName }) {
  const [open, setOpen] = React.useState(false);
  const box = React.useRef(null);
  const btn = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const away = (e) => { if (box.current && !box.current.contains(e.target)) setOpen(false); };
    const esc = (e) => { if (e.key === "Escape") { setOpen(false); btn.current && btn.current.focus(); } };
    document.addEventListener("mousedown", away);
    document.addEventListener("keydown", esc);
    return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc); };
  }, [open]);
  const [name, mark] = displayName(fullName, email);
  return (
    <div className="topright" ref={box}>
      {name && <span className="who">{name}</span>}
      <button ref={btn} className="acctbtn" aria-haspopup="true" aria-expanded={open}
        aria-label={"Account: " + (email || "")} onClick={() => setOpen((o) => !o)}>
        <span className="avatar" aria-hidden="true">{mark}</span>
      </button>
      {open && (
        <div className="acctmenu" role="menu">
          <div className="email">{email}</div>
          <button role="menuitem" onClick={() => { setOpen(false); window.signOut(); }}>Sign out</button>
        </div>
      )}
    </div>
  );
}

function TopBar({ top, email, fullName }) {
  return (
    <header className="topbar">
      <a className="brand" href={R.topHref(R.DEFAULT_TOP)} aria-label="Arete home">
        <span className="brand-mark" aria-hidden="true">A</span>
        <span>Arete<small>The Charlotte Social</small></span>
      </a>
      <nav className="toplinks" aria-label="Main">
        {R.TOPS.map((t) => (
          <a key={t} href={R.topHref(t)} className={t === top ? "on" : ""}
            aria-current={t === top ? "page" : undefined}>{R.MENUS[t].label}</a>
        ))}
      </nav>
      <AccountMenu email={email} fullName={fullName} />
    </header>
  );
}

function TabBar({ top }) {
  return (
    <nav className="tabbar" aria-label="Main">
      {R.TOPS.map((t) => (
        <a key={t} href={R.topHref(t)} className={t === top ? "on" : ""}
          aria-current={t === top ? "page" : undefined}>
          <Icon name={R.MENUS[t].icon} size={22} /><span>{R.MENUS[t].label}</span>
        </a>
      ))}
    </nav>
  );
}

// ---- left menu ----
function SideMenu({ top, sub }) {
  const m = R.MENUS[top];
  const extra = R.SECONDARY[top] || [];
  return (
    <aside className="side">
      <h1>{m.label}</h1>
      <nav className="sidenav" aria-label={m.label}>
        {m.items.map((it) => (
          <a key={it.id} className={"navitem" + (it.id === sub ? " on" : "")} href={R.href(top, it.id)}
            aria-current={it.id === sub ? "page" : undefined}>
            <Icon name={it.icon} /><span>{it.label}</span>
          </a>
        ))}
      </nav>
      {extra.length > 0 && <div className="sidediv" />}
      {extra.map((x) => (
        <a key={x.href} className="navitem sidesec" href={x.href}><Icon name={x.icon} /><span>{x.label}</span></a>
      ))}
    </aside>
  );
}

// ---- pages (Phase 1: every page is an empty state) ----
function EmptyPage({ item }) {
  return (
    <>
      <div className="card empty">
        <div className="in">
          <span className="empty-ic"><Icon name={item.icon} /></span>
          <span className="badge">Coming in Phase {item.phase}</span>
          <h2>Nothing here yet</h2>
          <p>{item.blurb}</p>
        </div>
      </div>
    </>
  );
}

function Shell({ email, fullName, preview }) {
  const route = useRoute();
  const title = React.useRef(null);
  const first = React.useRef(true);
  React.useEffect(() => {
    document.title = route.item.label + " · Arete";
    if (first.current) { first.current = false; return; }
    // on a page change: back to the top, focus the new page title
    window.scrollTo(0, 0);
    title.current && title.current.focus();
  }, [route.top, route.sub]);
  return (
    <>
      <a className="sr" href="#main-title" onClick={(e) => { e.preventDefault(); title.current && title.current.focus(); }}>Skip to content</a>
      <TopBar top={route.top} email={email} fullName={fullName} />
      <div className="frame">
        <SideMenu top={route.top} sub={route.sub} />
        <main className="main">
          <div className="wrap">
            <h1 className="pagetitle" id="main-title" tabIndex={-1} ref={title}>{route.item.label}</h1>
            {(() => {
              const Page = (window.ARETE_PAGES || {})[route.top + "/" + route.sub];
              return Page ? <Page key={route.href} /> : <EmptyPage item={route.item} />;
            })()}
          </div>
        </main>
      </div>
      <TabBar top={route.top} />
      {preview && <div className="preview-note">Local preview · not signed in · no data</div>}
    </>
  );
}

Object.assign(window, { Shell });
