/* WhySection / PathwaySection / FunnelSection, paper redesign.
   - No illustrations.
   - WhySection uses a left-rail editorial layout with draw-line dividers.
   - FunnelSection now hosts a single, deeper Bank-vs-Private timeline. */

function WhySection() {
  const ref = useReveal(0.1);
  const headlineRef = useRef(null);
  const [typeOn, setTypeOn] = useState(false);

  // Headline as ordered segments so the typewriter can preserve the italic word
  const HEAD_SEGS = [
    { t: "Property capital, " },
    { t: "made clear",  em: true },
    { t: "." },
    { br: true },
    { t: "Each deal routed to the pathway it actually fits." },
  ];
  const HEAD_TOTAL = HEAD_SEGS.reduce((n, s) => n + (s.t ? s.t.length : 0), 0);
  const [typed, setTyped] = useState(0);

  // Trigger typewriter only on first viewport entry
  useEffect(() => {
    const el = headlineRef.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { setTypeOn(true); io.disconnect(); }
      });
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    if (!typeOn) return;
    // Brief delay so the section reveal-in finishes before typing starts
    let i = 0;
    let intervalId = null;
    const startId = setTimeout(() => {
      intervalId = setInterval(() => {
        i += 1;
        setTyped(i);
        if (i >= HEAD_TOTAL) clearInterval(intervalId);
      }, 26);
    }, 240);
    return () => { clearTimeout(startId); if (intervalId) clearInterval(intervalId); };
  }, [typeOn, HEAD_TOTAL]);

  // Render the segments revealing `typed` characters across them
  const renderHeadline = () => {
    let used = 0;
    return HEAD_SEGS.map((s, idx) => {
      if (s.br) return <br key={idx}/>; // always reserve the second line to avoid layout jump
      const start = used;
      used += s.t.length;
      if (typed <= start) return null;
      const slice = s.t.slice(0, typed - start);
      return s.em
        ? <span key={idx} className="serif-em">{slice}</span>
        : <span key={idx}>{slice}</span>;
    });
  };

  const items = [
    { n: "01", k: "Clear pathway logic",       v: "Every deal mapped to the most-aligned funding profile from the very first conversation." },
    { n: "02", k: "Fast structured assessment", v: "Indicative pathway in minutes, not weeks of broker shopping or repeat submissions." },
    { n: "03", k: "Curated capital network",   v: "Fifty-plus private credit and non-bank sources unified inside a single matching engine." },
    { n: "04", k: "Aligned lender match",      v: "Routed only to funders whose appetite genuinely fits the location, sector and leverage." },
    { n: "05", k: "Lender-ready metrics",      v: "LVR, GRV, presales, permits and stage-of-build structured the way credit teams expect." },
    { n: "06", k: "Confident next step",       v: "Senior, stretch, mezzanine or bridge, chosen with transparent, defensible reasoning." },
  ];

  return (
    <section id="why" ref={ref} className="section reveal" style={{ background: "#fff" }}>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 64 }}>
          <span className="tag">What DPF delivers</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.1fr)", gap: 80, alignItems: "start" }} className="why-grid">
          <div className="reveal">
            <h2
              ref={headlineRef}
              className="display h2"
              style={{ margin: 0, minHeight: "2.2em" }}
              aria-label="Property capital, made clear. Each deal routed to the pathway it actually fits."
            >
              {renderHeadline()}
              {typed < HEAD_TOTAL && typeOn && (
                <span className="dpf-type-caret" aria-hidden="true"/>
              )}
            </h2>
            <p className="body-l" style={{ marginTop: 32, maxWidth: 520 }}>
              DPF translates each scenario, leverage, security, stage, urgency, into the funding pathway most aligned to it, drawn from a curated network of private credit and non-bank capital sources across Australia.
            </p>
          </div>

          <div className="reveal" style={{ display: "flex", flexDirection: "column" }}>
            {items.map((it, i) => (
              <div key={it.n} className="reveal" data-delay={Math.min(i, 5)} style={{ padding: "24px 0", display: "grid", gridTemplateColumns: "56px 1fr", gap: 24, alignItems: "start", borderTop: i === 0 ? "1px solid var(--mist-2)" : "1px solid var(--mist)" }}>
                <div className="mono" style={{ fontSize: 12, color: "var(--steel)" }}>- {it.n}</div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 500, letterSpacing: "-0.01em" }}>{it.k}</div>
                  <div className="body" style={{ fontSize: 14, marginTop: 6 }}>{it.v}</div>
                </div>
              </div>
            ))}
            <div style={{ height: 1, background: "var(--mist-2)" }}/>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width:900px){ .why-grid { grid-template-columns: 1fr !important; gap: 56px !important; } }
        .dpf-type-caret {
          display: inline-block;
          width: 0.05em;
          height: 0.78em;
          background: currentColor;
          margin-left: 0.06em;
          vertical-align: -0.04em;
          animation: dpf-type-blink 1s steps(2) infinite;
        }
        @keyframes dpf-type-blink { 50% { opacity: 0; } }
      `}</style>
    </section>
  );
}

/* TrackRecord, credibility strip. Honest framing: the company is new but
   the directors aren't. Speaks to the founders' track record only. */
function TrackRecord() {
  const ref = useReveal(0.12);
  return (
    <section ref={ref} className="section reveal" style={{ background: "var(--pearl)", borderTop: "1px solid var(--mist)", borderBottom: "1px solid var(--mist)", position: "relative", overflow: "hidden" }}>
      {/* Blended photo — visible toward the right, washed into the page behind the text. */}
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: "url(assets/established-estate.jpg)", backgroundSize: "cover", backgroundPosition: "center", opacity: 0.5 }} />
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "linear-gradient(100deg, var(--pearl) 0%, rgba(247,246,241,0.93) 34%, rgba(247,246,241,0.62) 64%, rgba(247,246,241,0.26) 100%)" }} />
      <div aria-hidden="true" style={{ position: "absolute", left: 0, right: 0, top: 0, height: 90, background: "linear-gradient(to top, transparent, var(--pearl))" }} />
      <div aria-hidden="true" style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 90, background: "linear-gradient(to bottom, transparent, var(--pearl))" }} />
      <div className="container" style={{ position: "relative", zIndex: 1 }}>
        <div className="reveal" style={{ marginBottom: 32 }}>
          <span className="tag">Track record</span>
        </div>
        <div className="reveal" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.05fr) minmax(0, 1fr)", gap: 64, alignItems: "start" }} className="track-grid">
          <div>
            <h2 className="display h2" style={{ margin: 0 }}>
              A new platform with <span className="serif-em">established relationships</span> behind it.
            </h2>
            <p className="body-l" style={{ marginTop: 24, maxWidth: 560 }}>
              Direct Property Finance is a young company. The team building it is not. Across roughly three decades of combined experience in Australian property and structured credit, the people behind it have helped originate <strong style={{ color: "var(--ink)", fontWeight: 600 }}>over $1&nbsp;billion</strong> in property lending since 2009, working alongside the private credit funds, family offices and non-bank lenders that make up the network you're matched to.
            </p>
            <p className="body" style={{ marginTop: 18, maxWidth: 560 }}>
              The platform is the meeting point those relationships have always needed. Honest, structured introductions, not deal flow brokered for a fee.
            </p>
          </div>

          <div className="reveal track-stats" style={{ display: "grid", gridTemplateColumns: "1fr", gap: 1, background: "var(--mist)", border: "1px solid var(--mist)" }}>
            {[
              { v: "$1bn+",        k: "Team-originated lending",       s: "Cumulative across Australian property since 2009" },
              { v: "Since 2009",   k: "Active in capital markets",    s: "Senior debt, structured credit and private credit" },
              { v: "Director-led", k: "Senior relationships only",    s: "Direct lines to credit decision-makers, not panels" },
            ].map((it) => (
              <div key={it.k} style={{ background: "var(--bone)", padding: "28px 32px" }}>
                <div className="display" style={{ fontSize: 38, lineHeight: 1, letterSpacing: "-0.02em" }}>{it.v}</div>
                <div style={{ marginTop: 14, fontSize: 15, fontWeight: 500, letterSpacing: "-0.005em" }}>{it.k}</div>
                <div className="small" style={{ marginTop: 4 }}>{it.s}</div>
              </div>
            ))}
          </div>
        </div>
        <p className="small reveal" style={{ marginTop: 28, maxWidth: 720, color: "var(--slate)" }}>
          Figures relate to cumulative origination by the founding directors prior to and during the formation of Direct Property Finance. Indicative; subject to lender confidentiality on specific transactions.
        </p>
      </div>
      <style>{`@media (max-width:900px){ .track-grid { grid-template-columns: 1fr !important; gap: 48px !important; } }`}</style>
    </section>
  );
}

function PathwaySection() {
  const ref = useReveal(0.08);
  const steps = [
    { k: "Deal Data",         v: "Project, security, leverage, stage, urgency, location." },
    { k: "Assessment Engine", v: "AI-assisted metric review and lender-appetite mapping." },
    { k: "Pathway Match",     v: "Suitable funding profile, senior, stretch, mezz, bridge." },
    { k: "Next Step",         v: "Indicative pathway and structured intro to capital." },
  ];
  return (
    <section id="pathway" ref={ref} className="section reveal" style={{ background: "#fff", borderTop: "1px solid var(--mist)" }}>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 48 }}>
          <span className="tag">The platform</span>
        </div>
        <div className="reveal" style={{ maxWidth: 980 }}>
          <h2 className="display h2" style={{ margin: 0 }}>
            A structured pathway between <span className="serif-em">the deal and the capital</span> most suited to it.
          </h2>
        </div>

        <div className="reveal" style={{ marginTop: 88, position: "relative" }}>
          <div style={{ position: "absolute", left: "8%", right: "8%", top: 36, height: 1, background: "var(--mist-2)" }}/>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24, position: "relative", zIndex: 2 }} className="pathway-grid">
            {steps.map((s, i) => (
              <div key={i} className="reveal pathway-step" data-delay={i} style={{ textAlign: "center" }}>
                <div className="pathway-step__circle">
                  <span className="mono pathway-step__num" style={{ fontSize: 12 }}>0{i+1}</span>
                </div>
                <div className="pathway-step__title" style={{ marginTop: 24, fontSize: 18, fontWeight: 500, letterSpacing: "-0.01em" }}>{s.k}</div>
                <div className="body" style={{ fontSize: 13, marginTop: 6, maxWidth: 220, margin: "6px auto 0" }}>{s.v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width:900px){.pathway-grid{grid-template-columns:repeat(2,1fr) !important}}
        .pathway-step { cursor: default; transition: transform .35s cubic-bezier(.2,.8,.2,1); }
        .pathway-step__circle {
          width: 72px; height: 72px; margin: 0 auto; border-radius: 50%;
          border: 1px solid var(--ink); background: #fff;
          display: flex; align-items: center; justify-content: center;
          position: relative;
          transition: background .3s ease, transform .3s ease, box-shadow .3s ease;
        }
        .pathway-step__circle::before {
          content: ""; position: absolute; inset: -6px; border-radius: 50%;
          border: 1px solid var(--steel); opacity: 0;
          transition: opacity .3s ease, transform .3s ease;
          transform: scale(0.9);
        }
        .pathway-step__num { transition: color .25s ease; }
        .pathway-step__title { transition: color .25s ease; }
        .pathway-step:hover { transform: translateY(-3px); }
        .pathway-step:hover .pathway-step__circle {
          background: var(--ink);
          box-shadow: 0 8px 20px -10px rgba(10,10,10,0.35);
        }
        .pathway-step:hover .pathway-step__circle::before { opacity: 1; transform: scale(1); }
        .pathway-step:hover .pathway-step__num { color: var(--bone); }
        .pathway-step:hover .pathway-step__title { color: var(--steel); }
      `}</style>
    </section>
  );
}

