/* global React */
const { useState: useStateContact } = React;

// ─────────────────────────────────────────────────────────────
// CONTACT
// ─────────────────────────────────────────────────────────────

const CONTACT_FORMSPREE = 'https://formspree.io/f/xdajlrzz';

const ContactScreen = ({ navigate }) => {
  const a = window.CS_DATA.agency;
  const [form, setForm] = useStateContact({ name: '', email: '', org: '', subject: '', message: '' });
  const [sent, setSent] = useStateContact(false);
  const [submitting, setSubmitting] = useStateContact(false);
  const [error, setError] = useStateContact(null);
  const update = (k) => (v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(CONTACT_FORMSPREE, {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _subject: `Enquiry · ${form.subject || form.name}`.trim(),
          _replyto: form.email,
          'Name':         form.name,
          'Email':        form.email,
          'Organisation': form.org || '(not provided)',
          'Subject':      form.subject,
          'Brief':        form.message,
          'Submitted from': typeof window !== 'undefined' ? window.location.href : '',
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error((data && data.error) || `Submission failed (${res.status}). Please email agency@centrestage.org.au directly.`);
      }
      setSent(true);
    } catch (err) {
      setError(err.message || 'Submission failed. Please try again or email agency@centrestage.org.au.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <main data-screen-label="Contact">
      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '56px 48px 96px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 48 }}>
          <Eyebrow style={{ color: 'var(--mid)' }}>Contact <Slash /> Head Office, Geelong</Eyebrow>
          <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
          <a href={`mailto:${a.email}`} className="cs-mono" style={{ color: 'var(--mid)', textDecoration: 'none' }}>
            {a.email}
          </a>
        </div>

        <h1 style={{
          fontFamily: 'var(--font-display)', fontWeight: 900,
          fontSize: 'clamp(64px, 11vw, 168px)', letterSpacing: '-0.035em', lineHeight: 0.88,
          margin: 0, color: 'var(--ink)', textWrap: 'balance',
        }}>
          The brief begins here.
        </h1>

        <p data-ee="standard" style={{ fontSize: 21, lineHeight: 1.5, color: 'var(--ink)', margin: '40px 0 0', maxWidth: '54ch' }}>
          For casting directors, producers, and industry partners. We represent talent Australia-wide with touchpoints across Geelong, Ballarat, Newcastle, Melbourne, Sydney and Brisbane.
        </p>
        <div data-ee="easy" style={{ marginTop: 40, maxWidth: '50ch', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <p style={{ fontSize: 20, lineHeight: 1.5, color: 'var(--ink)', margin: 0 }}>
            Want to talk to us?
          </p>
          <p style={{ fontSize: 18, lineHeight: 1.55, color: 'var(--ink)', margin: 0 }}>
            Send us an email or fill in the form on this page. We will reply in two work days.
          </p>
        </div>
      </section>

      {/* Editorial silhouette band */}
      <section style={{ background: 'var(--ink)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 1, background: 'var(--hairline-ink)' }}>
          {window.CS_DATA.cities.map((c, i) => (
            <div key={c} style={{ position: 'relative' }}>
              <Portrait
                src={window.CS_DATA.images.portraits[i].url}
                treatment={['mono','warm','cool','deep','mono','warm'][i % 6]}
                ratio="3 / 4" hoverScale={true}
                code={String(i + 1).padStart(2, '0')}
              />
              <div style={{
                position: 'absolute', bottom: 12, left: 14, right: 14,
                fontFamily: 'var(--font-display)', fontWeight: 900,
                fontSize: 'clamp(16px, 1.4vw, 22px)', letterSpacing: '-0.02em', lineHeight: 1,
                color: 'var(--paper)', textShadow: '0 1px 4px rgba(0,0,0,0.5)',
              }}>{c}</div>
            </div>
          ))}
        </div>
      </section>

      <Hairline />

      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '96px 48px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 96, alignItems: 'flex-start' }}>

          {/* Office card */}
          <div>
            <Eyebrow style={{ color: 'var(--mid)' }}>The studio</Eyebrow>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontWeight: 900,
              fontSize: 56, letterSpacing: '-0.025em', lineHeight: 0.95,
              margin: '20px 0 32px',
            }}>
              Head Office.<br/>Geelong.
            </h2>

            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--ink)', lineHeight: 1.8, letterSpacing: '0.02em' }}>
              <div>{a.address}</div>
              <div>{a.suburb}</div>
              <div style={{ color: 'var(--mid)' }}>{a.region}</div>
            </div>

            <div style={{ marginTop: 40, paddingTop: 32, borderTop: '1px solid var(--hairline)' }}>
              <Eyebrow style={{ color: 'var(--mid)' }}>National touchpoints</Eyebrow>
              <div style={{ marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--ink)', lineHeight: 1.8, letterSpacing: '0.02em' }}>
                {window.CS_DATA.cities.filter(c => c !== 'Geelong').map(c => (
                  <div key={c}>{c}</div>
                ))}
              </div>
            </div>

            <div style={{ marginTop: 40, paddingTop: 32, borderTop: '1px solid var(--hairline)' }}>
              <Eyebrow style={{ color: 'var(--mid)' }}>Direct</Eyebrow>
              <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
                <a href={`mailto:${a.email}`}
                   style={{
                     fontFamily: 'var(--font-sans)', fontSize: 22, fontWeight: 700,
                     letterSpacing: '-0.01em', color: 'var(--ink)', textDecoration: 'none',
                   }}
                   onMouseEnter={e => { e.currentTarget.style.textDecoration = 'underline'; e.currentTarget.style.textUnderlineOffset = '4px'; }}
                   onMouseLeave={e => { e.currentTarget.style.textDecoration = 'none'; }}>
                  {a.email}
                </a>
              </div>
            </div>

            <div style={{ marginTop: 40, paddingTop: 32, borderTop: '1px solid var(--hairline)' }}>
              <Eyebrow style={{ color: 'var(--mid)' }}>Social</Eyebrow>
              <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
                <a href={a.facebook} target="_blank" rel="noopener"
                   style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', textDecoration: 'none', color: 'var(--ink)', padding: '8px 0', borderBottom: '1px solid var(--hairline)' }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em' }}>Facebook</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.04em' }}>@centrestageausagency ↗</span>
                </a>
                <a href={a.instagram} target="_blank" rel="noopener"
                   style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', textDecoration: 'none', color: 'var(--ink)', padding: '8px 0', borderBottom: '1px solid var(--hairline)' }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em' }}>Instagram</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.04em' }}>@centrestageausagency ↗</span>
                </a>
              </div>
            </div>

            {/* Map placeholder */}
            <div style={{ marginTop: 40 }}>
              <Eyebrow style={{ color: 'var(--mid)' }}>Find us</Eyebrow>
              <div style={{
                marginTop: 16, position: 'relative', overflow: 'hidden',
                aspectRatio: '4 / 3', background: 'var(--ink)',
                border: '1px solid var(--ink)',
              }}>
                {/* Stylised map: grid + pin */}
                <svg viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
                  <rect width="400" height="300" fill="var(--ink)" />
                  {/* Roads */}
                  <g stroke="var(--mid)" strokeWidth="1" fill="none">
                    <line x1="0" y1="80" x2="400" y2="80" />
                    <line x1="0" y1="160" x2="400" y2="160" />
                    <line x1="0" y1="240" x2="400" y2="240" />
                    <line x1="80" y1="0" x2="80" y2="300" />
                    <line x1="200" y1="0" x2="200" y2="300" />
                    <line x1="320" y1="0" x2="320" y2="300" />
                  </g>
                  {/* Highway (Hamilton Hwy diagonal) */}
                  <line x1="0" y1="220" x2="400" y2="140" stroke="var(--paper)" strokeWidth="2" />
                  {/* Pin */}
                  <g transform="translate(200 160)">
                    <circle r="20" fill="none" stroke="var(--paper)" strokeWidth="1" opacity="0.4">
                      <animate attributeName="r" from="6" to="32" dur="3s" repeatCount="indefinite" />
                      <animate attributeName="opacity" from="0.6" to="0" dur="3s" repeatCount="indefinite" />
                    </circle>
                    <circle r="6" fill="var(--paper)" />
                  </g>
                  {/* Label */}
                  <text x="216" y="158" fill="var(--paper)" fontFamily="JetBrains Mono, monospace" fontSize="11" letterSpacing="1.2">
                    UNIT 2, 255 HAMILTON HWY
                  </text>
                  <text x="216" y="174" fill="var(--mid-soft)" fontFamily="JetBrains Mono, monospace" fontSize="10" letterSpacing="1.2">
                    FYANSFORD VIC 3221
                  </text>
                </svg>
              </div>
            </div>
          </div>

          {/* Form */}
          <div>
            {!sent ? (
              <form onSubmit={submit} noValidate>
                <Eyebrow style={{ color: 'var(--mid)' }}>Enquiry</Eyebrow>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontWeight: 900,
                  fontSize: 56, letterSpacing: '-0.025em', lineHeight: 0.95,
                  margin: '20px 0 56px',
                }}>
                  Casting briefs.<br/>Industry enquiries.
                </h2>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 36 }}>
                    <TextField label="Your name" name="name" required placeholder="First and last" value={form.name} onChange={update('name')} />
                    <TextField label="Email" name="email" type="email" required placeholder="you@studio.com" value={form.email} onChange={update('email')} />
                  </div>
                  <TextField label="Organisation" name="org" placeholder="Studio, production, or self" value={form.org} onChange={update('org')} hint="Optional" />
                  <TextField label="Subject" name="subject" placeholder="Casting · feature · shoot Q1 2026" value={form.subject} onChange={update('subject')} required />
                  <TextArea
                    label="Brief" name="message" required rows={6}
                    placeholder="A few lines on the role, the dates, and any talent you have in mind."
                    value={form.message} onChange={update('message')}
                  />
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em' }}>
                      {error
                        ? <span style={{ color: '#A8362A' }}>{error}</span>
                        : <span style={{ color: 'var(--mid)' }}>Reply window <span style={{ color: 'var(--ink)' }}>≤ 2 working days</span></span>}
                    </span>
                    <button type="submit" className="cs-btn"
                      style={{ opacity: submitting ? 0.4 : 1, pointerEvents: submitting ? 'none' : 'auto' }}>
                      {submitting ? 'Sending…' : 'Send enquiry'} <span style={{ marginLeft: 8 }}>→</span>
                    </button>
                  </div>
                </div>
              </form>
            ) : (
              <div style={{ border: '1px solid var(--hairline)', padding: 48 }}>
                <Eyebrow style={{ color: 'var(--mid)' }}>Received <Slash /> CST-{Math.floor(Math.random()*9000 + 1000)}</Eyebrow>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontWeight: 900,
                  fontSize: 64, letterSpacing: '-0.025em', lineHeight: 0.95,
                  margin: '20px 0 24px',
                }}>
                  Thank you.
                </h2>
                <p style={{ fontSize: 19, lineHeight: 1.55, color: 'var(--ink)', maxWidth: '40ch', margin: 0 }}>
                  Your enquiry has reached us. Expect a reply within two working days, sent from <a href={`mailto:${a.email}`} style={{ color: 'var(--ink)' }}>{a.email}</a>.
                </p>
                <div style={{ marginTop: 40 }}>
                  <Button onClick={(e) => { e.preventDefault(); navigate('home'); }}>Back to home</Button>
                </div>
              </div>
            )}
          </div>

        </div>
      </section>
    </main>
  );
};

Object.assign(window, { ContactScreen });
