const { useState, useMemo, useEffect, useRef, Fragment } = React;

// ═══════════════════════════════════════════════════════════════
// Matrix — Towers (vertical capital stack as buildings)
// ═══════════════════════════════════════════════════════════════
function StackDiagram({ dark, lang, columns }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const lime = "#EDFE38";
  const muted = dark ? "#8A827F" : "#6B6361";

  // Collect per-tier aggregate stats from currently visible columns
  const tierStats = useMemo(() => {
    const stats = {}; // { [tier]: {count, rLo, rHi} }
    if (!columns) return stats;
    for (const col of columns) {
      for (const [tier, cell] of col.cells.entries()) {
        if (!cell || !cell.product) continue;
        const rng = window.formatRange(cell.product);
        if (!rng || rng.kind === "multiple") {
          stats[tier] = stats[tier] || { count: 0, rLo: Infinity, rHi: -Infinity };
          stats[tier].count++;
          continue;
        }
        stats[tier] = stats[tier] || { count: 0, rLo: Infinity, rHi: -Infinity };
        stats[tier].count++;
        stats[tier].rLo = Math.min(stats[tier].rLo, rng.lo);
        stats[tier].rHi = Math.max(stats[tier].rHi, rng.hi);
      }
    }
    return stats;
  }, [columns]);

  const bands = [
    { label: "SR",   color: "#4866B2", tier: "senior-debt" },
    { label: "MEZZ", color: "#6D85C3", tier: "mezzanine" },
    { label: "PREF", color: "#A1B0D4", tier: "pref-equity" },
    { label: "COMM", color: "#D4B24A", tier: "common-equity" },
    { label: "LP",   color: lime,      tier: "syndicate-lp" },
  ];
  return (
    <svg viewBox="0 0 120 80" preserveAspectRatio="none" width="100%" height="100%" style={{ display: "block" }}>
      <rect width="120" height="80" fill={dark ? "#0D0D0D" : "#EAE4DB"}/>
      {bands.map((b, i) => {
        const y = 12 + i * 12;
        const stat = tierStats[b.tier];
        const hasRange = stat && isFinite(stat.rLo);
        return (
          <g key={i}>
            <rect x="20" y={y} width="80" height="12" fill={b.color} opacity={dark ? 0.85 : 1}/>
            <text x="26" y={y + 8.2} textAnchor="start" fontFamily="ui-monospace,monospace" fontSize="5.5" fill={i === 4 ? "#393433" : "#FFFFFF"} letterSpacing="1">
              {b.label}
            </text>
            {hasRange && (
              <text x="94" y={y + 8.2} textAnchor="end" fontFamily="ui-monospace,monospace" fontSize="5" fill={i === 4 ? "#393433" : "#FFFFFF"} opacity="0.9" letterSpacing="0.3">
                {Math.round(stat.rLo)}–{Math.round(stat.rHi)}%
              </text>
            )}
          </g>
        );
      })}
      <rect x="0" y="72" width="120" height="8" fill={text}/>
      <g stroke={muted} strokeWidth="0.7" fill="none">
        <line x1="8" y1="14" x2="8" y2="68"/>
        <path d="M 6 66 L 8 70 L 10 66"/>
        <line x1="112" y1="14" x2="112" y2="68"/>
        <path d="M 110 16 L 112 12 L 114 16"/>
      </g>
      <text x="8" y="78" fontFamily="ui-monospace,monospace" fontSize="3.5" fill={muted} textAnchor="middle" letterSpacing="0.5">PRIORITY</text>
      <text x="112" y="78" fontFamily="ui-monospace,monospace" fontSize="3.5" fill={muted} textAnchor="middle" letterSpacing="0.5">UPSIDE</text>
    </svg>
  );
}

