/* global React */
const { useState: useStateCH, useEffect: useEffectCH } = React;

// ============ Fade-in wrapper ============
function CHFadeIn({ children, delay = 0, duration = 1000, className = "", style = {} }) {
  const [visible, setVisible] = useStateCH(false);
  useEffectCH(() => {
    const t = setTimeout(() => setVisible(true), delay);
    return () => clearTimeout(t);
  }, [delay]);
  return (
    <div
      className={"ch-fade " + (visible ? "ch-fade-in " : "") + className}
      style={{ transitionDuration: duration + "ms", ...style }}>
      {children}
    </div>
  );
}

// ============ Character-stagger heading ============
function CHAnimatedHeading({ text, className = "", style = {}, charDelay = 30, initialDelay = 200 }) {
  const [armed, setArmed] = useStateCH(false);
  useEffectCH(() => {
    const t = setTimeout(() => setArmed(true), initialDelay);
    return () => clearTimeout(t);
  }, [initialDelay]);
  const lines = text.split("\n");
  return (
    <h1 className={"ch-heading " + className} style={style}>
      {lines.map((line, lineIdx) => (
        <span className="ch-heading-line" key={lineIdx}>
          {Array.from(line).map((ch, charIdx) => {
            const totalDelay =
              lineIdx * line.length * charDelay + charIdx * charDelay;
            return (
              <span
                key={charIdx}
                className={"ch-char " + (armed ? "ch-char-in" : "")}
                style={{ transitionDelay: totalDelay + "ms" }}>
                {ch === " " ? "\u00A0" : ch}
              </span>
            );
          })}
        </span>
      ))}
    </h1>
  );
}

// ============ Cinematic Hero ============
window.CinematicHero = function CinematicHero({ openForm, videoSrc }) {
  const src = videoSrc || (window.__TWEAKS && window.__TWEAKS.cinematicVideoSrc) || "";

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "eyebrow":    "new",
    "headline":   "new",
    "sub":        "new",
    "rightPanel": "card"
  }/*EDITMODE-END*/;

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const eyebrowText = t.eyebrow === "new"
    ? "DISTRESSED REAL ESTATE CREDIT"
    : "VRB Capital · Private Credit Fund";

  const headlineText = t.headline === "new"
    ? "Buy below collateral value.\nCreate returns from mortgage notes."
    : "Asset‑backed returns\nfrom mortgage notes.";

  const subText = t.sub === "new"
    ? "VRB Capital acquires sub-performing and non-performing mortgage notes secured by U.S. real estate. Every investment begins with current collateral value—not loan balance—and is actively managed through resolution."
    : "We acquire sub‑performing and non‑performing first‑lien mortgage notes secured by U.S. real estate. Underwritten to the collateral. Resolved in‑house.";

  return (
    <section className="ch-hero" data-screen-label="Cinematic Hero">
      {src ? (
        <video
          className="ch-video"
          src={src}
          autoPlay
          loop
          muted
          playsInline
        />
      ) : (
        <div className="ch-video ch-video-placeholder" aria-hidden="true">
          <div className="ch-video-grid"></div>
          <div className="ch-video-noise"></div>
          <div className="ch-video-vignette"></div>
        </div>
      )}

      <div className="ch-stage">
        <div className="ch-bottom">
          <div className="ch-grid">
            <div className="ch-left">
              <CHFadeIn delay={120} duration={700}>
                <div className="ch-eyebrow">{eyebrowText}</div>
              </CHFadeIn>

              <CHAnimatedHeading
                key={headlineText}
                text={headlineText}
                charDelay={28}
                initialDelay={220}
              />

              <CHFadeIn delay={1100} duration={900}>
                <p className="ch-lede">{subText}</p>
              </CHFadeIn>

              <CHFadeIn delay={1500} duration={900}>
                <div className="ch-cta">
                  <button className="ch-btn ch-btn-solid" onClick={openForm}>
                    Request Investor Materials
                  </button>
                  <a href="track-record.html" className="ch-btn ch-btn-glass liquid-glass">
                    View Track Record →
                  </a>
                </div>
              </CHFadeIn>
            </div>

            <div className="ch-right">
              <CHFadeIn delay={1750} duration={900}>
                {t.rightPanel === "card" ? (
                  <div className="ch-what-we-do liquid-glass">
                    <div className="ch-wwd-label">WHAT WE DO</div>
                    <p className="ch-wwd-body">
                      VRB Capital acquires discounted mortgage notes secured by residential, multifamily, and hospitality real estate.
                    </p>
                    <p className="ch-wwd-body">
                      We underwrite each position to today's as-is collateral value, acquire only where downside is protected, and execute every resolution internally—from loan modification to payoff, foreclosure, or REO sale.
                    </p>
                  </div>
                ) : (
                  <div className="ch-tag liquid-glass">
                    Acquire. Underwrite. Resolve.
                  </div>
                )}
              </CHFadeIn>
            </div>
          </div>

          <CHFadeIn delay={1900} duration={900} className="ch-meta-wrap">
            <div className="ch-meta liquid-glass">
              <div className="ch-meta-item">
                <div className="k">Capital Deployed</div>
                <div className="v">$71.3M+</div>
              </div>
              <div className="ch-meta-divider"></div>
              <div className="ch-meta-item">
                <div className="k">Realized Loss Rate</div>
                <div className="v">0.0%</div>
              </div>
              <div className="ch-meta-divider"></div>
              <div className="ch-meta-item">
                <div className="k">Weighted Avg. Basis</div>
                <div className="v">63% of UPB</div>
              </div>
              <div className="ch-meta-divider"></div>
              <div className="ch-meta-item">
                <div className="k">Fund Structure</div>
                <div className="v">Reg D · 506(b)</div>
              </div>
            </div>
          </CHFadeIn>
        </div>
      </div>

      <TweaksPanel>
        <TweakSection label="Hero Copy" />
        <TweakRadio label="Eyebrow" value={t.eyebrow}
          options={["new", "current"]}
          onChange={(v) => setTweak("eyebrow", v)} />
        <TweakRadio label="Headline" value={t.headline}
          options={["new", "current"]}
          onChange={(v) => setTweak("headline", v)} />
        <TweakRadio label="Sub" value={t.sub}
          options={["new", "current"]}
          onChange={(v) => setTweak("sub", v)} />
        <TweakSection label="Right Panel" />
        <TweakRadio label="Style" value={t.rightPanel}
          options={["card", "tag"]}
          onChange={(v) => setTweak("rightPanel", v)} />
      </TweaksPanel>
    </section>
  );
};

Object.assign(window, { CinematicHero: window.CinematicHero });
