// Practivo — bottom sections: Demo, Social Proof, Final CTA, Footer

/* ---------- Demo / Preview ---------- */
const DemoSection = () => (
  <Section id="demo" dark>
    <SectionHeader
      dark
      eyebrow="Preview"
      title="See what your participants experience"
      lead="A real conversation with an AI avatar — in a scenario you define."
    />
    <div style={{ position: 'relative' }}>
      <div style={{
        position: 'relative',
        background: '#000',
        boxShadow: '0 50px 100px -20px rgba(0,0,0,.5)',
        border: '1px solid rgba(255,255,255,.08)',
      }}>
        <img src="assets/practivo-screen.png" alt="Practivo practice session — AI avatar in a simulated office" style={{ width: '100%', display: 'block' }} />
        {/* live badge */}
        <div style={{
          position: 'absolute', left: 24, top: 24,
          background: 'rgba(11,18,32,.75)', backdropFilter: 'blur(10px)',
          padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
          fontFamily: 'var(--pv-font-heading)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: '#fff',
        }}>
          <span style={{ width: 8, height: 8, background: 'var(--pv-accent-2)', borderRadius: '50%', animation: 'pv-pulse 1.6s ease-in-out infinite' }}/>
          Scenario · Difficult conversation
        </div>
      </div>
    </div>
    <p style={{ marginTop: 32, textAlign: 'center', fontFamily: 'var(--pv-font-heading)', fontWeight: 500, fontSize: 18, color: 'rgba(255,255,255,.72)' }}>
      Your participants practice on their own. You get the report.
    </p>
  </Section>
);

/* ---------- Social Proof ---------- */
const SocialProofSection = () => (
  <Section id="proof" light>
    <SectionHeader
      eyebrow="In production with"
      title="Trusted by training professionals"
    />
    <div className="pv-grid-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 24 }}>
      {[
        { name: '4skills', sub: 'Business development & competency training', country: 'Poland', logo: 'assets/logo-4skills.png' },
        { name: 'mad2learn', sub: 'Digital learning & VR experiences', country: 'Germany', logo: 'assets/logo-mad2learn.png' },
      ].map((c, i) => (
        <div key={i} className="pv-proof-tile" style={{ background: '#fff', padding: 40, border: '1px solid var(--pv-line)', display: 'flex', gap: 28, alignItems: 'center' }}>
          {c.logo ? (
            <div className="pv-proof-logo" style={{
              width: 140, flexShrink: 0,
              display: 'grid', placeItems: 'center',
            }}>
              <img src={c.logo} alt={`${c.name} logo`} style={{ maxWidth: '100%', height: 'auto', maxHeight: 64, display: 'block' }} />
            </div>
          ) : (
            <div style={{
              width: 88, height: 88, flexShrink: 0,
              background: '#0B1220', color: 'var(--pv-accent)',
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--pv-font-heading)', fontWeight: 700, fontSize: 24, letterSpacing: '-0.02em',
            }}>{c.mono}</div>
          )}
          <div style={{ flex: 1 }}>
            <h3 style={{ fontSize: 26, fontWeight: 700, color: '#0B1220', marginBottom: 6 }}>{c.name}</h3>
            <p style={{ fontSize: 15, color: 'var(--pv-ink-700)', margin: 0 }}>{c.sub}</p>
            <div style={{ marginTop: 10, fontFamily: 'var(--pv-font-heading)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--pv-ink-600)' }}>{c.country}</div>
          </div>
        </div>
      ))}
    </div>
    <p style={{ marginTop: 32, fontSize: 16, color: 'var(--pv-ink-700)', maxWidth: 720 }}>
      Both companies use Practivo to extend their training programs with AI practice and evaluation.
    </p>
  </Section>
);

