// waiv-home-sections.jsx — homepage sections built on the Direction-B system.
// Reuses WaivCard3D, WAIV_FINISHES, the .wv-phone mockup, buttons & eyebrows.

const { useState, useEffect, useRef } = React;

/* ── minimal stroked icon set ── */
const ICON_PATHS = {
  user: 'M5 20a7 7 0 0 1 14 0 M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8',
  share: 'M6 12a3 3 0 1 0 0-.01 M18 6a3 3 0 1 0 0-.01 M18 18a3 3 0 1 0 0-.01 M8.6 10.6l6.8-3.4 M8.6 13.4l6.8 3.4',
  card: 'M3 7h18v11H3z M3 10h18',
  grid: 'M4 4h7v7H4z M13 4h7v7h-7z M13 13h7v7h-7z M4 13h7v7H4z',
  calendar: 'M4 6h16v15H4z M4 10h16 M8 3v4 M16 3v4',
  wifi: 'M3 9a15 15 0 0 1 18 0 M6 12.5a10 10 0 0 1 12 0 M9 16a5 5 0 0 1 6 0 M12 19.5h.01',
  link: 'M9.5 14.5l5-5 M8 11l-2 2a3.5 3.5 0 0 0 5 5l2-2 M16 13l2-2a3.5 3.5 0 0 0-5-5l-2 2',
  chart: 'M4 20V4 M4 20h16 M8 16v-4 M12 16V8 M16 16v-7',
  edit: 'M4 20h4l10-10-4-4L4 16z M14 6l4 4',
  refresh: 'M4 11a8 8 0 0 1 14-5l2 2 M20 13a8 8 0 0 1-14 5l-2-2 M18 3v5h-5 M6 21v-5h5',
  users: 'M3 20a6 6 0 0 1 12 0 M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7 M16 7a3 3 0 0 1 1 5.8 M16.5 14a6 6 0 0 1 4.5 6',
  shield: 'M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z M9 12l2 2 4-4',
  building: 'M5 21V4h9v17 M14 9h5v12 M8 8h3 M8 12h3 M8 16h3 M17 13h0 M17 17h0',
  bolt: 'M13 3L5 13h6l-1 8 8-11h-6z',
  arrow: 'M5 12h14 M13 6l6 6-6 6',
};
function Ico({ n }) {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      {ICON_PATHS[n].split(' M').map((d, i) => (
        <path key={i} d={(i ? 'M' : '') + d} strokeLinecap="round" strokeLinejoin="round" />
      ))}
    </svg>
  );
}

function Kicker({ children }) {
  return <div className="wv-kicker"><span className="wv-kicker-mark" />{children}</div>;
}

/* ───────── marquee trust strip ───────── */
function TrustStrip() {
  const names = ['Founders', 'Realtors', 'Photographers', 'Consultants', 'Creators', 'Recruiters', 'Architects', 'Freelancers'];
  const loop = [...names, ...names];
  return (
    <div className="wv-marquee">
      <div className="wv-marquee-lbl">The handshake, upgraded — for the people who live on introductions</div>
      <div className="wv-marquee-track">
        {loop.map((n, i) => <span key={i}>{n}</span>)}
      </div>
    </div>
  );
}

/* ───────── how it works ───────── */
function HowItWorks() {
  const [active, setActive] = useState(0);
  const steps = [
    { t: 'Tap your waiv to any phone', d: 'Hold the card near the top of any modern smartphone. The NFC chip wakes instantly — no app, no QR scanner, no pairing.' },
    { t: 'Your Onelynk profile opens', d: 'A beautiful full-screen profile appears in their browser within a second: your photo, links, socials and a one-tap save-contact button.' },
    { t: 'They keep you — for good', d: 'One tap saves your details straight to their phone. Update your profile anytime; every card you ever handed out updates with it.' },
  ];
  useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % 3), 3800);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="wv-sec" id="how">
      <div className="wv-container">
        <div className="wv-sec-head" data-reveal>
          <Kicker>HOW IT WORKS</Kicker>
          <h2 className="wv-sec-title">Three seconds from <em>stranger</em> to saved.</h2>
        </div>
        <div className="wv-how">
          <div className="wv-steps" data-reveal>
            {steps.map((s, i) => (
              <div key={i} className={`wv-step ${i === active ? 'is-active' : ''}`} onMouseEnter={() => setActive(i)}>
                <div className="wv-step-num">0{i + 1}</div>
                <div>
                  <h3 className="wv-step-t">{s.t}</h3>
                  <p className="wv-step-d">{s.d}</p>
                </div>
              </div>
            ))}
          </div>
          <div className="wv-how-stage" data-reveal data-reveal-delay="1">
            <div className="wv-how-glow" />
            <div className="wv-tapcard">
              <WaivCard3D w={210} finish="midnightgold" />
            </div>
            <div className="wv-phone">
              <div className="wv-phone-screen">
                <div className="wv-phone-notch" />
                <div className="wv-phone-toast">⚡ Received via waiv</div>
                <div className="wv-phone-card">
                  <div className="wv-phone-avatar" />
                  <div className="wv-phone-line wv-phone-line--lg" />
                  <div className="wv-phone-line wv-phone-line--sm" />
                  <div className="wv-phone-chips"><span /><span /><span /></div>
                  <div className="wv-phone-save">Save contact</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────── card / finishes deep-dive ───────── */
