/* The Raise-Readiness Scorecard — interactive app.
   Aesthetic: confidential underwriting file (ivory stock, evergreen ink,
   brass rules, mono ledger type). */
const { useState, useEffect, useMemo, useRef } = React;
const { SECTIONS, TIERS, tierFor, TOTAL, ITEM_COUNT } = window.SCORECARD;

const STORE_KEY = "aeg_scorecard_v1";

/* ====================================================================
   CONFIG — edit these. This is the only block you should need to touch.
   ==================================================================== */
const CONFIG = {
  handle: "nickjayala",                          // Instagram handle (no @)
  bookingUrl: "https://services.raiseoscrm.com/widget/booking/0uRP1yoRTgEbCkCsT1Ch",   // 30-min deal breakdown calendar
  programUrl: "https://nickjayala.com/room",         // low-score destination
  programPrice: "$10",                           // entry price shown on the button
  amazonUrl: "https://a.co/d/0dX3u5FA",          // Amazon listing for the book
  bookTitle: "Capital Is the Game",              // optional — leave "" to hide the printed title
  callThreshold: 65,                             // score at/above this books the call; below routes to the program
  // Lead capture: paste your GoHighLevel INBOUND WEBHOOK url here (Workflow > add
  // trigger "Inbound Webhook" > copy the URL). Every gate submission POSTs the lead
  // + score to it and creates/updates the contact. Leave "" to run in prototype mode.
  webhookUrl: "https://services.leadconnectorhq.com/hooks/IOp0znVyDdc6nwhl7Gnj/webhook-trigger/47262745-d366-4623-86d8-bf5bccd6a86c",
};

/* ---- Tweaks ------------------------------------------------------------ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": ["#34A81F", "#247F17", "#EAF6E4"],
  "paperTone": "ivory",
  "showWeights": true
}/*EDITMODE-END*/;

const PAPER_TONES = {
  ivory: { paper: "#F4F4EE", paper2: "#EAEAE2", surface: "#FFFFFF", line: "#E0E0D7", lineSoft: "#ECECE4" },
  cool:  { paper: "#F1F4F3", paper2: "#E7EBEA", surface: "#FFFFFF", line: "#DCE0DE", lineSoft: "#E9EDEB" },
  warm:  { paper: "#F6F3EC", paper2: "#ECE8DE", surface: "#FFFFFF", line: "#E4DFD3", lineSoft: "#F0ECE1" },
};

/* ---- helpers ----------------------------------------------------------- */
function useCountUp(target, run, dur = 1100) {
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!run) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) { setV(target); return; }
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, run, dur]);
  return v;
}

const Arrow = () => <span aria-hidden style={{ fontSize: 15, marginTop: -1, fontFamily: "var(--sans)" }}>&rarr;</span>;

/* ---- Wordmark + Masthead ---------------------------------------------- */
function Wordmark({ small }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <span aria-hidden style={{
        width: small ? 15 : 17, height: small ? 15 : 17, flex: "0 0 auto", position: "relative",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
      }}>
        <span style={{ position: "absolute", inset: 0, border: "1.5px solid var(--accent)", transform: "rotate(45deg)" }} />
        <span style={{ width: small ? 4.5 : 5, height: small ? 4.5 : 5, background: "var(--brass)", transform: "rotate(45deg)" }} />
      </span>
      <span className="eyebrow" style={{ letterSpacing: ".24em", color: "var(--ink)", fontSize: small ? 9.5 : 10 }}>
        NICK&nbsp;AYALA
      </span>
    </div>
  );
}

function Masthead({ meta = "CONFIDENTIAL" }) {
  return (
    <header style={{ paddingTop: 18 }}>
      <div style={{ height: 2, background: "var(--ink)" }} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0 9px" }}>
        <Wordmark small />
        <span className="eyebrow" style={{ fontSize: 9, letterSpacing: ".22em", color: "var(--muted)", flex: "0 0 auto" }}>{meta}</span>
      </div>
      <div style={{ height: 1, background: "var(--line)" }} />
    </header>
  );
}

/* dotted-leader row */
function LeaderRow({ left, right, strong }) {
  return (
    <div style={{ display: "flex", alignItems: "baseline" }}>
      <span className="eyebrow" style={{ fontSize: 10, letterSpacing: ".16em", color: "var(--ink-soft)" }}>{left}</span>
      <span className="leader" />
      <span className="serif tnum" style={{ fontSize: strong ? 19 : 16, fontWeight: 500, color: "var(--ink)", flex: "0 0 auto", whiteSpace: "nowrap" }}>{right}</span>
    </div>
  );
}

