// sections.jsx — Page sections.
const { useEffect, useRef, useState } = React;

const PORTFOLIO = [
  { id:"sintalk",    name:"Sintalk",     domain:"",  role:"Telecom",     sector:"Telecommunications and omnichannel",
    headline:"Licensed telecom and omnichannel platform for customer operations.",
    desc:"Voice, messaging, and contact-channel infrastructure (including WhatsApp and Instagram) used by companies that operate large customer bases.",
    year:"" },
  { id:"calculos",   name:"Calculos",    domain:"",  role:"Accounting",  sector:"Accounting and tax",
    headline:"Accounting, tax, and corporate structuring.",
    desc:"A licensed accounting firm serving the companies in the network and external clients. Handles bookkeeping, tax filings, and corporate structuring.",
    year:"" },
  { id:"kavdigital", name:"KavDigital",  domain:"",  role:"Digital",     sector:"Digital agency and engineering",
    headline:"Digital agency with an in-house engineering team.",
    desc:"Performance media planning and execution, paired with a development team that builds and maintains the digital products of clients inside and outside the network.",
    year:"" },
  { id:"kavalesk",   name:"Kavalesk",    domain:"",  role:"Payments",    sector:"Payment gateway",
    headline:"Payment gateway authorised under BACEN rules.",
    desc:"Card and PIX processing for merchants and platforms. Built around Brazilian instant-payment standards and the controls required of regulated payment providers.",
    year:"" },
  { id:"redepixel",  name:"RedePixel",   domain:"",  role:"Hosting",     sector:"Hosting and cloud",
    headline:"Hosting and cloud infrastructure for the network.",
    desc:"Managed hosting, infrastructure, and operations. Provides the underlying compute that companies inside the network and external clients run on.",
    year:"" },
  { id:"elite",      name:"Elite",       domain:"",  role:"Media",       sector:"YouTube multi-channel network",
    headline:"Multi-channel network for Brazilian YouTube creators.",
    desc:"Represents creators on YouTube. Handles channel management, rights and licensing, and monetisation across the videos under the network.",
    year:"" },
];

// ─── HERO ───────────────────────────────────────────────────────────
function Hero({ introDone }) {
  const sceneRef = useScrollScene(1);
  return (
    <section id="hero" className="hero scene scene-hero" ref={sceneRef} data-intro-done={introDone || undefined}>
      <div className="hero-skyline" aria-hidden="true" />
      <div className="hero-skyline-veil" aria-hidden="true" />
      <span className="hero-bg-glyph" aria-hidden="true">
        <span className="hbg-line hbg-line-2">Kav.</span>
      </span>

      <div className="hero-top">
        <span className="hero-loc">
          <span><span className="dot" />KAVNETWORK</span>
          <span className="sep">·</span>
          <span>Holding Co.</span>
        </span>
      </div>

      <div className="hero-stage">
        <div className="hero-stage-grid">
          <div className="hero-stage-left">
            <h1 className="hero-title">
              <span className="row row-1">A holding company</span>
              <span className="row row-2">that <em className="hero-emph">operates</em> the companies</span>
              <span className="row row-3">it builds.</span>
            </h1>
            <div className="hero-ctas">
              <a href="#network" className="btn btn-primary">View the network <span className="arrow">→</span></a>
              <a href="#speak" className="btn btn-ghost">Speak with us</a>
            </div>
          </div>
          <aside className="hero-globe-stage" aria-hidden="true">
            <HeroGlobe />
          </aside>
        </div>
      </div>

      <div className="hero-bot">
        <span className="hb-l">For founders building in regulated sectors.</span>
        <span className="scroll-hint">Scroll <span className="sh-arrow"/></span>
      </div>
    </section>
  );
}

