"use client";

import { useState } from "react";
import Link from "next/link";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeftIcon, CheckCircleIcon } from "@heroicons/react/24/solid";
import {
  RUN_FILTER_BUILT_FORMS,
  RUN_FILTER_PROPERTY_TYPES,
  RunFilters,
  RunStatus,
  estimateRunMinutes,
  historyRefetchInterval,
  isLargeRun,
  MAX_FILTER_POSTCODES,
  selectionSummary,
} from "@/lib/modellingRuns/model";
import { usePortfolioTags } from "@/app/portfolio/[slug]/components/useTags";
import { tagDotColour } from "@/lib/tags/colour";

export interface ScenarioOption {
  id: string;
  name: string;
  goal: string;
  goalValue: string | null;
  housingType: string;
  budget: number | null;
  status: "modelled" | "awaiting" | "running";
  modelledCount: number;
}

interface PreviewResponse {
  matchedProperties: number;
  perScenario: { scenarioId: string; alreadyModelled: number }[];
}

interface RunHistoryRow {
  taskId: string;
  triggeredAt: string;
  triggeredBy: string;
  scenarios: { id: string; name: string | null }[];
  selection: string;
  previewedPropertyCount: number;
  planCount: number;
  status: RunStatus;
}

const STATUS_LABELS: Record<RunStatus["state"], string> = {
  dispatched: "Starting up",
  in_progress: "In progress",
  complete: "Complete",
  failed: "Failed",
};

function RunBadge({ status }: { status: ScenarioOption["status"] }) {
  if (status === "running") {
    return (
      <span className="ml-auto inline-flex flex-none items-center gap-1.5 rounded-full bg-brandblue px-2.5 py-0.5 text-xs font-semibold text-white">
        <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-300" />
        Modelling in progress
      </span>
    );
  }
  const modelled = status === "modelled";
  return (
    <span
      className={`ml-auto inline-flex flex-none items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-semibold ${
        modelled ? "bg-brandlightblue text-brandmidblue" : "bg-amber-50 text-amber-800"
      }`}
    >
      <span className={`h-1.5 w-1.5 flex-none rounded-full ${modelled ? "bg-brandmidblue" : "bg-brandgold"}`} />
      {modelled ? "Modelled" : "Awaiting modelling"}
    </span>
  );
}

function FilterColumn({
  title,
  options,
  selected,
  onToggle,
  emptyHint,
}: {
  title: string;
  options: { value: string; label?: string; count?: number; colour?: string }[];
  selected: Set<string>;
  onToggle: (value: string) => void;
  emptyHint?: React.ReactNode;
}) {
  return (
    <div>
      <div className="mb-2.5 flex items-baseline gap-2">
        <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.1em] text-gray-600">
          {title}
        </span>
        <span className="text-[11.5px] text-gray-400">
          · {selected.size ? `${selected.size} selected` : "all"}
        </span>
      </div>
      <div className="flex max-h-56 flex-col gap-1 overflow-y-auto pr-1.5">
        {options.length === 0 && emptyHint ? (
          <p className="text-[12.5px] leading-relaxed text-gray-400">{emptyHint}</p>
        ) : (
          options.map((o) => {
            const on = selected.has(o.value);
            return (
              <label
                key={o.value}
                className={`flex cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-[13.5px] transition ${
                  on ? "bg-brandlightblue" : "hover:bg-gray-50"
                } ${o.value === "Unknown" ? "mt-1 border-t border-dashed border-gray-200 pt-2.5" : ""}`}
              >
                <input
                  type="checkbox"
                  checked={on}
                  onChange={() => onToggle(o.value)}
                  className="h-[15px] w-[15px] accent-brandmidblue"
                />
                {o.colour && (
                  <span
                    className="h-2.5 w-2.5 shrink-0 rounded-full border"
                    style={{ backgroundColor: tagDotColour(o.colour) }}
                  />
                )}
                <span className="truncate">{o.label ?? o.value}</span>
                {o.count != null && (
                  <span className="ml-auto text-[11.5px] tabular-nums text-gray-400">{o.count}</span>
                )}
              </label>
            );
          })
        )}
      </div>
    </div>
  );
}

