All files / src/pages/flowsheet-page/economics/cost-items-panel/unit-costs UnitCostCard.tsx

64% Statements 160/250
73.09% Branches 182/249
52.94% Functions 18/34
68.26% Lines 142/208

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 827                                                                                                                                                                                                                    32x 32x   32x 32x 32x   32x 32x 32x 32x 32x   32x     32x 32x 32x 32x 32x 32x           32x 32x   32x   32x   32x 32x 32x 32x 32x 32x 32x   32x 1x               32x 1x                                 1x   4x 4x         4x       4x     3x 3x 3x         3x       3x                                       3x   1x         1x 1x 1x     1x 1x 1x                                                         2x 2x       2x     1x 1x 1x             32x 32x 32x     32x     32x         32x               32x 32x     32x               32x     32x       32x       32x                 32x             32x   32x                               32x   32x   32x     32x                     32x       32x                                             32x                                 2x                                                                                                                                                 1x   1x                                 1x                                                                                                                       116x     4x   120x 121x 126x       32x         32x 32x 32x 32x 32x 32x   32x   6x 6x                             1x 1x 1x 74x           32x 74x   32x       36x   42x     32x                 32x           36x     36x               48x 32x 32x 32x 32x   32x               6x 6x                                   80x           32x 68x   32x       36x   40x                                   32x 32x 32x   6x           9x                             17x         7x                 1x   26x                   17x 17x   17x     17x 17x 17x 17x             36x                                                                
import { ChevronDown } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import type {
  CapitalCostLineRead,
  CostableItemRead,
  CostCurveAuthoring,
  CostCurveEquipmentCategoryRead,
  CostCurveRead,
  CostDriverRead,
  EconomicsLangFactorDefaultRead,
  EconomicsResultLineRead,
  EquipmentMappingRead,
  PatchedCapitalCostLine,
  PatchedCostableItem,
  PatchedEquipmentMapping,
  SimulationObjectRead,
} from "@/api/apiStore.gen";
import { DepreciationModeEnum } from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import { CapitalCostBreakdown } from "../../capital/EconomicsCapitalBreakdown";
import {
  apiFieldMessages,
  CostCurveDriverInputsControls,
  hasInvalidDriverSpecPayload,
  mutationErrorMessage,
  requiredDriverSpecsFromCurve,
} from "../../cost-curves";
import { scrollElementIntoEconomicsContext } from "../../shared/model/economicsScroll";
import { ValueWithFixedUnitField } from "../../shared/ui/EconomicsFormFields";
import { EconomicsWarningNotice } from "../../shared/ui/EconomicsWarningNotice";
import { CapitalDepreciationControls } from "../depreciation/CapitalDepreciationControls";
import { MappingControls } from "../mapping/MappingControls";
import {
  type CapitalDepreciationDraft,
  capitalDepreciationDraftFromLine,
} from "../model/capitalDepreciationDraft";
import {
  capitalLineEstimateLabel,
  costDriverSizingLabel,
  costDriverSizingValueLabel,
  costItemWarningGroups,
  formatUnitOperationType,
  isStaleUnsupportedSupportedUnit,
  isUnsupportedUnitCost,
  usesInstalledCostBasis,
  visibleMappingFieldMessages,
  visibleUnitSaveState,
} from "../model/capitalLineHelpers";
import {
  FOCUSED_CONTEXT_SCROLL_CLASS,
  type ResourceFieldMessages,
  type ResourceSaveStates,
  type SaveState,
  type UnitCostRow,
} from "../model/capitalLineTypes";
import { FormState, WarningList } from "../ui/CapitalLineUi";
import { UnitInclusionControl } from "./UnitInclusionControl";
 
