/* BankVsPrivateTimeline, blueprint split-screen.

   Layout:
   - Sticky inner panel; user scrolls through ~320vh.
   - LEFT half: two slim vertical tracks (Major bank | Direct Property Finance)
     with milestone dots and short labels. Tracks fill top→down.
   - RIGHT half: three big ticking numbers stacked, then a descriptive
     sentence that updates by scroll phase.
   - Sits directly on the FunnelSection's blueprint grid background, no
     white card wrapper, separated only by mono-typed dashed hairlines. */
function BankVsPrivateTimeline() {
  const wrap = useRef(null);
  const [p, setP] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      const el = wrap.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const raw = (vh * 0.55 - r.top) / (r.height - vh * 0.45);
      setP(Math.max(0, Math.min(1, raw)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, []);

  const dpfPct = Math.min(1, p / 0.22);
  const bankPct = (() => {
    if (p < 0.14) return p / 0.14 * 0.18;
    if (p < 0.32) return 0.18 + (p - 0.14) * 0.67;
    if (p < 0.52) return 0.30;
    if (p < 0.70) return 0.30 + (p - 0.52) * 1.67;
    if (p < 0.88) return 0.60;
    return 0.60 + (p - 0.88) * 2.0;
  })();

  const dollarCost = Math.round(p * 487000);
  const weeksLost  = (p * 14.2);

  // Phase-based commentary that updates as the user scrolls.
  const phases = [
    { upTo: 0.10, h: "Day 1 · the clock starts",
      v: "Both files lodged the same morning. The bank takes the full credit application path; Direct Property Finance takes the structured-brief path." },
    { upTo: 0.22, h: "Week 1 · routes diverge",
      v: "Bank in initial review. Direct Property Finance has already identified the lender profile and shaped the brief for committee-free assessment." },
    { upTo: 0.35, h: "Week 3 · Direct Property Finance drawn",
      v: "Term sheet issued, valuation complete, Direct Property Finance facility drawn. The bank file has only just reached its first credit committee." },
    { upTo: 0.52, h: "Week 6 · the meter ticks",
      v: "Bank requests a valuation re-run plus an additional documentation round. Extra interest is now accruing daily on the existing facility." },
    { upTo: 0.70, h: "Week 12 · still at committee",
      v: "Bank file resubmitted after the re-doc. Conditional approval granted, with new conditions to clear. ROI drag is now real, not theoretical." },
    { upTo: 0.88, h: "Week 18 · presale window closes",
      v: "Second valuation re-run requested. A presale unit is lost to the timeline. The bank file is held pending final conditions." },
    { upTo: 1.00, h: "Week 22+ · approved, eventually",
      v: "Bank file finally cleared, 19 weeks after Direct Property Finance drew down. By now the bank-side extra interest alone is approaching half a million dollars." },
  ];
  const phase = phases.find((ph) => p <= ph.upTo) || phases[phases.length - 1];

  const bankSteps = [
    { y: 0.04, k: "Application lodged",     note: "Day 1" },
    { y: 0.18, k: "Initial review",         note: "Week 1" },
    { y: 0.30, k: "Committee · 1st round",  note: "Week 4" },
    { y: 0.45, k: "Valuation re-run",       note: "Week 6",  pen: true },
    { y: 0.55, k: "Resubmitted",            note: "Week 8" },
    { y: 0.70, k: "Conditional approval",   note: "Week 12" },
    { y: 0.85, k: "Final conditions",       note: "Week 18", pen: true },
    { y: 1.00, k: "Settle, if approved",   note: "Week 22+" },
  ];
  const dpfSteps = [
    { y: 0.05, k: "Brief parsed",           note: "Hour 4" },
    { y: 0.22, k: "Pathway identified",     note: "Day 1" },
    { y: 0.45, k: "Term sheet",             note: "Day 3" },
    { y: 0.82, k: "Documentation",          note: "Day 7–10" },
    { y: 1.00, k: "Settled",                note: "Week 3" },
  ];

  const dash = "1px dashed rgba(80,110,140,0.4)";
  const monoCap = { fontSize: 11, color: "#3B5168", letterSpacing: "0.05em", textTransform: "uppercase" };

  return (
    <div ref={wrap} style={{ position: "relative", minHeight: "320vh" }}>
      <div style={{ position: "sticky", top: 88, paddingTop: 8 }}>
        <div style={{ padding: "28px 0", borderTop: dash, borderBottom: dash }}>

          {/* Top measurement bar */}
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "baseline",
            gap: 16, flexWrap: "wrap", marginBottom: 28, paddingBottom: 16,
            borderBottom: "1px dashed rgba(80,110,140,0.25)",
          }}>
            <div className="mono" style={monoCap}>Fig. 03 · funding routes for the same $20m deal</div>
            <div className="mono" style={monoCap}>22-week window · scroll ↓</div>
          </div>

          {/* Split-screen */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "start" }} className="bvp-split">

            {/* LEFT, twin vertical tracks */}
            <div>
              <div className="mono" style={{ ...monoCap, marginBottom: 18 }}>Timeline</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }} className="bvp-tracks">
                <VTrack title="Major bank"        subtitle="Committee · valuations · re-docs" tone="signal" pct={bankPct} steps={bankSteps} />
                <VTrack title="Direct Property Finance"  subtitle="Pathway · term sheet · settle"   tone="steel"  pct={dpfPct}  steps={dpfSteps}  />
              </div>
            </div>

            {/* RIGHT, numbers + descriptive sentence */}
            <div>
              <div className="mono" style={{ ...monoCap, marginBottom: 18 }}>What's happening</div>

              <div style={{ display: "grid", gap: 18, marginBottom: 28 }}>
                <BigStat label="Extra interest accruing"  value={"$" + dollarCost.toLocaleString("en-AU")} tone="signal" sub="while the bank file sits with committee" />
                <BigStat label="Weeks lost"               value={weeksLost.toFixed(1) + " wks"}            tone="signal" sub="against the Direct Property Finance track" />
                <BigStat label="Direct Property Finance"         value={dpfPct >= 1 ? "Settled" : "Active"}        tone="steel"  sub={dpfPct >= 1 ? "Week 3 · drawn down" : `Day ${Math.max(1, Math.round(dpfPct * 21))} · drawing`} />
              </div>

              <div style={{ paddingTop: 22, borderTop: dash }}>
                <div className="mono" style={{ ...monoCap, marginBottom: 10 }}>Now</div>
                <h3 className="display" style={{ fontSize: 30, margin: 0, letterSpacing: "-0.025em", lineHeight: 1.1 }}>{phase.h}</h3>
                <p className="body" style={{ marginTop: 12, fontSize: 16, lineHeight: 1.6, maxWidth: 480 }}>{phase.v}</p>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div style={{
            marginTop: 28, paddingTop: 22, borderTop: "1px dashed rgba(80,110,140,0.25)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
            gap: 12, flexWrap: "wrap",
          }}>
            <div className="small" style={{ maxWidth: 560 }}>
              Indicative only. Real outcomes vary by deal. The point is the shape: when private credit is the right fit, the cost of waiting on the wrong track compounds quickly, and we move before the bank's first committee meeting.
            </div>
            <a href="assessment.html" className="btn btn--primary">Get my pathway <span className="arrow"><I.Arrow/></span></a>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .bvp-split  { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
        @media (max-width: 720px) {
          .bvp-tracks { grid-template-columns: 1fr !important; gap: 24px !important; }
        }
      `}</style>
    </div>
  );
}

function BigStat({ label, value, tone, sub }) {
  const c = tone === "signal" ? "var(--signal)" : "var(--steel)";
  return (
    <div>
      <div className="label" style={{ color: c }}>{label}</div>
      <div
        className="display"
        style={{
          fontSize: "clamp(34px, 4.4vw, 56px)",
          marginTop: 6,
          letterSpacing: "-0.025em",
          color: "var(--ink)",
          fontVariantNumeric: "tabular-nums",
          lineHeight: 1.04,
        }}
      >
        {value}
      </div>
      <div className="small" style={{ marginTop: 4 }}>{sub}</div>
    </div>
  );
}

/* Slim vertical track for the blueprint split-screen.
   Track line is 1px, milestones are 9px dots with compact two-line labels. */
function VTrack({ title, subtitle, tone, pct, steps }) {
  const c = tone === "signal" ? "var(--signal)" : "var(--steel)";
  const trackH = 540;

  return (
    <div>
      <div className="label" style={{ color: tone === "signal" ? "var(--ink)" : "var(--steel)" }}>{title}</div>
      <div className="small" style={{ marginTop: 2, fontSize: 11, lineHeight: 1.4 }}>{subtitle}</div>

      <div style={{ position: "relative", marginTop: 20, height: trackH }}>
        {/* Track background line */}
        <div style={{
          position: "absolute", left: 8, top: 0, bottom: 0, width: 1,
          background: "rgba(80,110,140,0.32)",
        }}/>
        {/* Filled portion */}
        <div style={{
          position: "absolute", left: 8, top: 0, width: 1,
          height: `${pct * 100}%`, background: c,
          transition: "height .25s linear",
        }}/>
        {/* Play head */}
        <span style={{
          position: "absolute", left: 3, top: `calc(${pct * 100}% - 0.5px)`,
          width: 11, height: 1, background: "var(--ink)",
          transition: "top .25s linear",
        }}/>

        {/* Milestones */}
        {steps.map((s, i) => {
          const live = pct >= s.y - 0.001;
          return (
            <div key={i} style={{
              position: "absolute", left: 0, right: 0, top: `calc(${s.y * 100}% - 5px)`,
              display: "grid", gridTemplateColumns: "18px 1fr", alignItems: "start", columnGap: 10,
              opacity: live ? 1 : 0.4,
              transition: "opacity .5s ease",
            }}>
              <span style={{
                gridColumn: 1, justifySelf: "start", marginLeft: 4,
                width: 9, height: 9, marginTop: 1,
                borderRadius: 999,
                background: live ? c : "transparent",
                border: `1.5px solid ${live ? c : "rgba(80,110,140,0.5)"}`,
                boxShadow: live ? "0 0 0 3px #E5ECF3" : "none",
                transition: "background .3s ease, border-color .3s ease, box-shadow .3s ease",
              }}/>
              <div style={{ gridColumn: 2 }}>
                <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.25, letterSpacing: "-0.005em" }}>{s.k}</div>
                <div style={{ fontSize: 10, color: "var(--slate)", marginTop: 2, fontFamily: "var(--font-mono)" }}>
                  {s.note}
                  {s.pen && <span style={{ color: "var(--signal)" }}> · penalty</span>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.BankVsPrivateTimeline = BankVsPrivateTimeline;