export default function RunModellingClient({
  portfolioId,
  portfolioName,
  scenarios,
}: {
  portfolioId: string;
  portfolioName: string;
  scenarios: ScenarioOption[];
}) {
  const queryClient = useQueryClient();
  const [selScenarios, setSelScenarios] = useState<Set<string>>(new Set());
  const [selPcs, setSelPcs] = useState<Set<string>>(new Set());
  const [selTypes, setSelTypes] = useState<Set<string>>(new Set());
  const [selForms, setSelForms] = useState<Set<string>>(new Set());
  const [selTags, setSelTags] = useState<Set<string>>(new Set());
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [done, setDone] = useState<{ properties: number; scenarios: number } | null>(null);

  const filters: RunFilters = {
    ...(selPcs.size ? { postcodes: [...selPcs].sort() } : {}),
    ...(selTypes.size ? { propertyTypes: [...selTypes] } : {}),
    ...(selForms.size ? { builtForms: [...selForms] } : {}),
    ...(selTags.size ? { tagIds: [...selTags].map(Number) } : {}),
  };
  const scenarioIds = [...selScenarios].sort();

  const { data: tags = [] } = usePortfolioTags(portfolioId);

  const postcodesQuery = useQuery<{ postcode: string; count: number }[], Error>({
    queryKey: ["portfolio-postcodes", portfolioId],
    staleTime: 5 * 60 * 1000,
    queryFn: async () => {
      const res = await fetch(`/api/portfolio/${portfolioId}/postcodes`);
      const body = await res.json();
      if (!res.ok) throw new Error(body.error ?? "Couldn't load postcodes");
      return body.postcodes;
    },
  });

  const preview = useQuery<PreviewResponse, Error>({
    queryKey: ["run-preview", portfolioId, scenarioIds, filters],
    enabled: scenarioIds.length > 0 && !done,
    keepPreviousData: true,
    retry: false,
    queryFn: async () => {
      const res = await fetch(`/api/portfolio/${portfolioId}/modelling-runs/preview`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scenarioIds, filters }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(body.error ?? "Couldn't count the selection");
      return body;
    },
  });

  const history = useQuery<RunHistoryRow[], Error>({
    queryKey: ["modelling-runs", portfolioId],
    // v4 signature: (data, query). Fast while a run is moving, slow at rest.
    refetchInterval: (data) => historyRefetchInterval(data),
    queryFn: async () => {
      const res = await fetch(`/api/portfolio/${portfolioId}/modelling-runs`);
      const body = await res.json();
      if (!res.ok) throw new Error(body.error ?? "Couldn't load run history");
      return body.runs;
    },
  });

  const run = useMutation<unknown, Error, void>({
    mutationFn: async () => {
      const res = await fetch(`/api/portfolio/${portfolioId}/modelling-runs`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          scenarioIds,
          filters,
          previewedPropertyCount: preview.data?.matchedProperties ?? 0,
        }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(body.error ?? "Couldn't start modelling — please try again");
      return body;
    },
    onSuccess: () => {
      setDone({ properties: preview.data?.matchedProperties ?? 0, scenarios: scenarioIds.length });
      setSelScenarios(new Set());
      queryClient.invalidateQueries(["modelling-runs", portfolioId]);
    },
  });

  const toggle = (set: Set<string>, setter: (s: Set<string>) => void, value: string) => {
    const next = new Set(set);
    if (next.has(value)) next.delete(value);
    else next.add(value);
    setter(next);
  };

  const matched = preview.data?.matchedProperties;
  const planTotal = matched != null ? matched * scenarioIds.length : null;
  const remodel = (preview.data?.perScenario ?? []).filter((p) => p.alreadyModelled > 0);
  const scenarioById = new Map(scenarios.map((s) => [s.id, s]));
  const startRun = () => {
    if (tagsBlockRun) return;
    if (matched != null && isLargeRun(matched)) setConfirmOpen(true);
    else run.mutate();
  };
  const filterCount = selPcs.size + selTypes.size + selForms.size + selTags.size;
  const clearFilters = () => {
    setSelPcs(new Set());
    setSelTypes(new Set());
    setSelForms(new Set());
    setSelTags(new Set());
  };
  // The distributor can't resolve tag_ids yet (backend ask pending, ADR-0013):
  // preview counts tags in-app, but an actual run would model the unscoped set.
  // Guard the run until the backend lands — remove this once it does.
  const tagsBlockRun = selTags.size > 0;

  return (
    <div className="mx-auto max-w-4xl px-6 pb-48 pt-10">
      <Link
        href={`/portfolio/${portfolioId}`}
        className="mb-5 inline-flex items-center gap-1.5 rounded-lg text-sm font-semibold text-gray-600 transition hover:text-brandblue focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brandmidblue"
      >
        <ArrowLeftIcon className="h-4 w-4" aria-hidden />
        Back to {portfolioName}
      </Link>
      <h1 className="font-manrope text-3xl font-extrabold tracking-tight text-brandblue">
        Run your scenarios.
      </h1>
      <p className="mt-2 max-w-xl text-sm leading-relaxed text-gray-600">
        Choose the scenarios you want answered, then the homes to include. The counts you see are
        checked against your portfolio as you go — what you see is exactly what gets modelled.
      </p>

      {done ? (
        <div
          role="status"
          className="mt-6 rounded-2xl border border-emerald-200 bg-emerald-50/70 px-5 py-4"
        >
          <div className="flex flex-wrap items-start gap-3">
            <CheckCircleIcon className="mt-0.5 h-6 w-6 flex-none text-emerald-600" aria-hidden />
            <div className="min-w-0 flex-1">
              <h2 className="font-manrope text-base font-extrabold text-brandblue">
                Modelling started — you don&apos;t need to stay on this page
              </h2>
              <p className="mt-1 max-w-[60ch] text-[13px] leading-relaxed text-gray-600">
                We&apos;re modelling <b>{done.properties.toLocaleString()}</b>{" "}
                {done.properties === 1 ? "home" : "homes"} against <b>{done.scenarios}</b>{" "}
                scenario{done.scenarios === 1 ? "" : "s"} —{" "}
                <b>{(done.properties * done.scenarios).toLocaleString()}</b> plan
                {done.properties * done.scenarios === 1 ? "" : "s"}. Results for a run this size
                are typically ready within{" "}
                <b>~{estimateRunMinutes(done.properties * done.scenarios)} minutes</b> — progress
                updates under Recent runs below as it happens.
              </p>
            </div>
            <div className="flex flex-none items-center gap-2.5 self-center">
              <button
                onClick={() => setDone(null)}
                className="rounded-xl border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-brandblue transition hover:bg-gray-50"
              >
                Set up another run
              </button>
              <Link
                href={`/portfolio/${portfolioId}`}
                className="rounded-xl px-4 py-2 text-sm font-semibold text-white"
                style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
              >
                Back to portfolio
              </Link>
            </div>
          </div>
        </div>
      ) : (
        <>
          {/* Step 1 — scenarios */}
          <div className="mt-7 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.14em] text-brandmidblue">
              Step 1 · Scenarios
            </span>
            <h2 className="mt-0.5 font-manrope text-lg font-extrabold text-brandblue">
              Which questions are we asking?
            </h2>
            <p className="text-[13px] text-gray-500">
              Every selected scenario runs against the same property selection.
            </p>
            {scenarios.length === 0 ? (
              <div className="mt-4 rounded-xl border-[1.5px] border-dashed border-gray-200 px-4 py-8 text-center text-sm text-gray-500">
                No scenarios yet —{" "}
                <Link
                  href={`/portfolio/${portfolioId}/scenarios/new`}
                  className="font-semibold text-brandmidblue hover:underline"
                >
                  create your first scenario
                </Link>{" "}
                and come back to run it.
              </div>
            ) : (
              scenarios.map((s) => {
                const on = selScenarios.has(s.id);
                return (
                  <div key={s.id}>
                    <label
                      className={`mt-2.5 flex w-full cursor-pointer items-center gap-3.5 rounded-xl border px-4 py-3 text-left transition ${
                        on
                          ? "border-brandmidblue bg-white shadow-sm"
                          : "border-transparent bg-gray-50 hover:bg-gray-100"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={on}
                        onChange={() => toggle(selScenarios, setSelScenarios, s.id)}
                        className="h-4 w-4 shrink-0 accent-brandmidblue"
                      />
                      <span className="min-w-0">
                        <span className="block truncate font-manrope text-sm font-bold text-brandblue">
                          {s.name}
                        </span>
                        <span className="block text-xs text-gray-500">
                          {s.goal === "Increasing EPC" && s.goalValue
                            ? `Target EPC ${s.goalValue}`
                            : s.goal}{" "}
                          · {s.housingType}
                          {s.budget ? ` · £${s.budget.toLocaleString()} per home` : ""}
                        </span>
                      </span>
                      <RunBadge status={s.status} />
                    </label>
                    {on && s.status === "running" && (
                      <div className="ml-11 mt-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-1.5 text-xs text-amber-800">
                        This scenario is already being modelled. You can still include it — the
                        newest results are the ones you&apos;ll see.
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>

          {/* Step 2 — properties */}
          <div className="mt-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.14em] text-brandmidblue">
                Step 2 · Properties
              </span>
              {filterCount > 0 && (
                <button
                  onClick={clearFilters}
                  className="text-[13px] font-semibold text-brandmidblue transition hover:text-brandblue hover:underline"
                >
                  Remove all filters ({filterCount})
                </button>
              )}
            </div>
            <h2 className="mt-0.5 font-manrope text-lg font-extrabold text-brandblue">
              Which homes?
            </h2>
            <p className="text-[13px] text-gray-500">
              Leave a filter untouched to include everything. What you&apos;ve told us about a home
              takes priority over its EPC; &ldquo;Unknown&rdquo; picks out homes where we have
              neither.
            </p>
            <div className="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
              {postcodesQuery.isError ? (
                <div>
                  <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.1em] text-gray-600">
                    Postcode
                  </span>
                  <p className="mt-2.5 text-[13px] leading-relaxed text-red-700">
                    We couldn&apos;t load your portfolio&apos;s postcodes.{" "}
                    <button
                      onClick={() => postcodesQuery.refetch()}
                      className="font-semibold underline hover:text-red-800"
                    >
                      Try again
                    </button>
                  </p>
                </div>
              ) : postcodesQuery.isLoading ? (
                <div>
                  <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.1em] text-gray-600">
                    Postcode
                  </span>
                  <p className="mt-2.5 text-[13px] text-gray-500">Loading postcodes…</p>
                </div>
              ) : (
                <FilterColumn
                  title="Postcode"
                  options={(postcodesQuery.data ?? []).map((p) => ({
                    value: p.postcode,
                    count: p.count,
                  }))}
                  selected={selPcs}
                  onToggle={(v) => toggle(selPcs, setSelPcs, v)}
                />
              )}
              <FilterColumn
                title="Property type"
                options={RUN_FILTER_PROPERTY_TYPES.map((value) => ({ value }))}
                selected={selTypes}
                onToggle={(v) => toggle(selTypes, setSelTypes, v)}
              />
              <FilterColumn
                title="Built form"
                options={RUN_FILTER_BUILT_FORMS.map((value) => ({ value }))}
                selected={selForms}
                onToggle={(v) => toggle(selForms, setSelForms, v)}
              />
              <FilterColumn
                title="Tags"
                options={tags.map((t) => ({
                  value: t.id,
                  label: t.name,
                  colour: t.colour,
                  count: t.propertyCount,
                }))}
                selected={selTags}
                onToggle={(v) => toggle(selTags, setSelTags, v)}
                emptyHint={
                  <>
                    No tags yet — create them from the property table to run a
                    scenario over a hand-picked group.
                  </>
                }
              />
            </div>
            <p className="mt-3 text-[11.5px] leading-relaxed text-gray-400">
              Filters are limited to {MAX_FILTER_POSTCODES} postcodes per run.
            </p>
          </div>

        </>
      )}

      {/* Recent runs — always visible: after a run is triggered this is where
          its live status lands, so the banner above can say "watch below" */}
      <div className="mt-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <div className="flex items-baseline gap-3">
              <h2 className="font-manrope text-lg font-extrabold text-brandblue">Recent runs</h2>
              <span className="text-[13px] text-gray-500">
                what was asked, by whom, and how it went
              </span>
            </div>
            {history.isLoading ? (
              <p className="mt-4 text-sm text-gray-400">Loading…</p>
            ) : !history.data?.length ? (
              <p className="mt-4 text-sm text-gray-400">
                No runs yet — your first appears here the moment you trigger it.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="mt-3 w-full border-collapse text-[13px]">
                  <thead>
                    <tr>
                      {["When", "Scenarios", "Selection", "Properties", "Plans", "Status"].map(
                        (h) => (
                          <th
                            key={h}
                            className="border-b border-gray-100 px-3 py-2 text-left font-manrope text-[10.5px] font-extrabold uppercase tracking-[.09em] text-gray-400"
                          >
                            {h}
                          </th>
                        ),
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {history.data.map((r) => (
                      <tr key={r.taskId}>
                        <td className="whitespace-nowrap border-b border-gray-100 px-3 py-2.5 align-top">
                          {new Date(r.triggeredAt).toLocaleString("en-GB", {
                            day: "numeric",
                            month: "short",
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                          <span className="block text-[11.5px] text-gray-400">{r.triggeredBy}</span>
                        </td>
                        <td className="border-b border-gray-100 px-3 py-2.5 align-top">
                          {r.scenarios.map((s) => s.name ?? s.id).join(" · ") || "—"}
                        </td>
                        <td className="max-w-[220px] border-b border-gray-100 px-3 py-2.5 align-top text-[12px] text-gray-500">
                          {r.selection}
                        </td>
                        <td className="border-b border-gray-100 px-3 py-2.5 align-top tabular-nums">
                          {r.previewedPropertyCount.toLocaleString()}
                        </td>
                        <td className="border-b border-gray-100 px-3 py-2.5 align-top tabular-nums">
                          {r.planCount.toLocaleString()}
                        </td>
                        <td className="border-b border-gray-100 px-3 py-2.5 align-top">
                          <span
                            className={`whitespace-nowrap rounded-full px-2.5 py-0.5 font-manrope text-[10px] font-extrabold uppercase tracking-[.06em] ${
                              r.status.state === "complete"
                                ? "bg-emerald-50 text-emerald-700"
                                : r.status.state === "failed"
                                  ? "bg-red-50 text-red-700"
                                  : "bg-brandblue text-white"
                            }`}
                          >
                            {STATUS_LABELS[r.status.state]}
                          </span>
                          {/* Work is chunked into batches, so show a percentage —
                              the counts never line up with property/plan numbers */}
                          {r.status.state === "in_progress" && (
                            <>
                              <span className="mt-1 block text-[11px] tabular-nums text-gray-400">
                                {Math.round((100 * r.status.ready) / Math.max(1, r.status.total))}% done
                              </span>
                              <span className="mt-0.5 block h-1 w-20 overflow-hidden rounded-full bg-gray-100">
                                <span
                                  className="block h-full rounded-full bg-brandmidblue"
                                  style={{ width: `${Math.round((100 * r.status.ready) / Math.max(1, r.status.total))}%` }}
                                />
                              </span>
                            </>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
      </div>

      {/* Summary tray */}
      {!done && scenarioIds.length > 0 && (
        <div className="fixed bottom-6 left-1/2 z-40 w-[min(56rem,calc(100vw-2rem))] -translate-x-1/2 rounded-2xl border border-gray-200 bg-white/95 px-5 py-4 shadow-2xl backdrop-blur">
          <div className="flex flex-wrap items-center gap-3">
            <span
              className={`font-manrope text-xl font-extrabold tabular-nums text-brandblue ${preview.isFetching ? "opacity-40" : ""}`}
            >
              {matched != null ? matched.toLocaleString() : "—"}
              <span className="ml-1 text-xs font-semibold text-gray-400">properties</span>
            </span>
            <span className="text-gray-300">×</span>
            <span className="font-manrope text-xl font-extrabold tabular-nums text-brandblue">
              {scenarioIds.length}
              <span className="ml-1 text-xs font-semibold text-gray-400">
                scenario{scenarioIds.length > 1 ? "s" : ""}
              </span>
            </span>
            <span className="text-gray-300">=</span>
            <span
              className={`font-manrope text-xl font-extrabold tabular-nums text-brandblue ${preview.isFetching ? "opacity-40" : ""}`}
            >
              {planTotal != null ? planTotal.toLocaleString() : "—"}
              <span className="ml-1 text-xs font-semibold text-gray-400">plans</span>
            </span>
            <span className="flex items-center gap-1.5 text-[11px] text-gray-400">
              <span
                className={`h-1.5 w-1.5 rounded-full ${preview.isFetching ? "animate-pulse bg-gray-400" : preview.isError ? "bg-red-500" : "bg-emerald-600"}`}
              />
              {preview.isFetching
                ? "Counting…"
                : preview.isError
                  ? preview.error.message
                  : "Checked against your portfolio just now"}
            </span>
            <button
              onClick={startRun}
              disabled={
                preview.isFetching ||
                preview.isError ||
                !matched ||
                run.isLoading ||
                tagsBlockRun
              }
              className="ml-auto rounded-xl px-4 py-2 text-sm font-semibold text-white transition disabled:opacity-40"
              style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
            >
              {run.isLoading
                ? "Starting…"
                : tagsBlockRun
                  ? "Tag runs coming soon"
                  : matched
                    ? `Run modelling — ${planTotal!.toLocaleString()} plan${planTotal === 1 ? "" : "s"}`
                    : "No properties match"}
            </button>
          </div>
          {tagsBlockRun && (
            <div className="mt-2.5">
              <span className="inline-block w-fit rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-1 text-xs text-amber-800">
                You can preview a tag selection now, but running scenarios over
                tags needs a modelling-engine update that&apos;s on the way. The
                count above is exact — the run button unlocks once it lands.
              </span>
            </div>
          )}
          {(remodel.length > 0 || run.isError) && (
            <div className="mt-2.5 flex flex-col gap-1">
              {remodel.map((p) => (
                <span
                  key={p.scenarioId}
                  className="inline-block w-fit rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-1 text-xs text-amber-800"
                >
                  <b>{p.alreadyModelled.toLocaleString()}</b> of{" "}
                  {matched?.toLocaleString() ?? "—"} have already been modelled in &ldquo;
                  {scenarioById.get(p.scenarioId)?.name ?? p.scenarioId}&rdquo; — they&apos;ll be
                  modelled again and the newest results shown
                </span>
              ))}
              {run.isError && <span className="text-xs text-red-600">{run.error.message}</span>}
            </div>
          )}
        </div>
      )}

      {/* Large-run confirm */}
      {confirmOpen && (
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby="large-run-title"
          onKeyDown={(e) => {
            if (e.key === "Escape") setConfirmOpen(false);
          }}
          className="fixed inset-0 z-50 flex items-center justify-center bg-brandblue/35 p-5 backdrop-blur-sm"
        >
          <div className="max-w-md rounded-2xl bg-white p-7 shadow-2xl">
            <h3 id="large-run-title" className="font-manrope text-xl font-extrabold text-brandblue">
              This is a large run
            </h3>
            <p className="mt-2 text-sm leading-relaxed text-gray-600">
              You&apos;re about to model <b>{matched?.toLocaleString()}</b> homes across{" "}
              {scenarioIds.length} scenario{scenarioIds.length > 1 ? "s" : ""} —{" "}
              <b>{planTotal?.toLocaleString()}</b> plans. A run this size can&apos;t be stopped
              once it starts.
            </p>
            <div className="mt-3 rounded-xl border border-gray-100 bg-gray-50 px-3.5 py-2.5 text-[13px] leading-relaxed text-gray-600">
              <span className="block">
                <b className="font-semibold text-brandblue">Scenarios:</b>{" "}
                {scenarioIds.map((id) => scenarioById.get(id)?.name ?? id).join(" · ")}
              </span>
              <span className="mt-1 block">
                <b className="font-semibold text-brandblue">Homes:</b> {selectionSummary(filters)}
              </span>
            </div>
            <div className="mt-5 flex justify-end gap-2.5">
              <button
                autoFocus
                onClick={() => setConfirmOpen(false)}
                className="rounded-xl border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-brandblue hover:bg-gray-50"
              >
                Go back
              </button>
              <button
                onClick={() => {
                  setConfirmOpen(false);
                  run.mutate();
                }}
                className="rounded-xl px-4 py-2 text-sm font-semibold text-white"
                style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
              >
                Yes, run modelling
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
