// subpyramid.jsx — Tier 4 sub-pyramids (the four Investor Designs: Founder /
// Steward / Artisan / Originator, plus the shared Growth Layer). A clean,
// balanced trapezoid pyramid (same visual language as the home page) that is
// INTERACTIVE: hover or click any level and a detail panel reveals that level's
// options as risk-graded "stones" laid conservative -> aggressive. Elevation =
// risk (green bedrock -> red apex). The Design result lights the recommended
// entry level + stone. Also exports L180Lens.

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}%)`;
};

// trapezoid clip from a band's top/bottom widths (percent inset, scales fluidly)
window.l180BandClip = function (topW, botW) {
  const inset = ((botW - topW) / (2 * botW)) * 100;
  return `polygon(${inset}% 0, ${100 - inset}% 0, 100% 100%, 0% 100%)`;
};

function L180SubPyramid({ data, result, mode, onExit }) {
  const levels = data.levels;                 // index 0 = base (bedrock)
  const n = levels.length;
  const hasResult = !!result;
  const entryLevel = hasResult && result.realityActive && result.reality === data.key ? 1 : 0;
  const riskCol = hasResult ? result.risk : 2;
  const [active, setActive] = React.useState(entryLevel);

  // elevation accent: bedrock = brand theme, apex = danger red
  const fracOf = (li) => (n === 1 ? 0 : li / (n - 1));
  const accentFor = (frac) =>
    `color-mix(in oklch, ${data.theme} ${Math.round((1 - frac) * 100)}%, #DC2626 ${Math.round(frac * 100)}%)`;

  // trapezoid geometry — bands nest into one smooth, balanced pyramid
  const baseW = 720, apexW = 214;
  const step = (baseW - apexW) / n;
  const bandGeom = (li) => {
    const botW = baseW - li * step, topW = botW - step;
    const inset = ((botW - topW) / (2 * botW)) * 100;   // per-side slope inset, % of band
    return { widthPct: (botW / baseW) * 100, clip: window.l180BandClip(topW, botW), inset };
  };
  // where the beam's left edge meets the band's sloped right edge at the beam's
  // top (band 64px tall, beam 44px centered -> top at y=10px = 0.156 of height),
  // pulled a touch further left so the band fully covers the seam.
  const beamLeftPct = (inset) => Math.max(0, (100 - inset) + inset * 0.156 - 2);

  // recommended entry stone
  const recColOf = (lvl) => Math.round((riskCol / 4) * (lvl.cells.length - 1));
  const isRecStone = (li, ci) =>
    hasResult ? (li === entryLevel && ci === recColOf(levels[li])) : (li === 0 && ci === 0);

  const act = levels[active];
  const actFrac = fracOf(active);
  const actAccent = accentFor(actFrac);
  const riskWord = actFrac < 0.34 ? "Lower risk" : actFrac < 0.67 ? "Moderate risk" : "Higher risk";

  return (
    <div className="l180-funnel l180-mon" style={{
      background: `radial-gradient(135% 105% at 50% -12%, color-mix(in oklch, #DC2626 14%, ${L180_BRAND.ink}), ${L180_BRAND.navy} 42%, ${L180_BRAND.ink})`,
      display: "block", overflowY: "auto",
    }}>
      <div className="l180-funnel-top l180-mon-top">
        <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-mon-wrap">
        {/* hero */}
        <div className="l180-mon-hero">
          <div className="l180-mon-eyebrow" style={{ color: data.theme }}>Investor Design · {data.domain} Pyramid</div>
          <h2 className="l180-mon-title">{data.name}</h2>
          <p className="l180-mon-tag">“{data.tagline}”</p>
        </div>

        {/* interactive monument: pyramid navigator + live detail panel */}
        <div className="l180-mon-build">
          {/* the pyramid navigator */}
          <div className="l180-mon-nav">
            <div className="l180-mon-stack">
              <div className="l180-mon-cap" style={{ animationDelay: `${0.12 + n * 0.1}s` }}>
                <div className="l180-mon-cap-tri" />
              </div>

              {levels.slice().reverse().map((lvl) => {
                const li = levels.indexOf(lvl);          // 0 = base .. n-1 = apex
                const frac = fracOf(li);
                const accent = accentFor(frac);
                const g = bandGeom(li);
                const on = li === active;
                const isEntry = li === entryLevel;
                return (
                  <div key={li} className="l180-mon-bandwrap" style={{ width: `${g.widthPct}%`, animationDelay: `${0.1 + li * 0.09}s` }}>
                    <button type="button"
                      className={"l180-mon-band" + (on ? " on" : "") + (isEntry ? " entry" : "")}
                      style={{
                        clipPath: g.clip, WebkitClipPath: g.clip,
                        background: on
                          ? `linear-gradient(180deg, color-mix(in oklch, ${accent} 60%, #16161c), color-mix(in oklch, ${accent} 26%, #101015))`
                          : `linear-gradient(180deg, color-mix(in oklch, ${accent} 30%, #131318), color-mix(in oklch, ${accent} 12%, #0e0e12))`,
                        borderColor: `color-mix(in oklch, ${accent} ${on ? 92 : 50}%, transparent)`,
                        boxShadow: on
                          ? `0 0 46px color-mix(in oklch, ${accent} 55%, transparent), inset 0 1px 0 color-mix(in oklch, ${accent} 75%, transparent)`
                          : `0 0 18px color-mix(in oklch, ${accent} 18%, transparent), inset 0 1px 0 color-mix(in oklch, ${accent} 42%, transparent)`,
                      }}
                      onMouseEnter={() => setActive(li)}
                      onFocus={() => setActive(li)}
                      onClick={() => setActive(li)}>
                      <span className="l180-mon-band-name">{lvl.name}</span>
                    </button>
                    {on && <span className="l180-mon-beam" aria-hidden="true"
                      style={{
                        left: `${beamLeftPct(g.inset)}%`,
                        background: `linear-gradient(90deg, color-mix(in oklch, ${accent} 70%, #16161c), color-mix(in oklch, ${accent} 42%, #101015) 60%, color-mix(in oklch, ${accent} 18%, transparent))`,
                        boxShadow: `0 0 26px color-mix(in oklch, ${accent} 45%, transparent)`,
                        borderTop: `1px solid color-mix(in oklch, ${accent} 60%, transparent)`,
                        borderBottom: `1px solid color-mix(in oklch, ${accent} 30%, transparent)`,
                      }} />}
                  </div>
                );
              })}
            </div>

            <p className="l180-mon-navhint">Hover or tap a level to explore its options.</p>
          </div>

          {/* live detail panel */}
          <div className="l180-mon-panel" key={active}
               style={{ borderColor: `color-mix(in oklch, ${actAccent} 45%, transparent)` }}>
            <div className="l180-mon-panel-bar" style={{ background: `linear-gradient(90deg, ${actAccent}, color-mix(in oklch, ${actAccent} 30%, transparent))` }} />
            <div className="l180-mon-panel-head">
              <div className="l180-mon-panel-elev" style={{
                background: `linear-gradient(180deg, color-mix(in oklch, ${actAccent} 90%, white 10%), ${actAccent})`,
                boxShadow: `0 0 20px color-mix(in oklch, ${actAccent} 65%, transparent)`,
              }}>{active + 1}</div>
              <div className="l180-mon-panel-titles">
                <div className="l180-mon-panel-kicker">
                  Level {active + 1} of {n}
                  <span className="l180-mon-panel-risk" style={{ color: actAccent }}>· {riskWord}</span>
                </div>
                <h3 className="l180-mon-panel-name">{act.name}</h3>
              </div>
              {active === 0 && <span className="l180-mon-tagpill" style={{ color: data.theme, borderColor: `color-mix(in oklch, ${data.theme} 55%, transparent)` }}>BEDROCK</span>}
            </div>

            {act.note && <p className="l180-mon-panel-note">{act.note}</p>}

            {/* risk plot — every option pinned to its spot on the scale */}
            <div className="l180-mon-plot">
              <div className="l180-mon-plot-head">
                <span />
                <div className="l180-mon-plot-scale">
                  <span style={{ color: data.theme }}>◄ {data.axisLeft || "Conservative"}</span>
                  <span style={{ color: "#F87171" }}>{data.axisRight || "Aggressive"} ►</span>
                </div>
              </div>
              {act.cells.map((c, ci) => {
                const nc = act.cells.length;
                const pos = nc === 1 ? 0.5 : ci / (nc - 1);
                const col = window.l180RiskColor(pos);
                const isRec = isRecStone(active, ci);
                return (
                  <div key={ci} className={"l180-mon-row" + (isRec ? " rec" : "")}>
                    <div className="l180-mon-row-lbl">
                      <span className="l180-mon-row-ldot" style={{ background: col, boxShadow: `0 0 8px ${col}` }} />
                      <span className="l180-mon-row-name" style={isRec ? { color: "#fff" } : undefined}>{c}</span>
                      {isRec && <span className="l180-mon-stone-badge" style={{ background: col }}>START</span>}
                    </div>
                    <div className="l180-mon-row-track">
                      <span className="l180-mon-row-marker"
                            style={{
                              left: `calc(${pos} * (100% - 16px) + 8px)`,
                              background: col,
                              width: isRec ? 16 : 12, height: isRec ? 16 : 12,
                              boxShadow: isRec ? `0 0 16px ${col}` : `0 0 6px ${col}`,
                            }} />
                    </div>
                  </div>
                );
              })}
            </div>

            {active === (hasResult ? entryLevel : 0) && (
              <div className="l180-mon-panel-hint" style={{ color: hasResult ? L180_BRAND.risk[riskCol] : data.theme }}>
                ★ {hasResult ? "Your calibrated starting move." : "Everyone starts here — protection first."}
              </div>
            )}
          </div>
        </div>

        {/* the philosophy — load-bearing principles that run through every level */}
        <div className="l180-mon-foot">
          <div className="l180-mon-foot-head">
            <div className="l180-mon-eyebrow" style={{ color: data.theme }}>The Philosophy</div>
            <h3 className="l180-mon-foot-title">Principles that run through every level</h3>
            <p className="l180-mon-foot-lead">
              The triangle changes by path — the foundation never does. Whole life is the bedrock
              you build on, and the same load-bearing rules govern every step of the climb.
            </p>
          </div>
          <div className="l180-mon-pillars">
            {(window.L180_PRINCIPLES || data.education).map((e, i) => (
              <div key={i} className="l180-mon-pillar" style={{ "--accent": data.theme }}>
                <span className="l180-mon-pillar-n">{String(i + 1).padStart(2, "0")}</span>
                <h4 className="l180-mon-pillar-t">{e.t}</h4>
                <p className="l180-mon-pillar-txt">{e.d}</p>
              </div>
            ))}
          </div>
        </div>

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

// Lens overlay result — Founder / Artisan / Originator route back to the
// main pyramid with Design-specific emphasis at Tiers 2, 3, 5.
function L180Lens({ result, onExit, onReturn }) {
  const dna = window.L180_DNA[result.primary];
  const emphasis = {
    founder: ["Tier 2 — protect the business engine and personal floor", "Tier 3 — foundation asset as flexible business capital", "Tier 5 — operating + holding + IP entity structures"],
    artisan: ["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"],
    originator: ["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;
