/* global React */
/* ============================================================
   What each step pays: TWO KINDS OF PAYOFF.
   Relief (defensive, saturates) → Leverage (offensive, compounds),
   handed off at Standardized. Two forms: curves · ledger.
   Warm paper + serif. Green = relief, ochre = leverage (the remark).
   ============================================================ */

const PSTAGES = ["Manual", "Digital", "Standardized", "AI-augmented", "Scaled"];
const tr2 = (en, es) => (window.cecLang === "es" ? es : en);

const STEPS = [
  {
    fnum: "01", tnum: "02", from: "Manual", to: "Digital", type: "Relief",
    asks: "Get information out of heads and paper into shared digital files.",
    pays: "Work stops disappearing.",
    rest: "Files exist: searchable, shareable, backed up.",
  },
  {
    fnum: "02", tnum: "03", from: "Digital", to: "Standardized", type: "Relief", big: true,
    asks: "One standard on every project: same folders, naming, and review cadence.",
    pays: "Most of the daily relief lands here.",
    rest: "Every project starts organized; anyone finds anything in minutes; new hires onboard into a system.",
  },
  {
    fnum: "03", tnum: "04", from: "Standardized", to: "AI-augmented", type: "Leverage",
    asks: "Put AI on the standard: search, drafting, flagging; and train the team.",
    pays: "The standard starts working for you.",
    rest: "Answers with their source, reports draft themselves, errors caught, owner off the critical path.",
  },
  {
    fnum: "04", tnum: "05", from: "AI-augmented", to: "Scaled", type: "Leverage", horizon: true,
    asks: "AI works across functions and carries learning from one project to the next.",
    pays: "Take on more work without more of the owner.",
    rest: "Capability compounds: the horizon the climb points at.",
  },
];

