import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";

// Self-hosted fonts (no external network / no render-blocking @import).
import "@fontsource/cormorant-garamond/400.css";
import "@fontsource/cormorant-garamond/500.css";
import "@fontsource/cormorant-garamond/600.css";
import "@fontsource/dm-sans/300.css";
import "@fontsource/dm-sans/400.css";
import "@fontsource/dm-sans/500.css";
import "@fontsource/dm-sans/600.css";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import "@fontsource/jetbrains-mono/700.css";

// ── window.storage shim ──────────────────────────────────────────────
// The component was authored for the Claude artifact runtime, which
// provides an async window.storage.get/set backed by durable storage.
// Here we back it with localStorage so figures persist in the browser,
// matching the { value } return shape the component expects.
if (!window.storage) {
  window.storage = {
    async get(key) {
      const value = localStorage.getItem(key);
      return value === null ? null : { value };
    },
    async set(key, value) {
      localStorage.setItem(key, value);
      return true;
    },
    async delete(key) {
      localStorage.removeItem(key);
      return true;
    },
  };
}

// Friendly top-level error boundary — keeps a single bad render from
// blanking the whole dashboard, and logs the detail to the console.
class ErrorBoundary extends React.Component {
  constructor(p) { super(p); this.state = { err: null }; }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) { console.error("Dashboard render error:", err, info); }
  render() {
    if (this.state.err) {
      return (
        <div style={{ maxWidth: 560, margin: "80px auto", padding: 28, fontFamily: "system-ui, sans-serif", color: "#1A1F2E", textAlign: "center" }}>
          <div style={{ fontSize: 22, fontWeight: 600, marginBottom: 8 }}>Something went wrong</div>
          <div style={{ fontSize: 14, color: "#4A5568", lineHeight: 1.6, marginBottom: 20 }}>
            The dashboard hit an unexpected error. Your saved figures are safe in this browser. Reload to try again.
          </div>
          <button onClick={() => location.reload()} style={{ padding: "10px 20px", borderRadius: 10, border: "none", background: "#C9A96E", color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer" }}>
            Reload
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

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