/* ---- Intro ------------------------------------------------------------- */
function Intro({ onBegin }) {
  return (
    <div className="screen-enter" style={{ flex: 1, display: "flex", flexDirection: "column", paddingBottom: 38 }}>
      <Masthead meta="CONFIDENTIAL · SELF-ASSESSMENT" />

      <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", paddingTop: 18, paddingBottom: 18 }} className="stagger">
        <div style={{ animationDelay: "0ms", display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12 }}>
          <span className="eyebrow" style={{ color: "var(--brass)" }}>File RR&middot;100</span>
          <span className="eyebrow" style={{ fontSize: 9, color: "var(--muted)" }}>Real Estate &middot; Startups &middot; Businesses</span>
        </div>

        <h1 className="serif" style={{
          animationDelay: "60ms",
          fontWeight: 400, fontSize: "clamp(36px, 11.5vw, 54px)", lineHeight: 1.02,
          letterSpacing: "-.022em", margin: "12px 0 0",
        }}>
          The Raise-Readiness<br/>
          <span style={{ fontStyle: "italic", fontWeight: 300 }}>Scorecard</span>
        </h1>

        <p style={{ animationDelay: "140ms", margin: "18px 0 0", fontSize: 16, lineHeight: 1.55, color: "var(--ink-soft)" }}>
          This is the same hundred-point check I run on a deal before any investor sees it. Score yourself straight. The number tells you what an investor decides about you in the first ten minutes, while you still have time to do something about it.
        </p>

        {/* spec ledger replaces the stat row */}
        <div style={{ animationDelay: "220ms", marginTop: 22, paddingTop: 12, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 9 }}>
          <LeaderRow left="Sections" right="VI" />
          <LeaderRow left="Weighted checks" right="25" />
          <LeaderRow left="Points possible" right="100" />
          <LeaderRow left="Time required" right="~3 min" />
        </div>

        {/* hanging note replaces the boxed callout */}
        <div style={{ animationDelay: "300ms", marginTop: 20, paddingTop: 12, borderTop: "1px solid var(--ink)" }}>
          <div className="eyebrow" style={{ color: "var(--brass)" }}>Note to file</div>
          <p className="serif" style={{ margin: "8px 0 0", fontSize: 14.5, fontStyle: "italic", lineHeight: 1.5, color: "var(--ink-soft)" }}>
            Only check what you could defend out loud right now. If you couldn&rsquo;t back it up in a real conversation, it&rsquo;s a no, not a yes. Be hard on yourself here so the market doesn&rsquo;t have to be.
          </p>
        </div>
      </div>

      <div style={{ animationDelay: "380ms" }} className="stagger">
        <button className="btn btn-primary" onClick={onBegin}>Score my deal <Arrow /></button>
        <div style={{ marginTop: 16 }}>
          <span className="serif" style={{ fontSize: 15, fontStyle: "italic", color: "var(--ink)" }}>Nick Ayala</span>
        </div>
      </div>
    </div>
  );
}

/* ---- Check row --------------------------------------------------------- */
function CheckRow({ item, id, checked, onToggle, showWeights, idx }) {
  return (
    <button
      onClick={() => onToggle(id)}
      aria-pressed={checked}
      style={{
        textAlign: "left", width: "100%", background: checked ? "var(--accent-tint)" : "var(--surface)",
        border: "1px solid " + (checked ? "var(--accent)" : "var(--line-soft)"),
        borderRadius: 0, padding: "15px 15px 15px 14px", display: "flex", gap: 13, alignItems: "flex-start",
        transition: "border-color .16s ease, background .16s ease",
        animationDelay: (idx * 45) + "ms",
      }}
    >
      <span aria-hidden style={{
        flex: "0 0 auto", width: 21, height: 21, marginTop: 1, borderRadius: 0,
        border: "1.5px solid " + (checked ? "var(--accent)" : "var(--faint)"),
        background: checked ? "var(--accent)" : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center",
        transition: "all .16s ease",
      }}>
        {checked && (
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M2.5 6.2L4.8 8.5L9.5 3.5" stroke="var(--paper)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </span>
      <span style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        <span style={{ display: "grid", gridTemplateColumns: "1fr auto", alignItems: "start", columnGap: 10 }}>
          <span style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.35, color: "var(--ink)", textWrap: "pretty" }}>{item.t}</span>
          {showWeights && (
            <span className="mono tnum" style={{
              flex: "0 0 auto", fontSize: 10.5, fontWeight: 500, color: checked ? "var(--accent)" : "var(--faint)",
              letterSpacing: ".04em", marginTop: 2,
            }}>{String(item.p).padStart(2, "0")}</span>
          )}
        </span>
        <span style={{ display: "block", marginTop: 5, fontSize: 12.8, lineHeight: 1.5, color: "var(--muted)", textWrap: "pretty" }}>{item.d}</span>
      </span>
    </button>
  );
}

