All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Scenarios ScenarioDetails.tsx

84.17% Statements 266/316
52.02% Branches 154/296
29.16% Functions 7/24
89.39% Lines 236/264

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826                                                                                                                76x 76x 76x 76x         113x         113x                         113x         223x 678x 108x   329x 108x                       437x 452x     803x             803x 803x 803x       803x     803x 803x 803x   803x   803x 830x 830x       803x 803x 803x 803x 803x     803x 803x     803x     803x 831x   831x   803x       803x 1x             1x       1x   1x           887x   803x 28x     859x   803x 9x       857x   803x 2x           890x   803x         857x                       803x           884x   803x                   10x 3212x   803x     803x   803x               2409x   803x 13x       13x 3212x         2x         3x     3x                 2x       8x         803x 1x 803x   803x   1x 1x       1606x   803x 1x 803x   803x   1x 1x       1606x   803x                 4818x   803x   803x   803x   15257x   803x   10x               26x                               857x   803x       803x             803x     27x           803x   27x   803x         1606x 2409x 803x         27x           803x   27x   830x 803x   1606x     2409x   2409x 2409x 803x         27x           803x   27x   830x 803x   1606x     2409x   2409x 2409x             908x 27x         803x 830x 1013x     803x 803x       29x     803x       861x 105x   908x 897x       27x     803x           857x     857x 27x         830x 27x       803x                   857x     857x 27x         830x 911x   30x       803x   3x       857x   863x     27x   27x     830x 857x 27x   803x 27x                           803x   830x     27x   27x   803x               803x   135x     803x   27x 1x     857x         857x       27x   803x                               803x 28x     1x 803x       1x                   859x           830x 859x   803x   27x               803x     27x         803x       27x     803x   27x   803x             803x       3212x 803x                                                                       12848x 2409x       27x     803x 803x       895x                     129x 27x 27x                     803x   27x   4x 4x 4x     803x 803x   803x     857x 27x 803x 803x     830x   857x   803x         2409x 1061x         12045x     27x 109x         1021x 830x     105x   908x 3212x 8833x   803x 1606x 4818x      
import { CircleHelp, Plus, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import SelectInput from "@/ahuora-design-system/inputs/SelectInput";
import {
  AccessControlledButton as Button,
  AccessControlledCheckbox as Checkbox,
} from "@/ahuora-design-system/ui/accessControlled";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/ahuora-design-system/ui/alert-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { Input } from "@/ahuora-design-system/ui/input";
import { Label } from "@/ahuora-design-system/ui/label";
import { ScrollArea, ScrollBar } from "@/ahuora-design-system/ui/scroll-area";
import { Tabs, TabsContent } from "@/ahuora-design-system/ui/tabs";
import { TabListComponent } from "@/ahuora-design-system/ui/tabs-content";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  MssInputModeEnum,
  ScenarioRead,
  SolverOptionEnum,
  StateNameEnum,
  useCoreDataColumnListQuery,
  useCoreScenarioPartialUpdateMutation,
  useMssDeleteCreateMutation,
} from "@/api/apiStore.gen";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import { useProjectId } from "@/hooks/project";
import { NUMERIC_COLUMNS_TOOLTIP } from "@/lib/uploads/importNotes";
import {
  CSVUploaderButton,
  CSVUploaderFile,
  type CSVUploaderFileRef,
} from "@/pages/flowsheet-page/multi-steady-state/CSVUploader";
import { DownloadTagMappingsButton } from "../../../multi-steady-state/DownloadTagMappings";
import { DynamicCheck } from "./DynamicCheck";
import { LiveSolarData } from "./LiveSolarData";
import { OptimisationCheck } from "./OptimisationCheck";
import { ParameterSweepPanel } from "./ParameterSweepPanel";
import ScenarioDataPanel from "./ScenarioDataPanel";
import { ScenarioNameBadge } from "./ScenarioNameBadge";
import { useScenarioFileUpload } from "./useScenarioFileUpload";
 
const SOLVE_TIMEOUT_MIN_SECONDS = 5;
const SOLVE_TIMEOUT_MAX_SECONDS = 60 * 60;
const SOLVE_TIMEOUT_DEFAULT_SECONDS = 300;
const MSS_INPUT_MODE_OPTIONS = [
  { value: MssInputModeEnum.Csv, label: "CSV" },
  { value: MssInputModeEnum.ParameterSweep, label: "Parameter sweep" },
];
 
