import React from "react";
import ReactDOM from "react-dom/client";
import { Link, createBrowserRouter, RouterProvider } from "react-router-dom";

import { reverseRoutes } from "../../../admin/src-reverse/config/routes.js";
import { getAppMeta } from "../../../admin/src-reverse/runtime/settings.js";

import "./styles.css";

function normalizePreviewRoutes(routes) {
  return routes
    .filter((route) => route.page && route.page.render)
    .map((route) => ({
      path: route.path,
      element: <RecoveredRoutePage route={route} />,
    }));
}

function RecoveredRoutePage({ route }) {
  const page = route.page;
  const rendered = page.render();
  const meta = getAppMeta();
  const recovery = rendered.recovery || {};
  const LiveComponent = page.component || rendered.component || null;

  return (
    <div className="preview-shell">
      <aside className="preview-sidebar">
        <div className="preview-brand">
          <strong>{meta.title || "Admin Recovery Preview"}</strong>
          <span>{meta.version || "preview"}</span>
        </div>
        <nav className="preview-nav">
          {reverseRoutes
            .filter((item) => item.page?.status === "recovered")
            .map((item) => (
              <Link key={item.path} to={item.path} className={item.path === route.path ? "active" : ""}>
                {item.page.title}
              </Link>
            ))}
        </nav>
      </aside>
      <main className="preview-main">
        <header className="preview-header">
          <div>
            <h1>{page.title}</h1>
            <p>{recovery.summary || "Recovered page descriptor"}</p>
          </div>
          <div className="preview-badges">
            <span>{page.status}</span>
            <span>{page.featureKey}</span>
            <span>{page.moduleId}</span>
          </div>
        </header>
        <section className="preview-card-grid">
          <InfoCard title="Route">{page.routePath}</InfoCard>
          <InfoCard title="Namespaces">
            {(recovery.translationNamespaces || []).join(", ") || "-"}
          </InfoCard>
          <InfoCard title="APIs">{String((recovery.api || []).length)}</InfoCard>
          <InfoCard title="Source Refs">{String((recovery.sourceRefs || []).length)}</InfoCard>
        </section>
        <section className="preview-sections">
          {LiveComponent && (
            <Section title="Live React View">
              <div className="live-page-frame">
                <LiveComponent />
              </div>
            </Section>
          )}
          <Section title="API Inventory">
            <JsonBlock value={recovery.api || []} />
          </Section>
          <Section title="State Model">
            <JsonBlock value={recovery.stateModel || {}} />
          </Section>
          {"sections" in recovery && (
            <Section title="Sections">
              <JsonBlock value={recovery.sections || []} />
            </Section>
          )}
          {"tableModel" in recovery && (
            <Section title="Table Model">
              <JsonBlock value={recovery.tableModel || {}} />
            </Section>
          )}
          {"toolbarModel" in recovery && (
            <Section title="Toolbar Model">
              <JsonBlock value={recovery.toolbarModel || {}} />
            </Section>
          )}
          {"formModel" in recovery && (
            <Section title="Form Model">
              <JsonBlock value={recovery.formModel || {}} />
            </Section>
          )}
          {"dialogs" in recovery && (
            <Section title="Dialogs">
              <JsonBlock value={recovery.dialogs || {}} />
            </Section>
          )}
          <Section title="Interactions">
            <JsonBlock value={recovery.interactions || []} />
          </Section>
          <Section title="Notes">
            <JsonBlock value={recovery.notes || []} />
          </Section>
          <Section title="Source Refs">
            <JsonBlock value={recovery.sourceRefs || []} />
          </Section>
        </section>
      </main>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <section className="preview-section">
      <h2>{title}</h2>
      {children}
    </section>
  );
}

function InfoCard({ title, children }) {
  return (
    <article className="info-card">
      <span>{title}</span>
      <strong>{children}</strong>
    </article>
  );
}

function JsonBlock({ value }) {
  return <pre>{JSON.stringify(value, null, 2)}</pre>;
}

const recoveredRoutes = normalizePreviewRoutes(reverseRoutes);

const router = createBrowserRouter(recoveredRoutes);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
);
