// contact-page.jsx — Request a demo + direct email
const { useState: useStateCP } = React;

function ContactPage({ setPage }) {
  const isMobile = useIsMobile(640);
  const [sent, setSent] = useStateCP(false);
  const [form, setForm] = useStateCP({ name: '', email: '', company: '', role: '', industry: '', focus: '' });
  const [submitting, setSubmitting] = useStateCP(false);
  const [error, setError] = useStateCP(null);

  const onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    try {
      const response = await fetch('https://formspree.io/f/xwvypaqo', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.company,
          role: form.role,
          industry: form.industry,
          message: form.focus,
          _subject: `Demo request from ${form.name || 'a visitor'} at ${form.company || 'an unspecified company'}`,
        }),
      });
      if (response.ok) {
        setSent(true);
      } else {
        const data = await response.json().catch(() => null);
        setError(data?.error || 'Something went wrong on our end. Please try again, or email us directly.');
      }
    } catch (err) {
      setError('Network error. Please try again, or email us directly.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="page-fade">
      <section className="contact-top" style={{ position: 'relative', paddingTop: isMobile ? 100 : 160, overflow: 'hidden' }}>
        <div className="grid-bg"/>
        <div className="section" style={{ paddingTop: 20, position: 'relative' }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
            gap: isMobile ? 40 : 80,
            alignItems: 'flex-start',
          }}>
            <div>
              <Reveal>
                <div className="tag" style={{ marginBottom: 28 }}>
                  <span className="pulse-dot"/>
                  We give you your time back
                </div>
              </Reveal>
              <Reveal delay={80}>
                <h1 style={{
                  fontSize: 'clamp(36px, 5.5vw, 76px)', fontWeight: 500,
                  letterSpacing: '-0.035em', lineHeight: 0.98, margin: 0,
                  textWrap: 'balance',
                }}>
                  Let's Work<br/>Together.
                </h1>
              </Reveal>
              <Reveal delay={180}>
                <p style={{ marginTop: 24, fontSize: isMobile ? 15 : 17, color: 'var(--ink-dim)', maxWidth: 480, lineHeight: 1.5 }}>
                  Ready to explore what AI can do for your business? Every engagement
                  starts with a paid Discovery, where we map your workflows and identify
                  the highest-leverage AI opportunities.
                </p>
              </Reveal>
              <Reveal delay={280}>
                <div style={{ marginTop: 32, display: 'grid', gap: 14 }}>
                  {[
                    ['hello@timegainai.com', 'mail', 'mailto:hello@timegainai.com'],
                    ['linkedin.com/in/timegain-ai', 'link', 'https://www.linkedin.com/in/timegain-ai'],
                    ['Fishers, Indiana · remote nationwide', 'pin'],
                    ['Infinite Horizons LLC · dba Timegain AI Solutions', 'doc'],
                  ].map(([t, icon, href]) => {
                    const inner = (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--ink-dim)', fontSize: 14 }}>
                        <div style={{ width: 28, height: 28, borderRadius: 6, border: '1px solid var(--bg-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="var(--accent)" strokeWidth="1.4">
                            {icon === 'mail' && <><rect x="2" y="4" width="12" height="9" rx="1"/><path d="M2 5 L8 9 L14 5"/></>}
                            {icon === 'pin' && <><path d="M8 14 C8 14 13 9 13 6 A5 5 0 0 0 3 6 C3 9 8 14 8 14 Z"/><circle cx="8" cy="6" r="2"/></>}
                            {icon === 'doc' && <><rect x="3" y="2" width="10" height="12" rx="1"/><path d="M5 6 L11 6 M5 9 L11 9 M5 12 L9 12"/></>}
                            {icon === 'link' && <><path d="M7 9 A3 3 0 0 0 11 9 L13 7 A3 3 0 0 0 9 3 L8 4"/><path d="M9 7 A3 3 0 0 0 5 7 L3 9 A3 3 0 0 0 7 13 L8 12"/></>}
                          </svg>
                        </div>
                        <span style={{ wordBreak: 'break-word' }}>{t}</span>
                      </div>
                    );
                    if (href && href.startsWith('http')) {
                      return <a key={t} href={href} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>{inner}</a>;
                    }
                    return href ? <a key={t} href={href} style={{ textDecoration: 'none' }}>{inner}</a> : <div key={t}>{inner}</div>;
                  })}
                </div>
              </Reveal>
            </div>

            <Reveal delay={120}>
              <div style={{
                background: 'var(--bg-panel)', border: '1px solid var(--bg-line)',
                borderRadius: 16, padding: isMobile ? 20 : 32,
              }}>
                {!sent ? (
                  <form onSubmit={onSubmit} style={{ display: 'grid', gap: 16 }}>
                    <div className="mono" style={{ color: 'var(--accent)' }}>// REQUEST A DEMO</div>
                    <Field label="Your name" val={form.name} set={v => setForm({...form, name: v})} required/>
                    <Field label="Work email" val={form.email} set={v => setForm({...form, email: v})} type="email" required/>
                    <Field label="Company" val={form.company} set={v => setForm({...form, company: v})} required/>
                    <Field label="Your role" val={form.role} set={v => setForm({...form, role: v})} placeholder="Owner, Operations lead, VP..."/>
                    <Field label="Industry" val={form.industry} set={v => setForm({...form, industry: v})} placeholder="Field services, logistics, professional services..."/>
                    <div>
                      <Lab>What are you trying to solve?</Lab>
                      <textarea rows={4} value={form.focus} onChange={e => setForm({...form, focus: e.target.value})}
                        placeholder="Tell us about your business, the workflow or problem you'd like to solve, and any timeline you're working toward..."
                        style={{
                          width: '100%', background: 'var(--bg)', border: '1px solid var(--bg-line)',
                          borderRadius: 8, padding: 12, color: 'var(--ink)', fontFamily: 'var(--font-sans)',
                          fontSize: 14, resize: 'vertical', boxSizing: 'border-box',
                        }}/>
                    </div>
                    {error && (
                      <div style={{
                        padding: 12, borderRadius: 8,
                        background: 'rgba(244,114,128,0.08)',
                        border: '1px solid rgba(244,114,128,0.25)',
                        color: '#fda4af', fontSize: 13, lineHeight: 1.5,
                      }}>
                        {error} If the issue persists, email{' '}
                        <a href="mailto:hello@timegainai.com" style={{ color: 'inherit', textDecoration: 'underline' }}>
                          hello@timegainai.com
                        </a>{' '}
                        directly.
                      </div>
                    )}
                    <button
                      type="submit"
                      disabled={submitting}
                      className="btn btn-primary"
                      style={{
                        justifyContent: 'center', padding: '14px 20px', fontSize: 14,
                        opacity: submitting ? 0.6 : 1,
                        cursor: submitting ? 'not-allowed' : 'pointer',
                      }}
                    >
                      {submitting ? 'Sending...' : (
                        <>
                          Send request
                          <svg width="14" height="14" viewBox="0 0 12 12"><path d="M2 6h8M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </>
                      )}
                    </button>
                    <div style={{ fontSize: 11, color: 'var(--ink-faint)', fontFamily: 'var(--font-mono)', textAlign: 'center' }}>
                      Delivers to Baher directly · nothing shared
                    </div>
                  </form>
                ) : (
                  <div style={{ display: 'grid', gap: 20, padding: '20px 0' }}>
                    <div style={{
                      width: 56, height: 56, borderRadius: 28,
                      background: 'rgba(139,233,253,0.1)', border: '1px solid var(--accent)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <svg width="24" height="24" viewBox="0 0 24 24"><path d="M4 12 L10 18 L20 6" stroke="var(--accent)" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </div>
                    <div>
                      <div style={{ fontSize: 24, fontWeight: 500, marginBottom: 8, letterSpacing: '-0.02em' }}>Thanks. Your message is on its way.</div>
                      <p style={{ color: 'var(--ink-dim)', fontSize: 15, lineHeight: 1.5, margin: 0 }}>
                        We received your request and will reply within one business day.
                        If you would rather reach us directly, email hello@timegainai.com.
                      </p>
                    </div>
                    <button className="btn btn-ghost" onClick={() => setPage('home')}>Back to home</button>
                  </div>
                )}
              </div>
            </Reveal>
          </div>
        </div>
      </section>
    </div>
  );
}

function Lab({ children }) {
  return <div className="mono" style={{ fontSize: 10, marginBottom: 8, color: 'var(--ink-dim)' }}>{children}</div>;
}
function Field({ label, val, set, type='text', required, placeholder }) {
  return (
    <div>
      <Lab>{label}</Lab>
      <input type={type} value={val} onChange={e => set(e.target.value)} required={required} placeholder={placeholder} style={{
        width: '100%', background: 'var(--bg)', border: '1px solid var(--bg-line)',
        borderRadius: 8, padding: '12px 14px', color: 'var(--ink)', fontFamily: 'var(--font-sans)',
        fontSize: 14, outline: 'none', transition: 'border-color 0.2s', boxSizing: 'border-box',
      }}
      onFocus={e => e.target.style.borderColor = 'var(--accent)'}
      onBlur={e => e.target.style.borderColor = 'var(--bg-line)'}
      />
    </div>
  );
}

function LogoMarquee() {
  const tags = ['FIELD SERVICES', 'LOGISTICS', 'PROFESSIONAL SERVICES', 'CONSTRUCTION', 'REAL ESTATE', 'MANUFACTURING', 'HOME SERVICES', 'LEGAL', 'ACCOUNTING', 'ENGINEERING'];
  const loop = [...tags, ...tags, ...tags];
  return (
    <section style={{ padding: '24px 0', borderTop: '1px solid var(--bg-line)', borderBottom: '1px solid var(--bg-line)', overflow: 'hidden' }}>
      <div className="section" style={{ padding: '0 32px 12px' }}>
        <div className="mono" style={{ color: 'var(--ink-faint)', textAlign: 'center', fontSize: 11 }}>
          Industries we build for
        </div>
      </div>
      <div style={{ overflow: 'hidden' }}>
        <div style={{
          display: 'flex', gap: 64, width: 'max-content',
          animation: 'marquee-loop 60s linear infinite',
        }}>
          {loop.map((l, i) => (
            <div key={i} style={{
              fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500,
              color: 'var(--ink-faint)', letterSpacing: '0.12em', whiteSpace: 'nowrap',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{ width: 8, height: 8, borderRadius: 2, border: '1px solid var(--ink-faint)' }}/>
              {l}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.ContactPage = ContactPage;
window.LogoMarquee = LogoMarquee;
