/* app — root: providers, error boundary, router, mounts shell + Mr. Wing */

class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { if (window.console) console.error("Thirdwing render error:", error, info); }
  render() {
    if (this.state.error) {
      return (
        <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24, background: "var(--paper)", fontFamily: "var(--sans)" }}>
          <div className="card card-pad" style={{ maxWidth: 460, textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--danger-wash)", color: "var(--danger)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" /></svg>
            </div>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 600 }}>{window.tr ? tr("err.title") : "Something went wrong"}</h2>
            <p style={{ color: "var(--ink-3)", fontSize: 14, marginTop: 8 }}>{window.tr ? tr("err.body") : "We hit an unexpected error. Reload to continue — your trips and cards are saved."}</p>
            <button onClick={() => { location.hash = "home"; location.reload(); }} style={{ marginTop: 18, background: "var(--emerald)", color: "#fff", border: "none", borderRadius: 100, padding: "12px 24px", fontWeight: 600, cursor: "pointer", fontFamily: "var(--sans)" }}>{window.tr ? tr("err.reload") : "Reload Thirdwing"}</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

function NotFound() {
  const { t } = useLang();
  const { nav } = useStore();
  return (
    <main style={{ minHeight: "78vh", display: "grid", placeItems: "center", paddingTop: 96, background: "var(--paper)" }}>
      <div className="wrap" style={{ maxWidth: 540, textAlign: "center", paddingBottom: 60 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: "clamp(72px,14vw,140px)", fontWeight: 600, color: "var(--gold)", lineHeight: 1 }}>404</div>
        <h1 style={{ fontFamily: "var(--serif)", fontSize: 30, fontWeight: 600, marginTop: 8 }}>{t("nf.title")}</h1>
        <p className="muted" style={{ marginTop: 10, fontSize: 15.5 }}>{t("nf.sub")}</p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 24, flexWrap: "wrap" }}>
          <button className="btn btn-primary" onClick={() => nav("home")}><Icon name="globe" size={16} /> {t("nf.home")}</button>
          <button className="btn btn-ghost" onClick={() => nav("flights")}><Icon name="search" size={16} /> {t("booking.searchFlights")}</button>
        </div>
      </div>
    </main>
  );
}

function Toast() {
  const { notice, setNotice } = useStore();
  const { t } = useLang();
  React.useEffect(() => {
    if (!notice) return;
    const id = setTimeout(() => setNotice(null), notice.type === "error" ? 8000 : 5000);
    return () => clearTimeout(id);
  }, [notice, setNotice]);
  if (!notice) return null;
  const ok = notice.type !== "error";
  return (
    <div role="status" aria-live="polite" style={{ position: "fixed", insetInlineStart: "50%", transform: "translateX(-50%)", bottom: "calc(24px + env(safe-area-inset-bottom,0px))", zIndex: 400, maxWidth: "min(560px, calc(100vw - 32px))", background: ok ? "var(--emerald)" : "var(--ink)", color: "#fff", borderRadius: 14, boxShadow: "var(--shadow-lg)", padding: "14px 16px", display: "flex", gap: 12, alignItems: "flex-start", animation: "bubbleIn .3s ease" }}>
      <Icon name={ok ? "check" : "shield"} size={18} color={ok ? "#fff" : "var(--gold-l)"} style={{ flexShrink: 0, marginTop: 1 }} />
      <div style={{ fontSize: 14, lineHeight: 1.5, flex: 1 }}>{t(notice.key, notice.vars)}</div>
      <button onClick={() => setNotice(null)} aria-label={t("common.close")} style={{ background: "rgba(255,255,255,.18)", border: "none", color: "#fff", width: 26, height: 26, borderRadius: "50%", cursor: "pointer", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="x" size={14} /></button>
    </div>
  );
}

function Router() {
  const { route } = useStore();
  const map = {
    home: Home,
    flights: FlightsPage,
    hotels: HotelsPage,
    packages: PackagesPage,
    package: PackageDetailPage,
    booking: BookingPage,
    trips: TripsPage,
    auth: AuthPage,
    profile: ProfilePage,
    corporate: CorporatePage,
    about: AboutPage,
    support: SupportPage,
    legal: LegalPage,
    admin: AdminPage,
  };
  const Page = map[route] || NotFound;
  return <Page />;
}

function Chrome() {
  const { route } = useStore();
  const { t } = useLang();
  const isAdmin = route === "admin";
  return (
    <>
      <a href="#main" className="skip-link">{t("a11y.skip")}</a>
      <Header />
      <div id="main" tabIndex={-1}>
        <Router />
      </div>
      {!isAdmin && <Footer />}
      <MrWing />
      <MobileTabBar />
      <Toast />
    </>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <LangProvider>
        <StoreProvider>
          <Chrome />
        </StoreProvider>
      </LangProvider>
    </ErrorBoundary>
  );
}

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