function MatrixC({ columns, profile, t, lang, dark, selectedId, onSelectProduct, density, highlight, hideIneligible, onSetHideIneligible, statusFilter, onClearStatus, shortlist, toggleShortlist }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const accent = "#4866B2";
  const [openTier, setOpenTier] = useState(null);
  const visibleCols = hideIneligible ? columns.filter(c => Array.from(c.cells.values()).some(v => v.eligible)) : columns;

  const floorH = density === "compact" ? 64 : 80;
  const bodyRef = useRef(null);

  // Arrow-key navigation between focused floors
  const onMatrixKeyDown = (e) => {
    const tgt = e.target.closest("[data-floor]");
    if (!tgt) return;
    const [c, r] = tgt.getAttribute("data-floor").split(":").map(Number);
    let nc = c, nr = r;
    if (e.key === "ArrowUp") nr = r - 1;
    else if (e.key === "ArrowDown") nr = r + 1;
    else if (e.key === "ArrowLeft") nc = c - 1;
    else if (e.key === "ArrowRight") nc = c + 1;
    else if (e.key === "Home") { nc = 0; nr = 0; }
    else if (e.key === "End") { nc = visibleCols.length - 1; nr = TIER_ORDER.length - 1; }
    else return;
    e.preventDefault();
    // Find nearest existing floor (skip gaps)
    const findCell = (col, row) => bodyRef.current?.querySelector(`[data-floor="${col}:${row}"]`);
    let next = findCell(nc, nr);
    // If target missing (gap cell), step further in same direction up to grid edge
    if (!next && e.key === "ArrowUp") { while (nr > 0 && !next) { nr--; next = findCell(nc, nr); } }
    if (!next && e.key === "ArrowDown") { while (nr < TIER_ORDER.length - 1 && !next) { nr++; next = findCell(nc, nr); } }
    if (!next && e.key === "ArrowLeft") { while (nc > 0 && !next) { nc--; next = findCell(nc, nr); } }
    if (!next && e.key === "ArrowRight") { while (nc < visibleCols.length - 1 && !next) { nc++; next = findCell(nc, nr); } }
    next?.focus();
  };

  return (
    <div ref={bodyRef} onKeyDown={onMatrixKeyDown} className="r-matrix-body" style={{ padding: "24px 28px" }}>
      <div style={{ display: "flex", gap: 16, alignItems: "stretch", overflowX: "auto", paddingBottom: 8 }}>
        {/* Legend column on the left — tier rows only */}
        <div style={{ flexShrink: 0, width: 160, paddingRight: 16, borderRight: `1px dashed ${border}`, display: "flex", flexDirection: "column" }}>
          {/* Spacer matches the column header (198 content + 10 pad + 1 border + 8 margin = 217) so tier rows align with tower floors */}
          <div style={{ height: 217, flexShrink: 0 }}/>
          <div style={{ border: "1px solid transparent" }}>
            {TIER_ORDER.map((tier, idxFromTop) => {
              const isOpen = openTier === tier;
              const isLast = idxFromTop === TIER_ORDER.length - 1;
              return (
                <div key={tier}
                  onClick={() => setOpenTier(isOpen ? null : tier)}
                  onMouseEnter={() => { const root = bodyRef.current; if (root) root.setAttribute("data-tier-hover", tier); }}
                  onMouseLeave={() => { const root = bodyRef.current; if (root) root.removeAttribute("data-tier-hover"); }}
                  data-tier-row={tier}
                  style={{
                    height: floorH, display: "flex", alignItems: "center", gap: 8,
                    borderBottom: isLast ? "none" : `1px dashed ${border}`,
                    padding: "8px 0",
                    cursor: "pointer",
                    background: isOpen ? (dark ? "#1A1817" : "#F6F2EC") : "transparent",
                    transition: "background 160ms",
                  }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: muted, width: 20, textAlign: "right" }}>
                    {String(idxFromTop + 1).padStart(2,"0")}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 12.5, color: text, lineHeight: 1.1, letterSpacing: "-0.005em" }}>
                      {TIER_LABELS[tier][lang]}
                    </div>
                    <div style={{ fontSize: 9.5, color: muted, marginTop: 3, lineHeight: 1.2 }}>
                      {TIER_MICRO[tier][lang]}
                    </div>
                  </div>
                  <span style={{ color: muted, fontSize: 10, fontFamily: "var(--font-mono)" }}>{isOpen ? "−" : "+"}</span>
                </div>
              );
            })}
          </div>
          <div style={{ height: 64, background: "transparent" }}/>
        </div>

        {/* Towers */}
        {visibleCols.length === 0 && (
          <div style={{
            flex: 1, minHeight: 320, minWidth: 280,
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 16,
            color: muted, textAlign: "center", padding: "40px 24px",
            border: `1px dashed ${border}`,
          }}>
            <svg width="56" height="56" viewBox="0 0 56 56" fill="none" aria-hidden="true" style={{ opacity: 0.55 }}>
              <rect x="8" y="14" width="40" height="36" stroke={muted} strokeWidth="1.2" fill="none"/>
              <path d="M8 22h40M8 30h40M8 38h40" stroke={muted} strokeWidth="1" strokeDasharray="3 3"/>
              <circle cx="42" cy="14" r="7" fill={dark ? "#1A1817" : "#FAF7F3"} stroke={muted} strokeWidth="1.2"/>
              <path d="M39 14 L41.2 16.2 L45 12.5" stroke={muted} strokeWidth="1.3" fill="none" strokeLinecap="square"/>
            </svg>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: text, letterSpacing: "-0.015em", lineHeight: 1.15, maxWidth: 320 }}>
              {t.noDealsFilter}
            </div>
            <div style={{ fontSize: 12.5, color: muted, lineHeight: 1.5, maxWidth: 340 }}>
              {lang === "en"
                ? "Try a different status, widen your profile, or clear filters to see every project."
                : "Prueba otro estado, amplía tu perfil o limpia los filtros para ver todos los proyectos."}
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center", marginTop: 6 }}>
              {statusFilter && statusFilter !== "all" && onClearStatus && (
                <button onClick={onClearStatus} style={{
                  padding: "8px 14px",
                  border: `1px solid ${text}`, background: text, color: dark ? "#1A1817" : "#FAF7F3",
                  fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
                  cursor: "pointer",
                }}>{t.showAll}</button>
              )}
              {hideIneligible && onSetHideIneligible && (
                <button onClick={() => onSetHideIneligible(false)} style={{
                  padding: "8px 14px",
                  border: `1px solid ${border}`, background: "transparent", color: text,
                  fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
                  cursor: "pointer",
                }}>{lang === "en" ? "Show mismatches too" : "Mostrar no elegibles"}</button>
              )}
            </div>
          </div>
        )}
        {visibleCols.map((col, i) => (
          <Tower key={col.name} col={col} floorH={floorH}
            t={t} lang={lang} dark={dark}
            selectedId={selectedId}
            onSelectProduct={onSelectProduct}
            highlight={highlight}
            colIndex={i}
            shortlist={shortlist}
            toggleShortlist={toggleShortlist}
          />
        ))}
      </div>

      <LegendStrip t={t} lang={lang} dark={dark} hideIneligible={hideIneligible} onSetHideIneligible={onSetHideIneligible} position="bottom"/>

      {openTier && (
        <div style={{ marginTop: 20, padding: "16px 20px", background: dark ? "#1A1817" : "#F6F2EC", border: `1px solid ${border}` }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: muted, marginBottom: 4 }}>
            {TIER_LABELS[openTier].short}
          </div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: text, letterSpacing: "-0.015em", marginBottom: 6 }}>
            {TIER_LABELS[openTier][lang]}
          </div>
          <div style={{ fontSize: 13, color: text, lineHeight: 1.55, maxWidth: 680 }}>
            {TIER_EXPLAINERS[openTier][lang][window.__teaching || "basic"]}
          </div>
        </div>
      )}
    </div>
  );
}