export function UnitCostCard({
  row,
  curves,
  equipmentOptions,
  langFactorDefaults,
  capitalLine,
  resultLines,
  canEdit,
  busy,
  onEnableCosting,
  onCostableItemPatch,
  onMappingPatch,
  onCapitalLinePatch,
  onCreateCurve,
  costCurveSaving,
  resultStale,
  resultRunId,
  isFocused,
}: {
  row: UnitCostRow;
  curves: CostCurveRead[];
  equipmentOptions: readonly CostCurveEquipmentCategoryRead[];
  langFactorDefaults: EconomicsLangFactorDefaultRead[];
  capitalLine?: CapitalCostLineRead;
  resultLines: EconomicsResultLineRead[];
  canEdit: boolean;
  busy: boolean;
  onEnableCosting: (unit: SimulationObjectRead) => Promise<void>;
  onCostableItemPatch: (
    item: CostableItemRead,
    patch: PatchedCostableItem,
  ) => Promise<void>;
  onMappingPatch: (
    mapping: EquipmentMappingRead,
    patch: PatchedEquipmentMapping,
  ) => Promise<void>;
  onCapitalLinePatch: (
    line: CapitalCostLineRead,
    patch: PatchedCapitalCostLine,
  ) => Promise<void>;
  onCreateCurve: (curve: CostCurveAuthoring) => Promise<CostCurveRead>;
  costCurveSaving: boolean;
  resultStale: boolean;
  resultRunId: number | null;
  isFocused?: boolean;
}) {
  const item = row.costableItem;
  const unitName = row.unit.componentName || `Unit ${row.unit.id}`;
  const unsupportedByCostDriver =
    item?.cost_driver?.unresolved_reason_code === "unit_unsupported";
  const unsupported = isUnsupportedUnitCost(row) || unsupportedByCostDriver;
  const staleUnsupportedSupportedUnit = isStaleUnsupportedSupportedUnit(row);
  const controlsUnavailable =
    staleUnsupportedSupportedUnit || unsupportedByCostDriver;
  const mapping = controlsUnavailable ? undefined : item?.equipment_mapping;
  const driver = controlsUnavailable ? undefined : item?.cost_driver;
  const selectedCurve = curves.find(
    (curve) => curve.id === mapping?.cost_curve,
  );
  const curveSummary = mapping
    ? (selectedCurve?.name ?? "No curve selected")
    : "";
  const sizingSummary = costDriverSizingLabel(driver);
  const sizingValueSummary = costDriverSizingValueLabel(driver, capitalLine);
  const unitTypeSummary = formatUnitOperationType(row.unit.objectType);
  const estimateSummary = capitalLineEstimateLabel(capitalLine);
  const detailSummary = curveSummary;
  const warningGroups = costItemWarningGroups({
    capitalLine,
    driver,
    mapping,
    selectedCurve,
  });
  const unitResultLines = item
    ? resultLines.filter((line) => line.source_costable_item === item.id)
    : [];
  const [saveState, setSaveState] = useState<SaveState>({ kind: "idle" });
  const [fieldMessagesByResource, setFieldMessagesByResource] =
    useState<ResourceFieldMessages>({});
  const [saveStatesByResource, setSaveStatesByResource] =
    useState<ResourceSaveStates>({});
  const [open, setOpen] = useState(false);
  const articleRef = useRef<HTMLElement | null>(null);
  const saveTimeoutRefs = useRef<Record<string, number>>({});
  const pendingMappingPatch = useRef<PatchedEquipmentMapping>({});
  const pendingCostablePatch = useRef<PatchedCostableItem>({});
  const pendingCapitalLinePatch = useRef<PatchedCapitalCostLine>({});
 
  useEffect(() => {
    const saveTimeouts = saveTimeoutRefs.current;
    return () => {
      Object.values(saveTimeouts).forEach((timeoutId) =>
        window.clearTimeout(timeoutId),
      );
    };
  }, []);
 
  useEffect(() => {
    if (!isFocused) return;
    setOpen(true);
    window.requestAnimationFrame(() => {
      if (articleRef.current) {
        scrollElementIntoEconomicsContext(articleRef.current);
      }
      articleRef.current?.focus();
    });
  }, [isFocused, row.unit.id]);
 
  const scheduleSave = (
    key: string,
    action: () => Promise<void>,
    successMessage: string,
    delay = true,
  ) => {
    if (saveTimeoutRefs.current[key]) {
      window.clearTimeout(saveTimeoutRefs.current[key]);
    }
    setFieldMessagesByResource((current) => {
      if (!current[key]) return current;
      const next = { ...current };
      delete next[key];
      return next;
    });
    setSaveStatesByResource((current) => ({
      ...current,
      [key]: { kind: "saving", message: "Saving capital line" },
    }));
    setSaveState({ kind: "saving", message: "Saving capital line" });
    const run = async () => {
      try {
        await action();
        setFieldMessagesByResource((current) => {
          if (!current[key]) return current;
          const next = { ...current };
          delete next[key];
          return next;
        });
        setSaveStatesByResource((current) => ({
          ...current,
          [key]: { kind: "saved", message: successMessage },
        }));
        setSaveState({ kind: "saved", message: successMessage });
      } catch (error) {
        setFieldMessagesByResource((current) => ({
          ...current,
          [key]: apiFieldMessages(error),
        }));
        setSaveStatesByResource((current) => ({
          ...current,
          [key]: {
            kind: "error",
            message: mutationErrorMessage(error),
          },
        }));
        setSaveState({
          kind: "error",
          message: mutationErrorMessage(error),
        });
      }
    };
    if (delay) {
      saveTimeoutRefs.current[key] = window.setTimeout(run, 300);
    } else {
      void run();
    }
  };
 
  const saveMapping = (patch: PatchedEquipmentMapping) => {
    Iif (!mapping) return;
    pendingMappingPatch.current = { ...pendingMappingPatch.current, ...patch };
    scheduleSave(
      `mapping-${mapping.id}`,
      () => {
        const mergedPatch = pendingMappingPatch.current;
        pendingMappingPatch.current = {};
        return onMappingPatch(mapping, mergedPatch);
      },
      "Capital settings saved",
      true,
    );
  };
 
  const saveCostableItem = (patch: PatchedCostableItem) => {
    Iif (!item) return;
    pendingCostablePatch.current = {
      ...pendingCostablePatch.current,
      ...patch,
    };
    scheduleSave(
      `costable-${item.id}`,
      () => {
        const mergedPatch = pendingCostablePatch.current;
        pendingCostablePatch.current = {};
        return onCostableItemPatch(item, mergedPatch);
      },
      "Unit inclusion saved",
      true,
    );
  };
 
  const saveCapitalLine = (
    patch: PatchedCapitalCostLine,
    successMessage = "Peak demand saved",
  ) => {
    Iif (!capitalLine) return;
    pendingCapitalLinePatch.current = {
      ...pendingCapitalLinePatch.current,
      ...patch,
    };
    scheduleSave(
      `capital-line-${capitalLine.id}`,
      () => {
        const mergedPatch = pendingCapitalLinePatch.current;
        pendingCapitalLinePatch.current = {};
        return onCapitalLinePatch(capitalLine, mergedPatch);
      },
      successMessage,
      true,
    );
  };
 
  const costableResourceKey = item ? `costable-${item.id}` : "";
  const mappingResourceKey = mapping ? `mapping-${mapping.id}` : "";
  const capitalLineResourceKey = capitalLine
    ? `capital-line-${capitalLine.id}`
    : "";
  const capitalLineSaveState = capitalLine
    ? saveStatesByResource[capitalLineResourceKey]
    : undefined;
  const [peakDemandValue, setPeakDemandValue] = useStablePeakDemandValue(
    capitalLine,
    capitalLineSaveState,
  );
  const [depreciationDraft, setDepreciationDraft] =
    useStableCapitalDepreciationDraft(capitalLine, capitalLineSaveState);
  const patchDepreciation = (
    patch: PatchedCapitalCostLine,
    draftPatch: Partial<CapitalDepreciationDraft>,
  ) => {
    setDepreciationDraft(draftPatch);
    saveCapitalLine(patch, "Depreciation treatment saved");
  };
  const showPeakDemandField = capitalLine?.minimum_peak_demand_kw != null;
  const rawMappingFieldMessages = mapping
    ? (fieldMessagesByResource[mappingResourceKey] ?? {})
    : {};
  const requiredMessages = requiredCapitalLineMessages({
    item,
    mapping,
    driver,
    selectedCurve,
    capitalLine,
    peakDemandValue,
  });
  const apiVisibleMappingFieldMessages = mapping
    ? visibleMappingFieldMessages(mapping, rawMappingFieldMessages)
    : {};
  const mappingFieldMessages = {
    ...apiVisibleMappingFieldMessages,
    ...requiredMessages.mapping,
  };
  const capitalLineFieldMessages = {
    ...(fieldMessagesByResource[capitalLineResourceKey] ?? {}),
    ...requiredMessages.capitalLine,
  };
  const depreciationControls = capitalLine ? (
    <CapitalDepreciationControls
      idPrefix={`unit-capital-${capitalLine.id}`}
      draft={depreciationDraft}
      disabled={!canEdit || busy}
      fieldMessages={capitalLineFieldMessages}
      onPatch={patchDepreciation}
    />
  ) : null;
  const visibleSaveState = mapping
    ? visibleUnitSaveState(
        saveState,
        rawMappingFieldMessages,
        apiVisibleMappingFieldMessages,
      )
    : saveState;
  const detailsId = `unit-cost-details-${row.unit.id}`;
  const peakDemandField =
    showPeakDemandField && capitalLine ? (
      <ValueWithFixedUnitField
        id={`capital-peak-demand-${capitalLine.id}`}
        label="Peak demand"
        help="Electrical-upgrade demand for this unit. Must be at least the current flowsheet work."
        value={peakDemandValue}
        unit="kW"
        unitDisplay="compact-field"
        disabled={!canEdit || busy}
        error={capitalLineFieldMessages.peak_demand_kw}
        onValueChange={(value) => {
          setPeakDemandValue(value);
          saveCapitalLine({ peak_demand_kw: value || null });
        }}
      />
    ) : null;
  const selectedCurveDriverSpecs = requiredDriverSpecsFromCurve(selectedCurve);
  const selectedCurveHasInvalidDriverSpecs =
    hasInvalidDriverSpecPayload(selectedCurve);
  const usesCapitalLineDriverInputs =
    selectedCurveDriverSpecs.length > 0 &&
    !selectedCurveHasInvalidDriverSpecs &&
    Boolean(driver && capitalLine);
  const selectedSpecBackedCurveWithoutCapitalLine = Boolean(
    driver &&
      selectedCurve &&
      selectedCurveDriverSpecs.length > 0 &&
      !selectedCurveHasInvalidDriverSpecs &&
      !capitalLine,
  );
  // Keyed remounting resets optimistic capital-line driver input state when the
  // selected curve or persisted line changes, without synchronizing props into
  // local state with an effect.
  const driverInputsControlsKey =
    selectedCurve && capitalLine
      ? `${selectedCurve.id}:${selectedCurve.updated_at}:${capitalLine.id}:${JSON.stringify(capitalLine.driver_inputs ?? {})}`
      : "";
  const driverControls =
    selectedCurveHasInvalidDriverSpecs ? null : selectedSpecBackedCurveWithoutCapitalLine ? (
      <PendingCapitalLineInputsNotice />
    ) : driver &&
      usesCapitalLineDriverInputs &&
      selectedCurve &&
      capitalLine ? (
      <CostCurveDriverInputsControls
        key={driverInputsControlsKey}
        driver={driver}
        capitalLine={capitalLine}
        selectedCurve={selectedCurve}
        canEdit={canEdit}
        busy={busy}
        error={capitalLineFieldMessages.driver_inputs}
        sizingWarnings={warningGroups.sizing}
        onCapitalLinePatch={(patch) =>
          saveCapitalLine(patch, "Capital inputs saved")
        }
      />
    ) : !driver ? (
      <DefaultDriverSummary unsupported={unsupported} />
    ) : null;
  const mappingDriverControls =
    selectedCurveHasInvalidDriverSpecs ? null : selectedSpecBackedCurveWithoutCapitalLine ? (
      <PendingCapitalLineInputsNotice />
    ) : driver &&
      usesCapitalLineDriverInputs &&
      selectedCurve &&
      capitalLine ? (
      <CostCurveDriverInputsControls
        key={driverInputsControlsKey}
        driver={driver}
        capitalLine={capitalLine}
        selectedCurve={selectedCurve}
        canEdit={canEdit}
        busy={busy}
        error={capitalLineFieldMessages.driver_inputs}
        sizingWarnings={warningGroups.sizing}
        className="contents"
        onCapitalLinePatch={(patch) =>
          saveCapitalLine(patch, "Capital inputs saved")
        }
      />
    ) : !driver ? (
      <DefaultDriverSummary unsupported={unsupported} />
    ) : null;
 
  return (
    <article
      ref={articleRef}
      tabIndex={-1}
      className={cn(
        "rounded-md border bg-background",
        FOCUSED_CONTEXT_SCROLL_CLASS,
        isFocused ? "bg-primary/5 outline outline-1 outline-primary" : null,
      )}
      aria-label={`Capital lines for ${unitName}`}
    >
      <div className="grid grid-cols-[minmax(0,1fr)_auto] items-stretch">
        <button
          type="button"
          className="min-w-0 px-3 py-2 text-left hover:bg-muted/30"
          aria-label={`Toggle capital line item ${unitName}`}
          aria-expanded={open}
          aria-controls={detailsId}
          onClick={() => setOpen((current) => !current)}
        >
          <div className="min-w-0">
            <div className="flex min-w-0 items-center gap-2">
              <div className="min-w-0 truncate text-sm font-medium">
                {unitName}
              </div>
              {detailSummary && (
                <Badge
                  variant={selectedCurve ? "muted" : "pending"}
                  size="xs"
                  borderRadius="round"
                  className="h-[22px] max-w-[min(32rem,70%)] min-w-0 truncate"
                >
                  {detailSummary}
                </Badge>
              )}
            </div>
            <div className="mt-2 grid gap-2 text-xs text-muted-foreground sm:grid-cols-4">
              <SummaryMetric label="Type" value={unitTypeSummary} />
              <SummaryMetric label="Sizing" value={sizingSummary} />
              <SummaryMetric label="Sizing value" value={sizingValueSummary} />
              <SummaryMetric label="Capital cost" value={estimateSummary} />
            </div>
          </div>
        </button>
        <div className="flex flex-wrap items-center justify-end gap-2 px-2 py-2">
          {isFocused && (
            <Badge variant="secondary" size="xs" borderRadius="round">
              Selected unit
            </Badge>
          )}
          {item && !staleUnsupportedSupportedUnit && (
            <UnitInclusionControl
              item={item}
              canEdit={canEdit}
              error={fieldMessagesByResource[costableResourceKey]?.included}
              saveState={saveStatesByResource[costableResourceKey]}
              onChange={(included) => saveCostableItem({ included })}
            />
          )}
          {(!item || staleUnsupportedSupportedUnit) && (
            <Button
              type="button"
              size="sm"
              disabled={!canEdit || busy}
              aria-label={`Enable capital line for ${unitName}`}
              onClick={() => {
                scheduleSave(
                  `enable-${row.unit.id}`,
                  () => onEnableCosting(row.unit),
                  "Capital line enabled",
                  false,
                );
              }}
            >
              Enable capital line
            </Button>
          )}
          <Button
            type="button"
            size="sm"
            variant="ghost"
            className="h-8 px-2 text-muted-foreground"
            aria-label={`${open ? "Collapse" : "Expand"} capital line item ${unitName}`}
            aria-expanded={open}
            aria-controls={detailsId}
            onClick={() => setOpen((current) => !current)}
          >
            <ChevronDown
              className={`size-4 shrink-0 transition-transform ${
                open ? "rotate-180" : ""
              }`}
              aria-hidden="true"
            />
          </Button>
        </div>
      </div>
      {open && (
        <div id={detailsId} className="border-t p-3">
          <FormState state={visibleSaveState} />
          <div className="space-y-3">
            {mapping ? (
              <MappingControls
                mapping={mapping}
                unitObjectType={row.unit.objectType}
                driverControls={mappingDriverControls}
                selectedCurve={selectedCurve}
                warningGroups={warningGroups}
                curves={curves}
                equipmentOptions={equipmentOptions}
                langFactorDefaults={langFactorDefaults}
                canEdit={canEdit}
                onMappingPatch={saveMapping}
                onCreateCurve={onCreateCurve}
                costCurveSaving={costCurveSaving}
                fieldMessages={mappingFieldMessages}
                saveState={saveStatesByResource[mappingResourceKey]}
              >
                {peakDemandField}
                {depreciationControls}
              </MappingControls>
            ) : (
              <>
                {driverControls}
                <DefaultMappingSummary />
                <WarningList
                  label="Capital warnings"
                  warnings={warningGroups.general}
                />
                {peakDemandField}
                {depreciationControls}
              </>
            )}
            <CapitalCostBreakdown
              lines={unitResultLines}
              stale={resultStale}
              runId={resultRunId}
              unitName={row.unit.componentName}
            />
          </div>
        </div>
      )}
    </article>
  );
}
 
