// Contact.jsx — Contact page (combines Apply + Contact)
// Teal-accented. Form switches between Enrolment Enquiry (default) and General.

function ContactHero() {
  return (
    <section className="contact-hero">
      <div
        className="contact-hero__bg"
        style={{ backgroundImage: 'url(assets/photos/web/campus-gathering.jpg)' }} />
      
      <div className="contact-hero__wash" />
      <div className="container contact-hero__inner">
        <div className="contact-hero__eyebrow">Contact &middot; Enquire</div>
        <h1 className="contact-hero__title">
          Come and <em>see.</em>
        </h1>
        <p className="contact-hero__lede">
          The best way to know Broadacres is to come and see. Book a walkabout and we will show you around. For anything else, the form below comes straight to the office.
        </p>
      </div>
    </section>);

}

function ContactIntro() {
  return (
    <section className="contact-intro">
      <div className="container">
        <div className="contact-intro__grid">
          <div>
            <div className="eyebrow-txt">Get in touch</div>
            <h2 className="contact-intro__title">
              Hello. We&rsquo;re <em>glad</em> you&rsquo;re here.
            </h2>
          </div>
          <div className="contact-intro__body">
            <p>
              Whether you&rsquo;re thinking about enrolling, planning a walkabout, or just curious about how a Broadacres day unfolds &mdash; we&rsquo;d love to hear from you.
            </p>
            <p>
              Choose <em>Enrolment Enquiry</em> below for admissions, fees and grade availability. Choose <em>General Enquiry</em> for everything else.
            </p>
          </div>
        </div>
      </div>
    </section>);

}

const GRADES = [
'Under 2',
'Grade 0000 (turning 3)',
'Grade 000 (turning 4)',
'Grade 00 (turning 5)',
'Grade 0 (turning 6)',
'Grade 1', 'Grade 2', 'Grade 3', 'Grade 4', 'Grade 5', 'Grade 6',
'Grade 7', 'Grade 8', 'Grade 9', 'Grade 10', 'Grade 11', 'Grade 12'];

const YEARS = ['2026', '2027', '2028', '2029'];
const HEARD_ABOUT = ['', 'Billboard', 'Facebook', 'Instagram', 'YouTube', 'Google Search', 'Expo', 'Magazine', 'Broadacres family', 'Other'];

