// Responsive styles live in index.html, keyed off [data-bp-and-below~="…"]
// or @container queries on .r-tower. Do not add new inline ternaries on
// viewport width or `compact` — convert to a CSS class instead.

// Extracted from matrix.jsx 2026-05-14. No logic change — pure split.

function Tower({ col, floorH, t, lang, dark, selectedId, onSelectProduct, highlight, colIndex, towerHeadH, cellMode }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  const accent = "#4866B2";

  const rawStatus = col.products[0]?.status || "open";
  // Project is fully funded when plinth shows 100% — relabel the status pill.
  const _stats = window.plinthStats(col);
  const isFunded = _stats && _stats.pct >= 100 && rawStatus !== "closed";
  const status = isFunded ? "funded" : rawStatus;
  // Sheet override (Projects.status_label) takes precedence unless the project is funded.
  const statusLabelText = isFunded ? STATUS_LABEL.funded[lang] : (window.pickLang(col.statusLabel, lang) || STATUS_LABEL[status][lang]);
  return (
    <div className="r-tower" style={{
      animation: `towerIn 520ms cubic-bezier(.22,.61,.36,1) both`,
      animationDelay: `${colIndex * 70}ms`,
    }}>
      <div className="r-tower-head" style={{ borderBottom: `1px solid ${text}` }}>
       <div className="r-tower-head-inner">
        <div className="r-tower-status-row">
          <span className={`r-tower-status-dot ${status === "open" ? "r-dot-pulse" : ""}`} style={{ background: STATUS_DOT[status] }}/>
          <span className="r-tower-status-label" style={{ color: muted }}>
            {statusLabelText}
          </span>
        </div>
        <div className="r-tower-name" style={{ color: text }}>
          {col.name}
        </div>
        <div className="r-tower-image" style={{ border: `1px solid ${border}` }}>
          <img src={col.image} alt="" style={{ filter: dark ? "brightness(0.85)" : "none" }}/>
        </div>
        {/* Project-fact reminder under the image — single line: city · type
            on the left, total cost / units / dev timeline on the right.
            Portfolio entities (OpCo/DevCo) reuse this 2-line slot for a
            short "what is this entity" description instead of project facts. */}
        {(() => {
          const kindLabelText = window.pickLang(col.kindLabel, lang);
          let devYears = col.developmentTimelineYears > 0 ? col.developmentTimelineYears : null;
          if (!devYears) {
            const debtSibling = (col.products || []).find(p => p.type === "construction-debt");
            const src = debtSibling || (col.products && col.products[0]);
            devYears = src && src.holdPeriodYears ? src.holdPeriodYears[1] : null;
          }
          const isPortfolio = col.kind === "portfolio";
          const aboutShort = isPortfolio ? (col.products || []).map(p => window.pickLang(p.projectAboutShort, lang)).find(Boolean) : null;
          if (isPortfolio && aboutShort) {
            return (
              <div className="r-tower-blurb r-tower-blurb-clamp" style={{ color: muted }}>
                {aboutShort}
              </div>
            );
          }
          if (!isPortfolio) {
            // Source: 01-Projects.about_short (~3-sentence summary). Falls back
            // to project_card_blurb when about_short isn't populated yet.
            const blurb = window.pickLang(col.projectAboutShort, lang) || window.pickLang(col.projectCardBlurb, lang);
            if (blurb) {
              return (
                <div className="r-tower-blurb r-tower-blurb-clamp" style={{ color: muted }}>
                  {blurb}
                </div>
              );
            }
            // Blank-blurb fallback: empty 3-line spacer so layout doesn't jitter.
            return (
              <div className="r-tower-blurb-blank"/>
            );
          }
          const showRight = !isPortfolio && (col.totalCostUsd > 0 || col.unitsPlanned > 0);
          const rightText = showRight ? [
            col.totalCostUsd > 0 ? window.formatCurrencyShort(col.totalCostUsd) : null,
            col.unitsPlanned > 0 ? `${col.unitsPlanned} ${t.units.toLowerCase()}` : null,
            devYears ? `~${devYears}${t.yrs.slice(0,2)}` : null,
          ].filter(Boolean).join(" · ") : "";
          return (
            <div className="r-tower-facts">
              <span className="r-tower-facts-left" style={{ color: muted }}>
                {col.city}{kindLabelText ? ` · ${kindLabelText}` : ""}
              </span>
              {rightText && (
                <span className="r-tower-facts-right" style={{ color: muted }}>
                  {rightText}
                </span>
              )}
            </div>
          );
        })()}
       </div>
      </div>

      <div className="r-tower-floors" style={{ border: `1px solid ${text}`, background: isFunded ? (dark ? "#2A3A24" : "#D9E8C8") : (dark ? "#0D0D0D" : "#FFFFFF") }}>
      {/* Funded-tower-wide green sweep — fires across all four capital-stack
          rows when the user's profile clears the strategic threshold (e.g. a
          $500k+ check size on OpCo/DevCo). Conditional render mounts the
          element only when the strategic state is active, so the keyframe
          runs once per qualification flip. */}
      {isFunded && col.cells && Array.from(col.cells.values()).some(c => c && c.strategicActive) && (
        <div className="r-lit-sweep" key={`fs-${col.name}`} aria-hidden="true" style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          background: `linear-gradient(90deg, transparent 0%, ${dark ? "rgba(120,180,90,0.50)" : "rgba(80,150,60,0.60)"} 50%, transparent 100%)`,
          zIndex: 1,
        }}/>
      )}
        {TIER_ORDER.map((tier, idxFromTop) => {
          const cell = col.cells.get(tier);
          const isLast = idxFromTop === TIER_ORDER.length - 1;
          if (!cell) {
            // Funded towers: empty rows match the funded green so all four
            // capital-stack rows render as a single uniform block, and any
            // click anywhere in the green opens the sidebar for the tower's
            // strategic product (OpCo/DevCo each carry exactly one).
            const emptyBg = isFunded
              ? "transparent"
              : `repeating-linear-gradient(45deg, transparent 0 4px, ${dark?"#1A1817":"#F1EDE8"} 4px 8px)`;
            const fundedProduct = isFunded ? col.products[0] : null;
            const sharedStyle = {
              height: floorH, borderBottom: isLast ? "none" : `1px dashed ${border}`,
              display: "flex", alignItems: "center", justifyContent: "center", color: faint,
              fontFamily: "var(--font-mono)", fontSize: 14, opacity: 0.4,
              background: emptyBg,
            };
            if (fundedProduct) {
              return (
                <button key={tier} type="button"
                  onClick={() => onSelectProduct(fundedProduct)}
                  style={{
                    ...sharedStyle,
                    width: "100%", border: 0, padding: 0,
                    cursor: "pointer", font: "inherit", color: "inherit",
                    textAlign: "center",
                  }}
                  aria-label={`${col.name} — ${TIER_LABELS[tier][lang]}`}
                >·</button>
              );
            }
            return <div key={tier} style={sharedStyle}>·</div>;
          }
          const p = cell.product;
          const state = cell.strategicActive
            ? "strategic"
            : cell.strategicOnly
              ? "strategic-idle"
              : cell.eligible
                ? "lit"
                : "gray";
          const selected = p.id === selectedId;

          return (
            <TowerFloor key={tier}
              p={p} tier={tier} state={state} selected={selected}
              floorH={floorH} isLast={isLast}
              dark={dark} t={t} lang={lang}
              onClick={() => onSelectProduct(p)}
              floorIndex={idxFromTop} colIndex={colIndex}
              cellMode={cellMode}
            />
          );
        })}
      </div>
      <Plinth col={col} dark={dark} t={t} lang={lang}/>
    </div>
  );
}
