/* global React, ReactDOM, MainMenu, ContactForm */
const { useState: useStateA, useEffect: useEffectA } = React;

const AIMG = (filename, size = "web") => `/api/images/${size}/${encodeURIComponent(filename)}`;
const html = (s) => ({ dangerouslySetInnerHTML: { __html: s || "" } });

function AboutApp() {
  const [overlay, setOverlay] = useStateA(null); // null | "menu" | "contact"
  const [content, setContent] = useStateA(null);

  useEffectA(() => {
    fetch("/api/content").then((r) => r.json()).then(setContent).catch(() => setContent({ settings: {}, stats: [], press: [], approach: [] }));
  }, []);

  useEffectA(() => {
    document.body.style.overflow = overlay ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [overlay]);

  // Once the content is in the DOM: reveal blocks on scroll + count the stats.
  useEffectA(() => {
    if (!content) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const reveals = Array.from(document.querySelectorAll(".reveal, .reveal-img"));
    const nums = Array.from(document.querySelectorAll(".a-stat .num[data-count]"));
    if (reduce || typeof IntersectionObserver === "undefined") {
      reveals.forEach((el) => el.classList.add("in"));
      nums.forEach((el) => { el.textContent = el.getAttribute("data-count"); });
      return;
    }
    const revealIO = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); revealIO.unobserve(e.target); } });
    }, { threshold: 0.16, rootMargin: "0px 0px -8% 0px" });
    reveals.forEach((el) => revealIO.observe(el));

    const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
    const countUp = (el) => {
      const target = parseInt(el.getAttribute("data-count"), 10) || 0;
      const dur = 1500, start = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - start) / dur);
        el.textContent = String(Math.round(easeOutCubic(p) * target));
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    const countIO = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { countUp(e.target); countIO.unobserve(e.target); } });
    }, { threshold: 0.5 });
    nums.forEach((el) => countIO.observe(el));

    return () => { revealIO.disconnect(); countIO.disconnect(); };
  }, [content]);

  const openContact = () => setOverlay("contact");
  const nav = (where) => {
    setOverlay(null);
    if (where === "portfolio") window.location.href = "../galleries_test/Galleries_Test.html";
    if (where === "about") window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (!content) return <div className="a-page" style={{ minHeight: "100vh" }} />;
  const c = content.settings || {};
  const bioParas = (c.bio_text || "").split("||");

  return (
    <React.Fragment>
      {/* fixed blend-mode chrome — identical to home / galleries */}
      <div className="h-logo" onClick={() => { setOverlay(null); window.location.href = "../home_test/Home_Test.html"; }}>
        <div className="lname">NICKO TRENCHEV</div>
        <div className="lsub">STUDIO</div>
      </div>
      <button className="h-chrome-label h-menu-btn" onClick={() => setOverlay("menu")}>MENU</button>
      <button className="h-chrome-label h-contact-btn" onClick={openContact}>CONTACT</button>

      <div className="a-page">
        {/* HERO */}
        <section className="a-hero">
          <div className="a-eyebrow">{c.hero_eyebrow}</div>
          <h1 {...html(c.hero_title)} />
          <p className="a-hero-sub">{c.hero_subtitle}</p>
          <div className="a-scrollcue">
            <span>Scroll</span>
            <span className="line"></span>
          </div>
        </section>

        {/* BIO */}
        <section className="a-bio">
          <div className="a-portrait reveal-img">
            <div className="protected-image">
              <img src={AIMG(c.bio_portrait || "photo-1500648767791-00dcc994a43e")} alt="Nicko Trenchev" onContextMenu={(e) => e.preventDefault()} draggable="false" />
              <div className="img-guard"></div>
            </div>
            <div className="a-tag">{c.bio_portrait_tag}</div>
          </div>
          <div className="a-text reveal">
            <div className="a-eyebrow">{c.bio_eyebrow}</div>
            <h2>{c.bio_heading}</h2>
            {bioParas.map((p, i) => <p key={i} {...html(p)} />)}
            <div className="a-sign">
              {c.bio_signature}
              <small>{c.bio_signature_role}</small>
            </div>
          </div>
        </section>

        {/* STATEMENT */}
        <section className="a-statement">
          <p className="reveal" {...html(c.statement_quote)} />
        </section>

        {/* APPROACH */}
        <section className="a-approach">
          <div className="a-head reveal">
            <h2>{c.approach_heading}</h2>
            <div className="a-eyebrow">{c.approach_eyebrow}</div>
          </div>
          <div className="a-cols">
            {(content.approach || []).map((col, i) => (
              <div className="a-col reveal" data-delay={Math.min(i + 1, 3)} key={col.id}>
                <div className="num">{col.number}</div>
                <h3>{col.title}</h3>
                <p>{col.description}</p>
              </div>
            ))}
          </div>
        </section>

        {/* STATS */}
        <section className="a-stats">
          {(content.stats || []).map((st, i) => {
            const m = String(st.number == null ? "" : st.number).match(/^(\d[\d,]*)(.*)$/);
            return (
              <div className="a-stat reveal" data-delay={Math.min(i, 3)} key={st.id}>
                <div className="n">
                  {m
                    ? <React.Fragment><span className="num" data-count={m[1].replace(/,/g, "")}>0</span><span className="suf">{m[2]}</span></React.Fragment>
                    : st.number}
                </div>
                <div className="l">{st.label}</div>
              </div>
            );
          })}
        </section>

        {/* PRESS */}
        <section className="a-press">
          <div className="a-eyebrow reveal">— Selected recognition</div>
          <div className="row">
            {(content.press || []).map((p, i) => <span className="reveal" data-delay={Math.min(i, 3)} key={p.id}>{p.name}</span>)}
          </div>
        </section>

        {/* CTA */}
        <section className="a-cta">
          <div className="a-eyebrow reveal">{c.cta_eyebrow}</div>
          <h2 className="reveal" data-delay="1" {...html(c.cta_heading)} />
          <button className="a-contact-link reveal" data-delay="2" onClick={openContact}>
            START AN ENQUIRY
            <svg viewBox="0 0 80 24" fill="none"><path d="M0 12h74M64 3l11 9-11 9" stroke="#fff" strokeWidth="2.4"/></svg>
          </button>
        </section>

        {/* FOOTER */}
        <footer className="a-foot">
          <span>{c.footer_text}</span>
          <span>
            <a href="../galleries_test/Galleries_Test.html">Portfolio</a>
            &nbsp;·&nbsp;
            <a href="#" onClick={(e) => { e.preventDefault(); openContact(); }}>Contact</a>
            &nbsp;·&nbsp;
            <a href="#">Instagram</a>
          </span>
        </footer>
      </div>

      {/* overlays — shared from Overlays.jsx */}
      {overlay === "menu" && (
        <MainMenu onClose={() => setOverlay(null)} onContact={openContact} onNav={nav} />
      )}
      {overlay === "contact" && <ContactForm onClose={() => setOverlay(null)} />}
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AboutApp />);
