/* v3/topbar-hero.jsx — two-tier topbar + editorial hero */
const { useState: useV3S, useEffect: useV3E } = React;

const V3_NAV_PRIMARY = [
  { href: "/dashboard.html",   text: "Dashboard",         active: true },
  { href: "/macro.html",       text: "Macro" },
  { href: "/13f.html",         text: "Allocators" },
  { href: "/bulletin.html",    text: "Signals" },
  { href: "/hyperliquid.html", text: "HyperLiquid" },
  { href: "/ai-tracker.html",  text: "AI Research" },
  { href: "/earnings.html",    text: "Earnings" },
  { href: "/utilities.html",   text: "Utilities & Power" },
  { href: "/cpi.html",         text: "CPI Dashboard" },
  { href: "/account.html",     text: "Account" },
];

// Mirrors MORE_ITEMS in src/shared/header-v3.js — pages that don't fit in
// the primary nav, surfaced via a small "More ▾" dropdown.
// Names mirror the dashboard Trailhead grid (src/v3/trailhead.jsx).
const V3_MORE_ITEMS = [
  { href: "/heatmap.html",                     name: "Heatmap",           desc: "S&P 500 sector heatmap" },
  { href: "/screener.html",                    name: "Stock Screener",    desc: "Multi-factor stock screener" },
  { href: "/details.html",                     name: "Details",           desc: "Per-ticker deep dive · chart · fundamentals" },
  { href: "/portfolio.html",                   name: "Portfolio",         desc: "Track your holdings" },
  { href: "/commodities.html",                 name: "Commodities & FX",  desc: "Commodity & currency markets" },
  { href: "/relative-strength.html",           name: "Relative Strength", desc: "RS rankings & momentum" },
  { href: "/ai-tracker.html?tab=data-centers", name: "Data Centers",      desc: "Hyperscaler capacity & power demand" },
  { href: "/newsletter.html",                  name: "Newsletter",        desc: "Daily market briefings to your inbox" },
  { href: "/about.html",                       name: "About",             desc: "Why TMT · how it's built" },
];

function NavMoreV3() {
  const [open, setOpen] = useV3S(false);
  const [pos, setPos] = useV3S({ top: 0, left: -9999 });
  const btnRef = React.useRef(null);
  const menuRef = React.useRef(null);

  const place = React.useCallback(() => {
    const btn = btnRef.current;
    const menu = menuRef.current;
    if (!btn || !menu) return;
    const r = btn.getBoundingClientRect();
    const w = menu.offsetWidth || 240;
    setPos({
      top: r.bottom + 6,
      left: Math.max(8, Math.min(window.innerWidth - w - 8, r.right - w)),
    });
  }, []);

  useV3E(() => {
    if (!open) return;
    place();
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    const onResize = () => place();
    document.addEventListener("keydown", onKey);
    window.addEventListener("resize", onResize);
    window.addEventListener("scroll", onResize, { passive: true });
    return () => {
      document.removeEventListener("keydown", onKey);
      window.removeEventListener("resize", onResize);
      window.removeEventListener("scroll", onResize);
    };
  }, [open, place]);

  // Portal the menu to body — the .topbar has backdrop-filter, which creates
  // a containing block for position:fixed descendants. Without the portal the
  // panel would anchor to the topbar instead of the viewport.
  const menuPortal = open && ReactDOM.createPortal(
    <>
      <div className="more-backdrop open" onClick={() => setOpen(false)} />
      <div
        ref={menuRef}
        className="more-menu open"
        role="menu"
        aria-label="More tools"
        style={{ top: pos.top, left: pos.left }}
      >
        {V3_MORE_ITEMS.map(it => (
          <a key={it.href} className="more-item" href={it.href}>
            <span className="more-item-name">{it.name}</span>
            <span className="more-item-desc">{it.desc}</span>
          </a>
        ))}
      </div>
    </>,
    document.body
  );

  return (
    <>
      <button
        ref={btnRef}
        type="button"
        aria-expanded={open}
        aria-haspopup="true"
        onClick={(e) => { e.preventDefault(); e.stopPropagation(); setOpen(o => !o); }}
      >
        More <span className="chev">▾</span>
      </button>
      {menuPortal}
    </>
  );
}