function ContactForm() {
  const [type, setType] = React.useState('enrolment'); // 'enrolment' | 'general'
  const [submitted, setSubmitted] = React.useState(false);
  const [children, setChildren] = React.useState([
  { id: 1, name: '', surname: '', grade: '', year: '2026' }]
  );
  const [recaptcha, setRecaptcha] = React.useState(false);
  const [consent, setConsent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');

  const addChild = () => {
    setChildren((prev) => [...prev, { id: Date.now(), name: '', surname: '', grade: '', year: '2026' }]);
  };
  const removeChild = (id) => {
    setChildren((prev) => prev.length > 1 ? prev.filter((c) => c.id !== id) : prev);
  };
  const updateChild = (id, key, val) => {
    setChildren((prev) => prev.map((c) => c.id === id ? { ...c, [key]: val } : c));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!consent || !recaptcha || sending) return;
    const val = (id) => (document.getElementById(id)?.value || '').trim();
    // Client-side checks so a missing name or mistyped email gets instant,
    // specific feedback (the form has noValidate, so the browser won't catch these).
    if (!val('cf-name')) { setError('Please add your name.'); return; }
    if (!/.+@.+\..+/.test(val('cf-email'))) { setError('Please enter a valid email address so we can reply to you.'); return; }
    if (type === 'general' && !val('cf-msg')) { setError('Please add a short message so we know how to help.'); return; }
    const payload = {
      type,
      name: val('cf-name'), surname: val('cf-surname'),
      email: val('cf-email'), phone: val('cf-phone'),
      heard: val('cf-heard'), notes: val('cf-notes'), message: val('cf-msg'),
      company: val('cf-company'), // honeypot — must stay empty
      children: type === 'enrolment'
        ? children.map((c) => ({ name: c.name, surname: c.surname, grade: c.grade, year: c.year }))
        : []
    };
    setError('');
    setSending(true);
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (r.ok) { setSubmitted(true); return; }
      // Surface the server's specific reason (e.g. invalid email) rather than a vague failure.
      let msg = 'Something went wrong sending your enquiry. Please try again, or email us directly at apply@broadacres.com.';
      try { const d = await r.json(); if (d && d.error) msg = d.error; } catch (e2) {}
      setError(msg);
    } catch (err) {
      setError('Sorry — we couldn’t reach the server. Please check your connection and try again, or email us directly at apply@broadacres.com.');
    } finally {
      setSending(false);
    }
  };

  if (submitted) {
    return (
      <div className="contact-form">
        <div className="contact-form__success">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
            <path d="M5 13l4 4L19 7" />
          </svg>
          <div>
            <h3>Thank you. <em>We have your enquiry.</em></h3>
            <p>
              A member of our admissions team will be in touch shortly. If your matter is urgent, give us a call on +27 10 271 1700 during office hours.
            </p>
          </div>
        </div>
      </div>);

  }

  return (
    <form className="contact-form" onSubmit={submit} noValidate>
      {/* Honeypot — hidden from people, catches spam bots */}
      <input id="cf-company" name="company" type="text" tabIndex={-1} autoComplete="off" aria-hidden="true"
        style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 }} />
      {/* Type switch */}
      <div className="contact-form__switch" role="tablist" aria-label="Enquiry type">
        <button
          type="button"
          role="tab"
          aria-selected={type === 'enrolment'}
          className={type === 'enrolment' ? 'is-active' : ''}
          onClick={() => setType('enrolment')}>
          Enrolment Enquiry
        </button>
        <button
          type="button"
          role="tab"
          aria-selected={type === 'general'}
          className={type === 'general' ? 'is-active' : ''}
          onClick={() => setType('general')}>
          General Enquiry
        </button>
      </div>

      {/* Your details */}
      <fieldset className="contact-fieldset">
        <legend className="contact-fieldset__legend">Your details</legend>
        <div className="contact-grid">
          <div className="field">
            <label htmlFor="cf-name">Name <span className="req">*</span></label>
            <input id="cf-name" type="text" autoComplete="given-name" required />
          </div>
          <div className="field">
            <label htmlFor="cf-surname">Surname <span className="req">*</span></label>
            <input id="cf-surname" type="text" autoComplete="family-name" required />
          </div>
          <div className="field">
            <label htmlFor="cf-email">Email <span className="req">*</span></label>
            <input id="cf-email" type="email" autoComplete="email" required />
          </div>
          <div className="field">
            <label htmlFor="cf-phone">Phone <span className="req">*</span></label>
            <input id="cf-phone" type="tel" autoComplete="tel" required />
          </div>
        </div>
      </fieldset>

      {type === 'enrolment' &&
      <>
          {/* Children */}
          <fieldset className="contact-fieldset">
            <legend className="contact-fieldset__legend">About your child</legend>
            <div className="contact-children">
              {children.map((c, i) =>
            <div className="contact-child" key={c.id}>
                  <div className="contact-child__head">
                    <div className="contact-child__title">
                      Child <em>{i + 1}</em>
                    </div>
                    {children.length > 1 &&
                <button type="button" className="contact-child__remove" onClick={() => removeChild(c.id)}>
                        Remove
                      </button>
                }
                  </div>
                  <div className="contact-grid">
                    <div className="field">
                      <label>First name <span className="req">*</span></label>
                      <input type="text" value={c.name} onChange={(e) => updateChild(c.id, 'name', e.target.value)} required />
                    </div>
                    <div className="field">
                      <label>Surname</label>
                      <input type="text" value={c.surname} onChange={(e) => updateChild(c.id, 'surname', e.target.value)} />
                    </div>
                    <div className="field">
                      <label>Grade to enrol <span className="req">*</span></label>
                      <select value={c.grade} onChange={(e) => updateChild(c.id, 'grade', e.target.value)} required>
                        <option value="" disabled>Select a grade</option>
                        {GRADES.map((g) => <option key={g} value={g}>{g}</option>)}
                      </select>
                    </div>
                    <div className="field">
                      <label>Starting year <span className="req">*</span></label>
                      <select value={c.year} onChange={(e) => updateChild(c.id, 'year', e.target.value)} required>
                        {YEARS.map((y) => <option key={y} value={y}>{y}</option>)}
                      </select>
                    </div>
                  </div>
                </div>
            )}
              <button type="button" className="contact-add-child" onClick={addChild}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14" /></svg>
                Add another child
              </button>
            </div>
          </fieldset>

          {/* Where heard */}
          <fieldset className="contact-fieldset">
            <legend className="contact-fieldset__legend">A few last things</legend>
            <div className="contact-grid">
              <div className="field field--full">
                <label htmlFor="cf-heard">Where did you hear about us?</label>
                <select id="cf-heard" defaultValue="">
                  {HEARD_ABOUT.map((h, i) =>
                <option key={i} value={h} disabled={!h}>{h || 'Please choose...'}</option>
                )}
                </select>
              </div>
              <div className="field field--full">
                <label htmlFor="cf-notes">Anything else we should know? <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>(optional)</span></label>
                <textarea id="cf-notes" rows="4" placeholder="Sibling at the school, specific interests, special requirements..." />
              </div>
            </div>
          </fieldset>
        </>
      }

      {type === 'general' &&
      <fieldset className="contact-fieldset">
          <legend className="contact-fieldset__legend">Your enquiry</legend>
          <div className="contact-grid">
            <div className="field field--full">
              <label htmlFor="cf-msg">How can we help? <span className="req">*</span></label>
              <textarea id="cf-msg" rows="6" required placeholder="Tell us a little about what you'd like to know..." />
            </div>
          </div>
        </fieldset>
      }

      {/* Consent */}
      <div className="contact-consent">
        <div className="contact-consent__row">
          <input
            id="cf-consent"
            type="checkbox"
            checked={consent}
            onChange={(e) => setConsent(e.target.checked)} />
          
          <label htmlFor="cf-consent">
            I agree to allow this website to store my submitted information so the school can respond to my enquiry. <span className="req">*</span>
          </label>
        </div>
      </div>

      {/* Recaptcha placeholder */}
      <div
        className="contact-recaptcha"
        role="checkbox"
        aria-checked={recaptcha}
        tabIndex={0}
        onClick={() => setRecaptcha(!recaptcha)}
        onKeyDown={(e) => {if (e.key === ' ' || e.key === 'Enter') {e.preventDefault();setRecaptcha(!recaptcha);}}}
        style={{ cursor: 'pointer' }}>
        <div
          className="contact-recaptcha__check"
          style={recaptcha ? { borderColor: 'var(--ba-teal)', background: 'var(--ba-teal)', position: 'relative' } : {}}>
          {recaptcha &&
          <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" style={{ width: '100%', height: '100%' }}>
              <path d="M5 13l4 4L19 7" />
            </svg>
          }
        </div>
        <div className="contact-recaptcha__label">I&rsquo;m not a robot</div>
        <div className="contact-recaptcha__brand">
          <div className="contact-recaptcha__brand-icon">r</div>
          <div>reCAPTCHA</div>
        </div>
      </div>

      {/* Submit */}
      {error &&
      <p className="contact-form__error" role="alert" style={{ color: '#c0392b', margin: '0 0 14px', fontSize: '14px' }}>
          {error}
        </p>
      }
      <div className="contact-form__submit-row">
        <small>
          Your information is held in line with POPIA and used only to respond to your enquiry.
        </small>
        <button type="submit" className="btn btn-primary" disabled={!consent || !recaptcha || sending} style={!consent || !recaptcha || sending ? { opacity: 0.5, cursor: 'not-allowed' } : {}}>
          {sending ? 'Sending…' : 'Send enquiry'}
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
        </button>
      </div>
    </form>);

}