/* ---- Assessment -------------------------------------------------------- */
function Assessment({ secIdx, setSecIdx, checked, onToggle, showWeights, onComplete, onBack }) {
  const sec = SECTIONS[secIdx];
  const topRef = useRef(null);
  useEffect(() => { if (topRef.current) topRef.current.scrollTop = 0; window.scrollTo(0, 0); }, [secIdx]);

  const inSection = sec.items.filter((_, i) => checked[sec.id + "-" + i]).length;
  const last = secIdx === SECTIONS.length - 1;

  return (
    <div ref={topRef} style={{ flex: 1, display: "flex", flexDirection: "column", paddingBottom: 30 }}>
      <Masthead meta={"SECTION " + sec.roman + " OF VI"} />

      {/* segmented progress */}
      <div style={{ display: "flex", gap: 4, margin: "16px 0 22px" }}>
        {SECTIONS.map((s, i) => (
          <span key={s.id} style={{ flex: s.max, height: 3, background: "var(--line)", overflow: "hidden" }}>
            <span style={{
              display: "block", height: "100%",
              width: i < secIdx ? "100%" : i === secIdx ? "45%" : "0%",
              background: i <= secIdx ? "var(--accent)" : "transparent",
              transition: "width .4s ease",
            }} />
          </span>
        ))}
      </div>

      <div className="screen-enter" key={secIdx} style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 13 }}>
          <span className="serif tnum" style={{ fontSize: 30, fontWeight: 300, fontStyle: "italic", color: "var(--brass)", lineHeight: 1, flex: "0 0 auto" }}>{sec.roman}</span>
          <h2 className="serif" style={{ margin: 0, fontSize: 25, fontWeight: 500, letterSpacing: "-.01em", lineHeight: 1.1 }}>{sec.title}</h2>
        </div>
        <p className="serif" style={{ margin: "12px 0 0", fontStyle: "italic", fontSize: 15.5, lineHeight: 1.5, color: "var(--ink-soft)" }}>
          {sec.framing}
        </p>

        {/* persistent honesty directive — on every section */}
        <div style={{ marginTop: 18, background: "var(--surface)", border: "1px solid var(--line)", padding: "11px 13px" }}>
          <div className="eyebrow" style={{ color: "var(--brass)", fontSize: 8.5 }}>Read this &middot; Important</div>
          <p style={{ margin: "5px 0 0", fontSize: 11.8, lineHeight: 1.5, color: "var(--ink-soft)" }}>
            Only check what you could defend out loud right now. If you couldn&rsquo;t back it up in a real conversation, it&rsquo;s a no, not a yes. Be hard on yourself here so the market doesn&rsquo;t have to be.
          </p>
        </div>

        <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: 18 }}>
          {sec.items.map((item, i) => (
            <CheckRow key={i} idx={i} item={item} id={sec.id + "-" + i} checked={!!checked[sec.id + "-" + i]} onToggle={onToggle} showWeights={showWeights} />
          ))}
        </div>

        <div className="eyebrow" style={{ marginTop: 16, fontSize: 9.5, color: "var(--faint)" }}>
          <span className="tnum" style={{ color: "var(--muted)" }}>{String(inSection).padStart(2, "0")} / {String(sec.items.length).padStart(2, "0")}</span>&nbsp;&nbsp;checked &middot; max {sec.max} pts
        </div>
      </div>

      <div style={{ marginTop: 26 }}>
        <button className="btn btn-primary" onClick={last ? onComplete : () => setSecIdx(secIdx + 1)}>
          {last ? "See my score" : "Continue"} <Arrow />
        </button>
        <div style={{ textAlign: "center", marginTop: 4 }}>
          <button className="btn-text" onClick={secIdx === 0 ? onBack : () => setSecIdx(secIdx - 1)}>
            &larr; {secIdx === 0 ? "Back to start" : "Previous section"}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---- Email gate -------------------------------------------------------- */
