/* Pricing, FAQ, Contact, Footer, Booking Modal */


function FAQ() {
  const [open, setOpen] = React.useState(0);
  const items = [
    {
      q: "We're a small club. Are we too small?",
      a: "Probably not. If you have a written prospectus and a handful of existing or potential sponsors, there's usually enough to work with. The discovery call is where we figure that out honestly. We'll tell you if we're not the right fit.",
    },
    {
      q: "Do you take over our existing sponsor relationships?",
      a: "We become the day-to-day point of contact, but everything goes out under your club's name. Sponsors still feel like they're partnering with your club, because they are. We're the engine room, not the brand.",
    },
    {
      q: "How is this different from a marketing agency?",
      a: "We don't do creative, social media, or brand work. We do the unglamorous, high-leverage commercial work: managing renewals, building target lists, sending pitches, and booking meetings. It's a narrow scope on purpose.",
    },
    {
      q: "What's the minimum commitment?",
      a: "Foundation is month-to-month from day one. Growth has a 3-month minimum so we can actually generate momentum, then it's month-to-month. Performance is a 6-month engagement because outreach cycles take that long to compound.",
    },
    {
      q: "Do you work outside of football?",
      a: "Not yet. We're deliberately focused on grassroots and community football across Australia so we know the market, the audience, and what a realistic local sponsorship deal actually looks like.",
    },
    {
      q: "What does the club need to provide?",
      a: "Your current prospectus, a list of existing and past sponsors, and roughly an hour a month of one committee member's time for an update call. That's it. We do the rest.",
    },
  ];
  return (
    <section id="faq">
      <div className="container">
        <div className="faq-grid">
          <div className="reveal">
            <span className="eyebrow">FAQ</span>
            <h2 className="h2" style={{ marginTop: 16 }}>Common questions from club committees.</h2>
            <p className="lede" style={{ marginTop: 24 }}>
              If yours isn't here, ask it on the discovery call. We'd rather over-explain than under-deliver.
            </p>
          </div>
          <div className="faq-list reveal delay-1">
            {items.map((it, i) => (
              <div key={i} className={`faq-item${open === i ? ' open' : ''}`}>
                <button className="q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                  <span>{it.q}</span>
                  <span className="plus" aria-hidden="true"></span>
                </button>
                <div className="a"><p>{it.a}</p></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Contact({ onBook }) {
  const [form, setForm] = React.useState({ name: '', club: '', email: '', message: '' });
  const [touched, setTouched] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const errors = {};
  if (!form.name.trim()) errors.name = 'Required';
  if (!form.club.trim()) errors.club = 'Required';
  if (!form.email.trim()) errors.email = 'Required';
  else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errors.email = 'Invalid email';
  if (!form.message.trim()) errors.message = 'Required';

  const isValid = Object.keys(errors).length === 0;

  const showErr = (k) => touched[k] && errors[k];

  const onChange = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const onBlur = (k) => () => setTouched({ ...touched, [k]: true });

  const onSubmit = (e) => {
    e.preventDefault();
    setTouched({ name: true, club: true, email: true, message: true });
    if (!isValid) return;
    setSubmitting(true);
    fetch('https://formspree.io/f/xkoeodar', {
      method: 'POST',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: form.name, club: form.club, email: form.email, message: form.message }),
    })
      .then((res) => {
        setSubmitting(false);
        if (res.ok) {
          setSubmitted(true);
        } else {
          alert('Something went wrong. Please email us directly at hello@clubsidecommercial.com');
        }
      })
      .catch(() => {
        setSubmitting(false);
        alert('Something went wrong. Please email us directly at hello@clubsidecommercial.com');
      });
  };

  return (
    <section id="contact" className="contact-section">
      <svg
        style={{ position: 'absolute', bottom: '-180px', left: '-160px', width: '520px', height: '520px', color: '#fff', opacity: 0.07, pointerEvents: 'none' }}
        viewBox="0 0 520 520" fill="none" stroke="currentColor" strokeWidth="1.2"
        aria-hidden="true"
      >
        <circle cx="260" cy="260" r="255" />
        <circle cx="260" cy="260" r="140" />
        <circle cx="260" cy="260" r="40" />
      </svg>
      <div className="container" style={{ position: 'relative', zIndex: 1 }}>
        <div className="section-head reveal">
          <div className="col-left">
            <span className="eyebrow">Ready to talk?</span>
            <h2 className="h2">Let's see if there's<br/>something worth doing.</h2>
          </div>
          <div className="col-right">
            <p className="lede">
              Drop your details and a few sentences about your club. We'll come back within one business day with thoughts, honest feedback, and a time for a call if it makes sense.
            </p>
          </div>
        </div>

        <div className="contact-grid">
          <div className="contact-side reveal">
            <div className="item">
              <span className="label">Email</span>
              <span className="value">hello@clubsidecommercial.com</span>
            </div>
            <div className="item">
              <span className="label">Response time</span>
              <span className="value">Within one business day</span>
            </div>
            <div className="item">
              <span className="label">Based in</span>
              <span className="value">Brisbane · Working Australia-wide</span>
            </div>

            <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 16 }}>
              <span className="label" style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>
                Prefer to book straight in?
              </span>
              <button onClick={onBook} className="btn btn-secondary" style={{
                background: 'transparent',
                color: '#fff',
                borderColor: 'rgba(255,255,255,0.3)',
                alignSelf: 'flex-start'
              }}>
                <Icon.Calendar /> Book a 30-min discovery call
              </button>
            </div>
          </div>

          <div className="reveal delay-1">
            {submitted ? (
              <div className="form-success">
                <div className="check"><Icon.Check size={24} /></div>
                <h3>Thanks, {form.name.split(' ')[0]}.</h3>
                <p>We've got it. We'll reply to <strong style={{ color: '#fff' }}>{form.email}</strong> within one business day, usually faster.</p>
                <button onClick={() => { setSubmitted(false); setForm({ name: '', club: '', email: '', message: '' }); setTouched({}); }} className="btn btn-ghost btn-sm" style={{ color: 'rgba(255,255,255,0.8)' }}>
                  Send another message
                </button>
              </div>
            ) : (
              <form className="contact-form" onSubmit={onSubmit} noValidate>
                <div className="form-row">
                  <div className={`field${showErr('name') ? ' invalid' : ''}`}>
                    <label htmlFor="name">Your name</label>
                    <input id="name" type="text" placeholder="Jane Treasurer" value={form.name} onChange={onChange('name')} onBlur={onBlur('name')} />
                    {showErr('name') && <span className="err">{errors.name}</span>}
                  </div>
                  <div className={`field${showErr('club') ? ' invalid' : ''}`}>
                    <label htmlFor="club">Club name</label>
                    <input id="club" type="text" placeholder="Westbridge FC" value={form.club} onChange={onChange('club')} onBlur={onBlur('club')} />
                    {showErr('club') && <span className="err">{errors.club}</span>}
                  </div>
                </div>
                <div className={`field${showErr('email') ? ' invalid' : ''}`}>
                  <label htmlFor="email">Email</label>
                  <input id="email" type="email" placeholder="you@yourclub.com.au" value={form.email} onChange={onChange('email')} onBlur={onBlur('email')} />
                  {showErr('email') && <span className="err">{errors.email}</span>}
                </div>
                <div className={`field${showErr('message') ? ' invalid' : ''}`}>
                  <label htmlFor="message">A bit about your club</label>
                  <textarea id="message" placeholder="Where you're at, what's working, what isn't. A few sentences is plenty." rows="4" value={form.message} onChange={onChange('message')} onBlur={onBlur('message')} />
                  {showErr('message') && <span className="err">{errors.message}</span>}
                </div>
                <div className="form-actions">
                  <span className="form-note">We never share your details. Ever.</span>
                  <button type="submit" className="btn-submit" disabled={submitting}>
                    {submitting ? 'Sending…' : <>Send message <Icon.Arrow /></>}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-top">
          <div>
            <a href="#top" className="wordmark" style={{ fontSize: 22 }}>
              <span className="dot"></span>
              Clubside <span className="lite">Commercial</span>
            </a>
            <p className="footer-blurb">
              The outsourced commercial team for grassroots and community football clubs across Australia.
            </p>
          </div>
          <div className="footer-col">
            <h5>Service</h5>
            <ul>
              <li><a href="#services">Sponsor Retention</a></li>
              <li><a href="#services">Sponsor Acquisition</a></li>
              <li><a href="#pricing">Pricing</a></li>
              <li><a href="#process">How it works</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>
              <li><a href="#about">About</a></li>
              <li><a href="#faq">FAQ</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Get in touch</h5>
            <ul>
              <li><a href="mailto:hello@clubsidecommercial.com">hello@clubsidecommercial.com</a></li>
              <li><a href="#contact">Send a message</a></li>
              <li><a href="#contact">Book a call</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-mark">
          <span className="dot"></span>
          Clubside <span className="lite">Commercial.</span>
        </div>

        <div className="footer-bottom">
          <span>© 2026 Clubside Commercial</span>
          <span>Made in Australia</span>
        </div>
      </div>
    </footer>
  );
}

/* Booking Modal */
function BookingModal({ open, onClose }) {
  const today = new Date();
  today.setHours(0,0,0,0);
  const [view, setView] = React.useState({ y: today.getFullYear(), m: today.getMonth() });
  const [selDate, setSelDate] = React.useState(null);
  const [selTime, setSelTime] = React.useState(null);
  const [step, setStep] = React.useState('pick'); // pick | details | confirmed
  const [details, setDetails] = React.useState({ name: '', club: '', email: '' });
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      setStep('pick');
      setSelDate(null);
      setSelTime(null);
      setDetails({ name: '', club: '', email: '' });
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const monthName = new Date(view.y, view.m, 1).toLocaleString('en-AU', { month: 'long', year: 'numeric' });
  const firstDay = new Date(view.y, view.m, 1);
  const daysInMonth = new Date(view.y, view.m + 1, 0).getDate();
  const startOffset = (firstDay.getDay() + 6) % 7;

  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push({ muted: true });
  for (let d = 1; d <= daysInMonth; d++) {
    const date = new Date(view.y, view.m, d);
    const dow = date.getDay();
    const isPast = date < today;
    const isWeekend = dow === 0 || dow === 6;
    cells.push({
      day: d,
      date,
      disabled: isPast || isWeekend,
      today: date.getTime() === today.getTime(),
    });
  }
  while (cells.length % 7 !== 0) cells.push({ muted: true });

  const times = ['9:00 AM', '10:30 AM', '12:00 PM', '1:30 PM', '3:00 PM', '4:30 PM', '5:30 PM', '6:30 PM'];

  const fmtDate = (d) => d?.toLocaleDateString('en-AU', { weekday: 'long', day: 'numeric', month: 'long' });

  const canNext = selDate && selTime;
  const canSubmit = details.name.trim() && details.club.trim() && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(details.email);

  const onSubmitDetails = (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setSubmitting(true);
    fetch('https://formspree.io/f/xkoeodar', {
      method: 'POST',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
      body: JSON.stringify({
        type: 'Booking Request',
        name: details.name,
        club: details.club,
        email: details.email,
        date: fmtDate(selDate),
        time: selTime,
      }),
    })
      .then((res) => {
        setSubmitting(false);
        if (res.ok) {
          setStep('confirmed');
        } else {
          alert('Something went wrong. Please email us directly at hello@clubsidecommercial.com');
        }
      })
      .catch(() => {
        setSubmitting(false);
        alert('Something went wrong. Please email us directly at hello@clubsidecommercial.com');
      });
  };

  return (
    <div className={`modal-backdrop${open ? ' open' : ''}`} onClick={onClose} role="dialog" aria-modal="true" aria-label="Book a discovery call">
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ display: 'flex', flexDirection: 'row', height: 'min(720px, calc(100vh - 48px))' }}>
        <div className="modal-side" style={{ flex: '0 0 42%', overflowY: 'auto' }}>
          <button className="modal-close" onClick={onClose} aria-label="Close"><Icon.Close /></button>
          <span className="eyebrow">Book a discovery call</span>
          <h3>30 minutes.<br/>No pitch deck.</h3>
          <p className="desc">
            A short conversation to understand where your club is at and whether there's a fit. We'll come prepared.
          </p>
          <div className="details">
            <div className="row"><Icon.Clock /> 30 minutes</div>
            <div className="row"><Icon.Video /> Video or phone, your pick</div>
            <div className="row"><Icon.Calendar /> Times shown in your local time</div>
          </div>
        </div>
        <div className="modal-main" style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
          {step === 'pick' && (
            <React.Fragment>
              <div className="cal-head">
                <h4>{monthName}</h4>
                <div className="cal-nav">
                  <button
                    onClick={() => setView({ y: view.m === 0 ? view.y - 1 : view.y, m: (view.m + 11) % 12 })}
                    aria-label="Previous month"
                    disabled={view.y === today.getFullYear() && view.m === today.getMonth()}
                    style={view.y === today.getFullYear() && view.m === today.getMonth() ? { opacity: 0.3, cursor: 'not-allowed' } : {}}
                  >
                    <Icon.ChevL />
                  </button>
                  <button
                    onClick={() => setView({ y: view.m === 11 ? view.y + 1 : view.y, m: (view.m + 1) % 12 })}
                    aria-label="Next month"
                  >
                    <Icon.ChevR />
                  </button>
                </div>
              </div>

              <div className="cal-grid">
                {['M','T','W','T','F','S','S'].map((d, i) => <div key={i} className="cal-dow">{d}</div>)}
                {cells.map((c, i) => {
                  if (c.muted) return <div key={i} className="cal-day muted"></div>;
                  const isSel = selDate && selDate.getTime() === c.date.getTime();
                  return (
                    <button
                      key={i}
                      className={`cal-day${c.disabled ? ' disabled' : ''}${isSel ? ' selected' : ''}${c.today ? ' today' : ''}`}
                      onClick={() => !c.disabled && (setSelDate(c.date), setSelTime(null))}
                      disabled={c.disabled}
                    >
                      {c.day}
                    </button>
                  );
                })}
              </div>

              {selDate && (
                <React.Fragment>
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
                    AVAILABLE TIMES · {fmtDate(selDate).toUpperCase()}
                  </div>
                  <div className="cal-times">
                    {times.map((t) => (
                      <button
                        key={t}
                        className={`cal-time${selTime === t ? ' selected' : ''}`}
                        onClick={() => setSelTime(t)}
                      >
                        {t}
                      </button>
                    ))}
                  </div>
                </React.Fragment>
              )}

              <div className="cal-confirm">
                <div className="summary">
                  {canNext ? (
                    <span><strong>{fmtDate(selDate)}</strong> at <strong>{selTime}</strong></span>
                  ) : (
                    <span>{selDate ? 'Pick a time' : 'Pick a day to see times'}</span>
                  )}
                </div>
                <button
                  className="btn btn-primary"
                  disabled={!canNext}
                  style={canNext ? {} : { opacity: 0.4, cursor: 'not-allowed' }}
                  onClick={() => canNext && setStep('details')}
                >
                  Next <Icon.Arrow />
                </button>
              </div>
            </React.Fragment>
          )}

          {step === 'details' && (
            <form onSubmit={onSubmitDetails} style={{ display: 'flex', flexDirection: 'column', gap: 20, height: '100%' }}>
              <div>
                <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 6 }}>
                  YOUR BOOKING
                </div>
                <div style={{ fontFamily: 'var(--f-display)', fontSize: 17, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
                  {fmtDate(selDate)} at {selTime}
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 24, flex: 1 }}>
                {[
                  { label: 'Your name', type: 'text', key: 'name', placeholder: 'Jane Treasurer' },
                  { label: 'Club name', type: 'text', key: 'club', placeholder: 'Westbridge FC' },
                  { label: 'Email', type: 'email', key: 'email', placeholder: 'you@yourclub.com.au' },
                ].map(({ label, type, key, placeholder }) => (
                  <div key={key} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    <span style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>{label}</span>
                    <input
                      type={type}
                      placeholder={placeholder}
                      value={details[key]}
                      onChange={e => setDetails({...details, [key]: e.target.value})}
                      required
                      style={{
                        background: 'transparent',
                        border: 'none',
                        borderBottom: '1px solid var(--line-strong)',
                        padding: '10px 0',
                        fontSize: 16,
                        color: 'var(--ink)',
                        outline: 'none',
                        width: '100%',
                        fontFamily: 'var(--f-body)',
                      }}
                    />
                  </div>
                ))}
              </div>

              <div className="cal-confirm">
                <button type="button" onClick={() => setStep('pick')} style={{ fontFamily: 'var(--f-mono)', fontSize: 12, color: 'var(--ink-4)', letterSpacing: '0.04em' }}>
                  Back
                </button>
                <button type="submit" className="btn btn-primary" disabled={submitting || !canSubmit} style={(!submitting && canSubmit) ? {} : { opacity: 0.4, cursor: 'not-allowed' }}>
                  {submitting ? 'Confirming…' : <React.Fragment>Confirm booking <Icon.Arrow /></React.Fragment>}
                </button>
              </div>
            </form>
          )}

          {step === 'confirmed' && (
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 20,
              padding: '32px 0',
              textAlign: 'center',
              height: '100%',
            }}>
              <div style={{
                width: 64, height: 64, borderRadius: '50%',
                background: 'var(--accent-tint)',
                color: 'var(--accent)',
                display: 'grid', placeItems: 'center',
              }}>
                <Icon.Check size={28} />
              </div>
              <h3 style={{ fontFamily: 'var(--f-display)', fontSize: 26, letterSpacing: '-0.02em' }}>
                You're booked in.
              </h3>
              <div style={{
                background: 'var(--bg)',
                padding: '16px 24px',
                borderRadius: 12,
                fontFamily: 'var(--f-mono)',
                fontSize: 13,
                color: 'var(--ink-2)',
                letterSpacing: '0.02em',
              }}>
                {fmtDate(selDate)} · {selTime}
              </div>
              <p style={{ color: 'var(--ink-3)', fontSize: 14.5, maxWidth: '34ch' }}>
                We'll be in touch at <strong>{details.email}</strong> to confirm. Talk soon.
              </p>
              <button onClick={onClose} className="btn btn-secondary btn-sm" style={{ marginTop: 8 }}>Done</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FAQ, Contact, Footer, BookingModal });