function ContactAdminNote() {
  return (
    <div className="contact-admin-note">
      <div className="contact-admin-note__icon">i</div>
      <div>
        <h4>For internal reference</h4>
        <p>
          Submissions are emailed straight to the admissions office via the website&rsquo;s contact service (Resend), with the sender set as reply-to so the team can respond directly. The same payload will plug into the new admissions database when it&rsquo;s ready.
        </p>
        <div className="contact-admin-note__pipeline">
          <span className="contact-admin-note__step">Form</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ alignSelf: 'center', opacity: 0.4 }}><path d="M5 12h14M13 5l7 7-7 7" /></svg>
          <span className="contact-admin-note__step">Resend</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ alignSelf: 'center', opacity: 0.4 }}><path d="M5 12h14M13 5l7 7-7 7" /></svg>
          <span className="contact-admin-note__step">Admissions inbox</span>
        </div>
      </div>
    </div>);

}

/* ---------------------------------------------------------------
   CAMPUS MAPS
   Fill in EITHER field for each campus (or both). Leave '' to skip.

   • link  — a normal Google Maps URL. EASIEST option:
       1. Open Google Maps, search for the campus.
       2. Click "Share" → "Copy link"  (or use a directions URL like
          https://www.google.com/maps/dir/?api=1&destination=ADDRESS).
       3. Paste it as `link` below.
       → The map becomes clickable and shows a "Get directions" button
         that opens Google Maps in a new tab.

   • embed — a live interactive map inside the card:
       1. Google Maps → "Share" → "Embed a map".
       2. Copy ONLY the value inside src="..."  (starts with
          https://www.google.com/maps/embed?pb=...).
       3. Paste it as `embed` below.

   With neither set, the decorative placeholder is shown.
   --------------------------------------------------------------- */
