// ZION BookingPage — fill-in form for collabs/events.
// Sends to the partnerships inbox. On submit it opens the user's default mail
// client with all fields pre-populated as a structured email.

function BookingPage({ onBack }) {
  const TO = (typeof window !== 'undefined' && window.ZION_PARTNERSHIPS_EMAIL) || 'partnerships@levizion.com';

  const [form, setForm] = React.useState({
    name: '', brand: '', email: '', phone: '',
    eventType: 'Festival',
    date: '', location: '',
    audience: '', budget: '',
    details: '',
  });
  const [sent, setSent] = React.useState(false);
  const [agree, setAgree] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const update = (key) => (e) => setForm(f => ({ ...f, [key]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErr('');
    if (!agree) { setErr('Please confirm you’ve read the Safety guidelines and Terms & Policy.'); return; }
    const subject = `Booking · ${form.name || 'unnamed'}${form.brand ? ` (${form.brand})` : ''}`;
    const endpoint = (typeof window !== 'undefined' && window.ZION_BOOKING_ENDPOINT) || '';
    if (endpoint) {
      const data = {
        _subject: subject, _template: 'table', _honey: '',
        name: form.name, brand_company: form.brand, email: form.email, phone: form.phone,
        event_type: form.eventType, date: form.date, location: form.location,
        expected_audience: form.audience, budget: form.budget, details: form.details,
        safety_and_terms_agreed: 'Yes',
      };
      try {
        setBusy(true);
        const r = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(data) });
        if (r.ok) { setTimeout(() => { setBusy(false); setSent(true); }, 1450); } // let the STAY LIT do one full sweep, then show success
        else { setErr('Could not send. Please try again, or email ' + TO); setBusy(false); }
      } catch (e2) { setErr('Could not send. Check your connection.'); setBusy(false); }
    } else {
      // Fallback: open the visitor's mail client
      const body = [
        `Name: ${form.name}`, `Brand / company: ${form.brand}`, `Email: ${form.email}`, `Phone: ${form.phone}`, ``,
        `Event type: ${form.eventType}`, `Date: ${form.date}`, `Location: ${form.location}`,
        `Expected audience: ${form.audience}`, `Budget: ${form.budget}`, ``,
        `Details:`, form.details, ``, `Safety & Terms agreed: Yes`, `Sent via thefireballguy.com booking form`,
      ].join('\n');
      window.location.href = `mailto:${TO}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      setSent(true);
    }
  };

  return (
    <main style={{ background: '#0A0A0A', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      {/* Top ember wash */}
      <div aria-hidden style={{
        position: 'absolute', top: 0, left: 0, right: 0,
        height: 'clamp(200px, 22vw, 360px)', pointerEvents: 'none', zIndex: 0,
        background:
          'radial-gradient(ellipse 90% 70% at 50% 0%, #3A0F08 0%, rgba(58,15,8,0.4) 40%, rgba(10,10,10,0) 100%)',
      }} />

      <div style={{ position: 'relative', zIndex: 1, maxWidth: 880, margin: '0 auto', padding: '80px 32px 120px' }}>
        <a onClick={onBack} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
          fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)',
          marginBottom: 48, textDecoration: 'none',
        }}>← BACK</a>

        <div style={{
          fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.22em',
          textTransform: 'uppercase', color: '#F7591F', marginBottom: 12, textAlign: 'center',
        }}>Fire Performance</div>

        <h1 style={{
          fontFamily: 'Poppins, sans-serif', fontWeight: 900, fontStyle: 'italic',
          fontSize: 'clamp(56px, 9vw, 140px)',
          lineHeight: 0.95, letterSpacing: '-0.025em', textTransform: 'uppercase',
          margin: '4px 0 24px', color: '#fff', textAlign: 'center',
        }}>Events<span style={{ color: '#F7591F' }}>.</span></h1>

        <p style={{
          fontFamily: 'Poppins', fontWeight: 400,
          fontSize: 'clamp(15px, 1.2vw, 18px)', lineHeight: 1.7,
          color: 'rgba(255,255,255,0.78)', maxWidth: '56ch', margin: '0 auto 22px', textAlign: 'center',
        }}>
          Real <span style={{ color: '#F7591F', fontWeight: 700 }}>flaming</span> soccer ball.
          The Fireball Guy brings the <span style={{ color: '#F7591F', fontWeight: 700 }}>fireball</span> to
          festivals, brand activations, content shoots and private events worldwide. A new kind of
          sports entertainment built to stop a crowd. Bring it to your stage.
        </p>

        {/* Credibility tagline */}
        <div style={{
          fontFamily: 'Poppins', fontWeight: 700, fontSize: 11.5, letterSpacing: '0.18em',
          textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)', textAlign: 'center', margin: '0 0 40px',
        }}>
          Festivals · Brand activations · TV · Hotel & Resorts
        </div>

        {/* Event reels — coverflow showcase */}
        {window.EventReels && <window.EventReels />}

        {/* Glowing fire divider between the reels and the booking form */}
        <div style={{ position: 'relative', height: 1, margin: '54px auto 50px', maxWidth: 560,
          background: 'linear-gradient(90deg, transparent 0%, rgba(247,89,31,0.85) 50%, transparent 100%)' }}>
          <div aria-hidden style={{
            position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)',
            width: 340, height: 46, pointerEvents: 'none',
            background: 'radial-gradient(ellipse 50% 100% at 50% 50%, rgba(247,89,31,0.5) 0%, rgba(247,89,31,0) 70%)',
            filter: 'blur(8px)',
          }} />
        </div>

        {/* Booking section */}
        <h2 style={{
          fontFamily: 'Poppins, sans-serif', fontWeight: 900, fontStyle: 'italic',
          fontSize: 'clamp(28px, 4vw, 50px)', lineHeight: 1, letterSpacing: '-0.02em',
          textTransform: 'uppercase', margin: '0 0 10px', color: '#fff', textAlign: 'center',
        }}>Book the fireball guy<span style={{ color: '#F7591F' }}>.</span></h2>
        <p style={{
          fontFamily: 'Poppins', fontWeight: 400, fontSize: 15, lineHeight: 1.65,
          color: 'rgba(255,255,255,0.6)', margin: '0 auto 36px', maxWidth: '54ch', textAlign: 'center',
        }}>
          Tell us what you have in mind. The more detail, the faster we come back to you. Replies usually within 48 hours.
        </p>

        <form onSubmit={handleSubmit}>
          {/* Row: name + brand */}
          <Row>
            <Field label="Your name" required>
              <Input value={form.name} onChange={update('name')} required placeholder="Your full name" />
            </Field>
            <Field label="Brand / company">
              <Input value={form.brand} onChange={update('brand')} placeholder="Red Bull" />
            </Field>
          </Row>

          {/* Row: email + phone */}
          <Row>
            <Field label="Email" required>
              <Input type="email" value={form.email} onChange={update('email')} required placeholder="you@brand.com" />
            </Field>
            <Field label="Phone (optional)">
              <Input value={form.phone} onChange={update('phone')} placeholder="+1 555 ..." />
            </Field>
          </Row>

          {/* Row: event type + date */}
          <Row>
            <Field label="Event type">
              <Select value={form.eventType} onChange={update('eventType')}>
                {['Festival','Brand activation','Content shoot','Private event','TV / film','Other'].map(o =>
                  <option key={o} value={o}>{o}</option>
                )}
              </Select>
            </Field>
            <Field label="Date">
              <Input type="date" value={form.date} onChange={update('date')} />
            </Field>
          </Row>

          {/* Row: location + audience */}
          <Row>
            <Field label="Location" required>
              <Input value={form.location} onChange={update('location')} required placeholder="City, country" />
            </Field>
            <Field label="Expected audience">
              <Input value={form.audience} onChange={update('audience')} placeholder="e.g. 5,000" />
            </Field>
          </Row>

          {/* Budget */}
          <Field label="Budget">
            <Input value={form.budget} onChange={update('budget')} placeholder="USD, rough range is fine" />
          </Field>

          {/* Details */}
          <Field label="Tell us what you have in mind" required>
            <Textarea
              value={form.details}
              onChange={update('details')}
              required
              rows={6}
              placeholder="Stage, run-of-show, who else is performing, content output, anything else we should know…"
            />
          </Field>

          {/* Safety & terms acknowledgment (required) */}
          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', marginTop: 6 }}>
            <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ width: 18, height: 18, marginTop: 2, accentColor: '#F7591F', flexShrink: 0 }} />
            <span style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 12.5, lineHeight: 1.5, color: 'rgba(255,255,255,0.72)' }}>
              I confirm I've read the <strong style={{ color: '#fff' }}>Safety guidelines</strong> and <strong style={{ color: '#fff' }}>Terms &amp; Policy</strong>, and understand fire performances involve real, open flame and inherent risk.
            </span>
          </label>

          {err && <div style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 12.5, color: '#FF7A66', lineHeight: 1.5, marginTop: 6 }}>{err}</div>}

          {/* Submit */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 16, flexWrap: 'wrap' }}>
            <SubmitButton>{busy ? 'Sending…' : (sent ? '✓ Request sent' : 'Send request')}</SubmitButton>
            <span style={{
              fontFamily: 'Poppins', fontSize: 12, color: 'rgba(255,255,255,0.55)',
              letterSpacing: '0.06em',
            }}>
              {sent
                ? `Thanks — we'll reply within 48 hours.`
                : `Goes straight to ${TO}`}
            </span>
          </div>
        </form>

        {/* Direct email fallback */}
        <div style={{
          marginTop: 56, padding: '24px 0',
          borderTop: '1px solid rgba(255,255,255,0.12)',
          fontFamily: 'Poppins', fontSize: 14, color: 'rgba(255,255,255,0.7)',
        }}>
          Prefer email? Reach out directly at{' '}
          <a href={`mailto:${TO}`} style={{
            color: '#F7591F', textDecoration: 'none', fontWeight: 600,
          }}>{TO}</a>
        </div>
      </div>

      {/* Submit feedback — sending (STAY LIT loader) → sent confirmation */}
      {(busy || sent) && ReactDOM.createPortal(
        <div style={{
          position: 'fixed', inset: 0, zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
          background: 'rgba(8,6,4,0.88)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
        }}>
          <div style={{
            width: '100%', maxWidth: 440, textAlign: 'center',
            background: 'linear-gradient(180deg, #161310 0%, #0A0A0A 100%)',
            border: '1px solid rgba(247,89,31,0.4)', borderRadius: 20,
            padding: '46px 34px', boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
          }}>
            {!sent ? (
              <>
                <div className="zion-staylit-once" style={{ margin: '0 auto 20px' }} />
                <div style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 13, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)' }}>Sending your request…</div>
              </>
            ) : (
              <>
                <div style={{
                  width: 74, height: 74, margin: '0 auto 22px', borderRadius: '50%',
                  background: 'radial-gradient(circle at 50% 35%, #F7591F 0%, #B8390C 100%)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: '0 0 0 6px rgba(247,89,31,0.16), 0 16px 44px rgba(247,89,31,0.42)',
                }}>
                  <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12l5 5L20 6" /></svg>
                </div>
                <h3 style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 900, fontStyle: 'italic', textTransform: 'uppercase', fontSize: 30, lineHeight: 1, margin: '0 0 12px', color: '#fff' }}>Request sent<span style={{ color: '#F7591F' }}>.</span></h3>
                <p style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 14.5, lineHeight: 1.6, color: 'rgba(255,255,255,0.78)', margin: '0 0 6px' }}>
                  Thanks{form.name ? ', ' + form.name.split(' ')[0] : ''} — we've got your booking and we'll get back to you within <span style={{ color: '#fff', fontWeight: 600 }}>48 hours</span>.
                </p>
                <div className="zion-staylit-static" style={{ margin: '20px auto 24px', opacity: 0.95 }} />
                <button onClick={() => { setSent(false); setAgree(false); setForm({ name: '', brand: '', email: '', phone: '', eventType: 'Festival', date: '', location: '', audience: '', budget: '', details: '' }); }} style={{
                  background: '#F7591F', color: '#fff', border: 'none', cursor: 'pointer',
                  fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase',
                  padding: '14px 36px', borderRadius: 999, boxShadow: '0 10px 28px rgba(247,89,31,0.4)',
                }}>Done</button>
              </>
            )}
          </div>
        </div>,
        document.body
      )}
    </main>
  );
}