function MobileNavV3({ open, onClose }) {
  useV3E(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  return (
    <>
      <div className={"mobile-nav-backdrop" + (open ? " open" : "")} onClick={onClose} />
      <aside className={"mobile-nav" + (open ? " open" : "")} role="dialog" aria-label="Navigation" aria-hidden={!open}>
        <div className="mobile-nav-hd">
          <span className="brand-word">The Market <em>Terminal</em></span>
          <button className="x" type="button" aria-label="Close menu" onClick={onClose}>✕</button>
        </div>
        <div className="mobile-nav-section">Browse</div>
        <div className="mobile-nav-list">
          {V3_NAV_PRIMARY.map(it => (
            <a key={it.href}
               href={it.href}
               className={it.active ? "active" : ""}
               aria-current={it.active ? "page" : undefined}
               onClick={onClose}>
              {it.text}
            </a>
          ))}
        </div>
      </aside>
    </>
  );
}

function deriveAvatarInitials() {
  try {
    let name = '';
    let email = '';
    const sb = window.supabaseAuth && typeof window.supabaseAuth.getUser === 'function'
      ? window.supabaseAuth.getUser() : null;
    if (sb) {
      const meta = sb.user_metadata || {};
      name = meta.full_name || meta.name || meta.display_name || '';
      email = sb.email || '';
    }
    if (!name) {
      const ls = window.localStorageAuth && typeof window.localStorageAuth.getCurrentUser === 'function'
        ? window.localStorageAuth.getCurrentUser() : null;
      if (ls) {
        name = ls.displayName || '';
        email = email || ls.email || '';
      }
    }
    const src = (name || (email ? email.split('@')[0] : '')).trim();
    if (!src) return '';
    const parts = src.split(/[\s._\-]+/).filter(Boolean);
    if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
    return src.slice(0, 2).toUpperCase();
  } catch (_) { return ''; }
}

function TopbarV3({ onOpenWatchlist, onOpenTweaks, onOpenCmd }) {
  const t = useClock(1000);
  const [mobileOpen, setMobileOpen] = useV3S(false);
  const [initials, setInitials] = useV3S(deriveAvatarInitials);
  useV3E(() => {
    const update = () => setInitials(deriveAvatarInitials());
    const t1 = setTimeout(update, 400);
    const t2 = setTimeout(update, 1500);
    window.addEventListener("authStateChanged", update);
    return () => {
      clearTimeout(t1); clearTimeout(t2);
      window.removeEventListener("authStateChanged", update);
    };
  }, []);
  return (
    <>
    <header className="topbar">
      <div className="row1">
        <button
          className="tb-burger"
          type="button"
          aria-label="Open menu"
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen(o => !o)}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
            <path d="M4 7h16"/><path d="M4 12h16"/><path d="M4 17h16"/>
          </svg>
        </button>
        <div className="brand">
          <svg className="brand-mark tmt-mountain" viewBox="0 0 32 24" aria-hidden="true">
            {/* back ridge (warm/green accent) */}
            <path d="M1 21 L9 8 L13 14 L17 6 L22 13 L27 7 L31 21 Z" fill="currentColor" opacity="0.35"/>
            {/* front peak (solid) */}
            <path d="M1 21 L8 10 L12 15 L16 9 L21 16 L26 11 L31 21 Z" fill="currentColor" opacity="0.9"/>
            {/* accent snow-cap on main peak */}
            <path d="M8 10 L10 12.5 L12 10.2 L11 8.8 L9.5 10.2 L8.5 9 Z" fill="var(--paper)" opacity="0.9"/>
          </svg>
          <div className="brand-word">The Market <em>Terminal</em></div>
          <span className="brand-tag">Beta</span>
        </div>
        <nav className="nav-main">
          {V3_NAV_PRIMARY.filter(it => it.text !== "Account").map(it => (
            <a key={it.href} href={it.href} className={it.active ? "active" : undefined}>{it.text}</a>
          ))}
          <NavMoreV3 />
        </nav>
        <div className="tb-actions">
          <button className="tb-btn" onClick={onOpenWatchlist}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M12 2l2.4 7.2H22l-6 4.4 2.3 7.2L12 16.6 5.7 20.8 8 13.6 2 9.2h7.6z"/></svg>
            Watchlist
          </button>
          <button className="tb-btn" onClick={onOpenTweaks} style={{ position: "relative" }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="2.5"/><path d="M19 12a7 7 0 0 1-.1 1.2l2 1.6-2 3.4-2.4-1a7 7 0 0 1-2 1.2l-.4 2.6h-4l-.4-2.6a7 7 0 0 1-2-1.2l-2.4 1-2-3.4 2-1.6A7 7 0 0 1 5 12a7 7 0 0 1 .1-1.2l-2-1.6 2-3.4 2.4 1a7 7 0 0 1 2-1.2L10 3h4l.4 2.6a7 7 0 0 1 2 1.2l2.4-1 2 3.4-2 1.6c.1.4.2.8.2 1.2z"/></svg>
          </button>
          <div className="tb-avatar">{initials}</div>
        </div>
      </div>
      <div className="row2">
        <button className="search-v3" onClick={onOpenCmd} title="Search or command (⌘K)">
          <span className="g">⌕</span>
          <span className="p">Search symbols, news, funds, or type a command…</span>
          <span className="kbd">⌘K</span>
        </button>
        <div className="session-v3">
          <span className="pulse" />
          <span>NYSE · OPEN</span>
          <span className="sep">|</span>
          <span className="tabnum">{fmtClock(t)} ET</span>
          <span className="sep session-xtra">|</span>
          <span className="session-xtra" style={{ color: "var(--ink-3)" }}>Session T−3h 12m</span>
        </div>
      </div>
    </header>
    {/* Mobile nav must live OUTSIDE the .topbar so its fixed positioning
        escapes the topbar's backdrop-filter containing block */}
    <MobileNavV3 open={mobileOpen} onClose={() => setMobileOpen(false)} />
    </>
  );
}

const HERO_CATALYST_FALLBACK = {
  label: "This week",
  items: [{ d: "—", t: "Earnings calendar", hint: "Loading…", tone: "" }],
};

// Picks the soonest 4 prints from `pool`, dedup'd by symbol, sorted earliest first.
function shapeCatalysts(pool) {
  const seen = new Set();
  const dedup = [];
  for (const e of pool) {
    if (!e.symbol || seen.has(e.symbol)) continue;
    seen.add(e.symbol);
    dedup.push(e);
  }
  dedup.sort((a, b) => new Date(a.earningsDate) - new Date(b.earningsDate));
  return dedup.slice(0, 4).map((e, i) => {
    const dt = new Date(e.earningsDate);
    let dLabel = "—";
    if (!isNaN(dt.getTime())) {
      const wd = dt.toLocaleDateString('en-US', { weekday: 'short', timeZone: 'America/New_York' });
      const md = dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'America/New_York' });
      dLabel = `${wd} ${md}`;
    }
    const eps = e.epsEstimate != null ? `EPS est ${Number(e.epsEstimate).toFixed(2)}` : "Earnings";
    const hint = e.isEstimate ? `${eps} · est. date` : eps;
    return {
      d: dLabel,
      t: `${e.symbol} earnings`,
      hint,
      tone: i === 0 ? "warm" : "",
      href: `/details.html?symbol=${encodeURIComponent(e.symbol)}`,
    };
  });
}

