/* global React */
const { useState: useStateInsights, useEffect: useEffectInsights, useRef: useRefInsights } = React;

// ============ SUBPAGE: INSIGHTS ============
window.InsightsPage = function InsightsPage({ openForm }) {
  const [armed, setArmedIns] = useStateInsights(false);
  useEffectInsights(() => { const t = setTimeout(() => setArmedIns(true), 60); return () => clearTimeout(t); }, []);
  const insCls = (extra = "") => "hero-animate" + (armed ? " in" : "") + (extra ? " " + extra : "");
  const insDl = (ms) => ({ transitionDelay: ms + "ms" });

  const P = window.VRB_PHOTOS;
  const C = window.InsightsContent || {};
  const photoFor = (key) => (P && P[key]) || key;

  const hero = C.hero || {};
  const renderBold = (text = "") =>
    String(text).split(/(\*\*[^*]+\*\*)/g).map((part, i) =>
      part.startsWith("**") && part.endsWith("**")
        ? <strong key={i}>{part.slice(2, -2)}</strong>
        : part
    );
  const featured = { ...(C.featured || {}), photo: photoFor((C.featured || {}).photo) };
  const articles = (C.articles || []).map((a) => ({ ...a, photo: photoFor(a.photo) }));
  const resources = C.resources || [];
  const marketStats = C.marketStats || [];
  const articleHref = (item) => (item && item.published && item.slug) ? ("insights/" + item.slug + ".html") : null;

  return (
    <div>
      <section className="subpage-hero">
        <div className="subpage-hero-inner">
          <div>
            <div className={insCls("breadcrumbs")} style={insDl(0)}>
              <a href="index.html">VRB Capital</a>
              <span className="sep">/</span>
              <span>{hero.breadcrumb}</span>
            </div>
            <h1 className={insCls()} style={insDl(100)}>{hero.title}</h1>
            <p className={insCls("lede")} style={insDl(240)}>
              {renderBold(hero.lede)}
            </p>
          </div>
          <div className={insCls("hero-capsule")} style={insDl(300)}>
            <div className="label">{hero.policyLabel}</div>
            <p>{renderBold(hero.policy)}</p>
            <div className="hero-cta">
              <button onClick={() => openForm && openForm()} className="btn btn-hero-cta">Download the Investor Guide</button>
            </div>
          </div>
        </div>
      </section>

      {/* FEATURED LETTER */}
      <section className="section">
        <div className="container">
          <Reveal variant="fade"><div className="eyebrow">Featured</div></Reveal>
          <div style={{ fontSize: 36, marginBottom: 32 }}>
            <RevealWords text="The current quarter's letter." tag="h2" className="section-title" />
          </div>

          <article className="ins-featured">
            <div className="ins-featured-photo">
              <Photo src={featured.photo} label="Letter from the Managing Partner" ratio="4/3" />
              <div className="ins-featured-tag">{featured.cardTag}</div>
            </div>
            <div className="ins-featured-body">
              <div className="ins-meta">
                <span>{featured.eyebrow}</span>
              </div>
              <h3 className="ins-featured-title">{featured.title}</h3>
              <p className="ins-featured-summary">{featured.summary}</p>
              <div className="ins-byline">
                <div className="ins-byline-author">
                  <strong>{featured.author}</strong>
                  <span>{featured.role}</span>
                </div>
                <div className="ins-byline-meta">
                  <span>{featured.date}</span>
                  <span className="ins-byline-dot">·</span>
                  <span>{featured.readTime}</span>
                </div>
              </div>
              {articleHref(featured) ? (
                <a className="btn btn-primary" style={{ marginTop: 20 }} href={articleHref(featured)}>Read the full letter →</a>
              ) : (
                <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={() => openForm && openForm()}>Request full letter access →</button>
              )}
            </div>
          </article>
        </div>
      </section>

      {/* MARKET DATA STRIP */}
      <section className="section-navy" style={{ padding: "56px 0" }}>
        <div className="container">
          <div className="ins-market-strip">
            <div className="ins-market-head">
              <div className="eyebrow eyebrow-on-navy">Market Frame</div>
              <h3>The numbers behind the thesis.</h3>
            </div>
            <div className="ins-market-grid">
              {marketStats.map((s, i) => (
                <Reveal key={i} delay={i * 80} variant="scale">
                  <div className="ins-market-cell">
                    <div className="v">{s.v}</div>
                    <div className="k">{s.k}</div>
                  </div>
                </Reveal>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* ARTICLE GRID */}
      <section className="section section-alt" style={{ paddingBottom: 32 }}>
        <div className="container">
          <div className="section-head">
            <div>
              <Reveal variant="fade"><div className="eyebrow">Recent</div></Reveal>
              <RevealWords text="Letters, tear sheets, and commentary." tag="h2" className="section-title" />
            </div>
            <Reveal variant="fade" delay={120}><p className="section-lede">Every piece below was written by a member of the VRB Capital investment team, drawing on the firm's underwriting and portfolio management experience.</p></Reveal>
          </div>

          <div className="ins-grid">
            {articles.map((a, i) => {
              const href = articleHref(a);
              const Tag = href ? "a" : "article";
              const tagProps = href
                ? { href, className: "ins-card" }
                : { className: "ins-card", onClick: () => openForm && openForm(), style: { cursor: "pointer" } };
              return (
              <Reveal key={i} delay={i * 80} variant="scale">
                <Tag {...tagProps}>
                  <div className="ins-card-photo">
                    <Photo src={a.photo} label={a.title} ratio="16/10" />
                  </div>
                  <div className="ins-card-body">
                    <div className="ins-card-meta">
                      <span className="ins-tag">{a.tag}</span>
                      <span className="ins-card-date">{a.date}</span>
                    </div>
                    <h4 className="ins-card-title">{a.title}</h4>
                    <p className="ins-card-excerpt">{a.excerpt}</p>
                    <div className="ins-card-foot">
                      <span>{a.readTime} read</span>
                      <span className="ins-card-arrow">{href ? "Read article →" : "Request access →"}</span>
                    </div>
                  </div>
                </Tag>
              </Reveal>
              );
            })}
          </div>
        </div>
      </section>

      {/* RESOURCE LIBRARY */}
      <section id="resources" className="section" style={{ paddingTop: 32 }}>
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">Resources</div>
              <h2 className="section-title">Documents we share when investors ask.</h2>
            </div>
            <p className="section-lede">
              The glossary and FAQ are open to any visitor. The investor guide is available to qualified accredited investors on request. Each item below is a real document we deliver — not marketing material.
            </p>
          </div>

          <div className="ins-resources">
            {resources.map((r, i) => (
              <a
                className="ins-resource"
                key={i}
                href={r.href || undefined}
                onClick={r.href ? undefined : (e) => { e.preventDefault(); openForm && openForm(); }}
              >
                <div className="ins-resource-kind">{r.kind}</div>
                <div className="ins-resource-name">{r.name}</div>
                <div className="ins-resource-desc">{r.desc}</div>
                <div className="ins-resource-cta">{r.cta || "Request access →"}</div>
              </a>
            ))}
          </div>
        </div>
      </section>

      <CTASection />
    </div>
  );
};

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