// contact.jsx - CTA conversion section + footer.
// Engagement: low-friction form, reciprocity ("we'll show you how"), trust (NDA), dual path (write or book).

const BOOK_URL = 'https://outlook.office.com/book/PrometioGroup@prometio.group/s/tSXEtBHiCkGT8BWWaWf3kw2';
const CONTACT_EMAIL = 'hello@prometio.group';
const LINKEDIN_URL = 'https://www.linkedin.com/company/prometio-group-unleash-your-potential';
const GITHUB_URL = 'https://github.com/SebastianGilPinzon';

const CONTACT_ENDPOINT = 'https://egljtgwpkhqkudzitkka.supabase.co/functions/v1/contact-form';
const TURNSTILE_SITE_KEY = '0x4AAAAAACpZKswaqOwdZYsW';

function ContactForm() {
  const [vals, setVals] = React.useState({ name: '', email: '', message: '' });
  const [errs, setErrs] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');
  const [turnstileToken, setTurnstileToken] = React.useState('');
  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  // Render Turnstile widget once the script is loaded
  React.useEffect(() => {
    if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') return;
    let cancelled = false;
    const render = () => {
      if (cancelled || !window.turnstile || !turnstileRef.current) return;
      if (widgetIdRef.current) return;
      widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        theme: 'auto',
        size: 'flexible',
        callback: (t) => setTurnstileToken(t),
        'expired-callback': () => setTurnstileToken(''),
        'error-callback': () => setTurnstileToken(''),
      });
    };
    if (window.turnstile) render();
    else {
      const id = setInterval(() => { if (window.turnstile) { clearInterval(id); render(); } }, 200);
      return () => { cancelled = true; clearInterval(id); };
    }
    return () => { cancelled = true; };
  }, []);

  const set = (k) => (e) => setVals((v) => ({ ...v, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (vals.name.trim().length < 2) er.name = 'Name is required';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) er.email = 'Please enter a valid email';
    if (vals.message.trim().length < 10) er.message = 'Tell us a bit more about your challenge';
    setErrs(er);
    if (Object.keys(er).length > 0) return;
    setSubmitError('');
    setSending(true);
    const isPreview = location.hostname === 'localhost' || location.hostname === '127.0.0.1';
    try {
      if (isPreview) {
        await new Promise((r) => setTimeout(r, 600));
        setSent(true);
        return;
      }
      const res = await fetch(CONTACT_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: vals.name.trim(),
          email: vals.email.trim(),
          message: vals.message.trim(),
          cf_turnstile_token: turnstileToken,
        }),
      });
      if (!res.ok) throw new Error('Server returned ' + res.status);
      setSent(true);
    } catch (err) {
      setSubmitError("We couldn't send your message. Please try again or email hello@prometio.group.");
    } finally {
      setSending(false);
    }
  };

  const field = {
    width: '100%', padding: 'clamp(8px, 1.3vh, 12px) 14px', borderRadius: 12, fontSize: 14, fontFamily: 'var(--font-body)',
    background: 'color-mix(in srgb, var(--fg) 4%, transparent)', border: '1px solid var(--hairline)',
    color: 'var(--fg)', outline: 'none', transition: 'border-color 200ms ease'
  };
  const label = { fontSize: 13, color: 'var(--fg-muted)', marginBottom: 6, display: 'block' };
  const errStyle = { fontSize: 12, color: '#c0563f', marginTop: 5 };

  if (sent) {
    return (
      <div role="status" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 14, height: '100%', padding: '24px 0' }}>
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none" aria-hidden="true">
          <circle cx="24" cy="24" r="22" stroke="var(--accent)" strokeWidth="1.5" />
          <path d="M15 24.5L21 30.5L33 18.5" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <p style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '1.15rem', color: 'var(--fg)', margin: 0 }}>Message sent</p>
        <p style={{ fontSize: 14, color: 'var(--fg-muted)', maxWidth: 320, lineHeight: 1.6, margin: 0 }}>We&apos;ve received your challenge. Our team will respond within one business day.</p>
      </div>);

  }

  return (
    <form onSubmit={submit} noValidate>
      <div style={{ marginBottom: 'clamp(8px, 1.4vh, 14px)' }}>
        <label style={label} htmlFor="c-name">Your Name</label>
        <input id="c-name" style={field} placeholder="Jane Doe" value={vals.name} onChange={set('name')} />
        {errs.name && <p style={errStyle}>{errs.name}</p>}
      </div>
      <div style={{ marginBottom: 'clamp(8px, 1.4vh, 14px)' }}>
        <label style={label} htmlFor="c-email">Work Email</label>
        <input id="c-email" type="email" style={field} placeholder="jane@company.com" value={vals.email} onChange={set('email')} />
        {errs.email && <p style={errStyle}>{errs.email}</p>}
      </div>
      <div style={{ marginBottom: 'clamp(8px, 1.4vh, 14px)' }}>
        <label style={label} htmlFor="c-msg">Your Challenge</label>
        <textarea id="c-msg" rows={3} style={{ ...field, resize: 'none' }} placeholder="Tell us what you're working on..." value={vals.message} onChange={set('message')} />
        {errs.message && <p style={errStyle}>{errs.message}</p>}
      </div>
      <button type="submit" className="gcta" disabled={sending} style={{
        width: '100%', padding: 'clamp(9px, 1.4vh, 13px)', borderRadius: 12, border: 'none', cursor: sending ? 'wait' : 'pointer',
        fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--platinum)', background: 'var(--violet)',
        opacity: sending ? 0.7 : 1,
        transition: 'transform 200ms ease, background 200ms ease, opacity 200ms ease'
      }}
      onMouseEnter={(e) => { if (!sending) e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={(e) => {e.currentTarget.style.transform = 'none';}}>
        {sending ? 'Sending…' : 'Send Your Challenge'}</button>
      <div ref={turnstileRef} style={{ marginTop: 'clamp(8px, 1.4vh, 14px)' }} />
      {submitError && (
        <p style={{ fontSize: 12, color: '#c0563f', textAlign: 'center', marginTop: 10 }}>{submitError}</p>
      )}
      <p style={{ fontSize: 12, color: 'var(--fg-faint)', textAlign: 'center', marginTop: 'clamp(6px, 1vh, 12px)' }}>We respond within one business day.</p>
    </form>);

}

