"use client";

import {
  Boxes,
  Factory,
  Gauge,
  PackageOpen,
  Orbit,
  Rocket,
  Route,
  Timer,
  Zap,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";

import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  MACHINE_BY_ID,
  RECIPE_BY_ID,
  iconFor,
  iconForGroup,
} from "@/app/lib/factorio-data";
import { groupLabel, localizedName, tr } from "@/app/lib/i18n";
import {
  ROCKET_LOCATIONS,
  ROCKET_PRODUCTS,
  ROCKET_PRODUCT_BY_ID,
  calculateRocketFreight,
} from "@/app/lib/rocket-freight";
import type {
  EnergySourceSelection,
  ItemGroupId,
  Locale,
  QualityId,
  RateUnit,
  RocketFreightInput,
} from "@/app/lib/types";
import { FactorioIcon } from "./factorio-icon";
import { SearchPicker } from "./search-picker";
import {
  BeaconCountSelect,
  FieldLabel,
  GeometryDesign,
  MetricCard,
  ModuleConfigurator,
  QualitySelect,
  SectionTitle,
  SmartNumberInput,
  UnitSelect,
  formatNumber,
  formatPower,
  resolvedModules,
  type ModuleConfig,
} from "./calculator-widgets";
import type { SearchPickerGroup } from "./search-picker";

const selectClass = "h-10 w-full border-white/10 bg-[#17191b] text-zinc-100";
const silo = MACHINE_BY_ID.get("rocket-silo")!;
const rocketPart = RECIPE_BY_ID.get("rocket-part")!;
const defaultMachine: ModuleConfig = {
  mode: "auto",
  families: ["productivity"],
  tier: 3,
  quality: "normal",
  manual: [],
};
const defaultBeacon: ModuleConfig = {
  mode: "auto",
  families: ["speed"],
  tier: 3,
  quality: "normal",
  manual: [],
};
const GROUPS: ItemGroupId[] = [
  "logistics",
  "production",
  "intermediate-products",
  "space",
  "combat",
  "fluids",
];

function duration(seconds: number, locale: Locale) {
  if (!Number.isFinite(seconds)) return "—";
  if (seconds < 60) return `${formatNumber(seconds, locale, 1)} s`;
  if (seconds < 3600) return `${formatNumber(seconds / 60, locale, 1)} min`;
  return `${formatNumber(seconds / 3600, locale, 2)} h`;
}

