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

// ============ Reveal-on-scroll wrapper ============
// variant: "up" (default), "fade", "left", "right", "scale"
window.Reveal = function Reveal({ children, delay = 0, variant = "up" }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => entries.forEach((e) => {
        if (e.isIntersecting) {setShown(true);obs.disconnect();}
      }),
      { threshold: 0.06, rootMargin: "0px 0px -16px 0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  const cls = {
    up: "reveal",
    fade: "reveal-fade",
    left: "reveal-left",
    right: "reveal-right",
    scale: "reveal-scale"
  }[variant] || "reveal";
  return (
    <div
      ref={ref}
      className={cls + " " + (shown ? "in" : "")}
      style={{ transitionDelay: delay + "ms" }}>
      
      {children}
    </div>);

};

// ============ Scroll progress bar ============
window.ScrollProgress = function ScrollProgress() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const update = () => {
      const el = document.documentElement;
      const scrolled = el.scrollTop || document.body.scrollTop;
      const total = el.scrollHeight - el.clientHeight;
      setPct(total > 0 ? scrolled / total * 100 : 0);
    };
    window.addEventListener("scroll", update, { passive: true });
    return () => window.removeEventListener("scroll", update);
  }, []);
  return <div className="scroll-progress" style={{ width: pct + "%" }} />;
};