function BookingPanel({ onStart }) {
  const bullets = ['30-minute discovery call', 'Talk directly with a founder', 'Walk away with a concrete approach'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <p className="mono" style={{ fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--accent)', margin: '0 0 12px' }}>Prefer to talk live?</p>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '1.3rem', color: 'var(--fg)', margin: 0, lineHeight: 1.25 }}>Book a discovery call</h3>
      <ul style={{ listStyle: 'none', margin: 'clamp(10px, 1.6vh, 18px) 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 'clamp(7px, 1.2vh, 10px)' }}>
        {bullets.map((b) =>
        <li key={b} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14, color: 'var(--fg-muted)' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="square"><path d="M5 12l5 5L20 6" /></svg>
            {b}
          </li>
        )}
      </ul>
      <button type="button" onClick={onStart} style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        padding: 'clamp(9px, 1.4vh, 13px) 20px', borderRadius: 12, fontWeight: 600, fontSize: 15,
        color: 'var(--accent)', border: '1px solid var(--eyebrow-bd)', background: 'var(--accent-bg)',
        marginTop: 'clamp(14px, 2.2vh, 24px)', cursor: 'pointer', fontFamily: 'inherit',
      }} className="gcta">Schedule a call →</button>
    </div>);

}

function Footer({ theme }) {
  return (
    <footer style={{ borderTop: '1px solid var(--hairline)', padding: 'clamp(8px, 1.2vh, 16px) 0', marginTop: 'clamp(4px, 0.8vh, 16px)' }}>
      <div style={{ maxWidth: 1140, margin: '0 auto', padding: '0 40px', display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <img src={theme === 'dark' ? 'assets/logo-negativo.png' : 'assets/logo-positivo.png'} alt="Prometio Group" style={{ height: 24 }} />
          <span style={{ fontSize: 12.5, color: 'var(--fg-faint)' }}>© {new Date().getFullYear()} Prometio Group</span>
          <a href={`mailto:${CONTACT_EMAIL}`} style={{ fontSize: 12.5, color: 'var(--accent)', textDecoration: 'none' }}>{CONTACT_EMAIL}</a>
        </div>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
          {[['Blog', 'blog.html'], ['LinkedIn', LINKEDIN_URL], ['GitHub', GITHUB_URL], ['Privacy', '#'], ['Terms', '#']].map(([l, h]) =>
          <a key={l} href={h} target={h.startsWith('http') ? '_blank' : undefined} rel="noopener noreferrer" style={{ fontSize: 12.5, color: 'var(--fg-muted)', textDecoration: 'none' }}>{l}</a>
          )}
          <a href="#contact" onClick={(e) => { e.preventDefault(); const el = document.getElementById('contact'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }}
            style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: 'var(--accent)', textDecoration: 'none', whiteSpace: 'nowrap' }}>
            Work with us
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="square"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
          </a>
        </nav>
      </div>
    </footer>);

}

function Contact({ t }) {
  const [showBooking, setShowBooking] = React.useState(false);
  React.useEffect(() => {
    const open = () => setShowBooking(true);
    document.addEventListener('prometio:open-booking', open);
    return () => document.removeEventListener('prometio:open-booking', open);
  }, []);
  return (
    <section id="contact" data-screen-label="Contact" className="sec" aria-labelledby="cta-h" style={{ paddingTop: 'clamp(16px, 2.4vh, 32px)', paddingBottom: 0, flexDirection: 'column' }}>
      <div className="sec-wrap" style={{ flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 'clamp(8px, 1.4vh, 24px)', paddingBottom: 'clamp(4px, 0.8vh, 16px)' }}>
        {!showBooking && (
          <SectionHead eyebrow="Start the conversation" align="center" max={760} style={{ marginBottom: 'clamp(14px, 2vh, 26px)' }}
          sub="Scaling your platform, modernizing legacy systems, or launching something new? Tell us about your challenge. We'll show you how we'd approach it.">
            <span id="cta-h">Let&apos;s talk about <span className="accent">your</span> next project</span>
          </SectionHead>
        )}

        <div className="glass-stage" style={{ maxWidth: showBooking ? 1080 : 920, marginLeft: 'auto', marginRight: 'auto', marginTop: 'auto', marginBottom: 'auto', width: '100%', transition: 'max-width 250ms ease' }}>
        <Reveal delay={120} className="glass glass-pro eglass eglass-soft lift" style={{ borderRadius: 24, padding: 'clamp(18px, 2.4vh, 32px)', width: '100%' }}>
          {!showBooking && (
            <div className="contact-grid">
              <ContactForm />
              <div style={{ borderLeft: '1px solid var(--hairline)', paddingLeft: 'clamp(0px, 3vw, 32px)' }}>
                <BookingPanel onStart={() => setShowBooking(true)} />
              </div>
            </div>
          )}
          {showBooking && (
            <BookingWidget initialPhase="selecting" onClose={() => setShowBooking(false)} />
          )}
        </Reveal>
        </div>

      </div>

      <Footer theme={t.theme} />
    </section>);

}

window.Contact = Contact;