/* CONTACT — short form + sales/support split. */

// Web3Forms access key — swap this (or the endpoint) here to change provider.
const WEB3FORMS_ACCESS_KEY = "ad2a1933-9007-401f-99bb-01db3e18c0a3";

function ContactPage() {
  const { isMobile } = useBreakpoint();
  const [sent, setSent] = React.useState(false);
  return (
    <div data-screen-label="06 Contact">
      <section style={{ background: 'var(--paper)', padding: `clamp(24px, 4vw, 40px) var(--pad-x) clamp(56px, 9vw, 96px)` }}>
        <div style={{ maxWidth: 'var(--container-lg)', margin: '0 auto' }}>
          <Breadcrumbs trail={[{ l: 'Contact' }]} />
          <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.05fr 1fr', gap: 'var(--gap-lg)', alignItems: 'start' }}>
            <div>
              <Eyebrow>Contact</Eyebrow>
              <h1 style={{
                fontFamily: 'var(--font-display)', fontWeight: 300,
                fontSize: 'clamp(44px, 7vw, 88px)', lineHeight: 0.98, letterSpacing: '-0.045em',
                color: 'var(--ink)', margin: '20px 0 0',
              }}>
                Let's <em style={{ fontStyle: 'italic' }}>talk.</em>
              </h1>
              <p style={{ marginTop: 24, fontSize: 'clamp(16px, 1.6vw, 18px)', lineHeight: 1.6, color: 'var(--graphite)', maxWidth: '48ch' }}>
                Got a season to shoot, a question on credits, or a managed-service brief? Drop a line and we'll come back within one business day.
              </p>

              <div style={{ marginTop: 40, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
                {[
                  { l: 'Sales',     v: 'sales@vizostudio.ai',    sub: 'Custom and Pro brands' },
                  { l: 'Support',   v: 'help@vizostudio.ai',     sub: 'Account & billing' },
                  { l: 'Press',     v: 'press@vizostudio.ai',    sub: 'Editorial & comment' },
                  { l: 'Studio',    v: 'London · Remote',        sub: 'GMT · Mon – Fri' },
                ].map((c) => (
                  <div key={c.l} style={{ paddingTop: 16, borderTop: '1px solid var(--bone)' }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--slate)' }}>{c.l}</div>
                    <div style={{ marginTop: 8, fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{c.v}</div>
                    <div style={{ marginTop: 4, fontSize: 13, color: 'var(--graphite)' }}>{c.sub}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Form card */}
            <div style={{ background: 'var(--canvas)', border: '1px solid var(--mist)', borderRadius: 12, padding: isMobile ? 24 : 36 }}>
              {sent ? (
                <SentState onReset={() => setSent(false)} />
              ) : (
                <ContactForm onSubmit={() => setSent(true)} />
              )}
            </div>
          </div>
        </div>
      </section>

      <CTABand />
    </div>
  );
}

function ContactForm({ onSubmit }) {
  const [topic, setTopic] = React.useState('sales');
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError(null);
    setSending(true);
    const fd = new FormData(e.target);
    const name = (fd.get('name') || '').toString().trim();
    const payload = {
      access_key: WEB3FORMS_ACCESS_KEY,
      name,
      email: fd.get('email'),
      brand: fd.get('brand'),
      topic,
      message: fd.get('message'),
      // Hidden fields so the notification email reads cleanly:
      subject: `New ViZO enquiry from ${name || 'website visitor'}`,
      from_name: name ? `${name} \u00b7 ViZO` : 'ViZO enquiry',
      botcheck: fd.get('botcheck') || '',
    };
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success !== false) {
        onSubmit();
      } else {
        setError((data && data.message) || 'Something went wrong. Please try again.');
        setSending(false);
      }
    } catch (err) {
      setError('Network error \u2014 please check your connection and try again.');
      setSending(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <Eyebrow>Send us a note</Eyebrow>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(24px, 3vw, 32px)', letterSpacing: '-0.02em', color: 'var(--ink)', margin: '12px 0 24px' }}>
        Tell us what you're working on.
      </h2>

      <Field label="Name">
        <input required name="name" type="text" placeholder="Your name" style={inputStyle} />
      </Field>
      <Field label="Work email">
        <input required name="email" type="email" placeholder="you@brand.com" style={inputStyle} />
      </Field>
      <Field label="Brand / company">
        <input name="brand" type="text" placeholder="Brand name" style={inputStyle} />
      </Field>

      <Field label="Topic">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {[
            { k: 'sales',   l: 'Sales' },
            { k: 'support', l: 'Support' },
            { k: 'press',   l: 'Press' },
            { k: 'other',   l: 'Other' },
          ].map((o) => (
            <button key={o.k} type="button" onClick={() => setTopic(o.k)} style={{
              appearance: 'none',
              border: '1px solid ' + (topic === o.k ? 'var(--ink)' : 'var(--mist)'),
              background: topic === o.k ? 'var(--ink)' : 'transparent',
              color: topic === o.k ? 'var(--canvas)' : 'var(--ink)',
              fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
              padding: '7px 14px', borderRadius: 999, cursor: 'pointer',
              transition: 'all 200ms var(--ease-standard)',
            }}>{o.l}</button>
          ))}
        </div>
      </Field>

      <Field label="Message">
        <textarea required name="message" rows={5} placeholder="Briefly: what would you like to shoot, ship, or solve?" style={{ ...inputStyle, height: 'auto', padding: '12px 14px', resize: 'vertical', minHeight: 120 }} />
      </Field>

      {/* Honeypot — hidden from humans, catches bots */}
      <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ display: 'none' }} />

      {error &&
      <p role="alert" style={{ marginTop: 20, marginBottom: 0, fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.5, color: '#b3261e' }}>
        {error}
      </p>
      }

      <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--slate)', letterSpacing: '0.04em' }}>Reply within 1 business day</span>
        <Button variant="primary" size="large" arrow={!sending} style={{ opacity: sending ? 0.6 : 1, pointerEvents: sending ? 'none' : 'auto' }}>{sending ? 'Sending\u2026' : 'Send message'}</Button>
      </div>
    </form>
  );
}

function SentState({ onReset }) {
  return (
    <div style={{ textAlign: 'center', padding: '24px 8px' }}>
      <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--ink)', color: 'var(--canvas)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}>
        <Icon.check width="24" height="24" />
      </div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(26px, 3.5vw, 40px)', letterSpacing: '-0.02em', color: 'var(--ink)', margin: '20px 0 12px' }}>Message received.</h2>
      <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--graphite)', maxWidth: '36ch', margin: '0 auto' }}>
        We'll be back within one business day, usually faster. Check your inbox — we may need a sample to look at first.
      </p>
      <div style={{ marginTop: 28 }}>
        <Button variant="ghost" size="medium" onClick={onReset}>Send another</Button>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display: 'block', marginTop: 16 }}>
      <span style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--slate)', marginBottom: 8 }}>{label}</span>
      {children}
    </label>
  );
}

const inputStyle = {
  width: '100%', height: 44, padding: '0 14px',
  background: 'var(--paper)',
  border: '1px solid var(--mist)', borderRadius: 6,
  fontFamily: 'var(--font-sans)', fontSize: 15, color: 'var(--ink)',
  outline: 'none', transition: 'border-color 200ms var(--ease-standard)',
};

Object.assign(window, { ContactPage });