function Gate({ lead, setLead, onSubmit, sending, onBack }) {
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(lead.email.trim());
  const ready = lead.name.trim().length > 1 && emailOk && !sending;
  return (
    <div className="screen-enter" style={{ flex: 1, display: "flex", flexDirection: "column", paddingBottom: 36 }}>
      <Masthead meta="STEP VII · RELEASE OF FINDINGS" />

      <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", paddingTop: 18 }} className="stagger">
        <div className="eyebrow" style={{ color: "var(--brass)" }}>Score calculated</div>
        <h2 className="serif" style={{ margin: "12px 0 0", fontSize: 32, fontWeight: 500, letterSpacing: "-.015em", lineHeight: 1.1 }}>
          Where should I send the<br/>full breakdown?
        </h2>
        <p style={{ margin: "16px 0 26px", fontSize: 14.5, lineHeight: 1.62, color: "var(--ink-soft)", maxWidth: "34ch" }}>
          I&rsquo;ll send you the full breakdown: your tier, your weakest area, and the first thing I&rsquo;d fix. Your score is on the next screen.
        </p>

        <form style={{ display: "flex", flexDirection: "column", gap: 15 }} onSubmit={(e) => { e.preventDefault(); if (ready) onSubmit(); }}>
          <div className="field">
            <label htmlFor="g-name">First name</label>
            <input id="g-name" autoComplete="given-name" placeholder="Your name" value={lead.name} onChange={(e) => setLead({ ...lead, name: e.target.value })} />
          </div>
          <div className="field">
            <label htmlFor="g-email">Email</label>
            <input id="g-email" type="email" autoComplete="email" placeholder="you@firm.com" value={lead.email} onChange={(e) => setLead({ ...lead, email: e.target.value })} />
          </div>
          <div className="field">
            <label htmlFor="g-phone">Mobile <span style={{ textTransform: "none", letterSpacing: 0, color: "var(--faint)" }}>(optional)</span></label>
            <input id="g-phone" type="tel" autoComplete="tel" placeholder="(555) 000-0000" value={lead.phone} onChange={(e) => setLead({ ...lead, phone: e.target.value })} />
          </div>
          <button type="submit" className="btn btn-primary" disabled={!ready} style={{ marginTop: 6 }}>
            {sending ? "Sending\u2026" : "Show me my score"} {!sending && <Arrow />}
          </button>
        </form>

        <p className="eyebrow" style={{ margin: "16px 0 0", fontSize: 9, lineHeight: 1.7, color: "var(--muted)", letterSpacing: ".12em" }}>
          No spam. No list-swapping. Your answers stay between us.
        </p>
        <div style={{ margin: "16px 0 0", padding: "14px 15px", background: "var(--accent-tint)", border: "1px solid var(--accent)", borderLeft: "3px solid var(--accent)" }}>
          <div className="eyebrow" style={{ fontSize: 8.5, color: "var(--accent-deep)" }}>Before you submit</div>
          <p style={{ margin: "6px 0 0", fontSize: 13, lineHeight: 1.55, color: "var(--ink)", fontWeight: 500 }}>
            This only works if every box was honest. A score you inflated wastes your time and mine, and tells you nothing you can actually use. Check only what you can defend out loud.
          </p>
        </div>
      </div>

      <div style={{ textAlign: "center" }}>
        <button className="btn-text" onClick={onBack}>&larr; Back to the last section</button>
      </div>
    </div>
  );
}

/* ---- Result pieces ----------------------------------------------------- */
const TIER_ON_DARK = { ready: "#BFE8C8", close: "#EAD2A0", notyet: "#ECAE84", stop: "#EC9A8E" };