function FinishShowcase() {
  const [finish, setFinish] = useState('sapphire');
  const tiltRef = useRef(null);
  useEffect(() => {
    const el = tiltRef.current; if (!el) return;
    const cur = { rx: 6, ry: -20 }, tgt = { rx: 6, ry: -20 };
    let raf;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const nx = (e.clientX - (r.left + r.width / 2)) / window.innerWidth;
      const ny = (e.clientY - (r.top + r.height / 2)) / window.innerHeight;
      tgt.ry = -18 + nx * 26; tgt.rx = 6 - ny * 16;
    };
    const loop = () => {
      cur.rx += (tgt.rx - cur.rx) * 0.08; cur.ry += (tgt.ry - cur.ry) * 0.08;
      el.style.transform = `rotateX(${cur.rx.toFixed(2)}deg) rotateY(${cur.ry.toFixed(2)}deg) rotateZ(2deg)`;
      raf = requestAnimationFrame(loop);
    };
    window.addEventListener('pointermove', onMove); raf = requestAnimationFrame(loop);
    return () => { window.removeEventListener('pointermove', onMove); cancelAnimationFrame(raf); };
  }, []);
  const cfg = WAIV_FINISHES[finish];
  return (
    <section className="wv-sec wv-finishes-sec" id="cards">
      <div className="wv-container">
        <div className="wv-sec-head" data-reveal>
          <Kicker>THE CARD</Kicker>
          <h2 className="wv-sec-title">A first impression with <em>real weight.</em></h2>
          <p className="wv-sec-lede">Each waiv is a precision-finished card with a secure NFC chip embedded inside. Pick a finish — then carry an object people actually want to hold.</p>
        </div>
        <div className="wv-finish-layout">
          <div className="wv-finish-stage" data-reveal data-reveal-delay="1">
            <WaivCard3D ref={tiltRef} w={520} finish={finish} />
          </div>
          <div className="wv-finish-detail" data-reveal data-reveal-delay="1">
            <Kicker>FINISHES</Kicker>
            <div className="wv-finish-switch">
              {WAIV_FINISH_ORDER.map(id => (
                <button key={id} className={`wv-finish-chip ${id === finish ? 'is-active' : ''}`}
                  style={{ background: WAIV_FINISHES[id].grad }} onClick={() => setFinish(id)}
                  aria-label={WAIV_FINISHES[id].name} title={WAIV_FINISHES[id].name} />
              ))}
            </div>
            <div className="wv-finish-now">
              <h3>{cfg.name}</h3>
              <span>0{WAIV_FINISH_ORDER.indexOf(finish) + 1} / 0{WAIV_FINISH_ORDER.length}</span>
            </div>
            <div className="wv-specs">
              <div className="wv-spec"><p className="wv-spec-k">Chip</p><p className="wv-spec-v">NTAG 424 DNA<small>AES-encrypted, tamper-proof</small></p></div>
              <div className="wv-spec"><p className="wv-spec-k">Antenna</p><p className="wv-spec-v">13.56 MHz<small>copper coil, full-card</small></p></div>
              <div className="wv-spec"><p className="wv-spec-k">Print</p><p className="wv-spec-v">UV high-build<small>raised, scratch-resistant</small></p></div>
              <div className="wv-spec"><p className="wv-spec-k">Taps</p><p className="wv-spec-v">Unlimited<small>no subscription to share</small></p></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────── everything you can share — bento ───────── */
function ShareGrid() {
  const tiles = [
    { ico: 'user', t: 'Contacts', d: 'Name, number, email and address saved in one tap — straight into their phone.', cls: 'span2', chips: ['vCard', 'Apple Wallet', 'Google'] },
    { ico: 'share', t: 'Socials', d: 'Every handle, one place.', cls: '' },
    { ico: 'card', t: 'Payments', d: 'Get paid on the spot.', cls: '', chips: ['Venmo', 'PayPal', 'Cash App'] },
    { ico: 'grid', t: 'Portfolio & links', d: 'Showcase your work, menu, booking page or storefront — anything with a URL lives on your profile.', cls: 'span2 row2', big: true },
    { ico: 'calendar', t: 'Booking', d: 'Drop a calendar link and let people book you right after they tap.', cls: '' },
    { ico: 'wifi', t: 'Wi-Fi & more', d: 'Guest Wi-Fi, reviews, PDFs.', cls: '' },
  ];
  return (
    <section className="wv-sec" id="share">
      <div className="wv-container">
        <div className="wv-sec-head" data-reveal>
          <Kicker>ONE TAP, EVERYTHING</Kicker>
          <h2 className="wv-sec-title">Share whatever matters <em>most.</em></h2>
          <p className="wv-sec-lede">Your waiv isn't just a contact card. Mix and match what people see — and reorder it any time from your phone.</p>
        </div>
        <div className="wv-bento">
          {tiles.map((t, i) => (
            <div key={i} className={`wv-tile-x ${t.cls}`} data-reveal data-reveal-delay={(i % 4) + 1}>
              <div className="wv-tx-glow" />
              <div className="wv-tx-ico"><Ico n={t.ico} /></div>
              <div className="wv-tx-foot">
                <h3 className="wv-tx-t">{t.t}</h3>
                <p className="wv-tx-d">{t.d}</p>
                {t.chips && <div className="wv-tx-chips">{t.chips.map(c => <b key={c}>{c}</b>)}</div>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ───────── Onelynk digital profile ───────── */
function Onelynk() {
  const feats = [
    { ico: 'edit', t: 'Edit once, update everywhere', p: 'Change a job, a number, a link — every card you handed out reflects it instantly. Paper business cards can’t.' },
    { ico: 'chart', t: 'See who you’re connecting with', p: 'Live analytics on taps, profile views and saved contacts — know which rooms are working.' },
    { ico: 'bolt', t: 'No app for anyone', p: 'Your profile is just a web link. The person tapping needs nothing installed, ever.' },
  ];
  return (
    <section className="wv-sec wv-onelynk" id="onelynk">
      <div className="wv-container">
        <div className="wv-ol-layout">
          <div data-reveal>
            <Kicker>ONELYNK</Kicker>
            <h2 className="wv-sec-title">One link that <em>is</em> you.</h2>
            <p className="wv-sec-lede">Every waiv points to your Onelynk — a living profile you control from your phone.</p>
            <div className="wv-ol-feats">
              {feats.map((f, i) => (
                <div className="wv-ol-feat" key={i}>
                  <div className="wv-ol-feat-ico"><Ico n={f.ico} /></div>
                  <div><h4>{f.t}</h4><p>{f.p}</p></div>
                </div>
              ))}
            </div>
            <button className="wv-btn wv-btn-primary wv-magnetic">Claim your Onelynk <span className="wv-arrow">→</span></button>
          </div>
          <div className="wv-ol-stage" data-reveal data-reveal-delay="1">
            <div className="wv-ol-float wv-ol-float-1">
              <div className="wv-num">1.2k</div>
              <div className="wv-cap">profile<br />views</div>
            </div>
            <div className="wv-ol-float wv-ol-float-2">
              <div className="wv-num">+318</div>
              <div className="wv-cap">contacts<br />saved</div>
            </div>
            <div className="wv-ol-phone">
              <div className="wv-ol-notch" />
              <div className="wv-ol-screen">
                <div className="wv-ol-cover" />
                <div className="wv-ol-body">
                  <div className="wv-ol-avatar" />
                  <h3 className="wv-ol-name">Maya Okafor</h3>
                  <p className="wv-ol-role">Product Designer · Studio North</p>
                  <span className="wv-ol-tag">⚡ via waiv</span>
                  <div className="wv-ol-links">
                    <div className="wv-ol-link"><div className="wv-ol-link-ico"><Ico n="grid" /></div><div className="wv-ol-link-txt"><b>Portfolio</b><span>maya.design</span></div></div>
                    <div className="wv-ol-link"><div className="wv-ol-link-ico"><Ico n="calendar" /></div><div className="wv-ol-link-txt"><b>Book a coffee</b><span>cal.com/maya</span></div></div>
                    <div className="wv-ol-link"><div className="wv-ol-link-ico"><Ico n="share" /></div><div className="wv-ol-link-txt"><b>Instagram</b><span>@maya.makes</span></div></div>
                  </div>
                  <div className="wv-ol-save">Save contact</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────── for business ───────── */
function ForBusiness() {
  const cards = [
    { ico: 'users', t: 'Equip the whole team', p: 'Order matching cards for everyone and manage their profiles from one dashboard.' },
    { ico: 'building', t: 'On-brand, every tap', p: 'Lock logos, colors and layout so every profile looks unmistakably yours.' },
    { ico: 'refresh', t: 'CRM in real time', p: 'Pipe captured leads straight into Salesforce, HubSpot or a webhook automatically.' },
  ];
  return (
    <section className="wv-sec wv-biz" id="business">
      <div className="wv-container">
        <div className="wv-sec-head wv-sec-head--center" data-reveal>
          <Kicker>FOR BUSINESS</Kicker>
          <h2 className="wv-sec-title">Networking that scales <em>with the team.</em></h2>
          <p className="wv-sec-lede">From two-person studios to thousand-seat sales floors — deploy, brand and measure every connection from one place.</p>
        </div>
        <div className="wv-biz-grid">
          {cards.map((c, i) => (
            <div className="wv-biz-card" key={i} data-reveal data-reveal-delay={i + 1}>
              <div className="wv-biz-ico"><Ico n={c.ico} /></div>
              <h4>{c.t}</h4><p>{c.p}</p>
            </div>
          ))}
        </div>
        <div className="wv-biz-stats" data-reveal>
          <div className="wv-biz-stat"><b>7<em>×</em></b><span>more contacts kept</span></div>
          <div className="wv-biz-stat"><b>0</b><span>apps to install</span></div>
          <div className="wv-biz-stat"><b>40<em>k</em>+</b><span>professionals on waiv</span></div>
          <div className="wv-biz-stat"><b>1.4<em>m</em></b><span>taps shared</span></div>
        </div>
      </div>
    </section>
  );
}

/* ───────── final CTA — giant waving Tappy finale ───────── */
function FinalCTA() {
  const secRef = useRef(null);
  const pupL = useRef(null), pupR = useRef(null);
  const [happy, setHappy] = useState(false);
  const [bursts, setBursts] = useState([]);
  const keyRef = useRef(0);

  // eyes follow cursor
  useEffect(() => {
    const onMove = (e) => {
      [pupL, pupR].forEach(ref => {
        const el = ref.current; if (!el) return;
        const r = el.getBoundingClientRect();
        const dx = e.clientX - (r.left + r.width / 2), dy = e.clientY - (r.top + r.height / 2);
        const a = Math.atan2(dy, dx), d = Math.min(6, Math.hypot(dx, dy) / 28);
        el.style.transform = `translate(calc(-50% + ${Math.cos(a) * d}px), calc(-50% + ${Math.sin(a) * d}px))`;
      });
      const sec = secRef.current;
      if (sec) {
        const r = sec.getBoundingClientRect();
        sec.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100).toFixed(1) + '%');
        sec.style.setProperty('--my', ((e.clientY - r.top) / r.height * 100).toFixed(1) + '%');
      }
    };
    window.addEventListener('pointermove', onMove);
    return () => window.removeEventListener('pointermove', onMove);
  }, []);

  const CONFETTI = ['#ffd527', '#3f8bff', '#67b9a4', '#e0577f', '#cfe0ff', '#f2c200'];
  const celebrate = () => {
    setHappy(true);
    const k = ++keyRef.current;
    const pieces = Array.from({ length: 26 }, (_, i) => ({
      id: k + '-' + i,
      x: (Math.random() * 2 - 1) * 280,
      y: -120 - Math.random() * 200,
      rot: Math.random() * 360,
      c: CONFETTI[i % CONFETTI.length],
      dl: Math.random() * 0.12,
    }));
    setBursts(b => [...b, { k, pieces }]);
    setTimeout(() => setBursts(b => b.filter(x => x.k !== k)), 1500);
    setTimeout(() => setHappy(false), 1800);
  };

  return (
    <section className="wv-sec wv-cta" id="get" ref={secRef}>
      <ParticleField count={30} opacity={0.5} />
      <div className="wv-cta-glow" />
      <div className="wv-cta-spot" aria-hidden="true" />
      <div className={`fin-rings ${happy ? 'is-on' : ''}`} aria-hidden="true"><span /><span /><span /></div>

      <div className="wv-container fin-wrap">
        <div className="fin-eyebrow" data-reveal><span className="hb-eyebrow-mark" />SAY HELLO TO TAPPY</div>
        <h2 className="fin-title" data-reveal data-reveal-delay="1">Make the first move <em>unforgettable.</em></h2>

        <div className={`fin-mascot ${happy ? 'is-happy' : ''}`}
          onClick={celebrate} role="button" aria-label="Tap Tappy to celebrate">
          <div className="fin-arm fin-arm-l"><span className="fin-hand" /></div>
          <div className="fin-arm fin-arm-r"><span className="fin-hand" /></div>
          <div className="fin-body wv-card--midnightgold">
            <div className="fin-face">
              <div className="fin-brows"><i /><i /></div>
              <div className="fin-blush"><i /><i /></div>
              <div className="fin-eyes">
                <div className="fin-eye"><div className="fin-pupil" ref={pupL} /></div>
                <div className="fin-eye"><div className="fin-pupil" ref={pupR} /></div>
              </div>
              <div className="fin-mouth" />
            </div>
            <img className="fin-logo" src={(window.__resources&&window.__resources.logoYellow)||"assets/waiv-yellow.png"} alt="" />
            <div className="fin-chip" />
          </div>
          <div className="fin-confetti">
            {bursts.map(b => b.pieces.map(p => (
              <i key={p.id} style={{ '--cx': p.x + 'px', '--cy': p.y + 'px', '--cr': p.rot + 'deg', background: p.c, animationDelay: p.dl + 's' }} />
            )))}
          </div>
          <div className="fin-tip">tap me!</div>
        </div>

        <p className="fin-sub" data-reveal>Design your card in minutes. Free Onelynk profile included — for life.</p>
        <div className="wv-cta-row fin-cta" data-reveal>
          <button className="wv-btn wv-btn-primary wv-magnetic">Design your card</button>
          <button className="wv-btn wv-btn-ghost wv-magnetic">Compare plans <span className="wv-arrow">→</span></button>
        </div>
      </div>
    </section>
  );
}

/* ───────── footer ───────── */
function Footer() {
  const cols = [
    { h: 'Product', links: ['The card', 'Onelynk', 'Finishes', 'How it works', 'Pricing'] },
    { h: 'Company', links: ['About', 'Careers', 'Press', 'Sustainability'] },
    { h: 'Support', links: ['Help center', 'Activate a card', 'Contact', 'Privacy'] },
  ];
  return (
    <footer className="wv-foot">
      <div className="wv-container">
        <div className="wv-foot-top">
          <div className="wv-foot-brand">
            <img src={(window.__resources&&window.__resources.logoLight)||"assets/waiv-light.png"} alt="waiv" />
            <p>The premium NFC card and digital profile for people who live on introductions.</p>
          </div>
          {cols.map(c => (
            <div className="wv-foot-col" key={c.h}>
              <h5>{c.h}</h5>
              {c.links.map(l => <a key={l}>{l}</a>)}
            </div>
          ))}
        </div>
        <div className="wv-foot-bottom">
          <span>© 2026 waiv. Tap to connect.</span>
          <div className="wv-foot-socials">
            <a aria-label="Share"><Ico n="share" /></a>
            <a aria-label="Link"><Ico n="link" /></a>
            <a aria-label="Profile"><Ico n="user" /></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Ico, Kicker, TrustStrip, HowItWorks, FinishShowcase, ShareGrid, Onelynk, ForBusiness, FinalCTA, Footer });
