// App router for Market-Options
const KNOWN_SCREENS = [
  "landing", "login", "signup", "forgot", "reset-password", "verify-email",
  "dashboard", "docs", "keys", "analytics", "billing",
];

// Catches any uncaught render error so a single bad screen cannot white-screen
// the whole app — the user gets a recoverable fallback instead.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { failed: false };
  }
  static getDerivedStateFromError() {
    return { failed: true };
  }
  componentDidCatch(error, info) {
    console.error("Unhandled UI error:", error, info);
  }
  render() {
    if (!this.state.failed) return this.props.children;
    return (
      <div style={{
        minHeight: "100vh", display: "grid", placeItems: "center",
        background: "var(--bg, #0b0d10)", color: "var(--text, #e6e6e6)",
        fontFamily: "system-ui, sans-serif", padding: 24, textAlign: "center",
      }}>
        <div style={{ maxWidth: 380 }}>
          <div style={{ fontSize: 17, fontWeight: 600, marginBottom: 8 }}>
            Something went wrong
          </div>
          <div style={{ fontSize: 13, opacity: 0.7, marginBottom: 18, lineHeight: 1.5 }}>
            The page hit an unexpected error. Reloading usually fixes it.
          </div>
          <button
            onClick={() => window.location.reload()}
            style={{
              padding: "9px 16px", borderRadius: 8, border: 0, cursor: "pointer",
              background: "var(--green, #3fb950)", color: "#04130a", fontWeight: 600,
            }}
          >
            Reload
          </button>
        </div>
      </div>
    );
  }
}

function App() {
  const [screen, setScreen] = useState("landing");

  useEffect(() => {
    // Sync to the hash so a refresh keeps the current screen. Two query
    // params route to dedicated screens regardless of hash:
    //   ?billing=...                 — return from the payment provider
    //   ?action=verify-email&token=  — confirmation link from the email
    //   ?action=reset-password&token=— password-reset link from the email
    const params = new URLSearchParams(window.location.search);
    const fromHash = (window.location.hash || "").replace("#", "");
    const action = params.get("action");
    if (action === "verify-email") {
      setScreen("verify-email");
      if (fromHash !== "verify-email") window.location.hash = "verify-email";
    } else if (action === "reset-password") {
      setScreen("reset-password");
      if (fromHash !== "reset-password") window.location.hash = "reset-password";
    } else if (params.get("billing")) {
      setScreen("billing");
      if (fromHash !== "billing") window.location.hash = "billing";
    } else if (KNOWN_SCREENS.includes(fromHash)) {
      setScreen(fromHash);
    }
    const onHash = () => {
      const h = (window.location.hash || "").replace("#", "");
      // Only navigate to recognised screens — an unknown hash is ignored so
      // the chrome (sidebar vs full-bleed) never ends up in a broken state.
      if (KNOWN_SCREENS.includes(h)) setScreen(h);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const navigate = (next) => {
    setScreen(next);
    window.location.hash = next;
    window.scrollTo(0, 0);
  };

  // Screens that have their own full chrome (no sidebar)
  const fullbleed = ["landing", "login", "signup", "forgot", "reset-password", "verify-email"];
  // Screens that require an authenticated session.
  const protectedScreens = ["dashboard", "keys", "analytics", "docs", "billing"];

  // Auth guard — a protected screen falls back to login without a session.
  let activeScreen = KNOWN_SCREENS.includes(screen) ? screen : "landing";
  if (protectedScreens.indexOf(activeScreen) !== -1 && !(window.Auth && Auth.isAuthed())) {
    activeScreen = "login";
  }
  const isFullbleed = fullbleed.includes(activeScreen);

  let body;
  switch (activeScreen) {
    case "landing": body = <Landing onNavigate={navigate} />; break;
    case "login": body = <Login onNavigate={navigate} />; break;
    case "signup": body = <Signup onNavigate={navigate} />; break;
    case "forgot": body = <Forgot onNavigate={navigate} />; break;
    case "reset-password": body = <ResetPassword onNavigate={navigate} />; break;
    case "verify-email": body = <VerifyEmail onNavigate={navigate} />; break;
    case "dashboard": body = <Dashboard onNavigate={navigate} />; break;
    case "docs": body = <DocsPage onNavigate={navigate} />; break;
    case "keys": body = <KeysPage onNavigate={navigate} />; break;
    case "analytics": body = <Analytics onNavigate={navigate} />; break;
    case "billing": body = <BillingPage onNavigate={navigate} />; break;
    default: body = <Landing onNavigate={navigate} />;
  }

  // Sidebar logged-in nav key (map docs/dashboard/etc)
  const sideKey = ["dashboard", "docs", "keys", "analytics", "billing"].includes(activeScreen) ? activeScreen : null;

  return (
    <div
      className={`app ${isFullbleed ? "fullbleed" : ""}`}
      data-screen-label={`${activeScreen}`}
    >
      {!isFullbleed && <Sidebar active={sideKey} onNavigate={navigate} route={activeScreen} />}
      <div className="content">
        {body}
      </div>
    </div>
  );
}

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