const DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "comfortable",
  "accent": "oklch(0.72 0.18 55)",
  "scale": "mid",
  "mascot": true
}/*EDITMODE-END*/;

function useHashRoute() {
  const [hash, setHash] = React.useState(location.hash || "#/dashboard");
  React.useEffect(() => {
    const onHash = () => setHash(location.hash || "#/dashboard");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return [hash, h => (location.hash = h)];
}

function App() {
  const [hash, setHash] = useHashRoute();
  const [authed, setAuthed] = React.useState(false);
  const [authReady, setAuthReady] = React.useState(false); // true once Firebase resolves initial state
  const [currentUser, setCurrentUser] = React.useState(null);
  const [page, setPage] = React.useState("overview");
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [settings, setSettings] = React.useState(() => ({...DEFAULTS}));
  const [statsLoaded, setStatsLoaded] = React.useState(false);
  const [statsError, setStatsError] = React.useState(null);

  // Listen to Firebase Auth state — restores session across page reloads
  React.useEffect(() => {
    if (!window.__onAuthChanged) return;
    const ADMIN_EMAILS = [
      "adi@talio.fun", "adigold1@gmail.com", "info@adigoldstein.com",
      "elad@corefix.tech", "almog@corefix.tech", "kobi@corfix.tech", "rave@altfred.com",
    ];
    const unsub = window.__onAuthChanged(user => {
      setAuthReady(true);
      if (user && ADMIN_EMAILS.includes(user.email)) {
        setCurrentUser(user);
        setAuthed(true);
      } else {
        setCurrentUser(null);
        setAuthed(false);
      }
    });
    return unsub;
  }, []);

  React.useEffect(() => {
    if (!authed) return;
    window.__adminGetStats({}).then(result => {
      const s = result.data;
      Object.assign(KPIS, s.kpis);
      USERS.push(...s.users);
      STORIES.push(...s.stories);
      const toDateSeries = arr => arr.map(p => ({ date: new Date(p.date), v: p.value }));
      SIGNUPS_SERIES.push(...toDateSeries(s.signupsSeries));
      STORIES_SERIES.push(...toDateSeries(s.storiesSeries));
      DAU_SERIES.push(...toDateSeries(s.dauSeries));
      s.themeDist.forEach(t => {
        const row = THEME_DIST.find(r => r.theme === t.theme);
        if (row) row.stories = t.stories;
      });
      window.WAITLIST   = s.waitlist  ?? [];
      window.AUDIT_LOG  = s.auditLog  ?? [];
    }).catch(err => {
      console.error("adminGetStats failed", err);
      setStatsError(err?.message ?? String(err));
    }).finally(() => {
      setStatsLoaded(true);
    });
  }, [authed]);

  // Edit-mode protocol
  React.useEffect(() => {
    const onMsg = e => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  React.useEffect(() => {
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: settings }, "*");
  }, [settings]);

  // Expose navigation globally so sub-pages can trigger page switches
  React.useEffect(() => { window.__setPage = setPage; }, [setPage]);

  const onLogin = (user) => {
    setCurrentUser(user);
    setAuthed(true);
    setHash("#/dashboard");
  };

  const path = hash.replace(/^#/, "").replace(/\?.*/, "");

  if (!authReady) {
    return (
      <div style={{display:"flex", alignItems:"center", justifyContent:"center", height:"100vh", gap:10, color:"var(--ink-3)", fontSize:13}}>
        <span className="pulse" style={{width:8, height:8, borderRadius:"50%", background:"var(--accent)", display:"inline-block"}}/>
        Loading…
      </div>
    );
  }

  if (!authed) {
    return <Login onLogin={onLogin}/>;
  }

  if (!statsLoaded) {
    return (
      <div style={{display:"flex", alignItems:"center", justifyContent:"center", height:"100vh", gap:10, color:"var(--ink-3)", fontSize:13}}>
        <span className="pulse" style={{width:8, height:8, borderRadius:"50%", background:"var(--accent)", display:"inline-block"}}/>
        Loading dashboard data…
      </div>
    );
  }

  if (statsError) {
    return (
      <div style={{display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100vh", gap:8, color:"var(--red)", fontSize:13}}>
        <strong>Failed to load stats</strong>
        <code style={{fontSize:11, color:"var(--ink-2)", maxWidth:500, textAlign:"center"}}>{statsError}</code>
        <button className="btn sm" style={{marginTop:8}} onClick={() => { setStatsError(null); setStatsLoaded(false); }}>Retry</button>
      </div>
    );
  }

  let content;
  switch (page) {
    case "overview": content = <PageOverview/>; break;
    case "users": content = <PageUsers/>; break;
    case "stories": content = <PageStories/>; break;
    case "revenue": content = <PageRevenue/>; break;
    case "credits": content = <PageCredits/>; break;
    case "subs": content = <PageSubs/>; break;
    case "moderation": content = <PageModeration/>; break;
    case "crm": content = <PageCRM/>; break;
    case "announce": content = <PageAnnounce/>; break;
    case "banners": content = <PageBanners/>; break;
    case "pricing": content = <PagePricing/>; break;
    case "promos": content = <PagePromos/>; break;
    case "campaigns": content = <PageCampaigns/>; break;
    case "flags": content = <PageFlags/>; break;
    case "music":  content = <PageMusic/>; break;
    case "themes": content = <PageThemes/>; break;
    case "kanban": content = <PageKanban/>; break;
    case "audit": content = <PageAudit/>; break;
    case "settings": content = <PageSettings/>; break;
    default: content = <PageOverview/>;
  }

  return (
    <>
      <Shell page={page} setPage={setPage}>{content}</Shell>
      <TweaksPanel open={tweaksOpen} onClose={()=>setTweaksOpen(false)}
        settings={settings} setSettings={setSettings}/>
    </>
  );
}

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