import { Component, StrictMode } from "react";
import type { ErrorInfo, ReactNode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import { clearAttachments } from "./attachments";

class AppErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error("Rasa could not render", error, info.componentStack);
  }

  render() {
    if (!this.state.failed) return this.props.children;

    return (
      <main data-app-error="true" dir="rtl" style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24, background: "#f6f9f6", fontFamily: "Vazirmatn Variable, Tahoma, sans-serif" }}>
        <div style={{ maxWidth: 430, textAlign: "center", color: "#244438", lineHeight: 2 }}>
          <h1 style={{ fontSize: 25, margin: "0 0 8px" }}>رسا باز نشد</h1>
          <p style={{ fontSize: 13, color: "#697e70" }}>داده های ذخیره شده یا تنظیمات مرورگر مانع اجرای برنامه شده اند. می توانید دوباره تلاش کنید یا داده های محلی رسا را پاک کنید.</p>
          <div style={{ display: "flex", justifyContent: "center", flexWrap: "wrap", gap: 10, marginTop: 20 }}>
            <button type="button" onClick={() => window.location.reload()} style={{ padding: "8px 15px", border: "1px solid #b9d1c1", borderRadius: 8, background: "white", color: "#275743" }}>بارگذاری دوباره</button>
            <button type="button" onClick={async () => {
              if (!window.confirm("کلیدها، تنظیمات، گفتگوها و فایل های ذخیره شده رسا روی این مرورگر پاک شوند؟")) return;
              try { await clearAttachments(); } catch { /* Reset the rest even if file storage is unavailable. */ }
              try {
                for (const key of ["rasa.settings.v1", "rasa.chats.v1", "rasa.model.v1"]) localStorage.removeItem(key);
              } catch { /* Storage may be unavailable. */ }
              window.location.reload();
            }} style={{ padding: "8px 15px", border: 0, borderRadius: 8, background: "#087f68", color: "white" }}>بازنشانی داده های محلی</button>
          </div>
        </div>
      </main>
    );
  }
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  </StrictMode>
);