/* ===== form atoms =========================================== */

function Row({ children }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)',
      gap: 20, marginBottom: 20,
    }}>{children}</div>
  );
}

function Field({ label, required, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
      <span style={{
        fontFamily: 'Poppins', fontWeight: 600, fontSize: 12,
        letterSpacing: '0.14em', textTransform: 'uppercase',
        color: 'rgba(255,255,255,0.65)',
      }}>
        {label} {required && <span style={{ color: '#F7591F' }}>*</span>}
      </span>
      {children}
    </label>
  );
}

const inputBase = {
  fontFamily: 'Poppins, sans-serif', fontWeight: 500, fontSize: 15,
  color: '#fff',
  background: 'rgba(255,255,255,0.04)',
  border: '1px solid rgba(255,255,255,0.16)',
  borderRadius: 10,
  padding: '14px 16px',
  outline: 'none', width: '100%', boxSizing: 'border-box',
  transition: 'border-color 160ms, background 160ms, box-shadow 200ms',
};

function Input(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <input
      {...props}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        ...inputBase,
        borderColor: focus ? '#F7591F' : 'rgba(255,255,255,0.16)',
        boxShadow: focus ? '0 0 0 3px rgba(247,89,31,0.18)' : 'none',
      }}
    />
  );
}

function Textarea(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <textarea
      {...props}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        ...inputBase, resize: 'vertical', lineHeight: 1.5,
        borderColor: focus ? '#F7591F' : 'rgba(255,255,255,0.16)',
        boxShadow: focus ? '0 0 0 3px rgba(247,89,31,0.18)' : 'none',
      }}
    />
  );
}