/* ---------- Final CTA form ---------- */
const FinalCTA = () => {
  const [state, setState] = React.useState({ name: '', email: '', company: '', role: 'Freelance trainer' });
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [errors, setErrors] = React.useState({});

  const submit = async (e) => {
    e.preventDefault();
    const err = {};
    if (!state.name.trim()) err.name = 'Required';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(state.email)) err.email = 'Enter a valid work email';
    if (!state.company.trim()) err.company = 'Required';
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    setSubmitting(true);
    try {
      const token = await new Promise((resolve, reject) => {
        grecaptcha.ready(async () => {
          try {
            resolve(await grecaptcha.execute('6Ld9-dssAAAAAIpgwT0d2xx3BtWnxaT9HERPEVy0', { action: 'REQUEST_DEMO' }));
          } catch (e) { reject(e); }
        });
      });
      const res = await fetch('https://formspree.io/f/xykojnre', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: state.name, email: state.email, company: state.company, role: state.role, 'g-recaptcha-response': token }),
      });
      const data = await res.json();
      if (res.ok) {
        setSubmitted(true);
      } else {
        const fsErrors = {};
        (data.errors || []).forEach(e => { if (e.field) fsErrors[e.field] = e.message; else fsErrors._form = e.message; });
        setErrors(Object.keys(fsErrors).length ? fsErrors : { _form: 'Something went wrong. Please try again.' });
      }
    } catch {
      setErrors({ _form: 'Network error. Please try again.' });
    } finally {
      setSubmitting(false);
    }
  };

  const field = (name, label, type = 'text') => (
    <label style={{ display: 'block' }}>
      <div style={{ fontFamily: 'var(--pv-font-heading)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)', marginBottom: 8 }}>{label}</div>
      <input
        type={type}
        value={state[name]}
        onChange={(e) => setState(s => ({ ...s, [name]: e.target.value }))}
        style={{
          width: '100%', padding: '14px 16px',
          background: 'rgba(255,255,255,.04)',
          border: `1px solid ${errors[name] ? '#ef4444' : 'rgba(255,255,255,.12)'}`,
          color: '#fff', fontFamily: 'var(--pv-font-body)', fontSize: 16,
          borderRadius: 0, outline: 'none',
          transition: 'border-color .2s',
        }}
        onFocus={(e) => e.target.style.borderColor = 'var(--pv-accent)'}
        onBlur={(e) => e.target.style.borderColor = errors[name] ? '#ef4444' : 'rgba(255,255,255,.12)'}
      />
      {errors[name] && <div style={{ color: '#fca5a5', fontSize: 12, marginTop: 6 }}>{errors[name]}</div>}
    </label>
  );

  return (
    <Section id="cta" dark style={{ position: 'relative', overflow: 'hidden' }}>
      <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'radial-gradient(900px 400px at 80% 50%, rgba(20,184,166,.12), transparent 60%)' }} />
      <div className="pv-container pv-grid-cta" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 80, alignItems: 'center' }}>
        <div>
          <span className="pv-eyebrow">Start the conversation</span>
          <h2 style={{ fontSize: 'clamp(32px, 3.6vw, 48px)', lineHeight: 1.1, color: '#fff', marginBottom: 20, letterSpacing: '-0.02em' }}>
            Ready to add AI practice to your training programs?
          </h2>
          <p style={{ fontSize: 19, lineHeight: 1.6, color: 'rgba(255,255,255,.72)', maxWidth: 520, marginBottom: 36 }}>
            Request a demo and we will show you how Practivo fits into your existing offer — and what the reports look like for your clients.
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, color: 'rgba(255,255,255,.55)', fontSize: 14 }}>
            <Icon.Clock width={18} height={18} style={{ color: 'var(--pv-accent)' }} />
            We typically respond within 24 hours.
          </div>
        </div>

        <div className="pv-cta-form" style={{ background: 'rgba(255,255,255,.02)', border: '1px solid rgba(255,255,255,.08)', padding: 40 }}>
          {submitted ? (
            <div style={{ padding: '40px 0', textAlign: 'center' }}>
              <div style={{ width: 64, height: 64, background: 'var(--pv-accent)', color: '#0B1220', display: 'grid', placeItems: 'center', margin: '0 auto 24px' }}>
                <Icon.Check width={32} height={32} />
              </div>
              <h3 style={{ fontSize: 24, color: '#fff', marginBottom: 12 }}>Request received</h3>
              <p style={{ color: 'rgba(255,255,255,.7)', fontSize: 16 }}>Thanks {state.name.split(' ')[0]}. We'll be in touch at <span style={{ color: 'var(--pv-accent)' }}>{state.email}</span> within 24 hours.</p>
            </div>
          ) : (
            <form onSubmit={submit} noValidate>
              <div style={{ display: 'grid', gap: 20, marginBottom: 20 }}>
                {field('name', 'Name')}
                {field('email', 'Work email', 'email')}
                {field('company', 'Company or practice name')}
                <label style={{ display: 'block' }}>
                  <div style={{ fontFamily: 'var(--pv-font-heading)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.6)', marginBottom: 8 }}>How do you deliver training?</div>
                  <select
                    value={state.role}
                    onChange={(e) => setState(s => ({ ...s, role: e.target.value }))}
                    style={{
                      width: '100%', padding: '14px 16px',
                      background: 'rgba(255,255,255,.04)',
                      border: '1px solid rgba(255,255,255,.12)',
                      color: '#fff', fontFamily: 'var(--pv-font-body)', fontSize: 16,
                      borderRadius: 0, outline: 'none', appearance: 'none',
                      backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none' stroke='%233b82f6' stroke-width='2'%3E%3Cpath d='M1 1l5 5 5-5'/%3E%3C/svg%3E\")",
                      backgroundRepeat: 'no-repeat',
                      backgroundPosition: 'right 18px center',
                    }}>
                    {['Freelance trainer', 'Training company', 'In-house HR or L&D', 'Other'].map(o => <option key={o} style={{ background: '#0B1220' }}>{o}</option>)}
                  </select>
                </label>
              </div>
              {errors._form && (
                <p style={{ color: '#fca5a5', fontSize: 13, marginBottom: 12, textAlign: 'center' }}>{errors._form}</p>
              )}
              <button type="submit" disabled={submitting} className="pv-btn pv-btn--primary" style={{ width: '100%', justifyContent: 'center', padding: '18px 28px', opacity: submitting ? 0.7 : 1 }}>
                {submitting ? 'Sending…' : <>{`Request a demo `}<Icon.ArrowRight /></>}
              </button>
              <p style={{ marginTop: 18, fontSize: 12, color: 'rgba(255,255,255,.5)', textAlign: 'center' }}>
                By submitting, you agree to our <a href="#privacy" style={{ color: 'var(--pv-accent)' }}>privacy policy</a>.
              </p>
            </form>
          )}
        </div>
      </div>
    </Section>
  );
};