const CAMPUS_MAPS = {
  syringa: {
    link:  'https://www.google.com/maps/place/Broadacres+Academy+Preschool+%26+Junior+Prep+%7C+Syringa+Campus/@-25.9967682,27.9886855,17z/data=!3m1!4b1!4m6!3m5!1s0x1e9576e1682b3d25:0x6827ed2e1fba9e67!8m2!3d-25.9967682!4d27.9912658!16s%2Fg%2F1tff03vj',
    embed: 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3586.123601639679!2d27.988685510987224!3d-25.996768177109935!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1e9576e1682b3d25%3A0x6827ed2e1fba9e67!2sBroadacres%20Academy%20Preschool%20%26%20Junior%20Prep%20%7C%20Syringa%20Campus!5e0!3m2!1sen!2sza!4v1781185092493!5m2!1sen!2sza',
  },
  chartwell: {
    link:  'https://www.google.com/maps/place/Broadacres+Academy+Senior+Prep+%26+High+School+%7C+Chartwell+Campus/@-25.982547,27.9655246,17z/data=!3m1!4b1!4m6!3m5!1s0x4a4b1523c0bfc717:0x62ec8e40682fa124!8m2!3d-25.982547!4d27.9681049!16s%2Fg%2F11nwx6rcx_',
    embed: 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3586.557559863843!2d27.965524610986716!3d-25.982546977118666!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4a4b1523c0bfc717%3A0x62ec8e40682fa124!2sBroadacres%20Academy%20Senior%20Prep%20%26%20High%20School%20%7C%20Chartwell%20Campus!5e0!3m2!1sen!2sza!4v1781185058801!5m2!1sen!2sza',
  },
};

