/* ============================================================
   Asher Encounters — Book-a-Tour modal, event bus, floating CTA
   The single conversion surface. Any "Book a Tour" button fires
   window event 'asher:book'; the modal (mounted once at app root)
   listens and opens. Optional detail.program prefills the select.
   ============================================================ */
(function () {
  const DS = window.AsherEncountersDesignSystem_12251c;
  const { Button, Input, Eyebrow, Badge } = DS;
  const R = React;

  /* ===== Zoho Forms integration (Book-a-Tour queries only) =================
     Posts a normalized inquiry to the "Asher Encounters Tour Inquiry Form".
     Uses a hidden form + hidden iframe target so there's no page redirect and
     no CORS issue. Field names below come straight from the Zoho HTML export. */
  const ZOHO_ACTION = 'https://forms.zohopublic.com/monicahanasherv1/form/AsherEncountersTourInquiryForm/formperma/0n-LVLi8RlUb4rbCJULp8V27E8n49dHbGNPSDzMZjDU/htmlRecords/submit';

  /* Map any program label to the EXACT Zoho dropdown option string. */
  function zohoProgram(s) {
    s = (s || '').toLowerCase();
    if (s.indexOf('capital') > -1) return 'Capital & Conviction - AI Investor Tour';
    if (s.indexOf('frontier') > -1) return 'AI Frontier - Inside Silicon Valley';
    if (s.indexOf('compass') > -1) return 'Compass - College & Career Strategy Camp';
    return 'Not sure yet - help me choose';
  }

  /* fields: { first, last, email, phone, country, company, program } (program already a Zoho option) */
  function sendToZoho(fields) {
    return new Promise((resolve) => {
      const map = {
        'Name_First': fields.first || '',
        'Name_Last': fields.last || '',
        'Email': fields.email || '',
        'PhoneNumber_countrycode': fields.phone || '',
        'SingleLine': fields.country || '',
        'SingleLine1': fields.company || '',
        'Dropdown': fields.program || '-Select-',
      };
      let iframe, form, done = false;
      const cleanup = () => { try { form && form.remove(); } catch (e) {} setTimeout(() => { try { iframe && iframe.remove(); } catch (e) {} }, 1500); };
      const finish = () => { if (done) return; done = true; cleanup(); resolve(true); };
      try {
        const name = 'zoho_sink_' + Date.now();
        iframe = document.createElement('iframe');
        iframe.name = name; iframe.style.display = 'none';
        iframe.addEventListener('load', finish);
        document.body.appendChild(iframe);
        form = document.createElement('form');
        form.method = 'POST'; form.action = ZOHO_ACTION; form.target = name;
        form.acceptCharset = 'UTF-8'; form.enctype = 'multipart/form-data';
        form.style.display = 'none';
        Object.keys(map).forEach((k) => {
          const i = document.createElement('input');
          i.type = 'hidden'; i.name = k; i.value = map[k];
          form.appendChild(i);
        });
        document.body.appendChild(form);
        form.submit();
        setTimeout(finish, 2500); // fallback: cross-origin load may not fire
      } catch (e) { resolve(false); }
    });
  }

  function openBooking(program) {
    window.dispatchEvent(new CustomEvent('asher:book', { detail: { program } }));
  }

  /* Reusable Book-a-Tour button (the loudest CTA — violet, vivid) */
  function BookButton({ size = 'lg', program, label = 'Book a Tour', variant = 'violet', style = {}, iconRight = true }) {
    return R.createElement(Button, {
      variant, size, onClick: () => openBooking(program), style: { whiteSpace: 'nowrap', ...style },
      iconRight: iconRight ? R.createElement('i', { 'data-lucide': 'arrow-up-right', style: { width: 18, height: 18 } }) : null,
    }, label);
  }

  const PROGRAMS = [
    'Capital & Conviction — AI Investor Tour',
    'AI Frontier — Inside Silicon Valley',
    'Compass — College & Career Strategy Camp',
    'Not sure yet — help me choose',
  ];

  function BookingModal() {
    const [open, setOpen] = R.useState(false);
    const [program, setProgram] = R.useState(PROGRAMS[3]);
    const [sent, setSent] = R.useState(false);
    const [errors, setErrors] = R.useState({});
    const [mailtoHref, setMailtoHref] = R.useState('mailto:hello@asherventures.ai');

    R.useEffect(() => {
      const onBook = (e) => {
        setSent(false); setErrors({});
        if (e.detail && e.detail.program) setProgram(e.detail.program);
        setOpen(true);
      };
      window.addEventListener('asher:book', onBook);
      const onKey = (ev) => { if (ev.key === 'Escape') setOpen(false); };
      window.addEventListener('keydown', onKey);
      return () => { window.removeEventListener('asher:book', onBook); window.removeEventListener('keydown', onKey); };
    }, []);

    R.useEffect(() => {
      document.body.style.overflow = open ? 'hidden' : '';
      if (window.lucide) window.lucide.createIcons();
    }, [open, sent]);

    function submit(e) {
      e.preventDefault();
      const f = new FormData(e.target);
      const errs = {};
      if (!f.get('first').trim()) errs.first = 'Required';
      const email = f.get('email').trim();
      if (!email) errs.email = 'Required';
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errs.email = 'Enter a valid email';
      setErrors(errs);
      if (Object.keys(errs).length) return;
      const first = f.get('first').trim();
      const last = (f.get('last') || '').toString().trim();
      const name = (first + ' ' + last).trim();
      const val = (k) => (f.get(k) || '').toString().trim();
      /* Submit to Zoho Forms (Book-a-Tour pipeline). */
      sendToZoho({ first, last, email, phone: val('phone'), country: val('country'),
        company: val('company'), program: zohoProgram(program) });
      /* Build an email fallback (manual button only — not auto-opened). */
      const lines = [
        'Program of interest: ' + program, '',
        'Name: ' + name, 'Email: ' + email,
        'Phone: ' + (val('phone') || '—'), 'Country: ' + (val('country') || '—'),
        'Company / Fund: ' + (val('company') || '—'),
      ];
      setMailtoHref('mailto:hello@asherventures.ai?subject=' + encodeURIComponent('Tour Inquiry from ' + name)
        + '&body=' + encodeURIComponent(lines.join('\r\n')));
      setSent(true);
    }

    if (!open) return null;

    return R.createElement('div', { className: 'ae-modal-backdrop', onMouseDown: (e) => { if (e.target === e.currentTarget) setOpen(false); } },
      R.createElement('div', { className: 'ae-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Book a tour' },
        /* header */
        R.createElement('div', { style: { background: 'var(--ink)', padding: '26px 28px', position: 'relative' } },
          R.createElement('img', { src: 'assets/mark-cream.png', alt: '', 'aria-hidden': 'true', style: { position: 'absolute', right: -30, top: -34, width: 150, opacity: 0.10 } }),
          R.createElement('button', { 'aria-label': 'Close', onClick: () => setOpen(false), style: { position: 'absolute', top: 18, right: 18, width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--border-on-dark)', background: 'rgba(243,242,239,0.06)', color: 'var(--paper)', cursor: 'pointer', display: 'grid', placeItems: 'center' } },
            R.createElement('i', { 'data-lucide': 'x', style: { width: 18, height: 18 } })),
          R.createElement(Eyebrow, { color: 'var(--lavender)' }, 'Book a Tour'),
          R.createElement('h2', { style: { color: 'var(--paper)', fontSize: '1.6rem', margin: '10px 0 6px' } }, sent ? 'Request received' : 'Reserve your discovery call'),
          !sent && R.createElement('p', { style: { color: 'rgba(243,242,239,0.7)', fontSize: '0.92rem', margin: 0, maxWidth: '44ch' } }, 'Tell us a little about you and we’ll match you to the right cohort — and reply within 24 hours.')
        ),
        /* body */
        R.createElement('div', { style: { padding: '26px 28px 30px' } },
          sent
            ? R.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'flex-start' } },
                R.createElement(Badge, { tone: 'success' }, 'We’ll be in touch'),
                R.createElement('p', { style: { color: 'var(--text-muted)', margin: 0, lineHeight: 1.6 } }, 'Thank you — your request is in. Your cohort host will reach out within 24 hours. Prefer email? Use the button below or write to hello@asherventures.ai.'),
                R.createElement('div', { style: { display: 'flex', gap: 10, flexWrap: 'wrap' } },
                  R.createElement(Button, { variant: 'violet', onClick: () => setOpen(false) }, 'Done'),
                  R.createElement('a', { href: mailtoHref, style: { textDecoration: 'none' } },
                    R.createElement(Button, { variant: 'secondary',
                      iconRight: R.createElement('i', { 'data-lucide': 'mail', style: { width: 17, height: 17 } }) }, 'Email us instead'))))
            : R.createElement('form', { onSubmit: submit, style: { display: 'flex', flexDirection: 'column', gap: 16 }, noValidate: true },
                R.createElement('div', { className: 'ae-form-row', style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 } },
                  R.createElement(Input, { label: 'First name', name: 'first', placeholder: 'Jane', error: errors.first, autoFocus: true }),
                  R.createElement(Input, { label: 'Last name', name: 'last', placeholder: 'Investor' })
                ),
                R.createElement(Input, { label: 'Work email', name: 'email', type: 'email', placeholder: 'jane@fund.com', error: errors.email }),
                R.createElement('div', { className: 'ae-form-row', style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 } },
                  R.createElement(Input, { label: 'Phone (optional)', name: 'phone', type: 'tel', placeholder: '+1 555 000 1234' }),
                  R.createElement(Input, { label: 'Country', name: 'country', placeholder: 'Singapore' })
                ),
                R.createElement(Input, { label: 'Company / Fund', name: 'company', placeholder: 'Northwind Capital' }),
                R.createElement('label', { style: { display: 'flex', flexDirection: 'column', gap: 7 } },
                  R.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '0.68rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--slate)', fontWeight: 500 } }, 'Program of interest'),
                  R.createElement('select', { className: 'ae-select', name: 'program', value: program, onChange: (e) => setProgram(e.target.value) },
                    PROGRAMS.map((p) => R.createElement('option', { key: p, value: p }, p)))
                ),
                R.createElement(Button, { variant: 'violet', size: 'lg', type: 'submit', style: { alignSelf: 'stretch', marginTop: 4 } }, 'Request my discovery call'),
                R.createElement('p', { style: { fontSize: '0.78rem', color: 'var(--text-faint)', margin: 0, textAlign: 'center' } }, 'No obligation · We reply within 24 hours')
              )
        )
      )
    );
  }

  /* Floating Book-a-Tour — satisfies the "always one visible" rule on tall scrolls */
  function FloatingBook() {
    const [show, setShow] = R.useState(false);
    R.useEffect(() => {
      const onScroll = () => {
        const heroBtn = document.querySelector('[data-hero-cta]');
        const ctaBlock = document.querySelector('[data-cta-block]');
        const within = (el) => { if (!el) return false; const r = el.getBoundingClientRect(); return r.top < window.innerHeight && r.bottom > 0; };
        // hide while the hero CTA or the big CTA block is on screen (a loud Book button already visible)
        setShow(window.scrollY > 520 && !within(heroBtn) && !within(ctaBlock));
      };
      onScroll();
      window.addEventListener('scroll', onScroll, { passive: true });
      window.addEventListener('resize', onScroll);
      return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); };
    }, []);
    R.useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [show]);
    return R.createElement('div', { className: 'ae-float-book' + (show ? ' is-show' : '') },
      R.createElement(Button, { variant: 'violet', size: 'lg', onClick: () => openBooking(),
        iconRight: R.createElement('i', { 'data-lucide': 'arrow-up-right', style: { width: 18, height: 18 } }),
        style: { boxShadow: '0 10px 30px rgba(66,54,153,0.4), var(--squish-violet)' } }, 'Book a Tour')
    );
  }

  window.Asher = Object.assign(window.Asher || {}, { BookingModal, BookButton, FloatingBook, openBooking, PROGRAMS, sendToZoho, zohoProgram });
})();