// ─── §02 PLATFORM ──────────────────────────────────────────────────
function Platform() {
  const sceneRef = useScrollScene(1);
  const bullets = [
    ["01","Shared stack",        "Every company runs on the same payments, identity, and observability stack from day one."],
    ["02","Shared team",         "Engineers and operators are recruited at the holding and allocated to whichever company needs them this quarter."],
    ["03","Permanent capital",   "We do not raise a fund. Companies have the time to build well, fix what is broken, and compound."],
    ["04","New companies",       "If a sector needs an operator the market is not producing, we start the company ourselves."],
    ["05","Compliance baseline", "LGPD, PCI-DSS, SOC 2, and BACEN apply to every company from the first day, not as a later retrofit."],
  ];
  return (
    <section id="platform" className="section scene scene-platform" ref={sceneRef}>
      <div className="section-head">
        <span className="section-num">02</span>
        <span className="section-name">Platform</span>
      </div>
      <div className="platform-grid">
        <div>
          <Reveal as="h2" className="h2">
            One platform. <span className="serif-it">Every company runs on it.</span>
          </Reveal>
          <Reveal as="p" className="lead" delay={2}>
            KavNetwork operates the companies it owns. Every business in the network
            shares the same engineering platform, the same operating team, and the
            same capital base. When a sector needs an operator the market is not
            producing, we start the company ourselves.
          </Reveal>
        </div>
        <Reveal as="ul" className="platform-bullets" delay={2}>
          {bullets.map(([k,a,b]) => (
            <li key={k}>
              <span className="chk">{k}</span>
              <span><b>{a}</b> — {b}</span>
            </li>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

// Interlude: full-bleed photo with caption, bleeds outside the max-width track.
function Interlude({ src, eyebrow, caption, meta, id }) {
  const sceneRef = useScrollScene(1);
  return (
    <section id={id} className="interlude scene scene-interlude" ref={sceneRef}>
      <div className="interlude-media" style={{ backgroundImage: `url('${src}')` }} aria-hidden="true" />
      <div className="interlude-veil" aria-hidden="true" />
      <div className="interlude-grid">
        <span className="il-eyebrow">{eyebrow}</span>
        <p className="il-caption">{caption}</p>
        <span className="il-meta">{meta}</span>
      </div>
    </section>
  );
}
function Pillars() {
  const sceneRef = useScrollScene(1);
  const pillars = [
    { n: "01", t: "Conduct",       b: "We operate regulated businesses. A single standard of conduct applies across every company, with the same audits and the same enforcement.", tag: "Conduct" },
    { n: "02", t: "Security",      b: "Security, privacy, and data handling sit in the platform itself. Every product inherits the same controls by default.", tag: "Security & privacy" },
    { n: "03", t: "Compliance",    b: "Each regulation and standard the network operates under (LGPD, ANATEL, BACEN, PCI-DSS, ISO/IEC 27001) is mapped to specific controls in the platform, and those controls are monitored continuously.", tag: "Regulatory" },
    { n: "04", t: "Capital",       b: "Our capital is permanent. There is no fund cycle to force an exit, so companies have the time they need to build.", tag: "Capital" },
    { n: "05", t: "People",        b: "Engineers and operators are recruited at the holding and work across multiple companies in the network. Careers compound at the group level.", tag: "People" },
    { n: "06", t: "Transparency",  b: "We publish what we do, what we charge, and what we promise, in language non-specialists can read.", tag: "Transparency" },
  ];
  return (
    <section id="pillars" className="section scene scene-pillars" ref={sceneRef}>
      <div className="section-head">
        <span className="section-num">03</span>
        <span className="section-name">Pillars</span>
      </div>
      <div className="pillars-intro">
        <Reveal as="h2" className="h2">
          Six principles <span className="serif-it">that apply across every company.</span>
        </Reveal>
        <Reveal as="p" className="lead" delay={2}>
          KavNetwork builds, capitalises, and operates the companies in the
          network. The principles below set how we hire, what we promise to
          customers, and what we refuse to do.
        </Reveal>
      </div>
      <ol className="pillars-grid">
        {pillars.map(p => (
          <Reveal as="li" key={p.n} className="pillar">
            <span className="pl-tag">{p.tag}</span>
            <span className="pl-num">{p.n}</span>
            <h3 className="pl-title">{p.t}</h3>
            <p className="pl-body">{p.b}</p>
          </Reveal>
        ))}
      </ol>
    </section>
  );
}

// Network: horizontal scroll-pinned strip on desktop, vertical stack on mobile.
function Network() {
  const wrapRef = useRef(null);
  const stripRef = useRef(null);
  const fillRef  = useRef(null);
  const [activeIdx, setActiveIdx] = useState(-1);
  const [isMobile, setIsMobile] = useState(
    typeof window !== "undefined" && window.matchMedia("(max-width: 780px)").matches
  );
  useEffect(() => {
    const mq = window.matchMedia("(max-width: 780px)");
    const onChange = () => setIsMobile(mq.matches);
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);
  useEffect(() => {
    const wrap = wrapRef.current, strip = stripRef.current; if (!wrap || !strip) return;
    // Mobile uses a plain vertical stack; skip the horizontal-scroll math.
    if (isMobile) {
      strip.style.transform = "";
      if (fillRef.current) fillRef.current.style.transform = "scaleX(0)";
      return;
    }
    function update() {
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = r.height - vh;
      const progress = Math.max(0, Math.min(1, -r.top / total));
      const tx = -progress * (strip.scrollWidth - window.innerWidth);
      strip.style.transform = `translate3d(${tx}px, 0, 0)`;
      if (fillRef.current) fillRef.current.style.transform = `scaleX(${progress})`;
      const vc = window.innerWidth / 2;
      const items = strip.querySelectorAll(".dossier");
      let best = -1, bestDist = Infinity;
      items.forEach((el, i) => {
        const er = el.getBoundingClientRect();
        const ec = er.left + er.width / 2;
        const d = Math.abs(ec - vc);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setActiveIdx(best);
    }
    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, [isMobile]);
  return (
    <section id="network" className={`network ${isMobile ? "is-mobile" : ""}`} ref={wrapRef}>
      <div className="network-pin">
        <div className="network-strip" ref={stripRef}>
          <div className="net-intro">
            <span className="ni-num">04 / Network</span>
            <h2>Six companies <br/><span className="serif-it">across six sectors.</span></h2>
            <p>Telecom, accounting, digital agency, payments, hosting, and media. Each company runs independently. Each draws from the same engineering team, the same operating platform, and the same capital base.</p>
            <span className="ni-meta">{isMobile ? "Six companies" : "Six companies · scroll to view"}</span>
          </div>
          {PORTFOLIO.map((co, i) => {
            const hasDomain = co.domain && co.domain !== "—";
            const hasYear = co.year && co.year !== "—";
            return (
              <article key={co.id} className={`dossier ${activeIdx === i || isMobile ? "is-active" : ""}`}>
                <span className="d-wm">{String(i+1).padStart(2,"0")}</span>
                <header className="d-head">
                  <div className="d-h-l">
                    <span className="d-id">{String(i+1).padStart(2,"0")} / {String(PORTFOLIO.length).padStart(2,"0")}</span>
                    <span className="d-role">{co.role}</span>
                  </div>
                  <span className="d-domain">{co.domain}</span>
                </header>
                <div className="d-body">
                  <h3 className="d-name">{co.name}</h3>
                  <span className="d-sector">{co.sector}</span>
                  <p className="d-headline">{co.headline}</p>
                  <p className="d-desc">{co.desc}</p>
                </div>
                <footer className="d-foot">
                  <span>{hasYear ? `Est. ${co.year}` : "Est. —"}</span>
                  {hasDomain
                    ? <a href={`https://${co.domain}`} className="d-visit">Visit ↗</a>
                    : <span className="d-visit is-muted">Visit ↗</span>}
                </footer>
              </article>
            );
          })}
        </div>
        {!isMobile && (
          <div className="network-progress">
            <span className="np-fill" ref={fillRef} />
            <span className="np-current">{activeIdx >= 0 && PORTFOLIO[activeIdx] ? PORTFOLIO[activeIdx].name : "Network"}</span>
          </div>
        )}
      </div>
    </section>
  );
}

// ─── §05 SPEAK ──────────────────────────────────────────────────────
function Speak() {
  const sceneRef = useScrollScene(1);
  return (
    <section id="speak" className="section scene scene-speak" ref={sceneRef}>
      <div className="section-head">
        <span className="section-num">05</span>
        <span className="section-name">Speak</span>
      </div>
      <div className="speak-grid">
        <Reveal as="h2" className="speak-statement">
          <span className="row">If you are a founder building</span>
          <span className="row">in a sector the network should</span>
          <span className="row"><span className="serif-it">operate</span>, we would like to talk.</span>
        </Reveal>
        <Reveal as="div" delay={1}>
          <div className="speak-rows">
            <a className="speak-row" href="mailto:founders@kavnetwork.com">
              <span className="sr-l">Founders</span><span className="sr-m">Bring us your company</span><span className="sr-r">founders@kavnetwork.com</span>
            </a>
            <a className="speak-row" href="mailto:capital@kavnetwork.com">
              <span className="sr-l">Capital</span><span className="sr-m">Talk to the holding</span><span className="sr-r">capital@kavnetwork.com</span>
            </a>
            <a className="speak-row" href="mailto:jobs@kavnetwork.com">
              <span className="sr-l">Engineering</span><span className="sr-m">Join the team</span><span className="sr-r">jobs@kavnetwork.com</span>
            </a>
            <a className="speak-row" href="mailto:press@kavnetwork.com">
              <span className="sr-l">Press</span><span className="sr-m">Disclosures and inquiries</span><span className="sr-r">press@kavnetwork.com</span>
            </a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function EndSlate() {
  return (
    <footer className="end-slate">
      <div className="end-top">
        <div className="end-col">
          <p className="end-lead">KavNetwork LLC is a holding company that builds and operates six technology businesses across telecom, accounting, digital, payments, hosting, and media.</p>
        </div>
        <div className="end-col">
          <h5>Network</h5>
          <ul>{PORTFOLIO.map(p => <li key={p.id}><a href="#network">{p.name}</a></li>)}</ul>
        </div>
        <div className="end-col">
          <h5>Speak</h5>
          <ul>
            <li><a href="#speak">Founders</a></li><li><a href="#speak">Capital</a></li>
            <li><a href="#speak">Engineering</a></li><li><a href="#speak">Press</a></li>
          </ul>
        </div>
      </div>
      <div className="end-bot">
        <span>© KavNetwork LLC · Wilmington, Delaware</span>
        <span>Operating companies are independent legal entities.</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Hero, Platform, Interlude, Pillars, Network, Speak, EndSlate, PORTFOLIO });