function SummaryMetric({ label, value }: { label: string; value: string }) {
  return (
    <span className="min-w-0">
      <span className="block text-[11px] uppercase text-muted-foreground/80">
        {label}
      </span>
      <span className="block truncate text-foreground">{value}</span>
    </span>
  );
}
 
function useStablePeakDemandValue(
  capitalLine: CapitalCostLineRead | undefined,
  saveState?: SaveState,
): [string, (value: string) => void] {
  const canonicalValue =
    capitalLine?.peak_demand_kw ?? capitalLine?.minimum_peak_demand_kw ?? "";
  const canonicalKey = `${capitalLine?.id ?? ""}|${canonicalValue}|${capitalLine?.updated_at ?? ""}`;
  const [draftValue, setDraftValue] = useState(canonicalValue);
  const [draftDirty, setDraftDirty] = useState(false);
  const editBaseCanonicalKeyRef = useRef(canonicalKey);
  const pending = saveState?.kind === "saving";
 
  useEffect(() => {
    if (draftValue === canonicalValue) {
      editBaseCanonicalKeyRef.current = canonicalKey;
      setDraftDirty(false);
      return;
    }
    if (draftDirty && pending) {
      editBaseCanonicalKeyRef.current = canonicalKey;
      return;
    }
    Iif (draftDirty && saveState?.kind === "error") return;
    if (
      draftDirty &&
      saveState?.kind === "saved" &&
      canonicalKey === editBaseCanonicalKeyRef.current
    ) {
      return;
    }
    setDraftValue(canonicalValue);
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDraftDirty(false);
  }, [
    canonicalKey,
    canonicalValue,
    draftDirty,
    draftValue,
    pending,
    saveState?.kind,
  ]);
 
  const setDirtyDraftValue = (value: string) => {
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDraftValue(value);
    setDraftDirty(true);
  };
 
  return [draftValue, setDirtyDraftValue];
}
 