function FunnelSection() {
  const ref = useReveal(0.05);
  return (
    <section
      id="explore"
      ref={ref}
      className="section reveal"
      style={{ padding: 0, position: "relative", borderTop: "1px solid var(--mist)" }}
    >
      {/* Light top zone, the headline lives here, on pearl */}
      <div style={{ background: "var(--pearl)", padding: "120px 0 36px" }}>
        <div className="container">
          <div className="reveal" style={{ marginBottom: 32 }}>
            <span className="tag">Why private credit</span>
          </div>
          <div className="reveal" style={{ maxWidth: 980 }}>
            <h2 className="display h2" style={{ margin: 0 }}>
              Banks stall. <span className="serif-em">Private credit moves.</span>
            </h2>
            <p className="body-l" style={{ marginTop: 20, maxWidth: 640 }}>
              Scroll the timeline below. Watch the bank file get held at committee while the meter ticks over. By the time the bank's first valuation re-run lands, the Direct Property Finance pathway has already drawn down.
            </p>
          </div>
        </div>
      </div>

      {/* Liquid transition band, pearl → blueprint grey */}
      <LavaBubble topColor="var(--pearl)" inkColor="#E5ECF3" />

      {/* Blueprint zone, grid lines on pale blue-grey, no card wrapper.
          The timeline sits directly on the blueprint surface. A soft fade
          at the bottom hands off into the BigCTA below. */}
      <div style={{
        background: "#E5ECF3",
        backgroundImage: `linear-gradient(rgba(110,140,176,0.18) 1px, transparent 1px), linear-gradient(90deg, rgba(110,140,176,0.18) 1px, transparent 1px)`,
        backgroundSize: "60px 60px",
        padding: "40px 0 0",
      }}>
        <div className="container">
          <BankVsPrivateTimeline />
        </div>
        <div style={{ height: 140, background: "linear-gradient(to bottom, #E5ECF3, var(--pearl))" }} aria-hidden="true"/>
      </div>
    </section>
  );
}

Object.assign(window, { WhySection, TrackRecord, PathwaySection, FunnelSection });