function LegendStrip({ t, lang, dark, hideIneligible, onSetHideIneligible, position }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const faint = dark ? "#5A5654" : "#C1C1C1";

  const lime = "#EDFE38";
  const limeDim = dark ? "#2A2A1A" : "#F0F0C0";

  const [hover, setHover] = useState(null);

  // When hovering a legend token, temporarily dim non-matching cells via CSS attribute on body root
  useEffect(() => {
    const root = document.querySelector(".r-matrix-body");
    if (!root) return;
    root.setAttribute("data-legend-hover", hover || "");
    return () => root.removeAttribute("data-legend-hover");
  }, [hover]);

  const items = [
    {
      key: "lit",
      label: t.legendLit,
      swatch: (
        <span style={{
          width: 16, height: 10,
          background: lime, border: `1px solid ${dark ? "#7A7818" : "#9C9A18"}`,
          display: "inline-block",
        }}/>
      ),
      click: () => onSetHideIneligible && onSetHideIneligible(!hideIneligible),
      active: hideIneligible,
      cta: hideIneligible ? t.showAll : t.hideIneligible,
    },
    {
      key: "gray",
      label: t.legendGray,
      swatch: (
        <span style={{
          width: 16, height: 10,
          background: dark ? "#1F1D1B" : "#FFFFFF", border: `1px solid ${border}`,
          display: "inline-block",
        }}/>
      ),
    },
    {
      key: "empty",
      label: t.legendEmpty,
      swatch: (
        <span style={{
          width: 16, height: 10,
          background: `repeating-linear-gradient(45deg, transparent 0 3px, ${dark ? "#1A1817" : "#F1EDE8"} 3px 6px)`,
          border: `1px solid ${border}`,
          display: "inline-block",
        }}/>
      ),
    },
  ];

  return (
    <>
      <style>{`
        .r-matrix-body[data-legend-hover="lit"]   .r-floor:not(.r-floor-lit) { opacity: 0.25; transition: opacity 180ms; }
        .r-matrix-body[data-legend-hover="lit"]   .r-floor.r-floor-lit { opacity: 1; transition: opacity 180ms; }
        .r-matrix-body[data-legend-hover="gray"]  .r-floor.r-floor-lit { opacity: 0.25; transition: opacity 180ms; }
        .r-matrix-body[data-legend-hover="gray"]  .r-floor:not(.r-floor-lit) { opacity: 1; transition: opacity 180ms; }
        .r-matrix-body[data-tier-hover] .r-floor { opacity: 0.22; transition: opacity 160ms; }
        .r-matrix-body[data-tier-hover="senior-debt"]   .r-floor[data-tier="senior-debt"]   { opacity: 1; }
        .r-matrix-body[data-tier-hover="mezzanine"]     .r-floor[data-tier="mezzanine"]     { opacity: 1; }
        .r-matrix-body[data-tier-hover="preferred-equity"] .r-floor[data-tier="preferred-equity"] { opacity: 1; }
        .r-matrix-body[data-tier-hover="common-equity"]    .r-floor[data-tier="common-equity"]    { opacity: 1; }
        .r-matrix-body[data-tier-hover="lp-syndicate"]     .r-floor[data-tier="lp-syndicate"]     { opacity: 1; }
      `}</style>
      <div style={{
        display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap",
        ...(position === "bottom"
          ? { paddingTop: 14, marginTop: 16, borderTop: `1px dashed ${border}` }
          : { paddingBottom: 14, marginBottom: 14, borderBottom: `1px dashed ${border}` }),
      }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: muted }}>
          {lang === "en" ? "Legend" : "Leyenda"}
        </span>
        {items.map(it => (
          <span key={it.key}
            onMouseEnter={() => setHover(it.key)}
            onMouseLeave={() => setHover(null)}
            onFocus={() => setHover(it.key)}
            onBlur={() => setHover(null)}
            onClick={it.click}
            role={it.click ? "button" : undefined}
            tabIndex={it.click ? 0 : undefined}
            onKeyDown={it.click ? (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); it.click(); } } : undefined}
            style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "5px 8px",
              border: `1px solid ${it.active ? text : "transparent"}`,
              background: it.active ? (dark ? "#22201E" : "#F6F2EC") : "transparent",
              cursor: it.click ? "pointer" : "default",
              transition: "background 150ms, border-color 150ms",
            }}>
            {it.swatch}
            <span style={{ fontSize: 11, color: text, letterSpacing: "-0.005em" }}>
              {it.label}
            </span>
            {it.cta && (
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase", color: muted, paddingLeft: 6, borderLeft: `1px solid ${border}` }}>
                {it.cta}
              </span>
            )}
          </span>
        ))}
      </div>
    </>
  );
}

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

  const status = col.products[0]?.status || "open";

  return (
    <div className="r-tower" style={{
      flexShrink: 0, width: 200, display: "flex", flexDirection: "column",
      animation: `towerIn 520ms cubic-bezier(.22,.61,.36,1) both`,
      animationDelay: `${colIndex * 70}ms`,
    }}>
      <div style={{ paddingBottom: 10, borderBottom: `1px solid ${text}`, marginBottom: 8, height: 198, boxSizing: "content-box" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, height: 12, marginBottom: 4 }}>
          <span className={status === "open" ? "r-dot-pulse" : ""} style={{ width: 6, height: 6, background: STATUS_DOT[status], borderRadius: "50%" }}/>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 8.5, letterSpacing: "0.14em", textTransform: "uppercase", color: muted }}>
            {STATUS_LABEL[status][lang]}
          </span>
        </div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 16, color: text, letterSpacing: "-0.015em", lineHeight: 1.05, height: 18, marginBottom: 8 }}>
          {col.name}
        </div>
        <div style={{
          width: "100%", aspectRatio: "3 / 2",
          background: dark ? "#1A1817" : "#EAE4DB", border: `1px solid ${border}`,
          overflow: "hidden", position: "relative",
        }}>
          <img src={col.image} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", filter: dark ? "brightness(0.85)" : "none" }}/>
        </div>
        <div style={{ fontSize: 10.5, color: muted, letterSpacing: "0.01em", marginTop: 8, height: 14 }}>
          {col.city} · {t[col.kind] || col.kind}
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", border: `1px solid ${text}`, background: dark ? "#0D0D0D" : "#FFFFFF" }}>
        {TIER_ORDER.map((tier, idxFromTop) => {
          const cell = col.cells.get(tier);
          const isLast = idxFromTop === TIER_ORDER.length - 1;
          if (!cell) {
            return (
              <div key={tier} style={{
                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: `repeating-linear-gradient(45deg, transparent 0 4px, ${dark?"#1A1817":"#F1EDE8"} 4px 8px)`,
              }}>·</div>
            );
          }
          const p = cell.product;
          const state = cell.unanswered ? "gray" : 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}
              shortlist={shortlist} toggleShortlist={toggleShortlist}
            />
          );
        })}
      </div>
      <Plinth col={col} dark={dark} t={t} lang={lang}/>
    </div>
  );
}

