// Contact page — hero, contact form, FAQ, CTA.

const { useState: useState_CT, useRef: useRef_CT, useEffect: useEffect_CT } = React;

const CONTACT_EMPTY_FORM = {
  firstName: '',
  lastName: '',
  email: '',
  countryCode: '+44',
  phone: '',
  service: '',
  stage: '',
  support: '',
};

function ContactHero() {
  return (
    <section className="relative overflow-hidden" style={{ background: 'var(--sa-purple)' }}>
      <PinkFan size={180} color="var(--sa-pink)" className="absolute" style={{ left: -50, bottom: -40, opacity: 0.85 }} />
      <Checker size={120} color="var(--sa-lime)" className="absolute" style={{ right: -10, top: 30, opacity: 0.95 }} />

      <div className="container-wide sec-x py-16 md:py-24 relative text-center">
        <Reveal>
          <h1 className="text-white mx-auto" style={{
            font: '700 clamp(36px, 7vw, 72px)/1.1 var(--sa-font-sans)',
            letterSpacing: '-2px', maxWidth: 920, margin: '0 auto'
          }}>
            <span style={{ color: 'var(--sa-yellow)' }}>Get</span> In Touch With <span style={{ color: 'var(--sa-yellow)' }}>Us</span>
          </h1>
        </Reveal>
        <Reveal delay={120}>
          <p className="mt-5 mx-auto text-white/90 max-w-[640px]" style={{ font: '400 clamp(15px, 1.5vw, 18px)/1.55 var(--sa-font-sans)' }}>
            Have questions, need support, or just want to say hello? We're here to help.
          </p>
        </Reveal>
        <Reveal delay={200}>
          <div className="mt-7"><Btn href={DISCOVERY_CALL_HREF} size="lg">Book free 1:1 discovery call</Btn></div>
        </Reveal>
      </div>
    </section>
  );
}

