// Root app: shell, nav, tweaks integration

function App() {
  const { view, user } = useStore();

  // Initiale View aus WP-Seitenkontext (vom Deploy-Script gesetzt)
  React.useEffect(() => {
    if (window.F1_INITIAL_VIEW && view !== "loading") {
      setState(s => ({ ...s, view: window.F1_INITIAL_VIEW }));
    }
  }, []); // eslint-disable-line

  React.useEffect(() => { window.scrollTo(0, 0); }, [view]);

  // ---- Rendering ---------------------------------------------------------
  if (view === "loading") return <LoadingScreen />;
  if (!user || view === "auth") return <AuthScreen />;

  const isAdmin = user.isAdmin;

  const renderView = () => {
    switch (view) {
      case "dashboard":   return <Dashboard />;
      case "season":      return <SeasonScreen />;
      case "races":       return <RacesScreen />;
      case "race":        return <RaceScreen />;
      case "leaderboard": return <LeaderboardScreen />;
      case "admin":       return isAdmin ? <AdminScreen /> : <Dashboard />;
      case "profile":     return <ProfileScreen />;
      default:            return <Dashboard />;
    }
  };

  return (
    <div className="shell">
      <AppBar isAdmin={isAdmin} user={user} />
      <ErrorBoundary key={view}>
        {renderView()}
      </ErrorBoundary>
      <BottomNav isAdmin={isAdmin} />
      <Toast />
    </div>
  );
}

function UserMenu({ user, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="btn btn-ghost" style={{ padding: "8px 12px" }}
              onClick={() => setOpen(o => !o)}>
        <Avatar player={{ avatar: (user?.avatar || user?.name?.[0] || "?") }} size={22}/>
        <span>{user?.name || "—"}</span>
        <span style={{ fontSize: 10, opacity: 0.5, marginLeft: 2 }}>{open ? "▲" : "▼"}</span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', right: 0, top: 'calc(100% + 6px)', minWidth: 160,
          background: 'var(--bg-2)', border: '1px solid var(--line-2)',
          overflow: 'hidden', zIndex: 100,
          boxShadow: '0 8px 24px rgba(0,0,0,0.6)',
        }}>
          <div style={{ padding: '10px 14px', fontSize: 11, color: 'var(--ink-2)',
                        borderBottom: '1px solid var(--line-2)', letterSpacing: '0.06em' }}>
            {user?.email || user?.name}
          </div>
          <button
            onClick={() => { setOpen(false); setState({ view: 'profile' }); }}
            style={{ width: '100%', padding: '10px 14px', textAlign: 'left', background: 'none',
                     border: 'none', color: 'var(--ink-0)', cursor: 'pointer', fontSize: 13 }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-3)'}
            onMouseLeave={e => e.currentTarget.style.background = 'none'}
          >
            Profil
          </button>
          <button
            onClick={() => { setOpen(false); onLogout(); }}
            style={{ width: '100%', padding: '10px 14px', textAlign: 'left', background: 'none',
                     border: 'none', color: 'var(--ink-0)', cursor: 'pointer', fontSize: 13,
                     borderTop: '1px solid var(--line-2)' }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-3)'}
            onMouseLeave={e => e.currentTarget.style.background = 'none'}
          >
            Ausloggen
          </button>
        </div>
      )}
    </div>
  );
}

function AppBar({ isAdmin, user }) {
  const view = useStore(s => s.view);
  const tabs = [
    { k: "dashboard",   l: "PIT WALL" },
    { k: "races",       l: "RENNEN" },
    { k: "season",      l: "SAISON" },
    { k: "leaderboard", l: "TABELLE" },
    ...(isAdmin ? [{ k: "admin", l: "ADMIN" }] : []),
  ];

  const handleLogout = () => signOut();

  return (
    <div className="appbar" data-screen-label={`App / ${view}`}>
      {/* Logo + User — eine Zeile, luftiger */}
      <div className="container spread" style={{ paddingTop: 0, paddingBottom: 0 }}>
        {/* Logo */}
        <div style={{ display: "flex", alignItems: "center", gap: 28 }}>
          <div style={{ padding: "14px 0" }}>
            <Logo className="appbar-logo" styleOverride={{ width: "auto" }} />
          </div>
          {/* Tabs direkt neben Logo auf Desktop */}
          <div className="tabbar desktop-only" style={{ gap: 0 }}>
            {tabs.map(t => (
              <button key={t.k}
                      className={`tab ${view === t.k ? "active" : ""}`}
                      onClick={() => setState({ view: t.k })}>
                {t.l}
              </button>
            ))}
          </div>
        </div>
        {/* Rechts: Saison-Chip + User */}
        <div className="row" style={{ gap: 10 }}>
          <span className="chip chip-cyan desktop-only" style={{ fontSize: 10 }}>
            <span className="pulse" />Saison {window.SEED?.season || 2026}
          </span>
          <UserMenu user={user} onLogout={handleLogout} />
        </div>
      </div>
      {/* Mobile: Tabs in eigener Zeile */}
      <div className="mobile-only" style={{ borderTop: "1px solid var(--line)" }}>
        <div className="tabbar" style={{ padding: "0 4px" }}>
          {tabs.map(t => (
            <button key={t.k}
                    className={`tab ${view === t.k ? "active" : ""}`}
                    onClick={() => setState({ view: t.k })}>
              {t.l}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function BottomNav({ isAdmin }) {
  const view = useStore(s => s.view);
  const tabs = [
    { k: "dashboard",   l: "PIT",    i: "▣" },
    { k: "races",       l: "RACES",  i: "≡" },
    { k: "season",      l: "SAISON", i: "★" },
    { k: "leaderboard", l: "TABELLE",i: "P" },
    ...(isAdmin ? [{ k: "admin", l: "ADMIN", i: "⚙" }] : []),
  ];
  return (
    <div className="bottom-nav">
      {tabs.map(t => (
        <button key={t.k}
                className={view === t.k ? "active" : ""}
                onClick={() => setState({ view: t.k })}>
          <span className="nav-icon">{t.i}</span>
          {t.l}
        </button>
      ))}
    </div>
  );
}

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