"use client";

import { useEffect } from "react";

/**
 * The last line of defence: replaces the whole document when the root layout itself fails (for example when the app's first
 * script cannot be downloaded on a dead connection). There are no providers here, so it carries its own styles and its own two
 * languages, picked from the saved locale.
 */
export default function GlobalError({ error }: { error: Error & { digest?: string }; reset: () => void }) {
  useEffect(() => {
    console.error(error);
    const reload = () => window.location.reload();
    window.addEventListener("online", reload);
    return () => window.removeEventListener("online", reload);
  }, [error]);

  let ar = false;
  try {
    ar = localStorage.getItem("kapitano.locale") === "ar";
  } catch {
    // storage blocked: English
  }

  return (
    <html lang={ar ? "ar" : "en"} dir={ar ? "rtl" : "ltr"}>
      <body
        style={{
          margin: 0,
          minHeight: "100vh",
          display: "grid",
          placeItems: "center",
          background: "#f6f5fb",
          color: "#181626",
          fontFamily: "system-ui, -apple-system, 'Segoe UI', Tahoma, sans-serif",
        }}
      >
        <main style={{ maxWidth: 420, padding: 24, textAlign: "center" }}>
          <div
            aria-hidden
            style={{ width: 56, height: 56, borderRadius: 16, background: "#1b1255", color: "#fff", display: "grid", placeItems: "center", margin: "0 auto 16px", fontSize: 26 }}
          >
            ⚠
          </div>
          <h1 style={{ fontSize: 20, margin: "0 0 8px" }}>{ar ? "تعذّر تحميل التطبيق" : "The app could not load"}</h1>
          <p style={{ margin: "0 0 20px", color: "#6a6680", lineHeight: 1.6, fontSize: 14 }}>
            {ar
              ? "تحقّق من اتصالك بالإنترنت. ستُعاد تحميل الصفحة تلقائيًا عند عودة الاتصال."
              : "Check your internet connection. The page will reload by itself when you are back online."}
          </p>
          <button
            type="button"
            onClick={() => window.location.reload()}
            style={{ background: "#1b1255", color: "#fff", border: 0, borderRadius: 8, padding: "10px 20px", fontSize: 14, fontWeight: 500, cursor: "pointer" }}
          >
            {ar ? "إعادة تحميل الصفحة" : "Reload page"}
          </button>
        </main>
      </body>
    </html>
  );
}
