// Quizrs — app shell: routing, navigation, command palette, auth gate.

const NAV = [
  ["dashboard", "Home", "home"],
  ["library", "Quizzes", "library"],
  ["creator", "Create", "create"],
  ["player", "Play", "play"],
  ["stats", "Results", "stats"],
];

const TITLES = {
  dashboard: "Home", library: "Quizzes", creator: "Create",
  player: "Play", stats: "Results", settings: "Settings",
};

const SCREENS = {
  dashboard: () => window.Dashboard,
  library: () => window.Library,
  creator: () => window.Creator,
  player: () => window.Player,
  stats: () => window.Stats,
  settings: () => window.Settings,
};

// ── ⌘K command palette ──
function CommandPalette({ open, onClose, go }) {
  const { quizzes } = useStore();
  const [query, setQuery] = React.useState("");
  const inputRef = React.useRef(null);

  React.useEffect(() => { if (open) { setQuery(""); setTimeout(() => inputRef.current?.focus(), 30); } }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const q = query.toLowerCase();
  const navCmds = [
    { icon: "plus", label: "Create a new quiz", run: () => go("creator") },
    ...NAV.map(([id, label, icon]) => ({ icon, label: "Go to " + label, run: () => go(id) })),
    { icon: "settings", label: "Open Settings", run: () => go("settings") },
  ].filter((c) => !q || c.label.toLowerCase().includes(q));

  const quizHits = quizzes
    .filter((qz) => !q || qz.title.toLowerCase().includes(q))
    .slice(0, 6)
    .map((qz) => ({ icon: qz.isPoll ? "stats" : "library", label: qz.title, sub: qz.status === "live" ? "Live" : "Draft", run: () => go("stats", { id: qz.id }) }));

  const run = (cmd) => { onClose(); cmd.run(); };

  return (
    <div className="qz-modal-backdrop" onClick={onClose}>
      <div className="qz-palette" onClick={(e) => e.stopPropagation()}>
        <div className="row" style={{ gap: 10, padding: "14px 16px", borderBottom: "1px solid var(--hairline)" }}>
          <Icon name="search" size={18} className="muted" />
          <input ref={inputRef} value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search quizzes or jump to…"
            style={{ flex: 1, border: 0, outline: "none", background: "transparent", font: "inherit", fontSize: 15, color: "var(--ink)" }} />
          <kbd style={{ fontSize: 11 }}>Esc</kbd>
        </div>
        <div style={{ maxHeight: "52vh", overflowY: "auto", padding: 6 }}>
          {quizHits.length > 0 && (
            <>
              <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", padding: "8px 12px 4px" }}>Quizzes</div>
              {quizHits.map((c, i) => (
                <button key={"q" + i} className="qz-palette-row" onClick={() => run(c)}>
                  <Icon name={c.icon} size={16} className="muted" />
                  <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.label}</span>
                  {c.sub && <Badge tone={c.sub === "Live" ? "green" : "amber"}>{c.sub}</Badge>}
                </button>
              ))}
            </>
          )}
          <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", padding: "8px 12px 4px" }}>Actions</div>
          {navCmds.map((c, i) => (
            <button key={"n" + i} className="qz-palette-row" onClick={() => run(c)}>
              <Icon name={c.icon} size={16} className="muted" />
              <span style={{ flex: 1 }}>{c.label}</span>
            </button>
          ))}
          {navCmds.length === 0 && quizHits.length === 0 && (
            <div className="muted" style={{ padding: 24, textAlign: "center", fontSize: 13.5 }}>No matches.</div>
          )}
        </div>
      </div>
    </div>
  );
}

