/* app-sections-top.jsx — Nav, faux Jira product window, Hero, Trust, Pillars */
const { useState, useEffect, useRef } = React;

const TINT = {
  P: ['var(--P-surface)', 'var(--P-text)'],
  B: ['var(--B50)', '#0747A6'],
  R: ['var(--R-surface)', 'var(--R-text)'],
  T: ['var(--T-surface)', 'var(--T-text)'],
  G: ['var(--G-surface)', 'var(--G-text)'],
  Y: ['var(--Y-surface)', '#8a6d00']
};

function Ico({ name, ...rest }) {
  const C = window.Icons[name];
  return C ? <C {...rest} /> : null;
}

/* ---------------- NAV ---------------- */
function Nav({ darkHero, onDemo }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const onDark = darkHero && !scrolled;
  const logo = asset(onDark ? 'assets/qity-logo-dark.png' : 'assets/qity-logo-light.png');
  return (
    <header className={'nav' + (scrolled ? ' scrolled' : '') + (onDark ? ' on-dark' : '')}>
      <div className="nav-inner">
        <a href="#top" aria-label="Qity home"><img className="nav-logo" src={logo} alt="Qity" /></a>
        <nav className="nav-links">
          {window.NAV_LINKS.map((l) =>
          <a key={l.label} className="nav-link" href={l.href}>{l.label}</a>
          )}
        </nav>
        <div className="nav-spacer" />
        <div className="nav-cta">
          <button className="btn btn-primary nav-contact" onClick={onDemo}>Contact us</button>
          <button className="btn btn-ghost nav-burger" aria-label="Menu"><Ico name="Menu" /></button>
        </div>
      </div>
    </header>);

}

/* ---------------- FAUX JIRA WINDOW ---------------- */
function Donut({ pct, color }) {
  return (
    <div className="donut" style={{ background: `conic-gradient(${color} 0 ${pct}%, var(--N40) 0)` }}>
      <span className="val">{pct}%</span>
    </div>);

}

function JiraWindow() {
  const nav = [
  { icon: 'FileCheck', label: 'Document Control', active: true },
  { icon: 'Ruler', label: 'Design Control' },
  { icon: 'AlertTriangle', label: 'Risk Management' },
  { icon: 'ClipboardCheck', label: 'Audit Management' },
  { icon: 'Cap', label: 'Training' }];

  return (
    <div className="window" role="img" aria-label="Qity quality dashboard inside Jira">
      <div className="j-topbar">
        <div className="j-apps"><div className="g">{Array.from({ length: 9 }).map((_, i) => <i key={i} />)}</div></div>
        <div className="j-logo"><QMark className="mark" /> Qity</div>
        <div className="j-search"><Ico name="Search" /> Search quality records</div>
        <div className="j-right">
          <span className="j-icobtn"><Ico name="Bell" /></span>
          <span className="j-ava" />
        </div>
      </div>
      <div className="j-body">
        <aside className="j-side">
          <div className="grp">iQMS</div>
          {nav.map((n) =>
          <div key={n.label} className={'j-nav-item' + (n.active ? ' active' : '')}>
              <Ico name={n.icon} /> <span>{n.label}</span>
            </div>
          )}
        </aside>
        <main className="j-main">
          <div className="j-h1">My quality dashboard</div>
          <div className="j-sub">Wednesday, 19 Jun 2025 · Evidence is up to date</div>

          <div className="j-banner">
            <span className="dot" />
            <span><b style={{ fontWeight: 600 }}>DC-123, DC-125</b> and 2 others are waiting for your review.</span>
            <span className="b-act">Review now</span>
          </div>

          <div className="j-gadgets">
            <div className="j-gadget">
              <div className="gh">
                <span className="ic" style={{ background: 'var(--P-surface)', color: 'var(--P-text)' }}><Ico name="FileCheck" /></span>
                <span className="tt">Document Control</span>
              </div>
              <div className="gadget-stat">
                <Donut pct={72} color="var(--brand)" />
                <div className="meta"><b>8 documents</b> pending your approval<br />55 in a long review cycle</div>
              </div>
            </div>
            <div className="j-gadget">
              <div className="gh">
                <span className="ic" style={{ background: 'var(--R-surface)', color: 'var(--R-text)' }}><Ico name="AlertTriangle" /></span>
                <span className="tt">Use-related risks</span>
              </div>
              <div className="gadget-stat">
                <Donut pct={88} color="var(--G-bold)" />
                <div className="meta"><b>3 risks</b> need mitigation<br />24 controlled this quarter</div>
              </div>
            </div>
            <div className="j-gadget" style={{ gridColumn: '1 / -1' }}>
              <div className="gh">
                <span className="ic" style={{ background: 'var(--B50)', color: '#0747A6' }}><Ico name="Ruler" /></span>
                <span className="tt">Design Control — traceability</span>
              </div>
              <div className="j-row"><span className="key">WI-231</span><span className="nm">Firmware OTA update requirement</span><span className="sp loz loz-green">Released</span></div>
              <div className="j-row"><span className="key">DOC-55</span><span className="nm">Risk control verification report</span><span className="sp loz loz-yellow">QA approval</span></div>
              <div className="j-row"><span className="key">CC-15</span><span className="nm">Change request — sensor calibration</span><span className="sp loz loz-purple">Doc approval</span></div>
            </div>
          </div>
        </main>
      </div>
    </div>);

}