function CampusMap({ seed, label }) {
  const { link = '', embed = '' } = CAMPUS_MAPS[seed] || {};

  // Live interactive map
  if (embed) {
    return (
      <iframe
        className="campus-contact-card__iframe"
        src={embed}
        title={`Map of the ${label} campus`}
        loading="lazy"
        referrerPolicy="no-referrer-when-downgrade"
        allowFullScreen></iframe>);

  }

  const plate = (
    <>
      <MapPlaceholder seed={seed} />
      <div className="campus-contact-card__map-pin">
        <div className="campus-contact-card__map-pin-dot" />
        <div className="campus-contact-card__map-pin-stem" />
      </div>
    </>);


  // Placeholder, made clickable when a link is provided
  if (link) {
    return (
      <a
        className="campus-contact-card__maplink"
        href={link}
        target="_blank"
        rel="noopener noreferrer"
        aria-label={`Open the ${label} campus in Google Maps`}>
        {plate}
      </a>);

  }

  return (
    <>
      {plate}
      <div className="campus-contact-card__map-attr">Map &middot; placeholder</div>
    </>);

}

function MapPlaceholder({ seed }) {
  // Decorative SVG that suggests a satellite map plate. Will be replaced with
  // an embedded Google Map iframe at deploy time.
  const blobs = seed === 'syringa' ?
  [{ cx: 30, cy: 40, r: 18, c: '#A8C29A' }, { cx: 65, cy: 60, r: 22, c: '#B5CDA3' }, { cx: 80, cy: 25, r: 14, c: '#C9D8B4' }] :
  [{ cx: 25, cy: 55, r: 16, c: '#B5CDA3' }, { cx: 55, cy: 30, r: 20, c: '#A8C29A' }, { cx: 78, cy: 70, r: 18, c: '#C9D8B4' }];
  const roads = seed === 'syringa' ?
  "M0,55 L100,48 M40,0 L48,100" :
  "M0,40 L100,52 M55,0 L60,100 M0,80 L100,75";
  return (
    <svg viewBox="0 0 100 56" preserveAspectRatio="xMidYMid slice">
      <defs>
        <pattern id={`grid-${seed}`} width="6" height="6" patternUnits="userSpaceOnUse">
          <path d="M 6 0 L 0 0 0 6" fill="none" stroke="rgba(0,29,57,0.06)" strokeWidth="0.3" />
        </pattern>
      </defs>
      <rect width="100" height="56" fill={`url(#grid-${seed})`} />
      {blobs.map((b, i) =>
      <circle key={i} cx={b.cx} cy={b.cy} r={b.r} fill={b.c} opacity="0.55" />
      )}
      <path d={roads} stroke="#FFF" strokeWidth="1.4" fill="none" opacity="0.85" strokeLinecap="round" />
      <path d={roads} stroke="rgba(0,29,57,0.18)" strokeWidth="1.8" fill="none" opacity="0.6" strokeLinecap="round" />
    </svg>);

}

function ContactVisit() {
  return (
    <section className="contact-visit">
      <div className="container">
        <div className="contact-visit__head">
          <div className="eyebrow-txt">Visit us</div>
          <h2 className="contact-visit__title">
            Two campuses, <em>a short drive apart.</em>
          </h2>
        </div>

        <div className="campus-cards">
          <article className="campus-contact-card">
            <div className="campus-contact-card__map">
              <CampusMap seed="syringa" label="Syringa" />
            </div>
            <div className="campus-contact-card__body">
              <div className="campus-contact-card__phase">Preschool &middot; Junior Prep</div>
              <h3 className="campus-contact-card__name">
                Syringa <em>campus.</em>
              </h3>
              <p className="campus-contact-card__addr">
                28 Syringa Avenue (off Cedar Road)<br />
                Broadacres, Johannesburg, 2021
              </p>
              <div className="campus-contact-card__walkabout">
                <strong>Walkabouts:</strong> Preschool Tue 09:00 &middot; Junior Prep Thu 09:00
              </div>
            </div>
          </article>

          <article className="campus-contact-card">
            <div className="campus-contact-card__map">
              <CampusMap seed="chartwell" label="Chartwell" />
            </div>
            <div className="campus-contact-card__body">
              <div className="campus-contact-card__phase">Senior Prep &middot; High School</div>
              <h3 className="campus-contact-card__name">
                Chartwell <em>campuses.</em>
              </h3>
              <p className="campus-contact-card__addr">
                249 Fifth Street (Senior Prep) &middot; 88 Fifth Street (High School)<br />
                Access via Spencer Road, Chartwell, Johannesburg, 2055
              </p>
              <div className="campus-contact-card__walkabout">
                <strong>Walkabouts:</strong> Senior Prep Fri 09:00 &middot; High School Thu 09:00
              </div>
            </div>
          </article>
        </div>
      </div>
    </section>);

}

