import { useEffect } from "react";
import { Logo } from "./components/Logo";
import { ThemeToggle, useTheme } from "./components/ui";
import { Choose, Compare, Confirm, Landing, Review, Sign } from "./screens/screens";
import { STEPS, useMigration, type MigrationState, type StepId } from "./state/migration";

/** Steps the user may jump to directly. Confirmation is only reachable by signing. */
function reachable(step: StepId, state: MigrationState, blocked: boolean): boolean {
  const order = STEPS.map((s) => s.id);
  const target = order.indexOf(step);
  if (step === "confirm") return state.signed;
  if (blocked) return target <= 2; // overview, compare, choose remain readable
  if (step === "review" || step === "sign") return state.selected.length > 0;
  return true;
}

export function App({ initial }: { initial?: Partial<MigrationState> }) {
  const c = useMigration(initial);
  const [theme, toggleTheme] = useTheme();
  const currentIndex = STEPS.findIndex((s) => s.id === c.state.step);

  // Each step is a new screen: start it at the top rather than inheriting the
  // previous screen's scroll offset.
  useEffect(() => {
    window.scrollTo({ top: 0 });
    // On narrow viewports the stepper scrolls horizontally; keep the active
    // step visible without moving the page itself.
    document
      .querySelector<HTMLElement>(".step-btn[aria-current='step']")
      ?.scrollIntoView?.({ block: "nearest", inline: "center" });
  }, [c.state.step]);

  return (
    <div className="shell">
      <a className="skip-link" href="#main">
        Skip to content
      </a>

      <header className="topbar">
        <div className="topbar-inner">
          <div className="brand">
            <Logo />
            <span>Vaultfire</span>
            <span className="brand-sub">migration console</span>
          </div>
          <div className="topbar-right">
            <span className="badge badge-warn" data-testid="simulation-badge">
              simulation
            </span>
            <label className="scenario">
              <span className="small" id="scenario-label">
                data source
              </span>
              <select
                aria-labelledby="scenario-label"
                value={c.state.scenarioId}
                onChange={(e) =>
                  c.setScenario(e.target.value as "nominal" | "degraded")
                }
                data-testid="scenario-select"
              >
                <option value="nominal">healthy</option>
                <option value="degraded">failing (503)</option>
              </select>
            </label>
            <ThemeToggle theme={theme} onToggle={toggleTheme} />
          </div>
        </div>
      </header>

      <nav className="stepper" aria-label="Migration steps">
        <ol>
          {STEPS.map((s, i) => {
            const isCurrent = s.id === c.state.step;
            return (
              <li key={s.id}>
                <button
                  type="button"
                  className="step-btn"
                  aria-current={isCurrent ? "step" : undefined}
                  disabled={!reachable(s.id, c.state, c.blocked) && !isCurrent}
                  onClick={() => c.goto(s.id)}
                  data-testid={`step-${s.id}`}
                >
                  <span className="step-num" aria-hidden="true">
                    {i + 1}
                  </span>
                  {s.label}
                </button>
              </li>
            );
          })}
        </ol>
      </nav>

      <main id="main">
        <div
          className="main-inner"
          data-testid="step-container"
          data-step={c.state.step}
          data-step-index={currentIndex}
        >
          {c.state.step === "landing" && <Landing c={c} />}
          {c.state.step === "compare" && <Compare c={c} />}
          {c.state.step === "choose" && <Choose c={c} />}
          {c.state.step === "review" && <Review c={c} />}
          {c.state.step === "sign" && <Sign c={c} />}
          {c.state.step === "confirm" && <Confirm c={c} />}
        </div>
      </main>

      <footer>
        <div className="footer-inner">
          <span>
            Vaultfire V3 migration console — static simulation. No wallet, no RPC
            writes, no storage.
          </span>
          <span className="mono">
            Base pilot · chainId 8453 · caps per BASE_PILOT_CONFIG.md
          </span>
          <span>Mutual aid is not insurance.</span>
        </div>
      </footer>
    </div>
  );
}