/* ---------------- PRODUCT SCREENSHOT (real app) ---------------- */
function ProductShot({ src, alt }) {
  return (
    <div className="window">
      <div className="shot-wrap"><img src={src} alt={alt} /></div>
    </div>);

}

/* ---------------- HERO ---------------- */
function Hero({ tweaks, onDemo }) {
  const layout = tweaks.heroLayout; // 'right' | 'below'
  const motion = 'tilt'; // settled hero scroll motion
  const visualRef = useRef(null);
  useEffect(() => {
    const wrap = visualRef.current;if (!wrap) return;
    const win = wrap.querySelector('.window');if (!win) return;
    const cards = [
    { el: wrap.querySelector('.float-bl'), at: 0.07 },
    { el: wrap.querySelector('.float-tr'), at: 0.18 }];

    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      cards.forEach((c) => c.el && c.el.classList.add('popped'));
      return;
    }
    let raf = 0;
    let baseTop = null;
    const upd = () => {
      raf = 0;
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight || 800;
      const prog = Math.max(0, Math.min(1.2, (vh - r.top) / (vh * 0.85)));
      const p1 = Math.min(prog, 1);
      if (motion === 'tilt') {
        // leaning forward at the top, standing flat as you scroll down
        win.style.setProperty('--win-origin', 'bottom center');
        win.style.setProperty('--win-tiltX', (Math.max(0, 1 - prog) * 26).toFixed(2) + 'deg');
        win.style.setProperty('--win-lift', (-((prog - 0.5) * 14)).toFixed(1) + 'px');
        win.style.setProperty('--win-scale', (0.95 + p1 * 0.05).toFixed(3));
      } else if (motion === 'rise') {
        // rises up from below and scales into place
        win.style.setProperty('--win-origin', 'center center');
        win.style.setProperty('--win-tiltX', '0deg');
        win.style.setProperty('--win-lift', ((1 - p1) * 70 - 10).toFixed(1) + 'px');
        win.style.setProperty('--win-scale', (0.9 + p1 * 0.1).toFixed(3));
      } else {
        // lift (default): subtle settle
        win.style.setProperty('--win-origin', 'center center');
        win.style.setProperty('--win-tiltX', (Math.max(0, 1 - prog) * 5).toFixed(2) + 'deg');
        win.style.setProperty('--win-lift', (-((prog - 0.4) * 34)).toFixed(1) + 'px');
        win.style.setProperty('--win-scale', (0.965 + p1 * 0.035).toFixed(3));
      }
      if (baseTop === null) baseTop = r.top;
      const scrolled = baseTop - r.top; // how far the hero has scrolled up from its initial spot
      cards.forEach((c) => c.el && c.el.classList.toggle('popped', scrolled > vh * c.at));
    };
    const onScroll = () => {if (!raf) raf = requestAnimationFrame(upd);};
    upd();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {window.removeEventListener('scroll', onScroll);window.removeEventListener('resize', onScroll);cancelAnimationFrame(raf);};
  }, [layout, tweaks.heroSpot, motion]);
  return (
    <section className={'hero' + (tweaks.heroSpot ? ' hero-spot' : '') + (tweaks.heroBg ? ' hero-img' : '')} id="top" data-hl={layout}>
      <div className="hero-dots" />
      <div className="container hero-layout">
        <div className="hero-copy reveal in">
          <img className="hero-logo" src={asset('assets/qity-logo-light.png')} alt="Qity" />
          <h1 className="display h-hero" style={{ marginBottom: 12 }}>
            Quality <span className="hl hl-underline">built-in</span>, not bolted on.
          </h1>
          <p className="lead" style={{ marginTop: 18 }}>Qity's apps for Jira & Confluence turn your team’s everyday work into compliance evidence and documentation. Integrated with the tools you already use, built for regulated industries.


          </p>
          <div className="hero-cta">
            <button className="btn btn-brand btn-lg" onClick={onDemo}>Book a demo <Ico name="ArrowRight" /></button>
            <a className="btn btn-ghost btn-lg" href="#product">See how it works</a>
          </div>
          <div className="hero-badges">
            <span className="mp-badge mp-badge-lg">
              <span className="mp-pre">Coming soon to</span>
              <img className="mp-badge-logo" src={asset('assets/atlassian-marketplace.png')} alt="Atlassian Marketplace" />
            </span>
          </div>
        </div>
        <div className="hero-visual reveal in d1" ref={visualRef}>
          <ProductShot src={asset('assets/shots/design-control.png')} alt="Qity Design Control inside Jira — requirements, specifications and traceability" />
          <div className="float-card float-bl">
            <div className="fc-h"><span className="ic"><Ico name="Sparkles" /></span> Document Review Agent</div>
            <div className="fc-line"><b>DC-332 Design &amp; Development SOP</b> reviewed against <b style={{ color: 'var(--brand-deep)' }}>ISO 13485 clauses</b></div>
          </div>
          <div className="float-card float-tr">
            <div className="fc-h"><span className="ic" style={{ background: 'var(--G-surface)', color: 'var(--G-text)' }}><Ico name="GitBranch" /></span> CI/CD pipeline</div>
            <div className="fc-line"><b>Release build #1284</b> passed — detailed design and test descriptions updated in <b style={{ color: 'var(--brand-deep)' }}>Jira</b></div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------------- TRUST ---------------- */
function Trust() {
  const logos = [
  { name: 'Wyss Zurich', file: 'wyss', h: 26 },
  { name: 'FBGS', file: 'fbgs-mark', h: 28 },
  { name: 'Trince', file: 'trince', h: 26 },
  { name: 'Agricells', file: 'agricells', h: 34 },
  { name: 'Mantyx', file: 'mantyx', h: 32 },
  { name: 'Samplid', file: 'samplid', h: 28 },
  { name: 'Robovision', file: 'robovision', h: 40 },
  { name: 'NHa Normandy Hadrontherapy', file: 'nha', h: 32 }];

  const trackRef = useRef(null);
  const [copies, setCopies] = useState(2);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const track = trackRef.current;if (!track) return;
    const marquee = track.parentElement;if (!marquee) return;
    let cancelled = false;
    const measure = () => {
      if (cancelled) return;
      const kids = [...track.children].slice(0, logos.length);
      if (kids.length < logos.length) return;
      let setW = 0;
      kids.forEach((k) => {setW += k.getBoundingClientRect().width + (parseFloat(getComputedStyle(k).marginRight) || 0);});
      if (!setW) return;
      // enough copies that (copies-1) sets always exceed the viewport → never a gap
      const need = Math.ceil((marquee.clientWidth + setW) / setW) + 1;
      setCopies((c) => Math.max(2, need) === c ? c : Math.max(2, need));
      track.style.setProperty('--set-w', setW + 'px');
      track.style.setProperty('--marq-dur', (setW / 40).toFixed(1) + 's'); // ~40px/s
      setReady(true);
    };
    const imgs = [...track.querySelectorAll('img')];
    let pending = imgs.filter((im) => !im.complete).length;
    const onOne = () => {if (--pending <= 0) measure();};
    if (pending === 0) measure();else
    imgs.forEach((im) => {if (!im.complete) {im.addEventListener('load', onOne);im.addEventListener('error', onOne);}});
    const ro = new ResizeObserver(() => measure());
    ro.observe(marquee);
    return () => {cancelled = true;ro.disconnect();};
  }, []);
  const sets = Array.from({ length: copies }, () => logos).flat();

  return (
    <section className="container trust">
      <div className="trust-block">
        <p className="eyebrow center">TRUSTED BY</p>
        <div className="trust-marquee reveal">
          <div className={'trust-track' + (ready ? ' run' : '')} ref={trackRef}>
            {sets.map((l, i) =>
            <img key={i} className="trust-logo" src={asset('assets/cust-' + l.file + '.png')} alt={i < logos.length ? l.name : ''} aria-hidden={i >= logos.length} style={{ height: l.h }} />
            )}
          </div>
        </div>
      </div>
    </section>);

}