function Plinth({ col, dark, t, lang }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const faint = dark ? "#5A5654" : "#9A9290";
  const accent = "#4866B2";
  const lime = "#EDFE38";

  const s = window.plinthStats(col);
  if (!s) return null;
  const barBg = dark ? "#1A1817" : "#F1ECE4";
  const fillColor = s.status === "open" ? accent : s.status === "closed" ? (dark ? "#5A5654" : "#9A9290") : faint;

  const urgentClose = s.daysLeft != null && s.daysLeft <= 14;
  const secondary = s.status === "closed"
    ? t.fullySub
    : s.status === "coming-soon"
      ? `$${s.targetM}M ${t.target} · ${s.commits} ${t.commits}`
      : `$${s.raisedM}M / $${s.targetM}M · ${s.commits} ${t.commits}`;

  return (
    <div style={{
      borderLeft: `1px solid ${text}`,
      borderRight: `1px solid ${text}`,
      borderBottom: `1px solid ${text}`,
      background: dark ? "#0D0D0D" : "#FFFFFF",
      padding: "10px 12px 11px",
      display: "flex", flexDirection: "column", gap: 6,
    }}>
      {/* Progress bar */}
      <div style={{ position: "relative", height: 4, background: barBg }}>
        <div style={{
          position: "absolute", left: 0, top: 0, bottom: 0,
          width: `${Math.max(2, s.pct)}%`,
          background: fillColor,
          transition: "width 400ms cubic-bezier(.22,.61,.36,1)",
        }}/>
      </div>
      {/* Two-row stat line */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: 9.5, color: text,
          letterSpacing: "0.08em", textTransform: "uppercase",
          fontVariantNumeric: "tabular-nums",
        }}>
          {s.status === "closed" ? "100%" : `${s.pct}%`} {s.status !== "closed" && <span style={{ color: muted, fontWeight: 400 }}>{t.raised}</span>}
        </span>
        {s.daysLeft != null && (
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.08em",
            textTransform: "uppercase",
            color: urgentClose ? (dark ? "#FFB48A" : "#B04C1C") : muted,
            fontVariantNumeric: "tabular-nums",
          }}>
            {urgentClose && <span style={{ width: 4, height: 4, borderRadius: "50%", background: "currentColor", display: "inline-block" }}/>}
            {t.closeIn} {s.daysLeft}{t.daysShort}
          </span>
        )}
      </div>
      <div style={{
        fontSize: 10, color: muted, letterSpacing: "-0.005em", lineHeight: 1.3,
        fontVariantNumeric: "tabular-nums",
      }}>
        {secondary}
      </div>
    </div>
  );
}