function useEarningsCatalysts() {
  const [state, setState] = useV3S(HERO_CATALYST_FALLBACK);
  useV3E(() => {
    let alive = true;
    (async () => {
      try {
        const result = await window.TMT_API.getJSON('/earnings-calendar');
        if (!alive || !result || !result.success || !result.data) return;
        // Response shape: { data: { thisWeek, nextWeek, upcoming, ... } }
        const data = result.data;
        const thisWeek = Array.isArray(data.thisWeek) ? data.thisWeek : [];
        const nextWeek = Array.isArray(data.nextWeek) ? data.nextWeek : [];
        const upcoming = Array.isArray(data.upcoming) ? data.upcoming : [];

        let pool = thisWeek;
        let label = "This week";
        if (!pool.length) { pool = nextWeek; label = "Next week"; }
        if (!pool.length) { pool = upcoming; label = "Ahead"; }

        const items = shapeCatalysts(pool);
        if (!items.length) {
          setState({ label: "This week", items: [{ d: "—", t: "No upcoming earnings", hint: "Calendar quiet", tone: "" }] });
          return;
        }
        setState({ label, items });
      } catch (err) {
        if (alive) setState({
          label: "This week",
          items: [{ d: "—", t: "Earnings feed connecting", hint: "See calendar", tone: "", href: "/earnings.html" }],
        });
      }
    })();
    return () => { alive = false; };
  }, []);
  return state;
}

function HeroStrip() {
  const catalysts = useEarningsCatalysts();

  return (
    <section className="hero">
      <div className="hero-bottom">
        <div className="hero-catalysts">
          <span className="hca-label">{catalysts.label}</span>
          {catalysts.items.map((c, i) => (
            <a key={i} className={"hca-item tone-" + (c.tone || "")} href={c.href || "/earnings.html"}>
              <span className="hca-d">{c.d}</span>
              <span className="hca-t">{c.t}</span>
              <span className="hca-h">{c.hint}</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { TopbarV3, HeroStrip, MobileNavV3 });