function ComplianceStrip() {
  return (
    <section className="compliance-strip-sec">
      <div className="container compliance-strip">
        <p className="eyebrow center">Built for regulated industries</p>
        <div className="std-row reveal">
          {window.STANDARDS.map((s) =>
          <span key={s.label} className="std-chip">
              {s.img ? <img className="std-logo" src={asset('assets/certs/' + s.img + '.png')} alt="" /> : <Ico name="Shield" />}
              <span className="std-label">{s.label}</span>
            </span>
          )}
        </div>
      </div>
    </section>);

}

/* ---------------- PILLARS ---------------- */
function PillarIllo({ i }) {
  const illos = [
  // Jira items flowing into a document
  <svg viewBox="0 0 72 72" fill="none" key="0">
      <rect x="4" y="11" width="17" height="13" rx="3" fill="#CDEFDD" />
      <rect x="4" y="30" width="17" height="13" rx="3" fill="#CDEFDD" />
      <rect x="4" y="49" width="17" height="13" rx="3" fill="#CDEFDD" />
      <circle cx="11" cy="17.5" r="2.3" fill="#2FB874" />
      <circle cx="11" cy="36.5" r="2.3" fill="#2FB874" />
      <circle cx="11" cy="55.5" r="2.3" fill="#2FB874" />
      <path d="M23 17.5c11 0 9 18 18 18M23 36.5h18M23 55.5c11 0 9-18 18-18" stroke="#46DD8F" strokeWidth="2.2" strokeLinecap="round" />
      <rect x="43" y="18" width="25" height="37" rx="5" fill="#2FB874" />
      <path d="M61 18v7h7" fill="#1F9E63" />
      <path d="M49 33h13M49 41h13M49 49h9" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" />
    </svg>,
  // Pipeline of dots + robot producing documentation
  <svg viewBox="0 0 72 72" fill="none" key="1">
      <path d="M9 60h36" stroke="#C7D0DE" strokeWidth="3" strokeLinecap="round" />
      <circle cx="15" cy="60" r="5.5" fill="#46DD8F" />
      <circle cx="30" cy="60" r="5.5" fill="#2FB874" />
      <circle cx="45" cy="60" r="5.5" fill="#091E42" />
      <path d="M22 11v-4" stroke="#2FB874" strokeWidth="2.4" strokeLinecap="round" />
      <circle cx="22" cy="5.5" r="2.4" fill="#2FB874" />
      <rect x="9" y="13" width="26" height="22" rx="6" fill="#2FB874" />
      <circle cx="18" cy="24" r="3.1" fill="#fff" />
      <circle cx="28" cy="24" r="3.1" fill="#fff" />
      <rect x="11" y="39" width="22" height="9" rx="3" fill="#CDEFDD" />
      <path d="M37 26h6" stroke="#2FB874" strokeWidth="2.3" strokeLinecap="round" />
      <rect x="48" y="14" width="18" height="25" rx="3" fill="#CDEFDD" />
      <path d="M52 21h10M52 27h10M52 33h6" stroke="#2FB874" strokeWidth="2.2" strokeLinecap="round" />
    </svg>,
  // AI icon — sparkle
  <svg viewBox="0 0 72 72" fill="none" key="2">
      <path d="M33 12l5 15 15 5-15 5-5 15-5-15-15-5 15-5z" fill="#2FB874" />
      <path d="M56 39l2.2 5.8 5.8 2.2-5.8 2.2L56 57l-2.2-5.8L48 49l5.8-2.2z" fill="#46DD8F" />
    </svg>];

  return illos[i % illos.length];
}

