/* global React */
const { useState, useEffect, useRef } = React;

// ─── Subpage hero arm helper ────────────────────────────────────────────────
function useSubpageArm() {
  const [armed, setArmed] = useState(false);
  useEffect(() => {const t = setTimeout(() => setArmed(true), 60);return () => clearTimeout(t);}, []);
  return armed;
}
function subCls(armed, extra = "") {
  return "hero-animate" + (armed ? " in" : "") + (extra ? " " + extra : "");
}
function subDl(ms) {return { transitionDelay: ms + "ms" };}

// ─── ProcessScroll helpers ───────────────────────────────────────────────────
function PinCounter({ value, decimals, active }) {
  const [val, setVal] = useState(0);
  const fired = useRef(false);
  useEffect(() => {
    if (!active || fired.current) return;
    fired.current = true;
    const dur = 1400;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / dur);
      const e = 1 - Math.pow(1 - t, 3);
      setVal(value * e);
      if (t < 1) requestAnimationFrame(tick);else
      setVal(value);
    };
    requestAnimationFrame(tick);
  }, [active, value]);
  return React.createElement(React.Fragment, null,
  decimals > 0 ? val.toFixed(decimals) : Math.round(val).toLocaleString()
  );
}

function PanelSlide({ panel, isActive }) {
  return (
    <div className="ps-panel">
      <div className="ps-panel-bg-num">{panel.num}</div>
      <div className="ps-panel-inner">
        <div className="ps-left">
          <div className="ps-stage-tag">{panel.num} / {panel.stage}</div>
          <h2 className="ps-title">{panel.title}</h2>
          <p className="ps-body">{panel.body}</p>
          <p className="ps-detail">{panel.detail}</p>
        </div>
        <div className="ps-right">
          {panel.kpis.map((kpi, j) =>
          <div
            key={j}
            className={"ps-kpi" + (isActive ? " visible" : "")}
            style={{ transitionDelay: isActive ? j * 130 + "ms" : "0ms" }}>
            
              <div className="ps-kpi-value">
                {kpi.text ?
              <span>{kpi.text}</span> :

              <>
                    {kpi.prefix && <span className="ps-kpi-affix">{kpi.prefix}</span>}
                    <PinCounter value={kpi.value} decimals={kpi.decimals} active={isActive} />
                  </>
              }
                {kpi.suffix && <span className="ps-kpi-affix ps-kpi-suf">{kpi.suffix}</span>}
              </div>
              <div className="ps-kpi-label">{kpi.label}</div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

// ─── Process Pin-Scroll ──────────────────────────────────────────────────────
window.ProcessScroll = function ProcessScroll() {
  const outerRef = useRef(null);
  const trackRef = useRef(null);
  const hintRef = useRef(null);
  const [activePanel, setActivePanel] = useState(0);

  const panels = [
  {
    num: "01", stage: "SOURCING",
    title: "Relationship-driven sourcing pipeline.",
    body: "VRB Capital sources exclusively primarily through established relationships with banks, regional lenders, special servicers, and loan sale advisors.",
    detail: "Sachin Batra has maintained these counterparty relationships for 9+ years. The pipeline is a structural moat, not a cost center.",
    kpis: [
    { label: "Annual Screened Flow", value: 400, prefix: "$", suffix: "M+", decimals: 0 },
    { label: "Active Seller Relationships", value: 50, prefix: "", suffix: "+", decimals: 0 },
    { label: "Positions Acquired vs. Screened", value: 5, prefix: "<", suffix: "%", decimals: 0 }]

  },
  {
    num: "02", stage: "UNDERWRITING",
    title: "Two valuations. Every exit path considered. No exceptions.",
    body: "Every position receives two independent collateral valuations before capital is committed — a BPO and a desktop appraisal. Returns are then stress-tested across a minimum of three exit strategies, including loan modification, discounted payoff, and REO/asset disposition.",
    detail: "If the downside case does not return principal at acquisition basis, the deal is declined. No exceptions. This discipline has contributed to VRB Capital’s 0.0% realized principal loss rate to date.",
    kpis: [
    { label: "Independent Valuations Per Deal", value: 2, prefix: "", suffix: "", decimals: 0 },
    { label: "Exit Paths Stress-Tested, Minimum", value: 3, prefix: "", suffix: "+", decimals: 0 },
    { label: "Typical Acquisition Basis", text: "60-90", suffix: "% of UPB" }]

  },
  {
    num: "03", stage: "RESOLUTION",
    title: "Active management. Monthly review. In-house.",
    body: "Resolution is not outsourced. VRB Capital maintains direct borrower engagement, monitors servicer activity, and reviews every active position monthly against its documented resolution plan.",
    detail: "Modification, discounted payoff, short payoff, and REO are all executed in-house. The exit path chosen is always the highest risk-adjusted return, not the easiest execution.",
    kpis: [
    { label: "Avg. Hold — Resolved Positions", value: 14, prefix: "", suffix: " mo", decimals: 0 },
    { label: "Realized Principal Loss Rate", value: 0.0, prefix: "", suffix: "%", decimals: 1 },
    { label: "Workout Executed In-House", value: 100, prefix: "", suffix: "%", decimals: 0 }]

  },
  {
    num: "04", stage: "EXIT",
    title: "Returns from basis — not market timing.",
    body: "Every exit is underwritten before acquisition. Returns are realized by closing the spread between acquisition basis and resolved collateral value — through modification, payoff, or disposition.",
    detail: "Since inception, VRB Capital has fully resolved 80% of positions with a weighted average gross IRR of 64% and zero principal losses.",
    kpis: [
    { label: "Wtd. Avg. Gross IRR", text: "64%" },
    { label: "Positions Fully Resolved", text: "80%" },
    { label: "Realized Principal Loss", value: 0.0, prefix: "", suffix: "%", decimals: 1 }]

  }];


  useEffect(() => {
    function onScroll() {
      const outer = outerRef.current;
      const track = trackRef.current;
      if (!outer || !track) return;
      if (window.innerWidth <= 960) {
        track.style.transform = "";
        document.body.classList.remove("ps-pinned");
        return;
      }
      const rect = outer.getBoundingClientRect();
      const outerH = outer.offsetHeight;
      const vh = window.innerHeight;
      const scrolled = -rect.top;
      const maxScroll = outerH - vh;
      const p = Math.max(0, Math.min(1, scrolled / maxScroll));
      track.style.transform = `translateX(${-p * 75}%)`;
      if (hintRef.current) {
        hintRef.current.style.opacity = p > 0.04 ? "0" : "1";
      }
      const next = Math.min(3, Math.floor(p * 4));
      setActivePanel((prev) => prev !== next ? next : prev);
      // Retract the site nav while the section is pinned so it never covers the stepper
      const pinned = rect.top <= 0 && rect.bottom >= vh;
      document.body.classList.toggle("ps-pinned", pinned);
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => {
      window.removeEventListener("scroll", onScroll);
      document.body.classList.remove("ps-pinned");
    };
  }, []);

  return (
    <div ref={outerRef} id="process" className="ps-outer">
      <div className="ps-sticky">
        <div className="ps-nav">
          <span className="ps-nav-eyebrow">Investment Process</span>
          <div className="ps-nav-steps">
            {panels.map((p, i) =>
            <React.Fragment key={i}>
                <div className={"ps-nav-step" + (i === activePanel ? " active" : "") + (i < activePanel ? " done" : "")}>
                  <div className="ps-nav-dot" />
                  <span className="ps-nav-label">{p.stage}</span>
                </div>
                {i < panels.length - 1 &&
              <div className={"ps-nav-connector" + (i < activePanel ? " done" : "")} />
              }
              </React.Fragment>
            )}
          </div>
        </div>

        <div ref={trackRef} className="ps-track">
          {panels.map((panel, i) =>
          <PanelSlide key={i} panel={panel} isActive={i === activePanel} />
          )}
        </div>

        <div ref={hintRef} className="ps-hint">
          <span>Scroll to advance</span>
          <span className="ps-hint-arrow">↓</span>
        </div>
      </div>
    </div>);

};

// ─── FAQ accordion ───────────────────────────────────────────────────────────
function FAQItem({ q, a, defaultOpen }) {
  const [open, setOpen] = useState(!!defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--vrb-ink-200)" }}>
      <button
        onClick={() => setOpen((o) => !o)}
        style={{
          width: "100%", textAlign: "left", padding: "22px 28px", background: "transparent",
          border: "none", display: "flex", justifyContent: "space-between", alignItems: "center",
          fontFamily: "var(--font-sans)", fontSize: 16, fontWeight: 600, color: "var(--vrb-navy)",
          cursor: "pointer", gap: 16
        }}>
        
        <span>{q}</span>
        <span className={"faq-icon" + (open ? " open" : "")}>+</span>
      </button>
      <div className={"faq-answer" + (open ? " open" : "")}>
        <div className="faq-answer-inner">{a}</div>
      </div>
    </div>);

}

// ─── IRR bar cell (Track Record) ─────────────────────────────────────────────
function IrrCell({ irr, maxIrr = 35 }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => entries.forEach((e) => {if (e.isIntersecting) {setVisible(true);obs.disconnect();}}),
      { threshold: 0.5 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  if (irr === null) return <td ref={ref} className="num">—</td>;
  const pct = Math.min(irr / maxIrr, 1);
  return (
    <td ref={ref} className="num">
      <div className="irr-cell">
        <span>{irr.toFixed(1)}</span>
        <div className="irr-bar-track">
          <div className={"irr-bar-fill" + (visible ? " in" : "")} style={visible ? { transform: `scaleX(${pct})` } : {}} />
        </div>
      </div>
    </td>);

}

// ─── HOW WE INVEST PAGE ──────────────────────────────────────────────────────
window.HowWeInvestPage = function HowWeInvestPage({ openForm }) {
  const armed = useSubpageArm();

  const philosophy = [
  { n: "01", t: "Basis is protection.", b: "We never underwrite to a coupon we do not control. Our only reliable protection is acquisition basis relative to verified collateral value." },
  { n: "02", t: "Model three exits, minimum.", b: "Every acquisition is stress-tested against no fewer than three resolution paths — modification, discounted payoff, and disposition. We acquire only when each modeled path supports principal recovery under the stated underwriting case." },
  { n: "03", t: "Resolve in-house.", b: "Active borrower engagement and servicer oversight are not outsourced. Resolution is the work — and the source of alpha." }];


  const faqs = [
  { q: "How do non-performing loans generate returns?", a: "Returns are generated when a loan is resolved at a value above VRB Capital’s acquisition basis. Resolution may occur through loan modification, discounted payoff, short payoff, foreclosure, REO disposition, or note sale. The return profile depends on acquisition price, collateral value, resolution timing, borrower outcome, expenses, and interim cash flow" },
  { q: "What is the typical hold period?", a: "Hold periods across the portfolio have averaged 12–18 months. Residential resolutions tend to close faster — typically 6–14 months. Hospitality resolutions are more operationally intensive and can run 18–36 months. Hold periods vary by note type, borrower cooperation, and state foreclosure timelines. Investors should be prepared for an overall investment commitment of three to five years. " },
  { q: "How does VRB Capital seek to reduce principal loss risk?", a: "VRB Capital seeks to reduce principal loss risk through disciplined acquisition basis, independent collateral verification, legal review, borrower analysis, and multiple modeled resolution paths. Each position must support principal recovery under the stated underwriting case before approval. These controls reduce risk but do not eliminate it." },
  { q: "What regulatory framework governs the Fund?", a: "VRB Capital operates under Rule 506(b) of Regulation D. Offerings are made exclusively to accredited investors with a pre-existing substantive relationship with the firm. This website is informational and does not constitute an offer to sell or a solicitation of an offer to buy securities." },
  { q: "How are performance results reported?", a: "Performance reporting is provided through regular investor communications, loan-level reporting materials, and a secure investor portal where investors can log in to view their position, account information, and performance reporting. Reports include capital account information, portfolio updates, realized and unrealized performance, and relevant tax documentation, as applicable. Reporting format, timing, and content are governed by the investment offering and governing documents" }];


  return (
    <div>
      {/* ── Hero ── */}
      <section className="subpage-hero">
        <div className="subpage-hero-inner">
          <div>
            <div className={subCls(armed, "breadcrumbs")} style={subDl(0)}>
              <a href="index.html">VRB Capital</a>
              <span className="sep">/</span>
              <span>How We Invest</span>
            </div>
            <h1 className={subCls(armed)} style={subDl(100)}>Downside-first credit, resolved in-house.</h1>
            <p className={subCls(armed, "lede")} style={subDl(240)}>
              VRB Capital acquires sub-performing and non-performing mortgage notes in the $1M–$10M+ UPB range, underwrites to current as-is collateral value, and resolves every position through active in-house asset management.
            </p>
          </div>
          <div className={subCls(armed, "hero-capsule")} style={subDl(300)}>
            <div className="label">DIRECT NOTE INVESTMENTS</div>
            <p>
              VRB Capital buys discounted real estate loans where the collateral alone supports full recovery. The firm typically acquires loans at <strong>60–90% of UPB</strong> in the <strong>$1M–$10M+ UPB</strong> range and models every resolution path before committing capital: payoff, loan modification, foreclosure, and REO sale. Returns come from closing the gap between acquisition basis and the resolved value of the collateral.
            </p>
            <div className="hero-cta">
              <button onClick={() => openForm && openForm()} className="btn btn-hero-cta">Download the Investor Guide</button>
            </div>
          </div>
        </div>
      </section>

      {/* ── Philosophy ── */}
      <section className="section">
        <div className="container-narrow">
          <Reveal variant="fade"><div className="eyebrow">Philosophy</div></Reveal>
          <RevealWords text="Three principles govern every acquisition." tag="h2" className="section-title" />
          <div className="invest-principles">
            {philosophy.map((p, i) =>
            <Reveal key={i} delay={i * 100} variant="up">
                <div className="invest-principle">
                  <div className="invest-principle-num">{p.n}</div>
                  <h3 className="invest-principle-title">{p.t}</h3>
                  <p className="invest-principle-body">{p.b}</p>
                </div>
              </Reveal>
            )}
          </div>
        </div>
      </section>

      {/* ── Process pin-scroll ── */}
      <ProcessScroll />

      {/* ── Comparison ── */}
      <Comparison />

      {/* ── FAQ ── */}
      <section id="faq" className="section section-alt">
        <div className="container-narrow">
          <div className="section-head centered">
            <div>
              <Reveal variant="fade"><div className="eyebrow">Common Questions</div></Reveal>
              <RevealWords text="What investors ask most." tag="h2" className="section-title" />
            </div>
          </div>
          <Reveal variant="up" delay={80}>
            <div style={{ background: "var(--vrb-white)", border: "1px solid var(--vrb-ink-200)" }}>
              {faqs.map((f, i) =>
              <FAQItem key={i} q={f.q} a={f.a} defaultOpen={i === 0} />
              )}
            </div>
          </Reveal>
        </div>
      </section>

      <CTASection />
    </div>);

};

// ─── TRACK RECORD PAGE ───────────────────────────────────────────────────────
// ─── Track Record formatting + sub-components ────────────────────────────────
function trUSD(n) {
  return "$" + Math.round(n).toLocaleString("en-US");
}
function trUSDc(n) {
  return "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function trIRR(d) {
  if (d.irr === null) return "—";
  return (Number.isInteger(d.irr) ? d.irr : d.irr) + "%";
}

// Status line color: positive (paid/performing) vs neutral (workout)
function trStatusLabel(d) {
  if (d.status === "Paid") return "Paid " + d.paidDate + " · " + d.stage;
  if (d.status === "Performing") return "Performing · " + d.stage;
  return d.status;
}

function DealTile({ d }) {
  const positive = d.group === "worked";
  return (
    <article className={"deal-tile" + (positive ? " is-worked" : " is-workout")}>
      <div className="deal-tile-head">
        <div className="deal-loc">{d.city}, {d.state}</div>
        <span className="deal-asset">{d.asset}</span>
      </div>
      <div className="deal-metrics">
        <div className="deal-metric">
          <div className="k">UPB</div>
          <div className="v">{trUSD(d.upb)}</div>
        </div>
        <div className="deal-metric">
          <div className="k">{d.projected ? "Projected IRR" : "Realized IRR"}</div>
          <div className={"v" + (d.irr !== null ? " v-irr" : "")}>{trIRR(d)}</div>
        </div>
      </div>
      <div className="deal-tile-foot">
        <div className="deal-status">{trStatusLabel(d)}</div>
        <div className="deal-purchase">Purchase basis {trUSDc(d.purchase)}</div>
      </div>
    </article>);

}

function GroupBand({ tone, label, count }) {
  return (
    <div className={"deal-band deal-band-" + tone}>
      <span className="deal-band-label">{label}</span>
      <span className="deal-band-count">{count} {count === 1 ? "note" : "notes"}</span>
    </div>);

}

function CaseStudyRow({ d }) {
  const cs = d.caseStudy;
  const holdLabel = d.hold === "Active" ? "Active" : typeof d.hold === "number" ? d.hold + " months" : "—";
  const sp = d.status === "Paid"
    ? { cls: "pill", style: { background: "var(--vrb-light-blue)", color: "var(--vrb-blue)" }, text: "Completed" }
    : d.group === "workout"
    ? { cls: "pill pill-neg", style: null, text: d.stage }
    : { cls: "pill pill-pos", style: null, text: /bankruptcy/i.test(d.stage) ? "Performing under Bankruptcy Chapter 13" : "Performing · " + d.stage };
  return (
    <article className="case-row">
      <div className="case-row-head">
        <div className="case-row-title">
          <span className="case-num">{cs.num}</span>
          <div>
            <h3>{d.city}, {d.state}</h3>
            <div className="case-sub">{d.asset === "Multi-Family" ? "Multifamily" : "Residential"} · {d.lien}</div>
          </div>
        </div>
        <div className="case-row-status">
          <span className={sp.cls} style={sp.style}>{sp.text}</span>
          <div className="case-hold">Hold: {holdLabel}</div>
        </div>
      </div>
      <div className="case-row-metrics">
        <div className="case-metric case-metric-irr">
          <div className="v">{trIRR(d)}</div>
          <div className="k">{d.projected ? "Proj. IRR" : "IRR"}</div>
        </div>
        <div className="case-metric">
          <div className="v">{d.cltv ? d.cltv + "%" : "—"}</div>
          <div className="k">CLTV</div>
        </div>
        <div className="case-metric">
          <div className="v">{d.noteType}</div>
          <div className="k">Note Type</div>
        </div>
        <div className="case-metric">
          <div className="v">{d.strategy}</div>
          <div className="k">Exit Method</div>
        </div>
      </div>
      <div className="case-row-text">
        <div className="case-block">
          <div className="case-block-label">Strategy</div>
          <p>{cs.strategy}</p>
        </div>
        <div className="case-block">
          <div className="case-block-label">★ Key Takeaway</div>
          <p>{cs.takeaway}</p>
        </div>
      </div>
    </article>);

}

window.TrackRecordPage = function TrackRecordPage({ openForm }) {
  const armed = useSubpageArm();

  const deals = window.TrackRecord;
  const agg = window.TrackAggregate;
  const worked = deals.filter((d) => d.group === "worked");
  const workout = deals.filter((d) => d.group === "workout");
  const cases = deals.filter((d) => d.caseStudy).sort((a, b) => a.caseStudy.num - b.caseStudy.num);

  return (
    <div>
      <section className="subpage-hero">
        <div className="subpage-hero-inner">
          <div>
            <div className={subCls(armed, "breadcrumbs")} style={subDl(0)}>
              <a href="index.html">VRB Capital</a>
              <span className="sep">/</span>
              <span>Track Record</span>
            </div>
            <h1 className={subCls(armed)} style={subDl(100)}>Underwriting discipline. Realized results.</h1>
            <p className={subCls(armed, "lede")} style={subDl(240)}>Every position VRB Capital holds is disclosed with the same specificity used in diligence — acquisition basis, collateral coverage, resolution strategy, and realized gross IRR where the note has been worked out. <strong>This is downside-first underwriting, applied to every transaction.</strong> Past performance is not indicative of future results.</p>
          </div>
          <div className={subCls(armed, "hero-capsule")} style={subDl(300)}>
            <div className="label">Methodology</div>
            <p>
              Each note is shown with unpaid principal balance, acquisition (purchase) basis, combined loan-to-value at acquisition where disclosed, resolution stage, and gross IRR — <strong>projected</strong> on performing or active positions, <strong>realized</strong> on notes fully paid off. Gross IRR is shown before loan-level fees, expenses, and carried interest.
            </p>
            <div className="hero-cta">
              <button onClick={() => openForm && openForm()} className="btn btn-hero-cta">Download the Investor Guide</button>
            </div>
          </div>
        </div>
      </section>

      {/* ── Portfolio snapshot ── */}
      <section className="section">
        <div className="container">
          <div className="eyebrow">Portfolio Snapshot</div>
          <RevealWords text="The book, at a glance." tag="h2" className="section-title" style={{ fontSize: 36, marginBottom: 36 }} />
          <Reveal>
            <div className="snap">
              <div className="snap-hero">
                <div className="snap-hero-label">UPB Advised / Acquired</div>
                <div className="snap-hero-value">$<Counter to={71.3} decimals={1} />M+</div>
                <p className="snap-hero-note">Across the firm's active book of performing, sub-performing and non-performing mortgage notes. 80% of notes are fully worked out — performing or fully paid; 20% are in active workout.</p>
              </div>
              <div className="snap-stats">
                <div className="snap-stat">
                  <div className="k">AVERAGE RESOLUTION PERIOD</div>
                  <div className="v">14 months</div>
                  <div className="s">Average time from acquisition to resolution</div>
                </div>
                <div className="snap-stat">
                  <div className="k">PRIMARY RESOLUTION STRATEGY</div>
                  <div className="v">Pay-off</div>
                  <div className="s">Most common successful workout path</div>
                </div>
                <div className="snap-stat">
                  <div className="k">LOWEST REALIZED LOAN-LEVEL IRR</div>
                  <div className="v">{agg.minIRR}</div>
                  <div className="s">Floor across all disclosed loan-level returns</div>
                </div>
                <div className="snap-stat">
                  <div className="k">AVERAGE CLTV </div>
                  <div className="v">74%</div>
                  <div className="s">Average combined loan-to-value at purchase</div>
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* ── Case studies ── */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">Case Studies</div>
              <h2 className="section-title">How four positions were worked out.</h2>
            </div>
            <p className="section-lede">Selected transactions shown in full — the strategy applied at the note level and the takeaway for how VRB Capital converts distressed junior liens into realized return.</p>
          </div>
          <div className="case-rows">
            {cases.map((d, i) => <Reveal key={i} delay={i * 60}><CaseStudyRow d={d} /></Reveal>)}
          </div>
        </div>
      </section>

      <CTASection />
    </div>);

};

Object.assign(window, {
  ProcessScroll: window.ProcessScroll,
  HowWeInvestPage: window.HowWeInvestPage,
  TrackRecordPage: window.TrackRecordPage
});