function ContactConnect() {
  return (
    <section className="contact-connect">
      <div className="container">
        <div className="contact-connect__grid">
          <div className="contact-connect__col">
            <h3>Call us</h3>
            <p className="contact-connect__big">+27 10 271 1700</p>
          </div>
          <div className="contact-connect__col">
            <h3>Email us</h3>
            <p className="contact-connect__big">apply<span style={{ opacity: 1 }}>@</span>broadacres.com</p>
          </div>
          <div className="contact-connect__col">
            <h3>Office hours</h3>
            <p className="contact-connect__hours">Monday to Friday<br/><span className="contact-connect__hours-time">08:00–16:30</span></p>
          </div>
        </div>
      </div>
    </section>);
}

function ContactCareers() {
  return (
    <section className="contact-careers">
      <div className="container">
        <div className="contact-careers__grid">
          <div>
            <div className="eyebrow-txt">Careers</div>
            <h2 className="contact-careers__title">
              Working at <em>Broadacres.</em>
            </h2>
            <p className="contact-careers__body">
              Open roles for our teaching and support teams are posted on the ISASA careers site. To apply, please follow the process outlined there.
            </p>
            <div className="contact-careers__action">
              <a href="https://www.isasa.org/vacancies/" target="_blank" rel="noreferrer" className="btn btn-primary" style={{ borderBottom: 0 }}>
                View open roles
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M7 17L17 7M9 7h8v8" /></svg>
              </a>
            </div>
          </div>
          <div className="contact-careers__photo">
            <image-slot
              id="careers-teacher"
              shape="rounded"
              radius="18"
              src="assets/photos/careers-teacher.jpg"
              placeholder="Drop a photo of a teacher"></image-slot>
          </div>
        </div>
      </div>
    </section>);

}

function Contact({ onNavigate, tweaks }) {
  React.useEffect(() => {window.scrollTo({ top: 0 });}, []);

  return (
    <div className="contact-root">
      <ContactHero />
      <ContactIntro />

      <section className="contact-form-section" id="enquire">
        <div className="container">
          <div className="contact-form-wrap">
            <div>
              <ContactForm />
            </div>
          </div>
        </div>
      </section>

      <ContactVisit />
      <ContactConnect />
      <ContactCareers />

      {/* CTA */}
      <section className="phase-cta-photo">
        <div
          className="phase-cta-photo__bg"
          style={{ backgroundImage: `url(assets/photos/web/sp-walkabout.jpg)` }} />
        
        <div className="container">
          <div className="phase-cta-photo__grid">
            <h2 className="phase-cta-photo__title">
              Come and <em>walk the grounds.</em>
            </h2>
            <div className="phase-cta-photo__actions">
              <a className="btn btn-primary" href={window.WALKABOUT_URL} target="_blank" rel="noopener noreferrer">
                Book a walkabout
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
              </a>
              <a className="btn btn-ghost-light" href="https://fees.broadacres.com" target="_blank" rel="noopener noreferrer">View fees</a>
            </div>
          </div>
        </div>
      </section>

      <Footer onNavigate={onNavigate} />
    </div>);

}

Object.assign(window, { Contact });