function useStableCapitalDepreciationDraft(
  capitalLine: CapitalCostLineRead | undefined,
  saveState?: SaveState,
): [
  CapitalDepreciationDraft,
  (draftPatch: Partial<CapitalDepreciationDraft>) => void,
] {
  const canonicalDraft = useMemo(
    () =>
      capitalLine
        ? capitalDepreciationDraftFromLine(capitalLine)
        : {
            depreciation_mode: DepreciationModeEnum.StudyDefault,
            depreciation_life_years: "",
            depreciation_salvage_percent: "",
          },
    [capitalLine],
  );
  const canonicalKey = capitalLine
    ? [
        capitalLine.id,
        capitalLine.updated_at,
        canonicalDraft.depreciation_mode,
        canonicalDraft.depreciation_life_years,
        canonicalDraft.depreciation_salvage_percent,
      ].join("|")
    : "none";
  const [draft, setDraft] = useState(canonicalDraft);
  const [draftDirty, setDraftDirty] = useState(false);
  const editBaseCanonicalKeyRef = useRef(canonicalKey);
  const pending = saveState?.kind === "saving";
 
  useEffect(() => {
    if (
      draft.depreciation_mode === canonicalDraft.depreciation_mode &&
      draft.depreciation_life_years ===
        canonicalDraft.depreciation_life_years &&
      draft.depreciation_salvage_percent ===
        canonicalDraft.depreciation_salvage_percent
    ) {
      editBaseCanonicalKeyRef.current = canonicalKey;
      setDraftDirty(false);
      return;
    }
    if (draftDirty && pending) {
      editBaseCanonicalKeyRef.current = canonicalKey;
      return;
    }
    Iif (draftDirty && saveState?.kind === "error") return;
    if (
      draftDirty &&
      saveState?.kind === "saved" &&
      canonicalKey === editBaseCanonicalKeyRef.current
    ) {
      return;
    }
    setDraft(canonicalDraft);
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDraftDirty(false);
  }, [
    canonicalDraft,
    canonicalKey,
    draft,
    draftDirty,
    pending,
    saveState?.kind,
  ]);
 
  const setDirtyDraft = (draftPatch: Partial<CapitalDepreciationDraft>) => {
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDraft((current) => ({ ...current, ...draftPatch }));
    setDraftDirty(true);
  };
 
  return [draft, setDirtyDraft];
}
 
