// subpyramid.jsx — Tier 4 sub-pyramids (Analyst / Strategist). Two-axis:
// risk climbs vertically (level) AND horizontally (left=conservative ->
// right=aggressive). Highlights the recommended entry cell from the DNA result.
// Also exports L180Lens for the Builder/Professional/Innovator overlay.

window.l180RiskColor = function (pos /* 0..1 */) {
  const stops = L180_BRAND.risk;
  const x = pos * (stops.length - 1);
  const lo = Math.floor(x), hi = Math.min(stops.length - 1, lo + 1), f = x - lo;
  return `color-mix(in oklch, ${stops[lo]} ${(1 - f) * 100}%, ${stops[hi]} ${f * 100}%)`;
};

function L180SubPyramid({ data, result, mode, onExit }) {
  const levels = data.levels;              // index 0 = base
  const display = [...levels].reverse();   // top -> bottom for rendering
  const entryLevel = result && result.realityActive && result.reality === data.key ? 1 : 0;
  const riskCol = result ? result.risk : 2;
  const [hover, setHover] = React.useState(null); // {li, ci}

  const maxCells = Math.max(...levels.map((l) => l.cells.length));
  const cellW = 150, cellGap = 6;

  return (
    <div className="l180-funnel" style={{ background: `radial-gradient(120% 90% at 50% -5%, color-mix(in oklch, ${data.theme} 20%, ${L180_BRAND.navy}), ${L180_BRAND.navy} 55%, ${L180_BRAND.ink})`, display: "block", overflowY: "auto" }}>
      <div className="l180-funnel-top" style={{ position: "sticky", top: 0, zIndex: 10, background: "rgba(12,12,13,.74)", backdropFilter: "blur(10px)" }}>
        <button className="l180-back" onClick={onExit}>← Back to pyramid</button>
        <div className="l180-stagelabel">{data.dot} {data.name} · {data.domain}</div>
        <span style={{ width: 120 }} />
      </div>

      <div className="l180-subwrap">
        <div className="l180-subhead">
          <div className="l180-eyebrow" style={{ color: data.theme }}>Sub-Pyramid · {data.domain}</div>
          <h2 className="l180-fbig" style={{ fontSize: 34 }}>{data.name}</h2>
          <p className="l180-tagline-q" style={{ color: "rgba(255,255,255,.9)" }}>“{data.tagline}”</p>
          {result && (
            <div className="l180-subentry" style={{ borderColor: `color-mix(in oklch, ${data.theme} 45%, transparent)` }}>
              Entry calibrated to <strong style={{ color: L180_BRAND.risk[riskCol] }}>{result.riskLabel}</strong> ·
              starting at <strong>{levels[entryLevel].name}</strong>. The glowing cell is your recommended first move.
            </div>
          )}
        </div>

        {/* risk axis legend */}
        <div className="l180-riskaxis">
          <span>◄ Conservative</span>
          <div className="l180-riskbar" />
          <span>Aggressive ►</span>
        </div>

        {/* the pyramid of levels */}
        <div className="l180-sublevels">
          {display.map((lvl) => {
            const li = levels.indexOf(lvl);
            const n = lvl.cells.length;
            const isEntry = li === entryLevel;
            return (
              <div key={li} className="l180-sublevel">
                <div className="l180-sublevel-label">
                  <span className="l180-sublevel-num" style={{ color: data.theme }}>L{li + 1}</span>
                  <div>
                    <strong>{lvl.name}</strong>
                    <em>{lvl.note}</em>
                  </div>
                </div>
                <div className="l180-cellrow">
                  {lvl.cells.map((c, ci) => {
                    const pos = n === 1 ? 0.5 : ci / (n - 1);
                    const color = window.l180RiskColor(pos);
                    // recommended cell: entry level + risk column (scaled to this level's width)
                    const colForLevel = Math.round((riskCol / 4) * (n - 1));
                    const isRec = isEntry && ci === colForLevel;
                    const isHover = hover && hover.li === li && hover.ci === ci;
                    return (
                      <div key={ci}
                           className={"l180-cell" + (isRec ? " rec" : "")}
                           onMouseEnter={() => setHover({ li, ci })}
                           onMouseLeave={() => setHover(null)}
                           style={{
                             width: cellW,
                             background: `linear-gradient(180deg, color-mix(in oklch, ${color} 26%, ${L180_BRAND.navy}), color-mix(in oklch, ${color} 12%, ${L180_BRAND.ink}))`,
                             borderColor: isRec ? color : `color-mix(in oklch, ${color} 38%, transparent)`,
                             boxShadow: isRec ? `0 0 28px color-mix(in oklch, ${color} 55%, transparent)` : isHover ? `0 0 16px color-mix(in oklch, ${color} 35%, transparent)` : "none",
                             transform: isRec || isHover ? "translateY(-2px)" : "none",
                           }}>
                        <span className="l180-cell-dot" style={{ background: color }} />
                        <span className="l180-cell-name">{c}</span>
                        {isRec && <span className="l180-cell-badge" style={{ background: color }}>START HERE</span>}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>

        {/* education / cross-cutting */}
        <div className="l180-subedu">
          <div className="l180-eyebrow" style={{ color: data.theme }}>Runs alongside every level</div>
          <div className="l180-edugrid">
            {data.education.map((e, i) => (
              <div key={i} className="l180-educard" style={{ borderColor: `color-mix(in oklch, ${data.theme} 30%, transparent)` }}>{e}</div>
            ))}
          </div>
        </div>

        {mode === "agent" && (
          <div className="l180-agentchip" style={{ margin: "0 auto 30px" }}>
            Agent mode · in the live tool this maps to a client-specific allocation plan and modeling.
          </div>
        )}
      </div>
    </div>
  );
}

// Lens overlay result — Builder / Professional / Innovator route back to the
// main pyramid with DNA-specific emphasis at Tiers 2, 3, 5.
function L180Lens({ result, onExit, onReturn }) {
  const dna = window.L180_DNA[result.primary];
  const emphasis = {
    builder: ["Tier 2 — protect the business engine and personal floor", "Tier 3 — foundation asset as flexible business capital", "Tier 5 — operating + holding + IP entity structures"],
    professional: ["Tier 2 — own-occupation disability is non-negotiable", "Tier 3 — maximize tax-free growth on high income", "Tier 5 — PSC/PLLC + asset protection for the practice"],
    innovator: ["Tier 2 — protect the creator and the income runway", "Tier 3 — foundation asset funds the creative leap", "Tier 5 — IP-holding entities and licensing structures"],
  }[result.primary] || [];

  return (
    <div className="l180-funnel" style={{ background: `radial-gradient(120% 90% at 50% -5%, color-mix(in oklch, ${dna.color} 22%, ${L180_BRAND.navy}), ${L180_BRAND.navy} 55%, ${L180_BRAND.ink})` }}>
      <div className="l180-funnel-top">
        <button className="l180-back" onClick={onExit}>← Back to pyramid</button>
        <div className="l180-stagelabel">Lens Overlay</div>
        <span style={{ width: 120 }} />
      </div>
      <div className="l180-funnel-body">
        <div className="l180-fstep" style={{ maxWidth: 680, textAlign: "center" }}>
          <div className="l180-eyebrow" style={{ color: dna.color }}>{dna.name} Lens</div>
          <h2 className="l180-fbig" style={{ fontSize: 38, color: dna.color }}>You stay on the main pyramid</h2>
          <p className="l180-flead" style={{ margin: "0 auto 22px", maxWidth: 520 }}>{result.pathNote}</p>
          <div className="l180-lensgrid">
            {emphasis.map((e, i) => (
              <div key={i} className="l180-lenscard" style={{ borderColor: `color-mix(in oklch, ${dna.color} 38%, transparent)` }}>{e}</div>
            ))}
          </div>
          <button className="l180-bigcta" style={{ "--hue": dna.color, marginTop: 26 }} onClick={onReturn}>
            Return to the pyramid with my lens →
          </button>
        </div>
      </div>
    </div>
  );
}

window.L180SubPyramid = L180SubPyramid;
window.L180Lens = L180Lens;