// ============ Word-by-word reveal ============
window.RevealWords = function RevealWords({ text, tag = "h2", className = "", delay = 0 }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => entries.forEach((e) => {if (e.isIntersecting) {setShown(true);obs.disconnect();}}),
      { threshold: 0.08, rootMargin: "0px 0px -16px 0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  const words = text.split(" ");
  return React.createElement(
    tag,
    { ref, className },
    words.flatMap((w, i) => {
      const span = React.createElement("span", {
        key: i,
        className: "rw-word" + (shown ? " in" : ""),
        style: { transitionDelay: delay + i * 60 + "ms" }
      }, w);
      return i < words.length - 1 ? [span, " "] : [span];
    })
  );
};

// ============ Animated counter ============
window.Counter = function Counter({ to, prefix = "", suffix = "", decimals = 0, duration = 1400 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(to * eased);
            if (t < 1) {
              requestAnimationFrame(tick);
            } else {
              setVal(to);
              requestAnimationFrame(() => {
                if (ref.current) ref.current.classList.add("counted");
              });
            }
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [to, duration]);
  const formatted = decimals > 0 ?
  val.toFixed(decimals) :
  Math.round(val).toLocaleString();
  return (
    <span ref={ref} className="counter-target">
      {prefix}{formatted}{suffix}
    </span>);

};

// ============ Announcement bar ============
window.Announce = function Announce() {
  return (
    <div className="announce">
      <div className="left">
        <span style={{ opacity: 0.55 }}>VRB Capital LLC · Private Credit · Non-Performing &amp; Sub-Performing Mortgage Notes</span>
      </div>
      <div className="right">
        <span style={{ opacity: 0.55 }}>Accredited Investors Only</span>
      </div>
    </div>);

};

// ============ Navigation (multi-page, real <a href>) ============
window.Nav = function Nav({ current, openForm }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  // Close mobile menu on resize back to desktop
  useEffect(() => {
    const onResize = () => {if (window.innerWidth > 768) setMenuOpen(false);};
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  const links = [
  { id: "home", label: "Home", href: "index.html" },
  { id: "invest", label: "How We Invest", href: "how-we-invest.html" },
  { id: "track", label: "Track Record", href: "track-record.html" },
  { id: "insights", label: "Insights", href: "insights.html" },
  { id: "fdic", label: "Bank Intel", href: "fdic-report.html" },
  { id: "about", label: "About", href: "about.html" },
  { id: "contact", label: "Contact", href: "contact.html" }];

  return (
    <nav className={"nav " + (scrolled ? "scrolled" : "") + (menuOpen ? " menu-open" : "")}>
      <div className="nav-inner">
        <a href="index.html" className="nav-logo">
          <img src="assets/VRB_Capital_Logo.png" alt="VRB Capital" />
        </a>
        <ul className="nav-links">
          {links.map((l) =>
          <li key={l.id}>
              <a href={l.href} className={"nav-link " + (current === l.id ? "active" : "")}>{l.label}</a>
            </li>
          )}
        </ul>
        <div className="nav-cta">
          {openForm ?
          <button className="btn btn-secondary" onClick={openForm}>Request Investor Materials</button> :
          <a href="contact.html" className="btn btn-secondary">Request Investor Materials</a>}
        </div>
        <button
          className={"nav-hamburger " + (menuOpen ? "open" : "")}
          onClick={() => setMenuOpen((o) => !o)}
          aria-label="Toggle menu"
          aria-expanded={menuOpen}>
          
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>
      {menuOpen &&
      <div className="nav-mobile-menu">
          <ul>
            {links.map((l) =>
          <li key={l.id}>
                <a href={l.href} className={"nav-mobile-link " + (current === l.id ? "active" : "")}>{l.label}</a>
              </li>
          )}
          </ul>
          <div className="nav-mobile-cta">
            {openForm ?
          <button className="btn btn-primary" onClick={() => {setMenuOpen(false);openForm();}}>Request Investor Materials</button> :
          <a href="contact.html" className="btn btn-primary">Request Investor Materials</a>}
          </div>
        </div>
      }
    </nav>);

};

// ============ Compliance banner ============
window.Compliance = function Compliance() {
  return (
    <div className="compliance">
      <div className="compliance-inner">
        <span className="compliance-tag">506(b)</span>
        <span>
          This website is for informational purposes and does not constitute an offer to sell or a solicitation of an offer to buy any security. Investment opportunities are available only to accredited investors with whom VRB Capital has a pre-existing substantive relationship. Past performance is not indicative of future results.
        </span>
      </div>
    </div>);

};

// ============ Footer ============
window.Footer = function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-top">
          <div className="footer-brand">
            <img src="assets/VRB_Capital_Logo.png" className="footer-logo" alt="VRB Capital" />
            <p>VRB Capital LLC acquires and actively manages performing and non-performing mortgage loans secured by residential, multifamily, and hospitality real estate across the United States.</p>
            <div className="footer-tag">Perseverance · Integrity · Performance</div>
          </div>
          <div className="footer-col">
            <h5>Firm</h5>
            <ul>
              <li><a href="about.html">About</a></li>
              <li><a href="about.html#team">Team</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Strategy</h5>
            <ul>
              <li><a href="how-we-invest.html">How We Invest</a></li>
              <li><a href="track-record.html">Track Record</a></li>
              <li><a href="how-we-invest.html#process">Process</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Insights</h5>
            <ul>
              <li><a href="insights.html">Articles</a></li>
              <li><a href="insights.html#resources">Guides</a></li>
              <li><a href="fdic-report.html">Bank Intel</a></li>
              <li><a href="insights.html#resources">Glossary</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <ul>
              <li><a href="mailto:sachin@vrbcap.com">info@vrbcap.com</a></li>
              <li><a href="https://www.vrbcap.com" target="_blank" rel="noopener">www.vrbcap.com</a></li>
              <li><a href="contact.html">Schedule a Call</a></li>
              <li><a href="https://www.linkedin.com/company/vrbcap" target="_blank" rel="noopener">LinkedIn</a></li>
              <li><a href="investor-portal.html">Investor Portal</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-disclaimer">
          <strong style={{ color: "rgba(255,255,255,0.7)", display: "block", marginBottom: 8 }}>IMPORTANT DISCLOSURES</strong>
          This communication does not constitute an offer of securities. Any such offer will be made only to qualified accredited investors and only by means of confidential offering documents. Information contained herein has been obtained from sources believed to be reliable but is not guaranteed. Performance figures reflect realized results on completed transactions and are not necessarily indicative of the performance of any current or future offering. All investments involve risk, including possible loss of principal. Consult your tax, legal, and financial advisors before investing. Securities offered through Rule 506(b) of Regulation D under the Securities Act of 1933.
        </div>
        <div className="footer-bottom">
          <div>© 2026 VRB Capital LLC. All rights reserved.</div>
          <div style={{ display: "flex", gap: 20 }}>
            <a href="privacy-policy.html" style={{ color: "rgba(255,255,255,0.5)", textDecoration: "none" }}>Privacy Policy</a>
            <a href="terms-of-use.html" style={{ color: "rgba(255,255,255,0.5)", textDecoration: "none" }}>Terms of Use</a>
            <a href="disclosures.html" style={{ color: "rgba(255,255,255,0.5)", textDecoration: "none" }}>Disclosures</a>
          </div>
        </div>
      </div>
    </footer>);

};

// ============ Photo / Placeholder ============
window.Photo = function Photo({ src, label, ratio = "4/3", className = "" }) {
  const use = window.VRB_USE_PHOTO_PLACEHOLDERS;
  if (use) {
    return (
      <div className={className} style={{
        aspectRatio: ratio, background: "var(--vrb-navy)",
        display: "flex", alignItems: "flex-end", padding: 16,
        color: "rgba(255,255,255,0.7)", fontSize: 11,
        letterSpacing: "0.08em", textTransform: "uppercase",
        fontFamily: "var(--font-mono)"
      }}>
        Photo: {label}
      </div>);

  }
  return <img src={src} alt={label} className={className} loading="lazy" />;
};

// ============ Lead Magnet Form ============
window.LeadForm = function LeadForm() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [values, setValues] = useState({
    firstName: "", lastName: "", email: "", status: "", size: "", relation: "", _gotcha: ""
  });
  const onChange = (k) => (e) => setValues((v) => ({ ...v, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setError("");
    setSubmitting(true);
    try {
      await window.submitVrbForm(values, {
        subject: "VRB Capital — Investor Materials Request",
        fields: {
          firstName: "First Name", lastName: "Last Name", email: "Work Email",
          status: "Accredited Status"
        }
      });
      setSubmitted(true);
    } catch (err) {
      setError(err.message || "Something went wrong. Please email info@vrbcap.com directly.");
    } finally {
      setSubmitting(false);
    }
  };
  if (submitted) return (
    <div className="lead-form">
      <div className="form-success">
        <div className="check">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--vrb-navy)", margin: "0 0 12px 0" }}>Materials requested.</h3>
        <p style={{ fontSize: 14, color: "var(--vrb-ink-500)", lineHeight: 1.55, margin: 0 }}>
          A member of the VRB Capital team will contact you at <strong style={{ color: "var(--vrb-navy)" }}>{values.email || "your email"}</strong> within two business days to confirm accredited status and deliver offering materials.
        </p>
      </div>
    </div>);

  return (
    <form className="lead-form" onSubmit={submit}>
      <input type="text" name="_gotcha" tabIndex="-1" autoComplete="off" aria-hidden="true"
        value={values._gotcha} onChange={onChange("_gotcha")}
        style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
      <div className="form-eyebrow">Investor Inquiry · Accredited Only</div>
      <h3>Request the Investor Guide</h3>
      <div className="field field-row">
        <div>
          <label>First Name</label>
          <input required value={values.firstName} onChange={onChange("firstName")} />
        </div>
        <div>
          <label>Last Name</label>
          <input required value={values.lastName} onChange={onChange("lastName")} />
        </div>
      </div>
      <div className="field">
        <label>Work Email</label>
        <input type="email" required placeholder="name@firm.com" value={values.email} onChange={onChange("email")} />
      </div>
      <div className="field">
        <label>Accredited Status</label>
        <select required value={values.status} onChange={onChange("status")}>
          <option value="">Select...</option>
          <option>Yes</option>
          <option>No</option>
          <option>Not sure</option>
        </select>
      </div>
      {error &&
        <div role="alert" style={{ background: "var(--status-negative-bg)", color: "var(--status-negative)", fontSize: 13, lineHeight: 1.5, padding: "10px 14px", borderRadius: "var(--radius-sm)", marginBottom: 14 }}>
          {error}
        </div>
      }
      <button type="submit" className="btn btn-primary btn-lg" disabled={submitting}>{submitting ? "Sending…" : "Request Materials"}</button>
      <div className="form-disclaimer">Materials are provided only after investor qualification, consistent with applicable private offering requirements.</div>
    </form>);

};

Object.assign(window, {
  Reveal: window.Reveal,
  ScrollProgress: window.ScrollProgress,
  RevealWords: window.RevealWords,
  Counter: window.Counter,
  Announce: window.Announce,
  Nav: window.Nav,
  Compliance: window.Compliance,
  Footer: window.Footer,
  Photo: window.Photo,
  LeadForm: window.LeadForm
});