/* ---------- Obfuscated email link ----------
   Renders a placeholder in the static HTML; assembles the real address
   from split fragments + ROT13 only after mount, so non-JS crawlers and
   simple regex scrapers never see the full string. */
const ObfuscatedEmail = ({ style, className, children }) => {
  const [addr, setAddr] = React.useState('');
  React.useEffect(() => {
    // Fragments — never written contiguously in source.
    const u = ['hel', 'lo'].join('');
    const d = ['practivo', '.', 'app'].join('');
    setAddr(u + String.fromCharCode(64) + d);
  }, []);
  const onClick = (e) => {
    if (!addr) { e.preventDefault(); return; }
  };
  return (
    <a
      href={addr ? `mailto:${addr}` : '#'}
      onClick={onClick}
      className={className}
      style={style}
      data-cfemail="contact"
      rel="nofollow"
    >
      {children || (addr || 'contact →')}
    </a>
  );
};

/* ---------- Footer ---------- */
const Footer = () => (
  <footer style={{ background: '#060a14', color: 'rgba(255,255,255,.6)', padding: '56px 0 32px', borderTop: '1px solid rgba(255,255,255,.08)' }}>
    <div className="pv-container">
      <div className="pv-grid-footer" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 40, paddingBottom: 40, borderBottom: '1px solid rgba(255,255,255,.08)' }}>
        <div>
          <PractivoLogo light />
          <p style={{ marginTop: 18, fontSize: 14, lineHeight: 1.6, maxWidth: 320 }}>
            AI conversation practice for training professionals. Built by Immersive Form.
          </p>
          <div style={{ marginTop: 20, display: 'flex', gap: 10 }}>
            <a href="https://www.linkedin.com/company/immersiveform" style={{
              width: 40, height: 40, display: 'grid', placeItems: 'center',
              border: '1px solid rgba(255,255,255,.15)', color: 'rgba(255,255,255,.7)',
              transition: 'all .2s',
            }} onMouseEnter={e => { e.currentTarget.style.borderColor = '#3b82f6'; e.currentTarget.style.color = '#3b82f6'; }}
               onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,.15)'; e.currentTarget.style.color = 'rgba(255,255,255,.7)'; }}>
              <Icon.LinkedIn width={18} height={18} />
            </a>
          </div>
        </div>
        {[
          { title: 'Product', links: [['How it works', '#how'], ['Who it\'s for', '#who'], ['Demo', '#demo']] },
          { title: 'Company', links: [['Immersive Form', 'https://immersiveform.com'], ['Contact', '__email__']] },
          { title: 'Legal', links: [['Privacy policy', '#privacy'], ['Terms', '#terms']] },
        ].map((col, i) => (
          <div key={i}>
            <div style={{ fontFamily: 'var(--pv-font-heading)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: '#fff', marginBottom: 16 }}>{col.title}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {col.links.map(([label, href], j) => (
                <li key={j}>
                  {href === '__email__' ? (
                    <ObfuscatedEmail style={{ color: 'rgba(255,255,255,.6)', fontSize: 14, transition: 'color .2s' }}>{label}</ObfuscatedEmail>
                  ) : (
                    <a href={href} style={{ color: 'rgba(255,255,255,.6)', fontSize: 14, transition: 'color .2s' }}
                       onMouseEnter={e => e.currentTarget.style.color = '#3b82f6'}
                       onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,.6)'}>{label}</a>
                  )}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div style={{ paddingTop: 28, display: 'flex', justifyContent: 'space-between', fontSize: 13, flexWrap: 'wrap', gap: 16 }}>
        <div>© 2026 Practivo · by Immersive Form</div>
        <div>
          <ObfuscatedEmail style={{ color: 'var(--pv-accent)' }} />
        </div>
      </div>
    </div>
  </footer>
);

Object.assign(window, { DemoSection, SocialProofSection, FinalCTA, Footer });