function TowerFloor({ p, tier, state, selected, floorH, isLast, dark, t, lang, onClick, floorIndex, colIndex, shortlist, toggleShortlist }) {
  const text = dark ? "#FAF7F3" : "#393433";
  const muted = dark ? "#8A827F" : "#6B6361";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  const border = dark ? "#2A2825" : "#E2E0DF";
  const accent = "#4866B2";
  const lime = "#EDFE38";

  const [hover, setHover] = useState(false);

  const baseBg = selected
    ? (dark ? "#1C2540" : "#E8EDF7")
    : state === "lit"
      ? (dark ? "#2D3A1F" : "#FAFFCE")
      : "transparent";

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

  return (
    <button
      type="button"
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      data-floor={`${colIndex}:${floorIndex}`}
      data-tier={tier}
      aria-label={`${TIER_LABELS[tier][lang]} · ${p.name || ""} · ${state === "lit" ? (lang === "en" ? "eligible" : "elegible") : (lang === "en" ? "not eligible" : "no elegible")}`}
      className={`r-floor ${state === "lit" ? "r-floor-lit" : ""}`}
      style={{
        height: floorH, borderBottom: isLast ? "none" : `1px solid ${border}`,
        padding: "8px 12px", cursor: "pointer",
        background: baseBg,
        position: "relative", overflow: "hidden",
        outline: selected ? `2px solid ${accent}` : "none", outlineOffset: -2,
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        transform: hover && state !== "gray" ? "translateX(2px)" : "translateX(0)",
        transition: "transform 180ms cubic-bezier(.4,0,.2,1), background 260ms",
        textAlign: "left", font: "inherit", color: "inherit",
        border: 0,
        borderBottomWidth: isLast ? 0 : 1,
        borderBottomStyle: "solid",
        borderBottomColor: border,
        width: "100%",
      }}
    >
      {state === "lit" && !selected && (
        <div className="r-lit-sweep" style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          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={{
          position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: lime,
          transformOrigin: "bottom",
          animation: `litBarIn 420ms cubic-bezier(.22,.61,.36,1) ${litDelay}ms both`,
        }}/>
      )}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", position: "relative" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 8.5, letterSpacing: "0.14em", color: muted, textTransform: "uppercase" }}>
          <EligibilityGlyph state={state} dark={dark}/>
          {TIER_LABELS[tier].short}
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          {state === "lit" && shortlist && toggleShortlist && (
            <window.ShortlistStar id={p.id} shortlist={shortlist} toggle={toggleShortlist} dark={dark}/>
          )}
          <span style={{ width: 6, height: 6, background: STATUS_DOT[p.status], borderRadius: "50%", opacity: state === "gray" ? 0.3 : 1 }}/>
        </span>
      </div>
      <div style={{ position: "relative" }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 17, color, letterSpacing: "-0.015em", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>
          {window.formatRangeStr(p)}
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: state === "gray" ? faint : muted, letterSpacing: "0.08em", textTransform: "uppercase", marginTop: 2 }}>
          {p.holdPeriodYears[0]}–{p.holdPeriodYears[1]}{t.yrs.slice(0,2)} · MIN {window.formatCurrency(p.minimumInvestment.amount)}
        </div>
      </div>
    </button>
  );
}

window.MatrixC = MatrixC;

// Eligibility glyph — ✓ for eligible, — for not, ? for unanswered. Survives colorblindness + greyscale.
function EligibilityGlyph({ state, dark }) {
  const lime = "#EDFE38";
  const muted = dark ? "#8A827F" : "#6B6361";
  const faint = dark ? "#5A5654" : "#C1C1C1";
  if (state === "lit") {
    return (
      <svg width="9" height="9" viewBox="0 0 9 9" aria-label="Eligible">
        <path d="M1.5 4.5 L3.8 6.8 L7.5 2.5" stroke={dark ? lime : "#2B3710"} strokeWidth="1.4" fill="none" strokeLinecap="square"/>
      </svg>
    );
  }
  // "gray" covers both ineligible and unanswered — dash
  return (
    <svg width="9" height="9" viewBox="0 0 9 9" aria-label="Not eligible">
      <line x1="2" y1="4.5" x2="7" y2="4.5" stroke={faint} strokeWidth="1.4"/>
    </svg>
  );
}
