const { useState, useEffect, useMemo, useRef } = React;

/* Main app — top-level router for the prototype */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "populated": true
}/*EDITMODE-END*/;

// Prototype chrome (JUMP pill + tweaks) only shows with ?proto=1 — the site is live.
const PROTO = new URLSearchParams(window.location.search).has("proto");
// The map app: /map/ in production (site at domain root), ../index.html in the
// dev layout (site under /public-site/). Same origin either way → shared session.
const MAP_URL = window.location.pathname.includes("/public-site/") ? "../index.html" : "/map/";
const VALID_SCREENS = ["landing","login","signup","dashboard","billing","extension","admin_users","admin_analytics"];
function screenFromHash() {
  const h = (window.location.hash || "").replace(/^#\/?/, "");
  if (h.startsWith("waitlist")) return h;
  return VALID_SCREENS.includes(h) ? h : "landing";
}

function App() {
  const [screen, setScreen] = useState(screenFromHash());
  const [user, setUser] = useState({ ...window.CONTACTIQ_DATA.CURRENT_USER });
  const [t, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];
  const populated = t.populated;

  // Hash routing: deep links + back/forward work like a real site.
  useEffect(() => {
    const onHash = () => setScreen(screenFromHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Keep app-level `user` synced with the real Supabase profile + subscription
  // so every screen (dashboard banner, billing, etc.) reflects the live session
  // instead of the Maya Chen mock the prototype started with. On sign-out we
  // reset to the mock so the public/demo path stays usable.
  const ciq = window.ContactIQ ? window.ContactIQ.useContactIQ() : { isAuthed: false, profile: null, subscription: null };
  useEffect(() => {
    if (!ciq.isAuthed) {
      setUser({ ...window.CONTACTIQ_DATA.CURRENT_USER });
      return;
    }
    setUser(u => ({
      ...u,
      id:        (ciq.profile && ciq.profile.id) || u.id,
      name:      (ciq.profile && (ciq.profile.full_name || ciq.profile.email)) || u.name,
      email:     (ciq.profile && ciq.profile.email) || u.email,
      company:   (ciq.profile && ciq.profile.company) || u.company,
      role:      (ciq.profile && ciq.profile.role) || u.role,
      plan:      (ciq.subscription && ciq.subscription.plan) || u.plan,
      cardLast4: (ciq.subscription && ciq.subscription.card_last4) || u.cardLast4,
      paymentMethod: (ciq.subscription && ciq.subscription.card_brand) ? "card" : u.paymentMethod,
      trialEnds: (ciq.subscription && ciq.subscription.trial_ends_at)
                 ? ciq.subscription.trial_ends_at.slice(0, 10) : u.trialEnds,
    }));
  }, [ciq.isAuthed, ciq.profile, ciq.subscription]);

  // After sign-in, jump straight to the dashboard if still on a public screen.
  useEffect(() => {
    if (ciq.isAuthed && ["landing","login","signup"].includes(screen)) setScreen("dashboard");
  }, [ciq.isAuthed]);

  const go = (s) => {
    // "map" = the live map component (separate app, same origin → SSO via shared session)
    if (s === "map") { window.location.href = MAP_URL; return; }
    setScreen(s);
    try { window.history.pushState({}, "", "#" + s); } catch (_) {}
    // Scroll any scrollable container to top
    requestAnimationFrame(() => {
      document.querySelectorAll(".proto-screen, .work, .lp").forEach(el => el.scrollTop = 0);
    });
  };

  // Group label for the navigator
  let group;
  if (["landing", "login", "signup"].includes(screen)) group = "Public";
  else if (["admin_users", "admin_analytics"].includes(screen)) group = "Admin";
  else group = "Account";

  const render = () => {
    // Waitlist routes: "waitlist:full_report" / "waitlist:map" / "waitlist"
    if (screen.startsWith("waitlist")) {
      const target = screen.includes(":") ? screen.split(":")[1] : "upgrade";
      return <WaitlistPage go={go} user={user} target={target}/>;
    }
    switch (screen) {
      case "landing":   return <LandingPage   go={go}/>;
      case "signup":    return <RegisterPage  go={go} setUser={setUser}/>;
      case "login":     return <LoginPage     go={go}/>;
      case "dashboard": return <AppShell go={go} current="dashboard" user={user}><DashboardPage go={go} user={user} populated={populated}/></AppShell>;
      case "billing":   return <AppShell go={go} current="billing"   user={user}><BillingPage   go={go} user={user} setUser={setUser}/></AppShell>;
      case "extension": return <AppShell go={go} current="extension" user={user}><ExtensionPage go={go} user={user}/></AppShell>;
      case "admin_users":     return <AppShell go={go} current="admin_users"     user={user}><AdminUsersPage     go={go}/></AppShell>;
      case "admin_analytics": return <AppShell go={go} current="admin_analytics" user={user}><AdminAnalyticsPage/></AppShell>;
      default: return <LandingPage go={go}/>;
    }
  };

  // Tweaks panel
  const { TweaksPanel, TweakSection, TweakRadio } = window;

  return (
    <>
      <div className="proto-screen">
        {render()}
      </div>

      {/* Prototype navigator pill (dev only — add ?proto=1) */}
      {PROTO && (
      <nav className="proto-nav">
        <span className="proto-nav-eyebrow">JUMP</span>
        <div className="proto-nav-group">
          <button className={"proto-nav-btn " + (screen === "landing" ? "on" : "")} onClick={() => go("landing")}>Landing</button>
          <button className={"proto-nav-btn " + (screen === "signup"  ? "on" : "")} onClick={() => go("signup")}>Register</button>
          <button className={"proto-nav-btn " + (screen === "login"   ? "on" : "")} onClick={() => go("login")}>Login</button>
        </div>
        <div className="proto-nav-group">
          <button className={"proto-nav-btn " + (screen === "dashboard" ? "on" : "")} onClick={() => go("dashboard")}>Dashboard</button>
          <button className={"proto-nav-btn " + (screen === "billing"   ? "on" : "")} onClick={() => go("billing")}>Billing</button>
          <button className={"proto-nav-btn " + (screen === "extension" ? "on" : "")} onClick={() => go("extension")}>Extension</button>
          <button className={"proto-nav-btn " + (screen.startsWith("waitlist") ? "on" : "")} onClick={() => go("waitlist:upgrade")}>Waitlist</button>
        </div>
        <div className="proto-nav-group">
          <button className={"proto-nav-btn " + (screen === "admin_users" ? "on" : "")} onClick={() => go("admin_users")}>Admin · Users</button>
          <button className={"proto-nav-btn " + (screen === "admin_analytics" ? "on" : "")} onClick={() => go("admin_analytics")}>Admin · Analytics</button>
        </div>
      </nav>
      )}

      {/* Tweaks (dev only) */}
      {PROTO && TweaksPanel && (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Dashboard state"/>
          <TweakRadio
            label="Lookup history"
            value={t.populated ? "populated" : "empty"}
            options={["populated", "empty"]}
            onChange={(v) => setTweak("populated", v === "populated")}
          />
        </TweaksPanel>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