/* Catmull-Rom → bezier smoothing */
function smooth(pts) {
  if (pts.length < 2) return "";
  let d = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i], p1 = pts[i], p2 = pts[i + 1], p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C ${c1x} ${c1y}, ${c2x} ${c2y}, ${p2[0]} ${p2[1]}`;
  }
  return d;
}

function PHeader({ eyebrow, title, sub }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <p style={{ font: "700 13px var(--font-sans)", letterSpacing: ".15em", textTransform: "uppercase", color: "var(--green-deep)", margin: 0 }}>{eyebrow}</p>
      <h2 style={{ font: "500 36px/1.04 var(--font-serif)", letterSpacing: "-.01em", color: "var(--ink)", margin: "9px 0 0" }}>{title}</h2>
      <p style={{ font: "400 14px/1.4 var(--font-sans)", color: "var(--ink-mute)", margin: "8px 0 0" }}>{sub}</p>
    </div>
  );
}

function Lock() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <img src="assets/logo-mark.png" alt="" style={{ height: 22 }} />
      <span style={{ font: "300 16px/1 var(--font-sans)", letterSpacing: "-.01em", color: "var(--ink)" }}>Cecrop<b style={{ fontWeight: 700 }}>AI</b></span>
    </div>
  );
}

function PFoot({ children, embed }) {
  if (embed) return null;
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16, borderTop: "1.5px solid var(--stone)", paddingTop: 14 }}>
      <p style={{ font: "400 13px/1.42 var(--font-sans)", color: "var(--ink-soft)", margin: 0, maxWidth: 820 }}>{children}</p>
      <Lock />
    </div>
  );
}

/* ============================================================
   ① TWO CURVES: relief saturates, leverage compounds
   ============================================================ */
function PayoffCurves() {
  const VW = 1164, VH = 470;
  const L = 58, R = 48, T = 66, B = 64;
  const x = (i) => L + i * (VW - L - R) / 4;
  const yBot = VH - B, yTop = T;
  const y = (v) => yBot - v * (yBot - yTop);
  const relief = [0.06, 0.32, 0.84, 0.91, 0.93];
  const leverage = [0.02, 0.05, 0.17, 0.54, 0.99];
  const rPts = relief.map((v, i) => [x(i), y(v)]);
  const lPts = leverage.map((v, i) => [x(i), y(v)]);
  const rArea = smooth(rPts) + ` L ${x(4)} ${yBot} L ${x(0)} ${yBot} Z`;

  return (
    <div style={{ width: "100%", height: "100%", background: "var(--paper)", padding: "48px 58px 40px", display: "flex", flexDirection: "column", fontFamily: "var(--font-sans)" }}>
      <PHeader eyebrow="Moving up · what each step pays" title="First the climb removes pain. Then it compounds" sub="The payoff doesn’t shrink as a firm climbs; it changes character, handing off at the standard." />
      <div style={{ flex: 1, display: "flex", alignItems: "center" }}>
        <svg viewBox={`0 0 ${VW} ${VH}`} width="100%" style={{ display: "block" }}>
          <defs>
            <linearGradient id="reliefG" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#00603C" stopOpacity="0.22" />
              <stop offset="100%" stopColor="#00603C" stopOpacity="0.02" />
            </linearGradient>
          </defs>
          {/* baseline */}
          <line x1={L} y1={yBot} x2={VW - R} y2={yBot} stroke="var(--stone)" strokeWidth="1.5" />
          {/* horizon zone (after stage 4) */}
          <rect x={x(3)} y={yTop - 10} width={x(4) - x(3)} height={yBot - yTop + 10} fill="#20231F" opacity="0.03" />
          <line x1={x(3)} y1={yTop - 10} x2={x(3)} y2={yBot} stroke="var(--stone)" strokeWidth="1" strokeDasharray="3 5" />
          {/* hinge at standardized */}
          <line x1={x(2)} y1={yTop - 10} x2={x(2)} y2={yBot} stroke="#9A6F1E" strokeWidth="1.4" strokeDasharray="4 4" opacity="0.5" />
          {/* relief */}
          <path d={rArea} fill="url(#reliefG)" />
          <path d={smooth(rPts)} fill="none" stroke="#00603C" strokeWidth="3.4" strokeLinecap="round" />
          {/* leverage */}
          <path d={smooth(lPts)} fill="none" stroke="#C2922F" strokeWidth="3.4" strokeLinecap="round" />
          {/* dots */}
          {rPts.map((p, i) => <circle key={"r" + i} cx={p[0]} cy={p[1]} r="5" fill="#00603C" stroke="var(--paper)" strokeWidth="2.5" />)}
          {lPts.map((p, i) => <circle key={"l" + i} cx={p[0]} cy={p[1]} r="5" fill="#C2922F" stroke="var(--paper)" strokeWidth="2.5" />)}
          {/* curve labels */}
          <text x={x(1) + 8} y={y(0.40)} fill="#00603C" style={{ font: "700 16px var(--font-sans)" }}>Relief</text>
          <text x={x(1) + 8} y={y(0.40) + 19} fill="var(--ink-mute)" style={{ font: "500 12.5px var(--font-sans)" }}>removing pain: big, fast, finite</text>
          <text x={x(3) + 4} y={y(0.40)} textAnchor="end" fill="#9A6F1E" style={{ font: "700 16px var(--font-sans)" }}>Leverage</text>
          <text x={x(3) + 4} y={y(0.40) + 19} textAnchor="end" fill="var(--ink-mute)" style={{ font: "500 12.5px var(--font-sans)" }}>new capability: compounds, open-ended</text>
          {/* hinge label */}
          <text x={x(2)} y={yTop - 22} textAnchor="middle" fill="#9A6F1E" style={{ font: "700 13px var(--font-sans)" }}>The hinge</text>
          <text x={x(2)} y={yTop - 6} textAnchor="middle" fill="var(--ink-mute)" style={{ font: "500 12px var(--font-sans)" }}>relief banked · platform set</text>
          {/* stage labels */}
          {PSTAGES.map((s, i) => (
            <g key={s} opacity={i === 4 ? 0.55 : 1}>
              <text x={x(i)} y={yBot + 24} textAnchor="middle" fill="var(--ink)" style={{ font: "700 13px var(--font-sans)" }}>{`0${i + 1}`}</text>
              <text x={x(i)} y={yBot + 43} textAnchor="middle" fill="var(--ink-soft)" style={{ font: "500 12.5px var(--font-sans)" }}>{i === 4 ? "Scaled (horizon)" : s}</text>
            </g>
          ))}
        </svg>
      </div>
      <PFoot>
        By <em style={{ fontStyle: "italic", color: "var(--green-deep)" }}>Standardized</em> a firm has banked nearly all the relief, which is why a cautious firm can stop there. It’s also the platform the <em style={{ fontStyle: "italic", color: "#9A6F1E" }}>leverage</em> needs: the AI layer is upside, not the price of entry.
      </PFoot>
    </div>
  );
}

/* ============================================================
   ② THE LEDGER: what each step asks, and what it pays
   ============================================================ */
function TypeTag({ type }) {
  const relief = type === "Relief";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6, font: "700 11px var(--font-sans)",
      letterSpacing: ".06em", textTransform: "uppercase", padding: "5px 11px", borderRadius: 999,
      background: relief ? "var(--green-100)" : "var(--accent-ochre-fill)",
      color: relief ? "var(--green-deep)" : "#8A621A",
    }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: relief ? "var(--green-600)" : "var(--accent-ochre)" }}></span>
      {type}
    </span>
  );
}

function PayoffLedger() {
  return (
    <div style={{ width: "100%", height: "100%", background: "var(--paper)", padding: "48px 58px 40px", display: "flex", flexDirection: "column", fontFamily: "var(--font-sans)" }}>
      <PHeader eyebrow="Moving up · what each step pays" title="Every step pays before the next begins" sub="What each climb asks, what it returns, and which kind of payoff it is." />

      {/* column headers */}
      <div style={{ display: "grid", gridTemplateColumns: "210px 1fr 1.35fr 132px", gap: 26, paddingBottom: 11, borderBottom: "2px solid var(--ink)" }}>
        {["The move", "What it asks", "What it pays back", "Kind"].map((h) => (
          <span key={h} style={{ font: "700 11.5px var(--font-sans)", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-mute)" }}>{h}</span>
        ))}
      </div>

      {/* rows */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        {STEPS.map((s, i) => (
          <div key={i} style={{
            flex: 1, display: "grid", gridTemplateColumns: "210px 1fr 1.35fr 132px", gap: 26,
            alignItems: "center", padding: "0 0", borderBottom: i < 3 ? "1px solid var(--stone-soft)" : "none",
            opacity: s.horizon ? 0.72 : 1,
          }}>
            {/* move */}
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
                <span style={{ font: "300 18px var(--font-sans)", color: "var(--ink-mute)" }}>{s.fnum}</span>
                <span style={{ font: "600 14px var(--font-sans)", color: "var(--ink)" }}>{s.from}</span>
              </span>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--green-deep)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M5 12h14M13 6l6 6-6 6" /></svg>
              <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
                <span style={{ font: "300 18px var(--font-sans)", color: s.type === "Leverage" ? "#9A6F1E" : "var(--green-deep)" }}>{s.tnum}</span>
                <span style={{ font: "700 14px var(--font-sans)", color: "var(--ink)" }}>{s.to}</span>
              </span>
            </div>
            {/* asks */}
            <p style={{ font: "400 13.5px/1.45 var(--font-sans)", color: "var(--ink-soft)", margin: 0, paddingRight: 6 }}>{s.asks}</p>
            {/* pays */}
            <p style={{ font: "400 13.5px/1.45 var(--font-sans)", color: "var(--ink-soft)", margin: 0 }}>
              <b style={{ fontWeight: 700, color: "var(--ink)" }}>{s.pays}</b>{s.big && <span style={{ font: "700 10px var(--font-sans)", letterSpacing: ".06em", textTransform: "uppercase", color: "#8A621A", marginLeft: 8, verticalAlign: "middle" }}>★ the big one</span>}<br />{s.rest}
            </p>
            {/* kind */}
            <div><TypeTag type={s.type} />{s.horizon && <div style={{ font: "500 11px var(--font-sans)", color: "var(--ink-mute)", marginTop: 5 }}>horizon</div>}</div>
          </div>
        ))}
      </div>

      <PFoot>
        The first moves return <em style={{ fontStyle: "italic", color: "var(--green-deep)" }}>relief</em>: pain removed, big and finite. The later moves return <em style={{ fontStyle: "italic", color: "#9A6F1E" }}>leverage</em>: capability that compounds. Each pays before the next begins, so the climb is safe to start and safe to pause.
      </PFoot>
    </div>
  );
}

/* ============================================================
   ③ THE DIPTYCH: two words, two ideas, one hinge
   ============================================================ */
function PayoffDiptych({ embed }) {
  return (
    <div style={{ width: "100%", height: embed ? "auto" : "100%", background: "var(--paper)", padding: embed ? 0 : "56px 60px 44px", display: "flex", flexDirection: "column", fontFamily: "var(--font-sans)" }}>
      {!embed && (
      <div style={{ marginBottom: 30 }}>
        <p style={{ font: "700 13px var(--font-sans)", letterSpacing: ".15em", textTransform: "uppercase", color: "var(--green-deep)", margin: 0 }}>Moving up · what each step pays</p>
        <h2 style={{ font: "500 38px/1.04 var(--font-serif)", letterSpacing: "-.01em", color: "var(--ink)", margin: "10px 0 0" }}>First the climb removes pain. Then it compounds.</h2>
      </div>
      )}

      <div style={{ flex: embed ? "none" : 1, minHeight: embed ? 330 : "auto", display: "grid", gridTemplateColumns: "1fr 1fr", columnGap: 0, alignItems: "stretch", position: "relative" }}>
        {/* RELIEF */}
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 64px 0 8px" }}>
          <span style={{ font: "700 12px var(--font-sans)", letterSpacing: ".13em", textTransform: "uppercase", color: "var(--ink-mute)" }}>{tr2("Stages 1 → 3", "Etapas 1 → 3")}</span>
          <h3 style={{ font: "500 64px/1 var(--font-serif)", letterSpacing: "-.02em", color: "var(--green-deep)", margin: "12px 0 0" }}>{tr2("Relief", "Alivio")}</h3>
          <div style={{ height: 3, width: 56, background: "var(--green-600)", borderRadius: 3, margin: "22px 0 20px" }}></div>
          <p style={{ font: "400 17px/1.5 var(--font-sans)", color: "var(--ink-soft)", margin: 0, maxWidth: 420 }}>
            {window.cecLang === "es" ? (<>Archivos perdidos, caos, el dueño como cuello de botella: <b style={{ fontWeight: 700, color: "var(--ink)" }}>eliminados</b>. La ganancia es grande y rápida, y es <b style={{ fontWeight: 700, color: "var(--ink)" }}>finita</b>. Una vez despejado el desorden, queda despejado.</>) : (<>Lost files, chaos, the owner as the bottleneck: <b style={{ fontWeight: 700, color: "var(--ink)" }}>removed</b>. The gain is big and fast, and it is <b style={{ fontWeight: 700, color: "var(--ink)" }}>finite</b>. Once the mess is cleared, it’s cleared.</>)}
          </p>
          <p style={{ font: "600 14px/1.4 var(--font-sans)", color: "var(--green-deep)", margin: "22px 0 0" }}>{tr2("Mostly banked by stage 3. A cautious firm can stop here and keep it.", "Casi todo asegurado para la etapa 3. Una empresa cautelosa puede parar aquí y conservarlo.")}</p>
        </div>

        {/* LEVERAGE */}
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 8px 0 64px" }}>
          <span style={{ font: "700 12px var(--font-sans)", letterSpacing: ".13em", textTransform: "uppercase", color: "var(--ink-mute)" }}>{tr2("Stages 3 → 5", "Etapas 3 → 5")}</span>
          <h3 style={{ font: "500 64px/1 var(--font-serif)", letterSpacing: "-.02em", color: "#9A6F1E", margin: "12px 0 0" }}>{tr2("Leverage", "Palanca")}</h3>
          <div style={{ height: 3, width: 56, background: "var(--accent-ochre)", borderRadius: 3, margin: "22px 0 20px" }}></div>
          <p style={{ font: "400 17px/1.5 var(--font-sans)", color: "var(--ink-soft)", margin: 0, maxWidth: 420 }}>
            {window.cecLang === "es" ? (<>El estándar se vuelve una <b style={{ fontWeight: 700, color: "var(--ink)" }}>plataforma</b>. La IA multiplica la producción, y la empresa crece sin que crezca el dueño. Lento al principio, luego <b style={{ fontWeight: 700, color: "var(--ink)" }}>sin techo</b>.</>) : (<>The standard becomes a <b style={{ fontWeight: 700, color: "var(--ink)" }}>platform</b>. AI compounds output, and the firm grows without growing the owner. Slow to start, then <b style={{ fontWeight: 700, color: "var(--ink)" }}>open-ended</b>.</>)}
          </p>
          <p style={{ font: "600 14px/1.4 var(--font-sans)", color: "#9A6F1E", margin: "22px 0 0" }}>{tr2("Begins at AI-augmented. The upside a firm climbs toward once the relief is banked.", "Empieza en Asistida por IA. El potencial hacia el que sube una empresa una vez asegurado el alivio.")}</p>
        </div>

        {/* hinge divider */}
        <div style={{ position: "absolute", left: "50%", top: 0, bottom: 0, width: 0, borderLeft: "1.5px dashed var(--stone)", transform: "translateX(-50%)" }}></div>
        <div style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)", background: "var(--paper)", padding: "10px 0", display: "flex", flexDirection: "column", alignItems: "center", gap: 7 }}>
          <span style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--ink)", color: "var(--paper)", display: "grid", placeItems: "center" }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
          </span>
          <span style={{ font: "700 11px var(--font-sans)", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-mute)", writingMode: "horizontal-tb", whiteSpace: "nowrap" }}>{tr2("The standard", "El estándar")}</span>
        </div>
      </div>

      <PFoot embed={embed}>
        The same climb pays two different ways. The first half buys <em style={{ fontStyle: "italic", color: "var(--green-deep)" }}>peace</em>; the second half buys <em style={{ fontStyle: "italic", color: "#9A6F1E" }}>scale</em>, and the standard in the middle is what turns one into the other.
      </PFoot>
    </div>
  );
}

/* ============================================================
   ④ THE HINGE LINE: one line, one pivot
   ============================================================ */
function PayoffHinge() {
  return (
    <div style={{ width: "100%", height: "100%", background: "var(--paper)", padding: "56px 60px 44px", display: "flex", flexDirection: "column", fontFamily: "var(--font-sans)" }}>
      <div style={{ marginBottom: 8 }}>
        <p style={{ font: "700 13px var(--font-sans)", letterSpacing: ".15em", textTransform: "uppercase", color: "var(--green-deep)", margin: 0 }}>Moving up · what each step pays</p>
        <h2 style={{ font: "500 38px/1.04 var(--font-serif)", letterSpacing: "-.01em", color: "var(--ink)", margin: "10px 0 0" }}>One climb, two kinds of payoff</h2>
      </div>

      <div style={{ flex: 1, display: "flex", alignItems: "center" }}>
        <svg viewBox="0 0 1164 360" width="100%" style={{ display: "block" }}>
          {/* zone washes */}
          <rect x="40" y="40" width="542" height="240" fill="#00603C" opacity="0.06" rx="8" />
          <rect x="582" y="40" width="542" height="240" fill="#C2922F" opacity="0.07" rx="8" />
          {/* big zone words */}
          <text x="120" y="120" fill="var(--green-deep)" style={{ font: "500 52px var(--font-serif)" }}>Relief</text>
          <text x="120" y="150" fill="var(--ink-soft)" style={{ font: "400 16px var(--font-sans)" }}>Removing pain: big, fast, and finite.</text>
          <text x="1044" y="120" textAnchor="end" fill="#9A6F1E" style={{ font: "500 52px var(--font-serif)" }}>Leverage</text>
          <text x="1044" y="150" textAnchor="end" fill="var(--ink-soft)" style={{ font: "400 16px var(--font-sans)" }}>New capability: slow, then open-ended.</text>
          {/* baseline */}
          <line x1="40" y1="218" x2="1124" y2="218" stroke="var(--stone)" strokeWidth="2" />
          {/* stage ticks */}
          {[["Manual", 120], ["Digital", 360], ["AI-augmented", 820], ["Scaled", 1044]].map(([s, xp], i) => (
            <g key={i}>
              <line x1={xp} y1="212" x2={xp} y2="224" stroke="var(--stone)" strokeWidth="2" />
              <text x={xp} y="250" textAnchor="middle" fill="var(--ink-mute)" style={{ font: "500 13px var(--font-sans)" }}>{s}</text>
            </g>
          ))}
          {/* the hinge pivot at standardized (center) */}
          <circle cx="582" cy="218" r="13" fill="var(--ink)" stroke="var(--paper)" strokeWidth="3" />
          <text x="582" y="288" textAnchor="middle" fill="var(--ink)" style={{ font: "700 16px var(--font-sans)" }}>Standardized</text>
          <text x="582" y="309" textAnchor="middle" fill="var(--ink-mute)" style={{ font: "500 13px var(--font-sans)" }}>the hinge: relief banked, platform set</text>
        </svg>
      </div>

      <PFoot>
        Everything to the left of the standard is <em style={{ fontStyle: "italic", color: "var(--green-deep)" }}>relief</em> a firm can bank and keep. Everything to the right is <em style={{ fontStyle: "italic", color: "#9A6F1E" }}>leverage</em> that compounds, which is why the climb is safe to start, and worth continuing.
      </PFoot>
    </div>
  );
}

Object.assign(window, { PayoffCurves, PayoffLedger, PayoffDiptych, PayoffHinge });