function Select(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <select
      {...props}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        ...inputBase, appearance: 'none',
        backgroundImage:
          'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 12 8\' fill=\'none\' stroke=\'%23F7591F\' stroke-width=\'2\'><path d=\'M1 1 L6 6 L11 1\'/></svg>")',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'right 16px center',
        backgroundSize: '12px 8px',
        paddingRight: 40,
        borderColor: focus ? '#F7591F' : 'rgba(255,255,255,0.16)',
        boxShadow: focus ? '0 0 0 3px rgba(247,89,31,0.18)' : 'none',
      }}
    />
  );
}

function SubmitButton({ children }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  return (
    <button type="submit"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        fontFamily: 'Poppins, sans-serif', fontWeight: 800,
        fontSize: 14, letterSpacing: '0.14em', textTransform: 'uppercase',
        background: hover ? '#C8420E' : '#F7591F', color: '#fff',
        border: 'none', borderRadius: 999,
        padding: '18px 48px', cursor: 'pointer',
        boxShadow: hover
          ? '0 0 24px rgba(247,89,31,0.55), 0 8px 28px rgba(247,89,31,0.35)'
          : '0 8px 28px rgba(247,89,31,0.35)',
        transform: press ? 'scale(0.985)' : 'scale(1)',
        transition: 'transform 120ms cubic-bezier(0.7,0,0.2,1), background 140ms, box-shadow 200ms',
        display: 'inline-flex', alignItems: 'center', gap: 10,
      }}>
      {children}
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M5 12 H19" />
        <path d="M13 6 L19 12 L13 18" />
      </svg>
    </button>
  );
}

window.BookingPage = BookingPage;