function Pillars({ tweaks }) {
  const variant = 'tiles'; // settled on icon tiles
  const illo = true; // settled on flat illustrations
  return (
    <section className="sec" id="harmonization" style={{ backgroundColor: "rgb(245, 250, 240)" }}>
      <div className="container">
        <div className="section-head">
          <h2 className="h-sec">Quality evidence that builds itself</h2>
          <p className="lead" style={{ marginTop: 16 }}>Stop managing your quality in disconnected Word and Excel files.
Your documentation gets generated in the system where the work happens, with the help of automation and agentic AI.
          </p>
        </div>
        <div className={'pillars-wrap ' + variant}>
          {window.PILLARS.map((p, i) =>
          <article key={p.n} className="pillar reveal pillar-reveal" style={{ transitionDelay: i * 0.12 + 's' }}>
              {variant === 'rows' && <span className="p-num">{p.n}</span>}
              {illo ?
            <span className="p-illo"><PillarIllo i={i} /></span> :
            <span className="p-ico"><Ico name={p.icon} /></span>}
              {variant === 'rows' ?
            <>
                  <div>
                    <h3 style={{ marginBottom: 0 }}>{p.title}</h3>
                  </div>
                  <p>{p.body}</p>
                </> :

            <>
                  <h3>{p.title}</h3>
                  <p>{p.body}</p>
                </>
            }
            </article>
          )}
        </div>
      </div>
    </section>);

}

Object.assign(window, { Nav, Hero, JiraWindow, ProductShot, Trust, ComplianceStrip, Pillars, Ico, TINT });