function Shell() {
  const { user, folders, settings } = useStore();
  const [route, setRoute] = React.useState("dashboard");
  const [params, setParams] = React.useState({});
  const [paletteOpen, setPaletteOpen] = React.useState(false);

  const go = React.useCallback((r, p = {}) => {
    setRoute(r); setParams(p);
    const el = document.querySelector(".screen");
    if (el) el.scrollTop = 0;
  }, []);

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && (e.key === "k" || e.key === "K")) { e.preventDefault(); setPaletteOpen((o) => !o); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const Screen = SCREENS[route]();
  const title = TITLES[route];
  const fullBleed = route === "creator" || route === "player";

  return (
    <div className={"app" + (settings.density === "compact" ? " compact" : "")}>
      <CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} go={go} />

      <nav className="sidebar">
        <div className="brand">
          <img className="brand-mark" src="assets/icon.png" alt="" />
          <div className="brand-name">Quizrs</div>
        </div>
        <div className="nav-label">Workspace</div>
        {NAV.map(([id, label, icon]) => (
          <div key={id} className={"nav-item" + (route === id ? " active" : "")} onClick={() => go(id)}>
            <Icon name={icon} size={18} />
            <span className="nav-t">{label}</span>
          </div>
        ))}

        {folders.length > 0 && (
          <>
            <div className="nav-label">Collections</div>
            {folders.map((f) => (
              <div key={f.name} className="nav-item" onClick={() => go("library", { filter: f.name })}>
                <span style={{ width: 18, display: "grid", placeItems: "center", flex: "0 0 auto" }}>
                  <span style={{ width: 9, height: 9, borderRadius: 3, background: "var(--accent)" }} />
                </span>
                <span className="nav-t" style={{ fontSize: 13.5 }}>{f.name}</span>
                <span className="count">{f.count}</span>
              </div>
            ))}
          </>
        )}

        <div className="side-foot">
          <div className={"nav-item" + (route === "settings" ? " active" : "")} onClick={() => go("settings")}>
            <Icon name="settings" size={18} /><span className="nav-t">Settings</span>
          </div>
          <div className="user-chip" onClick={() => go("settings")} style={{ cursor: "pointer" }}>
            <Avatar name={user?.name || "You"} size={30} />
            <div style={{ minWidth: 0 }}>
              <div className="name">{user?.name || "You"}</div>
              <div className="role">{(user?.plan || "free") + " plan"}</div>
            </div>
            <Icon name="chevR" size={15} className="muted" style={{ marginLeft: "auto" }} />
          </div>
        </div>
      </nav>

      <div className="main">
        <header className="topbar">
          <h1>{title}</h1>
          <span className="spacer" />
          {!fullBleed && (
            <button className="search" onClick={() => setPaletteOpen(true)} style={{ cursor: "pointer", textAlign: "left" }}>
              <Icon name="search" size={16} />
              <span style={{ flex: 1, color: "var(--ink-3)", fontSize: 14 }}>Search…</span>
              <kbd>⌘K</kbd>
            </button>
          )}
          <Btn kind="primary" icon="plus" onClick={() => go("creator")}>New quiz</Btn>
        </header>

        <div className="screen" style={fullBleed ? { overflow: "hidden", display: "flex" } : null}>
          {fullBleed
            ? <div style={{ flex: 1, minHeight: 0 }}><Screen go={go} params={params} /></div>
            : <Screen go={go} params={params} />}
        </div>
      </div>
    </div>
  );
}

// ── auth gate: don't render the app until Clerk is ready + signed in ──
function AuthGate() {
  const { authReady, authIssue, user } = useStore();

  if (!authReady) {
    return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center" }}><Loading label="Loading Quizrs…" /></div>;
  }
  if (authIssue) {
    return (
      <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24 }}>
        <div className="card card-pad" style={{ maxWidth: 420, textAlign: "center" }}>
          <Icon name="flag" size={26} className="muted" />
          <h2 style={{ fontSize: 18, fontWeight: 700, margin: "10px 0 6px" }}>Sign-in required</h2>
          <div className="muted" style={{ fontSize: 13.5, marginBottom: 16 }}>{authIssue}</div>
          <Btn kind="primary" onClick={() => window.quizrsAuth?.redirectToSignIn?.(window.location.pathname)}>Sign in</Btn>
        </div>
      </div>
    );
  }
  if (!user) {
    return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center" }}><Loading label="Redirecting to sign-in…" /></div>;
  }
  return <Shell />;
}

function App() {
  return (
    <StoreProvider>
      <AuthGate />
    </StoreProvider>
  );
}

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