export function RocketFreightWorkspace({
  locale,
  onEnergy,
  energySelection,
  onEnergyToggle,
}: {
  locale: Locale;
  onEnergy: (source: EnergySourceSelection) => void;
  energySelection?: EnergySourceSelection;
  onEnergyToggle: (
    id: string,
    field: "includeDirect" | "includeChain",
    value: boolean,
  ) => void;
}) {
  const [productId, setProductId] = useState("");
  const [source, setSource] = useState("gleba");
  const [destination, setDestination] = useState("nauvis");
  const [targetRate, setTargetRate] = useState(60);
  const [unit, setUnit] = useState<RateUnit>("min");
  const [cargoPerTransit, setCargoPerTransit] = useState(1000);
  const [siloQuality, setSiloQuality] = useState<QualityId>("normal");
  const [research, setResearch] = useState(0);
  const [machineConfig, setMachineConfig] =
    useState<ModuleConfig>(defaultMachine);
  const [beaconConfig, setBeaconConfig] = useState<ModuleConfig>(defaultBeacon);
  const [beaconCount, setBeaconCount] = useState(0);
  const [beaconQuality, setBeaconQuality] = useState<QualityId>("normal");
  const [speedMode, setSpeedMode] = useState<"manual" | "thrusters">(
    "thrusters",
  );
  const [manualSpeed, setManualSpeed] = useState(250);
  const [thrusters, setThrusters] = useState(4);
  const [thrusterQuality, setThrusterQuality] = useState<QualityId>("normal");
  const [thrusterFill, setThrusterFill] = useState(80);
  const [platformMass, setPlatformMass] = useState(1000);
  const [platformWidth, setPlatformWidth] = useState(17);
  const [cargoBays, setCargoBays] = useState(0);
  const [cargoBayQuality, setCargoBayQuality] = useState<QualityId>("normal");
  const [loadingMode, setLoadingMode] = useState<
    "robots" | "inserters" | "ignore"
  >(
    "robots",
  );
  const [loadingInserterId, setLoadingInserterId] =
    useState<NonNullable<RocketFreightInput["loadingInserterId"]>>(
      "stack-inserter",
    );
  const [loadingInserterQuality, setLoadingInserterQuality] =
    useState<QualityId>("normal");
  const [loadingInserterCapacityBonus, setLoadingInserterCapacityBonus] =
    useState(7);
  const [logisticRobotCount, setLogisticRobotCount] = useState(50);
  const [workerRobotSpeedLevel, setWorkerRobotSpeedLevel] = useState(0);
  const [workerRobotCargoLevel, setWorkerRobotCargoLevel] = useState(0);
  const [includeEnergy, setIncludeEnergy] = useState(false);
  const machineModules = useMemo(
    () =>
      resolvedModules(machineConfig, silo.moduleSlots, silo, rocketPart),
    [machineConfig],
  );
  const beaconModules = useMemo(
    () => resolvedModules(beaconConfig, 2, silo, rocketPart, true),
    [beaconConfig],
  );
  const result = useMemo(() => calculateRocketFreight({
    productId,
    source,
    destination,
    targetRate,
    unit,
    cargoPerTransit,
    siloQuality,
    rocketPartProductivityLevel: research,
    siloModules: machineModules,
    beaconCount,
    beaconModules,
    beaconQuality,
    speedMode,
    manualSpeedKms: manualSpeed,
    thrusterCount: thrusters,
    thrusterQuality,
    thrusterFill: thrusterFill / 100,
    platformMassTons: platformMass,
    platformWidthTiles: platformWidth,
    cargoBays,
    cargoBayQuality,
    loadingMode,
    loadingInserterId,
    loadingInserterQuality,
    loadingInserterCapacityBonus,
    logisticRobotCount,
    workerRobotSpeedLevel,
    workerRobotCargoLevel,
    includeEnergy,
  }), [
    productId,
    source,
    destination,
    targetRate,
    unit,
    cargoPerTransit,
    siloQuality,
    research,
    machineModules,
    beaconCount,
    beaconModules,
    beaconQuality,
    speedMode,
    manualSpeed,
    thrusters,
    thrusterQuality,
    thrusterFill,
    platformMass,
    platformWidth,
    cargoBays,
    cargoBayQuality,
    loadingMode,
    loadingInserterId,
    loadingInserterQuality,
    loadingInserterCapacityBonus,
    logisticRobotCount,
    workerRobotSpeedLevel,
    workerRobotCargoLevel,
    includeEnergy,
  ]);
  const maximumBeacons = Math.max(
    0,
    silo.maxBeacons - (loadingMode === "ignore" ? 0 : 1),
  );
  useEffect(
    () =>
      onEnergy({
        id: "rocket-freight",
        label: tr(locale, "rocket"),
        icon: iconFor("rocket-silo"),
        directKw: result.electricKw,
        chainKw: 0,
        includeDirect: includeEnergy,
        includeChain: false,
        mode: "rocket",
      }),
    [includeEnergy, locale, onEnergy, result.electricKw],
  );
  const product = ROCKET_PRODUCT_BY_ID.get(productId);
  const options = useMemo(() => ROCKET_PRODUCTS.map((entry) => ({
    value: entry.id,
    label: localizedName(entry.id, locale, "item"),
    icon: entry.icon,
    meta: `${entry.capacity} / ${localizedName("rocket", locale, "entity")}`,
    keywords: entry.name,
    group: entry.group,
    subgroup: entry.subgroup,
    subgroupLabel: entry.subgroup
      ? localizedName(entry.subgroup, locale, "subgroup")
      : undefined,
  })), [locale]);
  const groups: SearchPickerGroup[] = useMemo(
    () =>
      GROUPS.filter((id) => options.some((option) => option.group === id)).map((id) => ({
        id,
        label: groupLabel(id, locale),
        icon: iconForGroup(id),
      })),
    [locale, options],
  );
  return (
    <div className="workspace-grid">
      <aside className="workspace-settings">
        <section className="panel-card">
          <SectionTitle
            number="01"
            title={tr(locale, "rocketCargo")}
            icons={[iconFor("rocket-silo"), iconFor("cargo-landing-pad")]}
          />
          <FieldLabel>{tr(locale, "product")}</FieldLabel>
          <SearchPicker
            value={productId}
            options={options}
            groups={groups}
            onChange={(id) => {
              const next = ROCKET_PRODUCT_BY_ID.get(id)!;
              setProductId(id);
              setCargoPerTransit(next.capacity);
            }}
            placeholder={tr(locale, "selectProduct")}
            searchPlaceholder={tr(locale, "searchProducts")}
            emptyText={tr(locale, "noMatch")}
          />
          <div className="mt-3 grid grid-cols-2 gap-2">
            <div>
              <FieldLabel>{tr(locale, "sourcePlanet")}</FieldLabel>
              <Select value={source} onValueChange={setSource}>
                <SelectTrigger className={selectClass}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {ROCKET_LOCATIONS.map((id) => (
                    <SelectItem key={id} value={id}>
                      {localizedName(id, locale, "space")}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <FieldLabel>{tr(locale, "destinationPlanet")}</FieldLabel>
              <Select value={destination} onValueChange={setDestination}>
                <SelectTrigger className={selectClass}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {ROCKET_LOCATIONS.map((id) => (
                    <SelectItem key={id} value={id}>
                      {localizedName(id, locale, "space")}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="target-rate-inline mt-3 grid grid-cols-[1fr_88px] gap-2 rounded-xl p-3">
            <div>
              <FieldLabel>{tr(locale, "targetRate")}</FieldLabel>
              <SmartNumberInput
                min={0}
                value={targetRate}
                onValueChange={setTargetRate}
              />
            </div>
            <div>
              <FieldLabel>{tr(locale, "unit")}</FieldLabel>
              <UnitSelect value={unit} onChange={setUnit} />
            </div>
          </div>
          <div className="mt-3">
            <FieldLabel
              detail={
                product
                  ? `${tr(locale, "rocketCapacity")}: ${product.capacity}`
                  : undefined
              }
            >
              {tr(locale, "cargoPerTransit")}
            </FieldLabel>
            <SmartNumberInput
              min={1}
              step={100}
              value={cargoPerTransit}
              onValueChange={setCargoPerTransit}
            />
          </div>
        </section>
        <section className="panel-card">
          <SectionTitle
            number="02"
            title={localizedName("rocket-silo", locale, "entity")}
            icons={[iconFor("rocket-silo"), iconFor("rocket-part"), iconFor("beacon")]}
          />
          <div className="grid grid-cols-2 gap-2">
            <div>
              <FieldLabel>{tr(locale, "machineQuality")}</FieldLabel>
              <QualitySelect
                value={siloQuality}
                onChange={(value) => setSiloQuality(value as QualityId)}
                locale={locale}
              />
            </div>
            <div>
              <FieldLabel>{tr(locale, "rocketPartResearch")}</FieldLabel>
              <SmartNumberInput
                min={0}
                step={1}
                value={research}
                onValueChange={setResearch}
              />
            </div>
          </div>
          <div className="mt-3">
            <ModuleConfigurator
              title={tr(locale, "machineModules")}
              locale={locale}
              slots={4}
              machine={silo}
              recipe={rocketPart}
              config={machineConfig}
              onChange={setMachineConfig}
              allowedFamilies={["productivity", "speed", "efficiency"]}
            />
          </div>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <div>
              <FieldLabel detail={`max ${maximumBeacons}`}>
                {tr(locale, "activePerMachine")}
              </FieldLabel>
              <BeaconCountSelect
                value={beaconCount}
                maximum={maximumBeacons}
                onChange={setBeaconCount}
              />
            </div>
            <div>
              <FieldLabel>{tr(locale, "beaconQuality")}</FieldLabel>
              <QualitySelect
                value={beaconQuality}
                onChange={(value) => setBeaconQuality(value as QualityId)}
                locale={locale}
              />
            </div>
          </div>
          <div className="mt-3">
            <ModuleConfigurator
              title={tr(locale, "beaconModules")}
              locale={locale}
              slots={2}
              machine={silo}
              recipe={rocketPart}
              beacon
              config={beaconConfig}
              onChange={setBeaconConfig}
              allowedFamilies={["speed", "efficiency"]}
            />
          </div>
        </section>
        <section className="panel-card">
          <SectionTitle
            number="03"
            title={tr(locale, "siloLoading")}
            icons={[iconFor("logistic-robot"), iconFor("stack-inserter"), iconFor("buffer-chest")]}
            note={loadingMode !== "ignore" ? tr(locale, "experimental") : undefined}
          />
          <div className="grid grid-cols-3 rounded-lg border border-white/8 bg-[#17191b] p-1">
            <button
              type="button"
              onClick={() => {
                setLoadingMode("robots");
                setBeaconCount((current) => Math.min(current, 15));
              }}
              className={`flex items-center justify-center gap-2 rounded py-2 text-xs ${loadingMode === "robots" ? "bg-[#303439] text-[#f7a72d]" : "text-zinc-500"}`}
            >
              <FactorioIcon src={iconFor("logistic-robot")} alt="" size="sm" />
              {tr(locale, "logisticRobots")}
            </button>
            <button
              type="button"
              onClick={() => {
                setLoadingMode("inserters");
                setBeaconCount((current) => Math.min(current, 15));
              }}
              className={`flex items-center justify-center gap-2 rounded py-2 text-xs ${loadingMode === "inserters" ? "bg-[#303439] text-[#f7a72d]" : "text-zinc-500"}`}
            >
              <FactorioIcon src={iconFor("stack-inserter")} alt="" size="sm" />
              {tr(locale, "inserters")}
            </button>
            <button
              type="button"
              onClick={() => setLoadingMode("ignore")}
              className={`flex items-center justify-center gap-2 rounded py-2 text-xs ${loadingMode === "ignore" ? "bg-[#303439] text-[#f7a72d]" : "text-zinc-500"}`}
            >
              <FactorioIcon src={iconFor("rocket-silo")} alt="" size="sm" />
              {tr(locale, "ignoreInsertion")}
            </button>
          </div>
          {loadingMode !== "ignore" ? (
            <div className="mt-3 space-y-3">
              <div className="notice-warning">
                {loadingMode === "robots"
                  ? tr(locale, "experimentalRobotLoading")
                  : tr(locale, "experimentalInserterLoading")}
              </div>
              <div>
                <FieldLabel>{tr(locale, "inserter")}</FieldLabel>
                <Select
                  value={loadingInserterId}
                  onValueChange={(value) =>
                    setLoadingInserterId(
                      value as NonNullable<
                        RocketFreightInput["loadingInserterId"]
                      >,
                    )
                  }
                >
                  <SelectTrigger className={selectClass}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {["inserter", "fast-inserter", "bulk-inserter", "stack-inserter"].map(
                      (id) => (
                        <SelectItem key={id} value={id}>
                          <span className="flex items-center gap-2">
                            <FactorioIcon src={iconFor(id)} alt="" size="sm" />
                            {localizedName(id, locale, "entity")}
                          </span>
                        </SelectItem>
                      ),
                    )}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <FieldLabel>{tr(locale, "inserterQuality")}</FieldLabel>
                  <QualitySelect
                    value={loadingInserterQuality}
                    onChange={(value) =>
                      setLoadingInserterQuality(value as QualityId)
                    }
                    locale={locale}
                  />
                </div>
                <div>
                  <FieldLabel>{tr(locale, "capacityResearch")}</FieldLabel>
                  <SmartNumberInput
                    min={0}
                    max={7}
                    step={1}
                    value={loadingInserterCapacityBonus}
                    onValueChange={(value) =>
                      setLoadingInserterCapacityBonus(Math.floor(value))
                    }
                  />
                </div>
              </div>
              {loadingMode === "robots" ? (
                <div className="grid grid-cols-3 gap-2">
                  <div>
                    <FieldLabel>{tr(locale, "logisticRobotCount")}</FieldLabel>
                    <SmartNumberInput
                      min={1}
                      max={300}
                      step={1}
                      value={logisticRobotCount}
                      onValueChange={(value) =>
                        setLogisticRobotCount(
                          Math.max(1, Math.min(300, Math.floor(value))),
                        )
                      }
                    />
                  </div>
                  <div>
                    <FieldLabel>{tr(locale, "workerRobotSpeedResearch")}</FieldLabel>
                    <SmartNumberInput
                      min={0}
                      max={100}
                      step={1}
                      value={workerRobotSpeedLevel}
                      onValueChange={(value) =>
                        setWorkerRobotSpeedLevel(Math.max(0, Math.floor(value)))
                      }
                    />
                  </div>
                  <div>
                    <FieldLabel>{tr(locale, "workerRobotCargoResearch")}</FieldLabel>
                    <SmartNumberInput
                      min={0}
                      max={3}
                      step={1}
                      value={workerRobotCargoLevel}
                      onValueChange={(value) =>
                        setWorkerRobotCargoLevel(
                          Math.max(0, Math.min(3, Math.floor(value))),
                        )
                      }
                    />
                  </div>
                </div>
              ) : null}
            </div>
          ) : (
            <div className="notice-warning mt-3">
              {tr(locale, "ignoreInsertionWarning")}
            </div>
          )}
        </section>
        <section className="panel-card">
          <SectionTitle
            number="04"
            title={tr(locale, "platformSpeed")}
            icons={[iconFor("thruster"), iconFor("space-platform-hub")]}
          />
          <div className="mb-3 grid grid-cols-2 rounded-lg border border-white/8 bg-[#17191b] p-1">
            <button
              type="button"
              onClick={() => setSpeedMode("thrusters")}
              className={`rounded py-2 text-xs ${speedMode === "thrusters" ? "bg-[#303439] text-[#f7a72d]" : "text-zinc-500"}`}
            >
              {tr(locale, "deriveFromThrusters")}
            </button>
            <button
              type="button"
              onClick={() => setSpeedMode("manual")}
              className={`rounded py-2 text-xs ${speedMode === "manual" ? "bg-[#303439] text-[#f7a72d]" : "text-zinc-500"}`}
            >
              {tr(locale, "manualSpeed")}
            </button>
          </div>
          {speedMode === "manual" ? (
            <div>
              <FieldLabel>km/s</FieldLabel>
              <SmartNumberInput
                min={0.01}
                step={10}
                value={manualSpeed}
                onValueChange={setManualSpeed}
              />
            </div>
          ) : (
            <>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <FieldLabel>{tr(locale, "thrusterCount")}</FieldLabel>
                  <SmartNumberInput
                    min={1}
                    step={1}
                    value={thrusters}
                    onValueChange={(value) => {
                      const count = Math.max(1, Math.floor(value));
                      setThrusters(count);
                      setPlatformWidth(count * 4 + 1);
                    }}
                  />
                </div>
                <div>
                  <FieldLabel>{tr(locale, "thrusterQuality")}</FieldLabel>
                  <QualitySelect
                    value={thrusterQuality}
                    onChange={(value) => setThrusterQuality(value as QualityId)}
                    locale={locale}
                  />
                </div>
                <div>
                  <FieldLabel>{tr(locale, "throttle")} %</FieldLabel>
                  <SmartNumberInput
                    min={10}
                    max={80}
                    step={5}
                    value={thrusterFill}
                    onValueChange={setThrusterFill}
                  />
                </div>
                <div>
                  <FieldLabel>{tr(locale, "platformWidth")}</FieldLabel>
                  <SmartNumberInput
                    min={5}
                    step={1}
                    value={platformWidth}
                    onValueChange={setPlatformWidth}
                  />
                </div>
                <div>
                  <FieldLabel>{tr(locale, "platformMass")} t</FieldLabel>
                  <SmartNumberInput
                    min={1}
                    step={100}
                    value={platformMass}
                    onValueChange={setPlatformMass}
                  />
                </div>
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="mt-3 w-full"
                onClick={() => setPlatformWidth(thrusters * 4 + 1)}
              >
                {tr(locale, "optimizedLayout")} · {thrusters * 4 + 1}{" "}
                {tr(locale, "tiles")}
              </Button>
            </>
          )}
          <div className="mt-3 grid grid-cols-2 gap-2 rounded-lg border border-white/8 bg-[#151719] p-3">
            <div>
              <FieldLabel detail={`${result.cargoBaySlotsEach} ${tr(locale, "slots")}`}>
                {tr(locale, "cargoBays")}
              </FieldLabel>
              <SmartNumberInput
                min={0}
                step={1}
                value={cargoBays}
                onValueChange={(value) => setCargoBays(Math.max(0, Math.floor(value)))}
              />
            </div>
            <div>
              <FieldLabel>{tr(locale, "cargoBayQuality")}</FieldLabel>
              <QualitySelect
                value={cargoBayQuality}
                onChange={(value) => setCargoBayQuality(value as QualityId)}
                locale={locale}
              />
            </div>
          </div>
        </section>
        <label className="panel-card flex items-center justify-between text-xs">
          <span>{tr(locale, "includeEnergy")}</span>
          <input
            type="checkbox"
            checked={energySelection?.includeDirect ?? includeEnergy}
            onChange={(event) => {
              setIncludeEnergy(event.target.checked);
              onEnergyToggle(
                "rocket-freight",
                "includeDirect",
                event.target.checked,
              );
            }}
          />
        </label>
      </aside>
      <section className="workspace-results">
        {!result.valid ? (
          <div className="panel-card flex min-h-56 flex-col items-center justify-center text-center">
            <Rocket className="mb-3 size-9 text-[#f7a72d]" />
            <h2 className="text-lg font-semibold">
              {tr(locale, "noProductSelected")}
            </h2>
            <p className="mt-2 text-xs text-zinc-500">
              {tr(locale, "rocketSelectionError")}
            </p>
          </div>
        ) : (
          <>
            <div className="result-hero">
              <div className="flex items-center gap-4">
                <FactorioIcon src={product!.icon} alt="" size="xl" />
                <div>
                  <p className="eyebrow">{tr(locale, "rocket")}</p>
                  <h2 className="text-2xl font-semibold">
                    {localizedName(productId, locale, "item")}
                  </h2>
                  <p className="text-xs text-zinc-500">
                    {result.path
                      .map((id) => localizedName(id, locale, "space"))
                      .join(" → ")}
                  </p>
                </div>
              </div>
              <div className="shrink-0 text-right">
                <strong className="block font-mono text-4xl text-[#f7a72d]">
                  {result.silosToPlace}
                </strong>
                <span className="font-mono text-[10px] uppercase tracking-wider text-zinc-500">
                  {tr(locale, "rocketSilosToPlace")}
                </span>
              </div>
            </div>
            <div className="panel-card">
              <h3 className="mb-3 text-sm font-semibold text-[#69c5df]">
                {tr(locale, "flightCalculation")}
              </h3>
              <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
              <MetricCard
                icon={<Route className="size-4" />}
                label={tr(locale, "path")}
                value={`${formatNumber(result.distanceKm, locale)} km`}
              />
              <MetricCard
                icon={<Timer className="size-4" />}
                label={tr(locale, "flightTime")}
                value={duration(result.flightSeconds, locale)}
                detail={`${formatNumber(result.speedKms, locale)} km/s`}
              />
              <MetricCard
                icon={<Orbit className="size-4" />}
                label={tr(locale, "platformsRequired")}
                value={String(result.platformsRequired)}
                detail={`${duration(result.roundTripSeconds, locale)} ${tr(locale, "roundTrip").toLowerCase()}`}
              />
              <MetricCard
                icon={<Zap className="size-4" />}
                label={tr(locale, "power")}
                value={formatPower(result.electricKw, locale)}
              />
              </div>
            </div>
            <div className="panel-card">
              <h3 className="mb-3 text-sm font-semibold text-[#f7a72d]">
                {tr(locale, "launchCalculation")}
              </h3>
              <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
              <MetricCard
                icon={<Boxes className="size-4" />}
                label={tr(locale, "launchesPerTransit")}
                value={String(result.launchesPerTransit)}
                detail={`${result.cargoCapacityPerRocket} / ${localizedName("rocket", locale, "entity")}`}
              />
              <MetricCard
                icon={<Factory className="size-4" />}
                label={tr(locale, "rocketSilosToPlace")}
                value={String(result.silosToPlace)}
                detail={`${result.sustainedSilos} ${tr(locale, "sustainedSilos").toLowerCase()}`}
              />
              <MetricCard
                icon={<Rocket className="size-4" />}
                label={tr(locale, "loadingTime")}
                value={duration(result.loadingSeconds, locale)}
                detail={
                  loadingMode !== "ignore"
                    ? `${duration(result.payloadInsertionSeconds, locale)} · ${tr(locale, "payloadInsertion")}`
                    : `${formatNumber(result.launchesPerMinute, locale)} · ${tr(locale, "launchesPerMinute")}`
                }
              />
              <MetricCard
                icon={<Gauge className="size-4" />}
                label={tr(locale, "landingTime")}
                value={duration(result.landingSeconds, locale)}
                detail={`${result.landingWaves} · ${tr(locale, "landingWaves")}`}
              />
              </div>
            </div>
            {result.siloBottleneck === "payload-wave" ? (
              <div className="notice-info items-start border border-[#69c5df]/30 bg-[#69c5df]/8 p-4">
                <Factory className="size-4 shrink-0" />
                <div>
                  <strong className="block text-xs text-[#a8e8f7]">
                    {tr(locale, "payloadWaveTitle")}
                  </strong>
                  <p className="mt-1 text-[11px] leading-relaxed text-zinc-400">
                    {tr(locale, "payloadWaveExplanation")}
                  </p>
                  <p className="mt-2 font-mono text-[10px] text-zinc-500">
                    {result.launchesPerTransit} {tr(locale, "launchesPerTransit").toLowerCase()} → {result.payloadWaveSilos} {tr(locale, "waveSilos").toLowerCase()} · {result.sustainedSilos} {tr(locale, "sustainedSilos").toLowerCase()}
                  </p>
                </div>
              </div>
            ) : null}
            {result.cargoStorageLimited ? (
              <div className="notice-warning">
                <Boxes className="size-4 shrink-0" />
                <span>
                  {tr(locale, "cargoStorageBottleneck")} {result.minimumCargoBays}
                  <br />
                  <span className="font-mono text-[10px] text-zinc-500">
                    {formatNumber(result.effectiveCargoPerTransit, locale)} / {formatNumber(result.requestedCargoPerTransit, locale)} · {formatNumber(result.platformCargoCapacity, locale)} max · {result.cargoBaySlotsEach} {tr(locale, "slots")} / {localizedName("cargo-bay", locale, "entity")}
                  </span>
                </span>
              </div>
            ) : null}
            {loadingMode !== "ignore" ? (
              <div className="panel-card grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                <MetricCard
                  icon={<PackageOpen className="size-4" />}
                  label={tr(locale, "payloadInsertion")}
                  value={duration(result.payloadInsertionSeconds, locale)}
                  detail={tr(locale, "experimental")}
                />
                <MetricCard
                  icon={<Gauge className="size-4" />}
                  label={loadingMode === "robots" ? tr(locale, "throughput") : tr(locale, "inserterThroughput")}
                  value={`${formatNumber(result.payloadInsertionRate, locale)}/s`}
                  detail={`${result.silosToPlace} × ${localizedName(loadingInserterId, locale, "entity")}`}
                />
                {loadingMode === "robots" ? (
                  <MetricCard
                    icon={<FactorioIcon src={iconFor("logistic-robot")} alt="" size="sm" />}
                    label={tr(locale, "robotSupplyTime")}
                    value={duration(result.robotSupplySeconds, locale)}
                    detail={`${result.logisticRobotCount} × ${result.robotCargoCapacity} · ${duration(result.robotFlightSeconds, locale)} ${tr(locale, "robotFlightTime").toLowerCase()}`}
                  />
                ) : null}
                <MetricCard
                  icon={<Rocket className="size-4" />}
                  label={tr(locale, "siloCycle")}
                  value={duration(result.siloCycleSeconds, locale)}
                  detail={`${tr(locale, "beacons")}: ${maximumBeacons} max`}
                />
              </div>
            ) : null}
            {loadingMode === "robots" ? (
              <div className="notice-info">
                {tr(locale, "bufferChestAssumption")}
              </div>
            ) : loadingMode === "ignore" ? (
              <div className="notice-warning">
                {tr(locale, "ignoreInsertionWarning")}
              </div>
            ) : null}
            <div className="panel-card">
              <h3 className="mb-3 text-sm font-semibold">
                {tr(locale, "rocketParts")}
              </h3>
              <div className="grid gap-2 sm:grid-cols-3">
                {result.rocketPartIngredientsPerSecond.map((entry) => (
                  <div
                    key={entry.id}
                    className="flex items-center gap-3 rounded-lg border border-white/7 bg-[#151719] p-3"
                  >
                    <FactorioIcon src={entry.icon} alt="" size="lg" />
                    <span className="min-w-0 flex-1 whitespace-normal break-words text-xs leading-tight">
                      {localizedName(entry.id, locale, "item")}
                    </span>
                    <strong className="font-mono text-xs">
                      {formatNumber(entry.amount, locale, 5)}/s
                    </strong>
                  </div>
                ))}
              </div>
              {speedMode === "thrusters" ? (
                <div className="mt-3 grid gap-2 sm:grid-cols-2">
                  {["thruster-fuel", "thruster-oxidizer"].map((id) => (
                    <div
                      key={id}
                      className="flex items-center gap-3 rounded-lg border border-white/7 bg-[#151719] p-3"
                    >
                      <FactorioIcon
                        src={iconFor(id, "fluid")}
                        alt=""
                        size="lg"
                      />
                      <span className="flex-1 text-xs">
                        {localizedName(id, locale, "fluid")}
                      </span>
                      <strong className="font-mono text-xs">
                        {formatNumber(result.thrusterFuelPerSecond, locale)}/s
                      </strong>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
            <div className="notice-warning">
              {tr(locale, "preloadedNotice")}
            </div>
            {speedMode === "thrusters" ? (
              <div className="notice-info">
                {tr(locale, "thrusterEstimateNotice")}
              </div>
            ) : null}
            <GeometryDesign
              layout={result.siloLayout}
              machine={silo}
              locale={locale}
              title={`${result.silosToPlace} × ${localizedName("rocket-silo", locale, "entity")}`}
              subtitle={`${result.siloLayout.uniqueBeacons} ${tr(locale, "beacons")} · ${result.siloLayout.average} ${tr(locale, "activePerMachine")} ${loadingMode !== "ignore" ? `· ${tr(locale, "experimental")}` : ""}`}
            />
          </>
        )}
      </section>
    </div>
  );
}