function ContactBand() {
  const [form, setForm] = useState_CT(CONTACT_EMPTY_FORM);
  const [errors, setErrors] = useState_CT({});
  const [sent, setSent] = useState_CT(false);
  const [submitting, setSubmitting] = useState_CT(false);
  const [status, setStatus] = useState_CT(null);

  const upd = (k) => (e) => {
    setForm(f => ({ ...f, [k]: e.target.value }));
    setErrors(er => ({ ...er, [k]: '' }));
    setStatus(null);
  };

  const setCountry = (country) => {
    setForm(f => ({ ...f, countryCode: country.dial_code }));
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;

    const er = {};
    if (!form.firstName.trim()) er.firstName = 'Required';
    if (!form.lastName.trim()) er.lastName = 'Required';
    if (!form.email.trim() || !/^\S+@\S+\.\S+$/.test(form.email)) er.email = 'Valid email required';
    if (!form.phone.trim()) er.phone = 'Required';
    if (!form.service.trim()) er.service = 'Required';
    if (!form.stage.trim()) er.stage = 'Required';
    if (!form.support.trim()) er.support = 'Required';
    setErrors(er);
    if (Object.keys(er).length) {
      setStatus({ type: 'error', message: 'Please complete the highlighted fields.' });
      return;
    }

    setSubmitting(true);
    setSent(false);
    setStatus(null);

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          sourcePage: window.location.pathname || '/contact',
        }),
      });
      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data.ok) {
        if (data.fields) {
          setErrors(er => ({ ...er, ...data.fields }));
        }
        setStatus({
          type: 'error',
          message: data.message || 'We could not submit your registration. Please try again.',
        });
        return;
      }

      setSent(true);
      setStatus({ type: 'success', message: data.message || 'Thanks, your registration has been submitted.' });
      setForm(CONTACT_EMPTY_FORM);
      setTimeout(() => {
        setSent(false);
        setStatus(null);
      }, 3500);
    } catch (error) {
      setStatus({
        type: 'error',
        message: 'We could not submit your registration. Please try again.',
      });
    } finally {
      setSubmitting(false);
    }
  };

  const serviceOptions = [
    'College Admissions & Career Guidance',
    'Research Paper Publication Program',
    'Proofreading & Academic Review',
    'Book a free 1:1 discovery call',
  ];

  const stageOptions = [
    'High school student',
    'Undergraduate student',
    'Graduate student',
    'Parent / guardian',
    'Working professional',
  ];

  return (
    <section className="contact-band" style={{ background: 'var(--sa-lavender-50)' }}>
      <div className="container-wide sec-x py-12 md:py-16">
        <div className="contact-band-layout grid lg:grid-cols-2 gap-10 lg:gap-14 items-start">
          {/* Left — info */}
          <Reveal direction="left">
            <h2 className="h-section contact-help-heading">
              <span className="contact-help-heading__line">Have <span className="text-sa-purple">Questions?</span></span>
              <span className="contact-help-heading__line">We're Here To Help!</span>
            </h2>
            <p className="body-md mt-5 max-w-[480px]">
              We're here to help. Submit your inquiry through the form, and our team will respond within 24–48 hours.
            </p>

            <div className="contact-info-grid grid sm:grid-cols-2 gap-8 mt-10">
              <div>
                <h5 className="font-bold text-sa-purple mb-2" style={{ fontSize: 15 }}>Email</h5>
                <a href="mailto:info@scholarlyaffairs.com" className="text-sa-ink font-medium hover:text-sa-purple no-underline" style={{ fontSize: 15 }}>info@scholarlyaffairs.com</a>
              </div>
              <div>
                <h5 className="font-bold text-sa-purple mb-2" style={{ fontSize: 15 }}>Phone</h5>
                <a href="tel:+447392559481" className="text-sa-ink font-medium hover:text-sa-purple no-underline" style={{ fontSize: 15 }}>+44 7392 559481</a>
              </div>
              <div className="sm:col-span-2">
                <h5 className="font-bold text-sa-purple mb-2" style={{ fontSize: 15 }}>Location</h5>
                <div className="text-sa-ink font-medium" style={{ fontSize: 15 }}>
                  Scholarly Affairs Ltd.<br />
                  13 Park Terrace, Cambridge CB1 1JH, United Kingdom
                </div>
              </div>
            </div>

            <div className="mt-8">
              <h5 className="font-bold text-sa-purple mb-3" style={{ fontSize: 15 }}>Follow Us</h5>
              <div className="flex gap-3">
                {[<TwitterGlyph />, <FacebookGlyph />, <InstagramGlyph />, <LinkedInGlyph />].map((g, i) => (
                  <a key={i} href="#" aria-label="social"
                     className="w-10 h-10 rounded-full bg-sa-yellow-mid text-sa-black inline-flex items-center justify-center transition-transform hover:scale-110">{g}</a>
                ))}
              </div>
            </div>
          </Reveal>

          {/* Right — form */}
          <Reveal direction="right" delay={100}>
            <form
              onSubmit={onSubmit}
              className="contact-registration-form"
              noValidate
              aria-busy={submitting}>
              <div className="contact-form-grid">
                <ContactField id="firstName" label="First Name" error={errors.firstName}>
                  <input id="firstName" type="text" value={form.firstName} onChange={upd('firstName')} placeholder="Enter your first name" />
                </ContactField>

                <ContactField id="lastName" label="Last Name" error={errors.lastName}>
                  <input id="lastName" type="text" value={form.lastName} onChange={upd('lastName')} placeholder="Enter your last name" />
                </ContactField>

                <ContactField id="email" label="Email Address" error={errors.email} wide>
                  <input id="email" type="email" value={form.email} onChange={upd('email')} placeholder="Enter your email address" />
                </ContactField>

                <ContactField id="phone" label="Phone Number" error={errors.phone} wide>
                  <div className="contact-phone-row">
                    <CountryCodePicker value={form.countryCode} onChange={setCountry} />
                    <input id="phone" type="tel" value={form.phone} onChange={upd('phone')} placeholder="Enter your phone number" />
                  </div>
                </ContactField>

                <ContactField id="service" label="Which service are you interested in exploring with Scholarly Affairs?" error={errors.service} wide>
                  <select id="service" value={form.service} onChange={upd('service')} aria-label="Which service are you interested in exploring with Scholarly Affairs?">
                    <option value=""></option>
                    {serviceOptions.map(option => <option key={option} value={option}>{option}</option>)}
                  </select>
                </ContactField>

                <ContactField id="stage" label="What is your current academic or professional stage?" error={errors.stage} wide>
                  <select id="stage" value={form.stage} onChange={upd('stage')} aria-label="What is your current academic or professional stage?">
                    <option value=""></option>
                    {stageOptions.map(option => <option key={option} value={option}>{option}</option>)}
                  </select>
                </ContactField>

                <ContactField id="support" label="What would you like support with?" error={errors.support} wide>
                  <textarea
                    id="support"
                    value={form.support}
                    onChange={upd('support')}
                    placeholder="Briefly describe your question, goal, challenge, or the kind of guidance you are looking for."
                  />
                </ContactField>
              </div>

              <div className="contact-form-submit">
                <button type="submit" className="contact-submit-button" disabled={submitting}>
                  {submitting ? 'Submitting...' : sent ? 'Registration Submitted' : 'Submit Registration'}
                </button>
                {status ? (
                  <p className={`contact-form-status is-${status.type}`} role="status" aria-live="polite">
                    {status.message}
                  </p>
                ) : null}
              </div>
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function CountryCodePicker({ value, onChange }) {
  const countries = window.COUNTRIES || [];
  const defaultCountry = countries.find(country => country.name === 'United Kingdom') || countries[0] || { name: 'United Kingdom', dial_code: '+44', flag: '🇬🇧' };
  const selected = countries.find(country => country.dial_code === value && country.name === 'United Kingdom')
    || countries.find(country => country.dial_code === value)
    || defaultCountry;
  const [open, setOpen] = useState_CT(false);
  const [query, setQuery] = useState_CT('');
  const pickerRef = useRef_CT(null);
  const searchRef = useRef_CT(null);

  useEffect_CT(() => {
    const onPointerDown = (event) => {
      if (pickerRef.current && !pickerRef.current.contains(event.target)) {
        setOpen(false);
      }
    };
    const onKeyDown = (event) => {
      if (event.key === 'Escape') setOpen(false);
    };
    document.addEventListener('mousedown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('mousedown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, []);

  useEffect_CT(() => {
    if (!open) return;
    requestAnimationFrame(() => searchRef.current?.focus());
  }, [open]);

  const filteredCountries = countries.filter(country => {
    const term = query.trim().toLowerCase();
    if (!term) return true;
    return country.name.toLowerCase().includes(term) || country.dial_code.includes(term);
  });

  const chooseCountry = (country) => {
    onChange(country);
    setQuery('');
    setOpen(false);
  };

  const flagClass = (country) => {
    const code = countryCodeFromFlag(country.flag);
    return code ? `fi fi-${code}` : '';
  };

  return (
    <div className="country-code-picker" ref={pickerRef}>
      <button
        type="button"
        className={`country-code-trigger ${open ? 'is-open' : ''}`}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen(isOpen => !isOpen)}>
        <span className={`country-code-trigger__flag ${flagClass(selected)}`} aria-hidden="true"></span>
        <span className="country-code-trigger__code">{selected.dial_code}</span>
        <Icon name="expand_more" size={16} className="country-code-trigger__chevron" />
      </button>

      {open ? (
        <div className="country-code-menu">
          <div className="country-code-search">
            <Icon name="search" size={17} />
            <input
              ref={searchRef}
              type="text"
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              placeholder="Search country or code..."
              aria-label="Search country or code"
            />
          </div>

          <div className="country-code-menu__label">All Countries</div>

          <div className="country-code-list" role="listbox" aria-label="Country dialing codes">
            {filteredCountries.length ? filteredCountries.map(country => {
              const isSelected = country.name === selected.name && country.dial_code === selected.dial_code;
              return (
                <button
                  key={`${country.name}-${country.dial_code}`}
                  type="button"
                  className={`country-code-option ${isSelected ? 'is-selected' : ''}`}
                  role="option"
                  aria-selected={isSelected}
                  onClick={() => chooseCountry(country)}>
                  <span className={`country-code-option__flag ${flagClass(country)}`} aria-hidden="true"></span>
                  <span className="country-code-option__name">{country.name}</span>
                  <span className="country-code-option__dial">{country.dial_code}</span>
                </button>
              );
            }) : (
              <div className="country-code-empty">No countries found</div>
            )}
          </div>
        </div>
      ) : null}
    </div>
  );
}

function countryCodeFromFlag(flag) {
  if (!flag) return '';
  return Array.from(flag)
    .map(char => String.fromCharCode((char.codePointAt(0) || 0) - 127397))
    .join('')
    .toLowerCase();
}

function ContactField({ id, label, error, wide, children }) {
  return (
    <div className={`contact-form-field ${wide ? 'contact-form-field--wide' : ''} ${id === 'service' ? 'contact-form-field--single-line-label' : ''} ${error ? 'has-error' : ''}`}>
      <label htmlFor={id}>
        {label} <span aria-hidden="true">*</span>
      </label>
      {children}
      {error ? <p className="contact-form-error">{error}</p> : null}
    </div>
  );
}

function ContactFAQ() {
  return (
    <section className="contact-faq bg-white">
      <div className="container-wide sec-x py-12 md:py-16 grid lg:grid-cols-[0.85fr_1.15fr] gap-10 lg:gap-16 items-start">
        <Reveal direction="left">
          <Badge>FAQ's</Badge>
          <h2 className="h-section mt-5">
            <span className="text-sa-purple">Frequently</span> Asked <br />Question
          </h2>
          <p className="body-md mt-5 max-w-[420px]">
            Have questions? We've got answers to help you get the most out of your learning journey.
          </p>
        </Reveal>
        <Reveal direction="right" delay={100}>
          <div>{FAQS_HOME.map((f, i) => <FAQRow key={i} {...f} color="purple" />)}</div>
        </Reveal>
      </div>
    </section>
  );
}

function ContactPage() {
  return (
    <div data-screen-label="Contact" className="page-enter">
      <ContactHero />
      <ContactBand />
      <ContactFAQ />
      <CTABand
        className="contact-cta"
        badge="Learn from Top Experts"
        title={<>Ready to <span className="text-sa-purple">Level Up?</span></>}
        body="Join hundreds of learners and take the next step in your personal and professional journey."
      />
    </div>
  );
}

Object.assign(window, { ContactPage });