function requiredCapitalLineMessages({
  item,
  mapping,
  driver,
  selectedCurve,
  capitalLine,
  peakDemandValue,
}: {
  item?: CostableItemRead;
  mapping?: EquipmentMappingRead;
  driver?: CostDriverRead;
  selectedCurve?: CostCurveRead;
  capitalLine?: CapitalCostLineRead;
  peakDemandValue: string;
}) {
  const active = Boolean(item?.included);
  const mappingMessages: Record<string, string> = {};
  const capitalLineMessages: Record<string, string> = {};
  if (!active) {
    return {
      mapping: mappingMessages,
      capitalLine: capitalLineMessages,
    };
  }
  if (mapping && !mapping.cost_curve) {
    mappingMessages.cost_curve = "Select a cost curve.";
  }
  if (mapping && !selectedCurve && mapping.cost_curve) {
    mappingMessages.cost_curve = "Selected cost curve is not available.";
  }
  if (
    mapping &&
    !usesInstalledCostBasis(mapping, selectedCurve) &&
    !mapping.use_study_lang_factor &&
    !hasFieldValue(mapping.install_factor)
  ) {
    mappingMessages.install_factor =
      "Enter a Lang factor value or use the study default.";
  }
  if (driver && selectedCurve) {
    const specs = requiredDriverSpecsFromCurve(selectedCurve);
    if (
      specs.length > 0 &&
      !capitalLineHasRequiredDriverInputs(capitalLine, selectedCurve)
    ) {
      capitalLineMessages.driver_inputs =
        "Select a compatible property or enter a custom value for every required input.";
    }
  }
  if (
    capitalLine &&
    capitalLine.minimum_peak_demand_kw != null &&
    !hasFieldValue(peakDemandValue)
  ) {
    capitalLineMessages.peak_demand_kw = "Enter a peak demand.";
  }
  return {
    mapping: mappingMessages,
    capitalLine: capitalLineMessages,
  };
}
 
