import { Suspense } from "react";
import type { Metadata } from "next";

import { AnalysisPageContent } from "./AnalysisPageContent";

// ── Metadata ──────────────────────────────────────────────────────────────────

interface PageProps {
  params: Promise<{ cad: string }>;
}

// Next.js delivers `cad` URL-encoded (":" -> "%3A"); decode once at the page
// boundary so downstream hooks/components see canonical "66:41:0204016:10"
// and re-encode exactly once when building API URLs / hrefs (prevents the
// double-encode that made backend regex reject the cad with HTTP 400).
// Regression history: PR #351 added this in Client Component; A7 split into
// Server Component (PR #356) dropped it; this restores in Server boundary.
export async function generateMetadata({
  params,
}: PageProps): Promise<Metadata> {
  const { cad: cadRaw } = await params;
  const cad = decodeURIComponent(cadRaw);
  return {
    title: `Анализ ${cad} — Site Finder`,
    description: `Анализ инвестиционного участка ${cad}`,
  };
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default async function AnalysisPage({ params }: PageProps) {
  const { cad: cadRaw } = await params;
  const cad = decodeURIComponent(cadRaw);

  return (
    <Suspense
      fallback={
        <div
          style={{
            padding: "40px 24px",
            textAlign: "center",
            color: "var(--fg-tertiary, #73767E)",
            fontSize: 14,
          }}
        >
          Загрузка анализа…
        </div>
      }
    >
      {/* key={cad}: client-side nav between two parcels under this same route
          template (RecentParcels / CompareTable link straight to /analysis/
          CAD_B) does NOT remount by default — App Router reuses the instance,
          so instance-local state (§7's useCreateConcept mutation result +
          autoRun refs, §3's selected competitor/filters, the chat thread in
          ChatDock/ChatPanel) would keep showing the OLD parcel's values until
          manually re-run/reselected. Forcing a remount on cad change resets
          all of it cleanly. Queries under this tree (parcel-analyze,
          parcel-forecast, …) are TanStack Query and keyed by cad, so a
          remount just re-subscribes to the (already cached) query result —
          no extra fetch waterfall. Same cad → same key → React does NOT
          remount (a normal re-render, e.g. horizon change, keeps state). */}
      <AnalysisPageContent key={cad} cad={cad} />
    </Suspense>
  );
}
