// 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 TowerFloor({ p, tier, state, selected, dark, t, lang, onClick, floorIndex, colIndex, cellMode, isMuted }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  const lime = "#EDFE38";

  // Padding is class-driven via [data-cell-mode] on .r-matrix-grid.
  const scale = {
    roomy: { gap: 22, numberFs: 18, labelFs: 9, metaFs: 9, showMeta: true,  metaLabels: "full" },
    dense: { gap: 8,  numberFs: 15, labelFs: 9, metaFs: 9, showMeta: true,  metaLabels: "short" },
    tight: { gap: 6,  numberFs: 15, labelFs: 9, metaFs: 9, showMeta: false, metaLabels: "none" },
  }[cellMode || "roomy"];

  // Strategic-state ink color (text on the funded-green wash). Background
  // is class-driven via r-floor-state-* + .dark .r-floor-state-* rules.
  const fundedInk = dark ? "#D8E6CC" : "#3F4F2E";

  const color = state === "gray" || state === "strategic-idle"
    ? faint
    : state === "strategic"
      ? fundedInk
      : text;
  const litDelay = (colIndex * 3 + (4 - floorIndex) * 2) * 30;

  return (
    <button
      type="button"
      onClick={onClick}
      data-floor={`${colIndex}:${floorIndex}`}
      data-tier={tier}
      aria-label={`${TIER_LABELS[tier][lang]} · ${window.pickLang(p.name, lang) || ""} · ${state === "lit" ? t.eligible : t.ineligible}`}
      className={`r-floor r-floor-state-${state}${state === "lit" ? " r-floor-lit" : ""}${selected ? " r-floor-selected" : ""}${isMuted ? " r-floor-muted" : ""}`}
    >
      {state === "lit" && !selected && (
        <div className="r-lit-sweep r-lit-sweep-fill" style={{
          background: `linear-gradient(90deg, transparent 0%, ${dark ? "rgba(237,254,56,0.18)" : "rgba(237,254,56,0.55)"} 50%, transparent 100%)`,
          animationDelay: `${litDelay}ms`,
        }}/>
      )}
      {state === "lit" && (
        <div className="r-lit-bar" style={{
          background: lime,
          animation: `litBarIn 420ms cubic-bezier(.22,.61,.36,1) ${litDelay}ms both`,
        }}/>
      )}
      {/* Tap affordance — small chevron in the top-right of every cell so it
          reads as obviously clickable. Mirrors the bordered `›` pill on
          mobile-card.jsx so desktop and mobile share the same visual cue. */}
      {(() => {
        const tapInk = state === "gray"
          ? faint
          : (state === "strategic" || state === "strategic-idle")
            ? fundedInk
            : (dark ? muted : "#9A8F8B");
        return (
          <span
            aria-hidden="true"
            className="r-floor-tap"
            style={{
              position: "absolute", top: 6, right: 8,
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              width: 20, height: 20,
              border: `1px solid ${tapInk}`,
              fontFamily: "var(--font-mono)", fontSize: 16, lineHeight: 1,
              color: tapInk,
              pointerEvents: "none",
              zIndex: 2,
            }}
          >›</span>
        );
      })()}
      <div className="r-floor-stack r-floor-stack-base" style={{ gap: scale.gap }}>
        {state === "strategic" || state === "strategic-idle" ? (
          <>
            <div className="r-floor-strategic-wrap">
              <div className="r-floor-strategic-title" style={{ color: fundedInk }}>
                {t.strategicOpenTitle}
              </div>
              <div className="r-floor-strategic-sub" style={{ color: fundedInk }}>
                {t.fundedSelective}
              </div>
            </div>
          </>
        ) : (() => {
          // Single source of truth: every cell reads detailStats[0..2].
          // [0] is the headline (label always shown; value renders as the
          // big number only when non-empty — so debt's "Customized by
          // Structure" with no value renders as label-only). [1] and [2]
          // are the two meta lines below the headline.
          const stats = Array.isArray(p.detailStats) ? p.detailStats : [];
          const pickStat = (s) => s ? {
            label: lang === "es" ? (s.labelEs || s.labelEn) : (s.labelEn || s.labelEs),
            value: lang === "es" ? (s.valueEs || s.valueEn) : (s.valueEn || s.valueEs),
          } : null;
          const head = pickStat(stats[0]);
          const meta = [pickStat(stats[1]), pickStat(stats[2])].filter(Boolean);
          const metaCellStyle = { fontSize: scale.metaFs, color: state === "gray" ? faint : muted };
          return (
            <>
              <div className="r-floor-price-wrap">
                {head && head.label && (
                  <div className="r-floor-price-label" style={{ fontSize: scale.labelFs, color: head.value ? (state === "gray" ? faint : muted) : color, lineHeight: 1.25 }}>
                    {head.label}
                  </div>
                )}
                {head && head.value && (
                  <div className="r-floor-price-value" style={{ fontSize: scale.numberFs, color }}>
                    {head.value}
                  </div>
                )}
              </div>
              {scale.showMeta && meta.length > 0 && (
                <div className="r-floor-meta-list">
                  {meta.map((s, i) => {
                    const isFull = scale.metaLabels === "full";
                    // Matrix-only shorthand. Detail panel reads detailStats
                    // verbatim — these substitutions stay scoped to the cell.
                    const shortLabel = (() => {
                      const raw = String(s.label || "").trim();
                      if (/^(hold period|typical duration|hold)$/i.test(raw)) return "HOLD";
                      if (/^minimum investment$/i.test(raw)) return "MIN";
                      if (/^down payment$/i.test(raw)) return "DOWN";
                      if (/^enganche$/i.test(raw)) return "ENGANCHE";
                      if (/^estimated delivery$/i.test(raw)) return "EST. DELIVERY";
                      if (/^entrega estimada$/i.test(raw)) return "ENTREGA EST.";
                      return raw;
                    })();
                    const shortValue = (() => {
                      const raw = String(s.value || "").trim();
                      const yrMatch = raw.match(/^(~?)(\d+(?:[\.\-–]\d+)?)\s*(yrs?|años?|a)$/i);
                      if (yrMatch) {
                        const suffix = /año|a$/i.test(yrMatch[3]) ? "a" : "yr";
                        return `${yrMatch[1]}${yrMatch[2]}${suffix}`;
                      }
                      const dollarMatch = raw.match(/^\$([\d,]+)(?:\.\d+)?$/);
                      if (dollarMatch) {
                        const n = parseInt(dollarMatch[1].replace(/,/g, ""), 10);
                        if (!Number.isNaN(n)) return window.formatCurrencyShort(n);
                      }
                      return raw;
                    })();
                    const labelOut = isFull ? `${shortLabel}:` : shortLabel;
                    return <div key={i} className="r-floor-meta-cell" style={metaCellStyle}>{labelOut} {shortValue}</div>;
                  })}
                </div>
              )}
            </>
          );
        })()}
      </div>
    </button>
  );
}