function ScoreHero({ score, tier }) {
  const display = useCountUp(score, true, 1200);
  const tl = TIER_ON_DARK[tier.tone] || "#EAD2A0";
  return (
    <div style={{
      position: "relative", overflow: "hidden", marginTop: 16,
      background: "#13241A", color: "#ECEEE7", padding: "22px 22px 24px",
      boxShadow: "0 26px 50px -26px rgba(0,0,0,.7)", border: "1px solid #23351F",
    }}>
      <div aria-hidden style={{ position: "absolute", top: -46, right: -46, width: 160, height: 160, borderRadius: "50%", border: "1px solid rgba(244,240,231,.07)", boxShadow: "0 0 0 16px rgba(244,240,231,.035)" }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", position: "relative", gap: 14 }}>
        <div className="eyebrow" style={{ color: "rgba(244,240,231,.55)", fontSize: 9, paddingTop: 4 }}>Findings &middot; RR&middot;100</div>
        <div style={{ transform: "rotate(-7deg)", border: "2px solid " + tl, color: tl, padding: "5px 11px 4px", textAlign: "center", flex: "0 0 auto", opacity: .92 }}>
          <div className="mono" style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: ".16em", lineHeight: 1 }}>{tier.label.toUpperCase()}</div>
          <div style={{ height: 1, background: tl, opacity: .5, margin: "4px 0 3px" }} />
          <div className="mono" style={{ fontSize: 7, letterSpacing: ".2em", opacity: .85 }}>ASSESSED</div>
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "flex-end", gap: 12, marginTop: 8, position: "relative" }}>
        <span className="serif tnum" style={{ fontSize: 108, fontWeight: 300, lineHeight: .76, letterSpacing: "-.035em", color: "#ECEEE7" }}>{display}</span>
        <span className="mono tnum" style={{ fontSize: 15, color: "rgba(244,240,231,.5)", paddingBottom: 16, letterSpacing: ".05em" }}>/ 100</span>
      </div>

      <div style={{ marginTop: 20, position: "relative" }}>
        <div style={{ display: "flex", height: 6, overflow: "hidden", gap: 2 }}>
          {[["stop", 45], ["notyet", 20], ["close", 20], ["ready", 15]].map(([t, w]) => (
            <span key={t} style={{ flex: w, background: "var(--" + t + ")", opacity: tier.tone === t ? 1 : .32 }} />
          ))}
        </div>
        <div style={{ position: "absolute", top: -5, left: score + "%", transform: "translateX(-50%)", transition: "left 1.2s cubic-bezier(.22,.61,.36,1)" }}>
          <div style={{ width: 2, height: 16, background: "#ECEEE7" }} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
          {["0", "45", "65", "85", "100"].map((n) => (
            <span key={n} className="eyebrow tnum" style={{ fontSize: 8, color: "rgba(244,240,231,.42)", letterSpacing: ".08em" }}>{n}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

function statusOf(pct) {
  if (pct >= 80) return { label: "Strong", col: "var(--accent)" };
  if (pct >= 55) return { label: "Solid", col: "var(--brass)" };
  return { label: "Needs work", col: "var(--notyet)" };
}

function SectionReport({ subtotals, checked }) {
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {SECTIONS.map((s, idx) => {
        const got = subtotals[s.id];
        const pct = Math.round((got / s.max) * 100);
        const st = statusOf(pct);
        const read = pct >= 80 ? s.reads.strong : pct >= 55 ? s.reads.solid : s.reads.thin;
        const gaps = s.items.filter((_, i) => !checked[s.id + "-" + i]);
        return (
          <div key={s.id} style={{ paddingTop: idx ? 18 : 0, marginTop: idx ? 18 : 0, borderTop: idx ? "1px solid var(--line)" : "none" }}>
            <div style={{ display: "flex", alignItems: "baseline" }}>
              <span className="serif" style={{ color: "var(--brass)", marginRight: 8, fontStyle: "italic", fontSize: 14, flex: "0 0 auto" }}>{s.roman}</span>
              <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", flex: "0 1 auto", lineHeight: 1.2 }}>{s.title}</span>
              <span className="leader" />
              <span className="mono tnum" style={{ fontSize: 11.5, color: "var(--ink-soft)", flex: "0 0 auto", letterSpacing: ".02em" }}>
                {String(got).padStart(2, "0")}<span style={{ color: "var(--faint)" }}>/{s.max}</span>
              </span>
            </div>
            <div style={{ height: 2, background: "var(--line)", marginTop: 7, overflow: "hidden" }}>
              <div style={{ height: "100%", width: pct + "%", background: st.col, transition: "width 1s cubic-bezier(.22,.61,.36,1)" }} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 11 }}>
              <span style={{ width: 6, height: 6, background: st.col, transform: "rotate(45deg)", flex: "0 0 auto" }} />
              <span className="eyebrow" style={{ color: st.col, fontSize: 8.5, whiteSpace: "nowrap" }}>{st.label}</span>
            </div>
            <p style={{ margin: "7px 0 0", fontSize: 13, lineHeight: 1.55, color: "var(--ink-soft)" }}>{read}</p>
            {gaps.length > 0 && (
              <div style={{ marginTop: 11 }}>
                <div className="eyebrow" style={{ fontSize: 8, color: "var(--muted)" }}>What cost you points</div>
                <ul style={{ margin: "7px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
                  {gaps.map((g, i) => (
                    <li key={i} style={{ fontSize: 12.5, lineHeight: 1.45, color: "var(--ink-soft)", display: "flex", gap: 9, alignItems: "flex-start" }}>
                      <span className="mono" aria-hidden style={{ color: "var(--notyet)", flex: "0 0 auto", fontSize: 12, lineHeight: 1.5 }}>&times;</span>
                      <span style={{ textWrap: "pretty" }}>{g.t}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function BookBand() {
  return (
    <div style={{ marginTop: 34, position: "relative", overflow: "hidden", background: "#080A07", color: "#ECEEE7", padding: "22px 20px", display: "flex", gap: 18, alignItems: "center", border: "1px solid #1E261B", boxShadow: "0 26px 50px -26px rgba(0,0,0,.7)" }}>
      <img
        src={(typeof window !== "undefined" && window.BOOK_COVER) ? window.BOOK_COVER : "scorecard/capital-is-the-game.png"}
        alt="Capital Is the Game by Nick Ayala"
        style={{ width: "116px", height: "174px", flex: "0 0 auto", objectFit: "cover", display: "block", boxShadow: "0 0 0 1px rgba(123,212,90,.28), 0 18px 32px -12px rgba(0,0,0,.85)" }}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="eyebrow" style={{ color: "#7BD45A", fontSize: 9, letterSpacing: ".18em" }}>&#9733; #1 New Release &middot; Private Equity</div>
        <p className="eyebrow" style={{ margin: "8px 0 0", fontSize: 8.5, color: "rgba(244,240,231,.6)", letterSpacing: ".13em" }}>The new book from best-selling author Nick Ayala</p>
        <h3 className="serif" style={{ margin: "5px 0 0", fontSize: 23, fontWeight: 500, lineHeight: 1.08, color: "var(--paper)", letterSpacing: "-.015em" }}>Capital Is the Game</h3>
        <p style={{ margin: "10px 0 14px", fontSize: 13, lineHeight: 1.52, color: "rgba(244,240,231,.84)" }}>Raising capital without it is raising blind. The 12 laws that quietly decide who gets funded and who gets passed, from the advisor who has raised and advised over $1B. Read it before your next conversation.</p>
        <a className="btn" href={CONFIG.amazonUrl} target="_blank" rel="noopener" style={{ background: "#7BD45A", color: "#0B0F0A", textDecoration: "none", padding: "13px 16px", fontSize: 11, width: "auto" }}>
          Get your copy on Amazon <span aria-hidden style={{ marginTop: -1 }}>&rarr;</span>
        </a>
      </div>
    </div>
  );
}

function CredentialStrip() {
  return (
    <div style={{ marginTop: 14, border: "1px solid var(--line)", background: "var(--surface)", padding: "13px 15px", display: "flex", gap: 13, alignItems: "center" }}>
      <span aria-hidden style={{ width: 19, height: 19, flex: "0 0 auto", position: "relative", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
        <span style={{ position: "absolute", inset: 0, border: "1.5px solid var(--accent)", transform: "rotate(45deg)" }} />
        <span style={{ width: 5, height: 5, background: "var(--brass)", transform: "rotate(45deg)" }} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="serif" style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)", lineHeight: 1.1 }}>Nick Ayala</div>
        <div className="eyebrow" style={{ fontSize: 8.5, color: "var(--muted)", letterSpacing: ".1em", marginTop: 3, lineHeight: 1.5 }}>Series 65 &amp; 63 licensed advisor &middot; $1B+ raised &amp; advised</div>
      </div>
    </div>
  );
}

function NextMove({ qualifies }) {
  if (qualifies) {
    return (
      <div style={{ marginTop: 30 }}>
        <div className="eyebrow" style={{ marginBottom: 11, color: "var(--accent-deep)" }}>By your score, you qualify</div>
        <div style={{ background: "var(--accent-tint)", border: "1px solid var(--accent)", padding: "22px 18px 20px" }}>
          <h3 className="serif" style={{ margin: 0, fontSize: 27, fontWeight: 500, lineHeight: 1.08, letterSpacing: "-.02em", color: "var(--ink)" }}>
            You&rsquo;ve earned a call with me.
          </h3>
          <p style={{ margin: "11px 0 0", fontSize: 14.5, lineHeight: 1.62, color: "var(--ink-soft)" }}>
            This is a free 30-minute video call, one on one with me, Nick. Not a pitch and not a sales call. Your score says you have a live, fundable deal, so we get on and I pressure-test where your raise is soft before an investor does it for you.
          </p>
          <div style={{ marginTop: 16 }}><CredentialStrip /></div>

          <div className="eyebrow" style={{ margin: "22px 0 3px", color: "var(--accent-deep)" }}>Book your call &middot; pick a time</div>
          <div className="eyebrow" style={{ margin: "0 0 10px", fontSize: 8, color: "var(--muted)", letterSpacing: ".12em" }}>Free &middot; 30 minutes &middot; live video, one on one</div>
          <div style={{ background: "#FFFFFF", border: "1px solid var(--line)", boxShadow: "var(--shadow)", overflow: "hidden" }}>
            <iframe
              src={CONFIG.bookingUrl}
              id="0uRP1yoRTgEbCkCsT1Ch_1780182454574"
              title="Book your 30-minute call with Nick Ayala"
              scrolling="no"
              style={{ width: "100%", height: 760, border: "none", display: "block" }}
            />
          </div>
          <a className="btn btn-ghost" href={CONFIG.bookingUrl} target="_blank" rel="noopener" style={{ textDecoration: "none", marginTop: 10, background: "#FFFFFF" }}>
            Calendar not loading? Open it here <Arrow />
          </a>
          <a className="btn btn-ghost" href={"https://instagram.com/" + CONFIG.handle} target="_blank" rel="noopener" style={{ textDecoration: "none", marginTop: 10, background: "#FFFFFF" }}>
            Questions first? DM @{CONFIG.handle}
          </a>
        </div>
      </div>
    );
  }
  return (
    <div style={{ marginTop: 30 }}>
      <div className="eyebrow" style={{ marginBottom: 11, color: "var(--brass)" }}>Recommended next step</div>
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderTop: "3px solid var(--ink)", padding: "22px 18px", boxShadow: "var(--shadow)" }}>
        <h3 className="serif" style={{ margin: 0, fontSize: 27, fontWeight: 500, lineHeight: 1.08, letterSpacing: "-.02em" }}>
          Get deal-ready first.
        </h3>
        <p style={{ margin: "11px 0 16px", fontSize: 14.5, lineHeight: 1.62, color: "var(--ink-soft)" }}>
          Your deal isn&rsquo;t ready to raise yet. That&rsquo;s fixable, and it&rsquo;s not the end of the road. The Come Up is where you start: the community and framework that gets your business tight enough to score in the green.
        </p>
        <a className="btn btn-primary" href={CONFIG.programUrl} target="_blank" rel="noopener" style={{ textDecoration: "none" }}>
          Start with The Come Up <Arrow />
        </a>
        <p style={{ margin: "14px 0 0", fontSize: 12.5, lineHeight: 1.55, color: "var(--muted)" }}>
          Get to the green, and the next step is a free 30-minute call with me.
        </p>
        <div style={{ marginTop: 14 }}><CredentialStrip /></div>
      </div>
    </div>
  );
}

function Result({ score, subtotals, checked, lead, sent, onRestart }) {
  const tier = tierFor(score);
  const qualifies = score >= CONFIG.callThreshold;
  const topRef = useRef(null);
  useEffect(() => { window.scrollTo(0, 0); if (topRef.current) topRef.current.scrollTop = 0; }, []);

  const weakest = useMemo(() => {
    return [...SECTIONS]
      .map((s) => ({ s, pct: subtotals[s.id] / s.max }))
      .sort((a, b) => a.pct - b.pct || b.s.max - a.s.max)[0].s;
  }, [subtotals]);

  const firstName = (lead.name || "").trim().split(" ")[0] || "Operator";

  return (
    <div ref={topRef} className="screen-enter" style={{ flex: 1, display: "flex", flexDirection: "column", paddingBottom: 40 }}>
      <Masthead meta="FINDINGS · CONFIDENTIAL" />

      {/* score hero — dark, high-contrast */}
      <ScoreHero score={score} tier={tier} />

      {sent && lead.email && (
        <div className="eyebrow" style={{ marginTop: 12, fontSize: 9, color: "var(--muted)", display: "flex", gap: 7, alignItems: "center", letterSpacing: ".1em" }}>
          <span style={{ color: "var(--accent)" }} aria-hidden>&#10003;</span>
          <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Full breakdown sent to {lead.email}</span>
        </div>
      )}

      <p className="serif" style={{ margin: "24px 0 0", fontSize: 25, fontWeight: 500, lineHeight: 1.2, letterSpacing: "-.02em" }}>
        {tier.verdict}
      </p>
      <p style={{ margin: "12px 0 0", fontSize: 14.5, lineHeight: 1.62, color: "var(--ink-soft)" }}>{firstName}, {tier.body}</p>

      {/* routed CTA — top priority, above the detail */}
      <NextMove qualifies={qualifies} />

      {/* book — surfaced high, right under the CTA */}
      <BookBand />

      {/* breakdown */}
      <div style={{ marginTop: 36 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Your section-by-section read</div>
        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", boxShadow: "var(--shadow)", padding: "20px 18px" }}>
          <SectionReport subtotals={subtotals} checked={checked} />
        </div>
      </div>

      {/* fix first */}
      <div style={{ marginTop: 26 }}>
        <div className="eyebrow" style={{ marginBottom: 14, color: "var(--brass)" }}>Fix this first</div>
        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderTop: "3px solid var(--accent)", boxShadow: "var(--shadow)", padding: "18px" }}>
          <h3 className="serif" style={{ margin: 0, fontSize: 19, fontWeight: 500, lineHeight: 1.2 }}>
            {weakest.roman}. {weakest.title}
          </h3>
          <p style={{ margin: "9px 0 0", fontSize: 13.8, lineHeight: 1.6, color: "var(--ink-soft)" }}>{weakest.fixFirst}</p>
        </div>
      </div>

      <div style={{ textAlign: "center", marginTop: 22 }}>
        <button className="btn-text" onClick={onRestart}>Retake the scorecard</button>
      </div>

      <Disclaimer />
    </div>
  );
}

function Disclaimer() {
  return (
    <div style={{ marginTop: 28, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
      <p style={{ margin: 0, fontSize: 9.8, lineHeight: 1.6, color: "var(--faint)" }}>
        Educational tool only. This scorecard is general education and does not constitute investment, legal, tax, or financial advice, an offer or solicitation of any security, or a recommendation to buy, sell, or hold any investment. Nick Ayala is an Investment Adviser Representative; use of this tool does not create an advisory, brokerage, or fiduciary relationship, and nothing here promises or implies any funding, outcome, or result. Consult your own licensed attorney, CPA, and advisors before making capital decisions.
      </p>
    </div>
  );
}

/* ---- lead submit ------------------------------------------------------- */
// Posts the lead + score to a GoHighLevel inbound webhook. Sends real JSON so GHL
// parses the fields for mapping; falls back to a no-cors text post if CORS blocks it.
async function submitLead(payload) {
  if (!CONFIG.webhookUrl) return { ok: true, mode: "prototype" };
  const body = JSON.stringify(payload);
  try {
    await fetch(CONFIG.webhookUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
      keepalive: true,
    });
    return { ok: true };
  } catch (e) {
    try {
      await fetch(CONFIG.webhookUrl, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body,
        keepalive: true,
      });
      return { ok: true, mode: "nocors" };
    } catch (e2) {
      return { ok: false, error: String(e2) };
    }
  }
}

/* ---- Root -------------------------------------------------------------- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [screen, setScreen] = useState("intro");   // intro | assess | gate | result
  const [secIdx, setSecIdx] = useState(0);
  const [checked, setChecked] = useState({});
  const [lead, setLead] = useState({ name: "", email: "", phone: "" });
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  // restore
  useEffect(() => {
    try {
      const raw = localStorage.getItem(STORE_KEY);
      if (raw) {
        const s = JSON.parse(raw);
        if (s.checked) setChecked(s.checked);
        if (s.lead) setLead(s.lead);
        if (s.sent) setSent(s.sent);
        // Always open on the cover (intro); don't auto-resume mid-flow.
      }
    } catch (e) {}
  }, []);
  useEffect(() => {
    try { localStorage.setItem(STORE_KEY, JSON.stringify({ checked, lead, screen, secIdx, sent })); } catch (e) {}
  }, [checked, lead, screen, secIdx, sent]);

  // apply tweaks
  useEffect(() => {
    const r = document.documentElement;
    const [a1, a2] = t.accent;
    r.style.setProperty("--accent", a1);
    r.style.setProperty("--accent-deep", a2);
    r.style.setProperty("--ready", a1);
    const tone = PAPER_TONES[t.paperTone] || PAPER_TONES.ivory;
    r.style.setProperty("--paper", tone.paper);
    r.style.setProperty("--paper-2", tone.paper2);
    r.style.setProperty("--surface", tone.surface);
    r.style.setProperty("--line", tone.line);
    r.style.setProperty("--line-soft", tone.lineSoft);
  }, [t.accent, t.paperTone]);

  const subtotals = useMemo(() => {
    const out = {};
    SECTIONS.forEach((s) => {
      out[s.id] = s.items.reduce((n, it, i) => n + (checked[s.id + "-" + i] ? it.p : 0), 0);
    });
    return out;
  }, [checked]);
  const score = useMemo(() => Object.values(subtotals).reduce((a, b) => a + b, 0), [subtotals]);

  const onToggle = (id) => setChecked((c) => ({ ...c, [id]: !c[id] }));

  const handleSubmit = async () => {
    setSending(true);
    const tier = tierFor(score);
    const weakest = [...SECTIONS]
      .map((s) => ({ s, pct: subtotals[s.id] / s.max }))
      .sort((a, b) => a.pct - b.pct || b.s.max - a.s.max)[0].s;
    const firstName = (lead.name || "").trim().split(" ")[0];
    const payload = {
      firstName,
      name: lead.name,
      email: lead.email,
      phone: lead.phone,
      source: "Raise-Readiness Scorecard",
      score,
      scoreOutOf: 100,
      tier: tier.label,
      qualifiesForCall: score >= CONFIG.callThreshold,
      weakestSection: weakest.title,
      sectionScores: SECTIONS.map((s) => s.title + ": " + subtotals[s.id] + "/" + s.max).join(" | "),
      submittedAt: new Date().toISOString(),
    };
    await submitLead(payload);
    setSending(false);
    setSent(true);
    setScreen("result");
  };

  const restart = () => {
    setChecked({}); setLead({ name: "", email: "", phone: "" }); setSecIdx(0); setSent(false); setScreen("intro");
    try { localStorage.removeItem(STORE_KEY); } catch (e) {}
  };

  return (
    <div className="stage">
      {screen === "intro" && <Intro onBegin={() => { setSecIdx(0); setScreen("assess"); }} />}
      {screen === "assess" && (
        <Assessment
          secIdx={secIdx} setSecIdx={setSecIdx}
          checked={checked} onToggle={onToggle}
          showWeights={t.showWeights}
          onComplete={() => setScreen("gate")}
          onBack={() => setScreen("intro")}
        />
      )}
      {screen === "gate" && (
        <Gate lead={lead} setLead={setLead} sending={sending} onSubmit={handleSubmit} onBack={() => { setSecIdx(SECTIONS.length - 1); setScreen("assess"); }} />
      )}
      {screen === "result" && (
        <Result score={score} subtotals={subtotals} checked={checked} lead={lead} sent={sent} onRestart={restart} />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Identity" />
        <TweakColor
          label="Accent"
          value={t.accent}
          options={[
            ["#34A81F", "#247F17", "#EAF6E4"],
            ["#1F9E6B", "#157A50", "#E4F4EE"],
            ["#2E7D32", "#1F5A23", "#E8F0E6"],
            ["#3F8CCF", "#2C6BA6", "#E6EFF6"],
          ]}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakRadio label="Surface" value={t.paperTone} options={["ivory", "cool", "warm"]} onChange={(v) => setTweak("paperTone", v)} />
        <TweakSection label="Assessment" />
        <TweakToggle label="Show point weights" value={t.showWeights} onChange={(v) => setTweak("showWeights", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