function capitalLineHasRequiredDriverInputs(
  capitalLine: CapitalCostLineRead | undefined,
  selectedCurve: CostCurveRead,
) {
  const specs = requiredDriverSpecsFromCurve(selectedCurve);
  Iif (specs.length === 0) return false;
  const inputs =
    capitalLine?.driver_inputs && typeof capitalLine.driver_inputs === "object"
      ? capitalLine.driver_inputs
      : {};
  return specs.every((spec) => {
    const input = inputs[spec.key];
    Iif (!input) return false;
    return input.source === "property"
      ? Boolean(input.property_info)
      : input.source === "manual" && hasFieldValue(input.manual_value);
  });
}
 
function hasFieldValue(value: unknown) {
  return value != null && String(value).trim() !== "";
}
 
function DefaultDriverSummary({
  unsupported = false,
}: {
  unsupported?: boolean;
}) {
  return (
    <div className="text-sm text-muted-foreground">
      {unsupported
        ? "No default sizing template is available for this unit operation yet."
        : "Sizing value is available after enablement."}
    </div>
  );
}
 
function PendingCapitalLineInputsNotice() {
  return (
    <EconomicsWarningNotice aria-label="Capital input setup warning">
      Capital inputs are available after the generated capital line is created.
    </EconomicsWarningNotice>
  );
}
 
function DefaultMappingSummary() {
  return (
    <div className="text-sm text-muted-foreground">
      Cost settings are available after enablement.
    </div>
  );
}