const ToggleCheckbox = ({
  id,
  label,
  checked,
  onChange,
  disabled = false,
  tooltipContent,
  tooltipAriaLabel,
}: {
  id: string;
  label: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
  tooltipContent?: string;
  tooltipAriaLabel?: string;
}) => (
  <div className="flex flex-row gap-2 py-2 items-center">
    <Checkbox
      id={id}
      aria-label={label}
      checked={checked}
      disabled={disabled}
      onCheckedChange={(checked) => onChange(checked as boolean)}
    />
    <Label htmlFor={id} className="text-sm">
      {label}
    </Label>
    {tooltipContent && (
      <ToolTipCover content={tooltipContent} asChild side="right">
        <Button
          type="button"
          variant="ghost"
          size="xs"
          className="text-muted-foreground"
          aria-label={tooltipAriaLabel ?? `${id}-info`}
        >
          <CircleHelp size={14} />
        </Button>
      </ToolTipCover>
    )}
  </div>
);
 
export function ScenarioDetails({
  scenario,
  onClose,
}: {
  scenario: ScenarioRead;
  onClose?: () => void;
}) {
  const access = useFlowsheetAccess();
  const canMutate = access?.can_edit ?? true;
  const [uploadSource, setUploadSource] = useState<"file" | "solar" | null>(
    null,
  );
  const mssInputMode =
    scenario.mss_input_mode === MssInputModeEnum.ParameterSweep
      ? MssInputModeEnum.ParameterSweep
      : MssInputModeEnum.Csv;
  const [pendingCsvFile, setPendingCsvFile] = useState<File | null>(null);
  const [showCsvSwitchDialog, setShowCsvSwitchDialog] = useState(false);
  const [showCsvModeSwitchDialog, setShowCsvModeSwitchDialog] = useState(false);
  const [showSweepModeSwitchDialog, setShowSweepModeSwitchDialog] =
    useState(false);
 
  const { data: dataColumns } = useCoreDataColumnListQuery(
    { scenario: scenario?.id },
    { skip: !scenario },
  );
 
  const [updateOptimization, updateOptimizationState] =
    useCoreScenarioPartialUpdateMutation();
  const deleteMssMutation = useMssDeleteCreateMutation();
  const deleteMSS = deleteMssMutation[0];
  const isUpdatingScenario = updateOptimizationState.isLoading;
  const id = useProjectId();
 
  const data =
    useCoreDataColumnListQuery({ scenario: scenario.id })?.data || [];
  const ratingMode = scenario.enable_rating || false;
  // Keep local input state separate from persisted scenario state so users can
  // type partial numeric values without dispatching API updates on each keystroke.
  const [solveTimeoutInput, setSolveTimeoutInput] = useState(
    String(scenario.solve_timeout_seconds ?? SOLVE_TIMEOUT_DEFAULT_SECONDS),
  );
  const parsedSolveTimeout = Number(solveTimeoutInput);
  const roundedSolveTimeout = Number.isFinite(parsedSolveTimeout)
    ? Math.round(parsedSolveTimeout)
    : null;
  const isSolveTimeoutOutOfRange =
    roundedSolveTimeout !== null &&
    (roundedSolveTimeout < SOLVE_TIMEOUT_MIN_SECONDS ||
      roundedSolveTimeout > SOLVE_TIMEOUT_MAX_SECONDS);
 
  const handleSolveTimeoutUpdate = () => {
    const timeoutSeconds = Math.round(Number(solveTimeoutInput));
    if (!Number.isFinite(timeoutSeconds)) {
      return;
    }
 
    // Clamp in the UI as well as backend validation so the field snaps back to
    // an acceptable value even when the user types outside the valid range.
    const clampedTimeout = Math.min(
      SOLVE_TIMEOUT_MAX_SECONDS,
      Math.max(SOLVE_TIMEOUT_MIN_SECONDS, timeoutSeconds),
    );
    setSolveTimeoutInput(String(clampedTimeout));
 
    updateOptimization({
      id: scenario.id,
      patchedScenario: {
        solve_timeout_seconds: clampedTimeout,
      },
    });
  };
 
  useEffect(() => {
    setSolveTimeoutInput(
      String(scenario.solve_timeout_seconds ?? SOLVE_TIMEOUT_DEFAULT_SECONDS),
    );
  }, [scenario.id, scenario.solve_timeout_seconds]);
 
  const updateUploadedFileName = (name: string) => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: { Uploaded_fileName: name },
    });
  };
 
  const handleEnableOptimization = () => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: {
        enable_optimization: !scenario.enable_optimization,
      },
    });
  };
 
  const setRatingMode = (value: boolean) => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: { enable_rating: value },
    });
  };
 
  const {
    handleFileUpload,
    abortUpload,
    clearUploadState,
    retryImport,
    uploadState,
    importTask,
    importStartError,
    isStartingImport,
    csvWarnings,
  } = useScenarioFileUpload({
    onSuccess: () => {},
    onError: () => {},
    updateUploadedFileName,
    flowsheetId: id,
    scenarioId: scenario.id,
  });
 
  const handleScenarioFileUpload = (file: File) => {
    if (
      scenario.mss_input_mode === MssInputModeEnum.ParameterSweep &&
      mssInputMode !== MssInputModeEnum.Csv
    ) {
      setPendingCsvFile(file);
      setShowCsvSwitchDialog(true);
      return;
    }
 
    void handleFileUpload(file);
  };
 
  const cancelCsvSwitch = () => {
    setPendingCsvFile(null);
    setShowCsvSwitchDialog(false);
  };
 
  const confirmCsvSwitch = () => {
    const file = pendingCsvFile;
    setPendingCsvFile(null);
    setShowCsvSwitchDialog(false);
 
    if (file) {
      void handleFileUpload(file);
    }
  };
 
  const requestMssInputModeChange = async (mode: MssInputModeEnum) => {
    await updateOptimization({
      id: scenario.id,
      patchedScenario: { mss_input_mode: mode },
    }).unwrap();
    clearUploadState();
  };
 
  const handleMssInputModeChange = (value: MssInputModeEnum) => {
    if (value === MssInputModeEnum.Csv) {
      if (hasParameterSweepInput) {
        setShowCsvModeSwitchDialog(true);
        return;
      }
 
      if (scenario.mss_input_mode === MssInputModeEnum.ParameterSweep) {
        void requestMssInputModeChange(MssInputModeEnum.Csv).catch(() => {
          toast.error("Could not switch to CSV input.");
        });
      }
      return;
    }
 
    if (
      value === MssInputModeEnum.ParameterSweep &&
      mssInputMode !== MssInputModeEnum.ParameterSweep &&
      hasCsvInput
    ) {
      setShowSweepModeSwitchDialog(true);
      return;
    }
 
    void requestMssInputModeChange(value).catch(() => {
      toast.error("Could not switch input mode.");
    });
  };
 
  const cancelCsvModeSwitch = () => {
    setShowCsvModeSwitchDialog(false);
  };
 
  const confirmCsvModeSwitch = async () => {
    try {
      await requestMssInputModeChange(MssInputModeEnum.Csv);
      setShowCsvModeSwitchDialog(false);
    } catch (error) {
      toast.error("Could not switch to CSV input.");
    }
  };
 
  const cancelSweepModeSwitch = () => {
    setShowSweepModeSwitchDialog(false);
  };
 
  const confirmSweepModeSwitch = async () => {
    try {
      await requestMssInputModeChange(MssInputModeEnum.ParameterSweep);
      setShowSweepModeSwitchDialog(false);
    } catch (error) {
      toast.error("Could not switch to parameter sweep input.");
    }
  };
 
  const clearFile = () => {
    clearUploadState();
    deleteMSS({
      deleteData: { flowsheet: id, scenario: scenario.id },
    });
    updateOptimization({
      id: scenario.id,
      patchedScenario: { Uploaded_fileName: "" },
    });
  };
 
  const hasFile = !!scenario.Uploaded_fileName && data && data.length > 0;
  const hasCsvInput =
    scenario.mss_input_mode !== MssInputModeEnum.ParameterSweep && hasFile;
  const hasParameterSweepInput =
    scenario.mss_input_mode === MssInputModeEnum.ParameterSweep &&
    (Boolean(scenario.parameterSweepDefinition) ||
      dataColumns?.some((column) => column.property_value != null));
 
  const handleTabChange = (value) => {
    if (value === StateNameEnum.Dynamic) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: {
          enable_dynamics: true,
          state_name: StateNameEnum.Dynamic,
        },
      });
    } else if (value === StateNameEnum.Mss) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: {
          enable_dynamics: false,
          state_name: StateNameEnum.Mss,
        },
      });
    } else if (value === StateNameEnum.SteadyState) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: {
          enable_dynamics: false,
          state_name: StateNameEnum.SteadyState,
        },
      });
    }
  };
 
  const csvUploaderRef = useRef<CSVUploaderFileRef>(null);
 
  return (
    <div className="flex flex-col bg pb-1 w-full h-full">
      <AlertDialog
        open={showCsvSwitchDialog}
        onOpenChange={(open) => {
          setShowCsvSwitchDialog(open);
          if (!open) {
            setPendingCsvFile(null);
          }
        }}
      >
        <AlertDialogContent className="w-[calc(100vw-2rem)] max-w-sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Replace parameter sweep?</AlertDialogTitle>
            <AlertDialogDescription>
              Uploading a CSV will remove existing parameter sweep data for this
              scenario.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelCsvSwitch}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmCsvSwitch}>
              Upload CSV
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <AlertDialog
        open={showCsvModeSwitchDialog}
        onOpenChange={setShowCsvModeSwitchDialog}
      >
        <AlertDialogContent className="w-[calc(100vw-2rem)] max-w-sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Switch to CSV input?</AlertDialogTitle>
            <AlertDialogDescription>
              Switching to CSV will remove existing parameter sweep data for
              this scenario.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelCsvModeSwitch}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              disabled={isUpdatingScenario}
              onClick={() => void confirmCsvModeSwitch()}
            >
              Switch to CSV
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <AlertDialog
        open={showSweepModeSwitchDialog}
        onOpenChange={setShowSweepModeSwitchDialog}
      >
        <AlertDialogContent className="w-[calc(100vw-2rem)] max-w-sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Switch to parameter sweep?</AlertDialogTitle>
            <AlertDialogDescription>
              Switching to parameter sweep will remove existing CSV data for
              this scenario.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelSweepModeSwitch}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              disabled={isUpdatingScenario}
              onClick={() => void confirmSweepModeSwitch()}
            >
              Switch to parameter sweep
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
 
      {/* Header */}
      <div
        className="flex flex-row gap-5 justify-between items-center bg-accent p-2"
        aria-label="scenario-header"
      >
        <ScenarioNameBadge scenario={scenario} />
        <div
          className="flex flex-row text-sm font-light items-center cursor-pointer"
          onClick={onClose}
          aria-label="scenario-back-btn"
        >
          <X size={24} />
        </div>
      </div>
 
      <ScrollArea className="flex-1 p-2 gap-2 text-sm">
        <Tabs value={scenario.state_name} onValueChange={handleTabChange}>
          <p className="text-sm">General settings:</p>
 
          {/* Optimisation Toggle */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox
              id="enable_optimization"
              label="Enable optimisation"
              checked={scenario.enable_optimization ?? false}
              onChange={handleEnableOptimization}
              tooltipContent="Enables optimisation mode for this scenario so configured objectives and variable bounds are applied during solve."
              tooltipAriaLabel="enable-optimisation-info"
            />
            {scenario.enable_optimization && (
              <OptimisationCheck optimization={scenario} />
            )}
          </div>
 
          {/* Initialization Toggle */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox
              id="disable_initialization"
              label="Skip initialisation"
              checked={scenario.disable_initialization ?? false}
              onChange={(checked) => {
                updateOptimization({
                  id: scenario.id,
                  patchedScenario: { disable_initialization: checked },
                });
              }}
              tooltipContent="Uses current variable values as the solve starting point instead of running an initialisation step."
              tooltipAriaLabel="skip-initialisation-info"
            />
            {scenario.disable_initialization && (
              <p className="text-xs">
                No initialisation will be performed. This may speed up solving
                if you have initialised previously.
              </p>
            )}
            <ToggleCheckbox
              id="skip_initialization_for_units_with_initial_values"
              label="Skip initialisation for units with initial values"
              checked={
                scenario.skip_initialization_for_units_with_initial_values ??
                false
              }
              onChange={(checked) => {
                updateOptimization({
                  id: scenario.id,
                  patchedScenario: {
                    skip_initialization_for_units_with_initial_values: checked,
                  },
                });
              }}
              tooltipContent="Runs initialisation only for units without saved initial values."
              tooltipAriaLabel="skip-initialisation-with-values-info"
            />
            {scenario.skip_initialization_for_units_with_initial_values && (
              <p className="text-xs">
                Only units with saved initial values will skip initialisation.
                New units will still run initialisation.
              </p>
            )}
          </div>
 
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox
              id="send_solve_complete_email"
              label="Email me when solve completes"
              checked={scenario.send_solve_complete_email ?? false}
              onChange={(checked) => {
                updateOptimization({
                  id: scenario.id,
                  patchedScenario: { send_solve_complete_email: checked },
                });
              }}
            />
          </div>
 
          {/* Rating Mode */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <div className="flex flex-row gap-2 py-2 items-center">
              <Checkbox
                id="rating-mode"
                checked={ratingMode}
                onCheckedChange={(checked) => setRatingMode(checked as boolean)}
              />
              <Label htmlFor="rating-mode" className="text-sm">
                Rating mode
              </Label>
              <ToolTipCover
                content="Disables any configured variable replacement"
                asChild
                side="right"
              >
                <Button
                  type="button"
                  variant="ghost"
                  size="xs"
                  className="text-muted-foreground"
                  aria-label="rating-mode-info"
                >
                  <CircleHelp size={14} />
                </Button>
              </ToolTipCover>
            </div>
          </div>
 
          {/* Solver Selection, combobox */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <div className="flex items-center gap-2">
              <Label htmlFor="solver-select" className="text-sm">
                Solver
              </Label>
 
              <div className="lg:w-44 md:w-40 sm:w-full">
                <SelectInput
                  ariaLabel="solver-select"
                  // If SelectInput supports id/aria-labelledby, this ties it to the Label above
                  // id="solver-select"
                  title={undefined} // keep label on same row (avoid duplicated title inside)
                  value={scenario.solver_option ?? ""}
                  data={
                    Object.entries(SolverOptionEnum).map(([, value]) => ({
                      label: value,
                      value: value,
                    })) as { label: string; value: string }[]
                  }
                  handleChange={(val: string) =>
                    updateOptimization({
                      id: scenario.id,
                      patchedScenario: { solver_option: val },
                    })
                  }
                />
              </div>
            </div>
          </div>
 
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <div className="flex items-center gap-1">
              <Label htmlFor="solve-timeout-seconds" className="text-sm">
                Solve timeout (seconds)
              </Label>
              <ToolTipCover
                content="For multi steady-state, only sub-solves are subject to timeouts."
                asChild
                side="right"
              >
                <Button
                  type="button"
                  variant="ghost"
                  size="xs"
                  className="text-muted-foreground"
                  aria-label="solve-timeout-scope"
                >
                  <CircleHelp size={14} />
                </Button>
              </ToolTipCover>
            </div>
            <Input
              value={solveTimeoutInput}
              onInput={(event) => {
                setSolveTimeoutInput(event.currentTarget.value);
              }}
              onBlur={handleSolveTimeoutUpdate}
              onKeyDown={(event) => {
                if (event.key === "Enter") {
                  event.currentTarget.blur();
                }
              }}
              type="number"
              min={SOLVE_TIMEOUT_MIN_SECONDS}
              max={SOLVE_TIMEOUT_MAX_SECONDS}
              step={1}
              id="solve-timeout-seconds"
              aria-label="solve-timeout-seconds"
              className="mt-2"
            />
            {isSolveTimeoutOutOfRange && (
              <p className="mt-2 text-xs text-rose-700">
                Timeout must be between {SOLVE_TIMEOUT_MIN_SECONDS} and{" "}
                {SOLVE_TIMEOUT_MAX_SECONDS} seconds.
              </p>
            )}
          </div>
 
          <p className="text-sm pb-2">Simulation-specific settings:</p>
 
          <TabListComponent
            tabValues={[
              { value: StateNameEnum.SteadyState, label: "Steady" },
              { value: StateNameEnum.Mss, label: "Multiple" },
              { value: StateNameEnum.Dynamic, label: "Dynamics" },
            ]}
            className="flex flex-row bg-muted text-secondary-foreground rounded-t-lg shadow-sm"
            writeAccessOnly
          />
 
          {/* Steady State */}
          <TabsContent value={StateNameEnum.SteadyState}>
            <p className="text-sm my-2">
              Solve the flowsheet based on the conditions set in the flowsheet.
              No additional settings are required.
            </p>
          </TabsContent>
 
          {/* Multiple Steady State */}
          <TabsContent value={StateNameEnum.Mss}>
            <p className="text-sm my-2">
              Solve the flowsheet multiple times with CSV data or a parameter
              sweep.
            </p>
            <div className="border p-2 rounded-lg my-2 bg-muted">
              <Label className="text-sm" htmlFor="mss-input-mode">
                Input mode
              </Label>
              <div className="mt-2">
                <SelectInput
                  id="mss-input-mode"
                  ariaLabel="mss-input-mode"
                  value={mssInputMode}
                  data={MSS_INPUT_MODE_OPTIONS}
                  disabled={!canMutate}
                  handleChange={handleMssInputModeChange}
                />
              </div>
            </div>
            {mssInputMode === MssInputModeEnum.Csv ? (
              <ScenarioDataPanel
                hasFile={hasFile}
                clearFile={clearFile}
                scenario={scenario}
                dataColumns={dataColumns ?? []}
                uploadState={uploadState}
                importTask={importTask}
                importStartError={importStartError}
                abortUpload={abortUpload}
                clearUploadState={clearUploadState}
                retryImport={retryImport}
                isStartingImport={isStartingImport}
                csvWarnings={csvWarnings}
                canMutate={canMutate}
                uploadControl={
                  <CSVUploaderButton
                    onUpload={handleScenarioFileUpload}
                    buttonText={
                      uploadState.status === "resume_available"
                        ? "Resume upload"
                        : "Choose file"
                    }
                    tooltipContent={NUMERIC_COLUMNS_TOOLTIP}
                  />
                }
                trailingAction={<DownloadTagMappingsButton />}
                containerAriaLabel="scn-multiple-container"
                progressAriaLabel="mss-upload-progress"
              />
            ) : (
              <ParameterSweepPanel
                scenario={scenario}
                dataColumns={dataColumns ?? []}
                canMutate={canMutate}
              />
            )}
          </TabsContent>
 
          {/* Dynamics Tab */}
          <TabsContent value={StateNameEnum.Dynamic}>
            <p className="text-sm my-2">
              Solve the flowsheet dynamically, incorporating time-based changes
              such as tank levels and battery charge levels.
            </p>
            <ScenarioDataPanel
              hasFile={hasFile}
              clearFile={clearFile}
              scenario={scenario}
              dataColumns={dataColumns ?? []}
              uploadState={uploadState}
              importTask={importTask}
              importStartError={importStartError}
              abortUpload={abortUpload}
              clearUploadState={clearUploadState}
              retryImport={retryImport}
              isStartingImport={isStartingImport}
              csvWarnings={csvWarnings}
              canMutate={canMutate}
              uploadControl={
                <>
                  <DropdownMenu>
                    <ToolTipCover
                      asChild
                      content={NUMERIC_COLUMNS_TOOLTIP}
                      delay={150}
                      side="top"
                    >
                      <DropdownMenuTrigger asChild>
                        <Button variant="outline">
                          <Plus /> Add data
                        </Button>
                      </DropdownMenuTrigger>
                    </ToolTipCover>
                    <DropdownMenuContent className="w-full p-0">
                      <DropdownMenuItem
                        onClick={() => {
                          setUploadSource("file");
                          setTimeout(
                            () => csvUploaderRef.current?.openFileDialog(),
                            0,
                          );
                        }}
                        disabled={!canMutate}
                      >
                        {uploadState.status === "resume_available"
                          ? "Resume upload"
                          : "Choose from file"}
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setUploadSource("solar")}
                        disabled={!canMutate}
                      >
                        Add live data
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
 
                  {uploadSource === "file" && (
                    <CSVUploaderFile
                      ref={csvUploaderRef}
                      onUpload={handleScenarioFileUpload}
                    />
                  )}
                </>
              }
              containerAriaLabel="scn-dynamic-upload-panel"
              progressAriaLabel="dynamic-upload-progress"
              emptyFileLabel="No data added"
            />
 
            {/* LiveSolarData stays mounted until upload is successful */}
            <div className="mt-2">
              {uploadSource === "solar" && (
                <LiveSolarData
                  optimization={scenario}
                  onAdded={() => setUploadSource(null)} //
                />
              )}
            </div>
 
            {/* Dynamic Check */}
            {scenario.enable_dynamics && (
              <DynamicCheck optimization={scenario} />
            )}
          </TabsContent>
        </Tabs>
 
        <ScrollBar orientation="vertical" />
      </ScrollArea>
    </div>
  );
}