/* ==========================================================================
   QuoteForm.jsx | Quote / booking form (used inside FinalCTA)
   Front-end validation with inline errors. Without MC_CONFIG.formEndpoint
   the form never claims an enquiry was sent; it shows a labelled
   submission placeholder instead.
   ========================================================================== */

const MC_PROPERTY_TYPES = ['House', 'Apartment or unit', 'Townhouse', 'Office', 'Other business', 'Other'];
const MC_FORM_ORDER = ['name', 'email', 'phone', 'suburb', 'service', 'property', 'date', 'details'];
const MC_FORM_HINTS = {
  date: 'Leave blank if you’re flexible.',
  details: 'Bedrooms, bathrooms, pets, access, anything that needs extra attention.',
};

function mcTodayISO() {
  const now = new Date();
  const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 10);
}

function mcValidateQuote(values) {
  const errors = {};
  const name = values.name.trim();
  if (!name) errors.name = 'Enter your full name.';
  else if (name.length < 2) errors.name = 'Enter your full name, not just an initial.';

  const email = values.email.trim();
  if (!email) errors.email = 'Enter your email address.';
  else if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) errors.email = 'Enter an email address like name@example.com.';

  const phone = values.phone.trim();
  const digits = phone.replace(/\D/g, '');
  if (!phone) errors.phone = 'Enter your phone number.';
  else if (!/^[+\d\s()-]+$/.test(phone) || digits.length < 8 || digits.length > 12) {
    errors.phone = 'Enter a phone number like 0412 345 678 or 02 9123 4567.';
  }

  if (!values.suburb.trim()) errors.suburb = 'Enter the suburb where the clean is needed.';
  if (!values.service) errors.service = 'Choose the service you need.';
  if (!values.property) errors.property = 'Choose your property type.';
  if (values.date && values.date < mcTodayISO()) errors.date = 'Choose today or a later date.';
  if (values.details.length > 1000) errors.details = `Keep this under 1,000 characters (it’s ${values.details.length} now).`;
  return errors;
}

function MCFieldError({ id, message }) {
  if (!message) return null;
  return (
    <p className="mc-field__error" id={id}>
      <MCIcon name="alert" />
      {message}
    </p>
  );
}

function MCQuoteForm({ intent, onIntentChange, service, onServiceChange }) {
  const [qfValues, setQfValues] = React.useState({
    name: '',
    email: '',
    phone: '',
    suburb: '',
    service: service || '',
    property: '',
    date: '',
    details: '',
  });
  const [qfErrors, setQfErrors] = React.useState({});
  const [qfTouched, setQfTouched] = React.useState({});
  const [qfAttempted, setQfAttempted] = React.useState(false);
  const [qfStatus, setQfStatus] = React.useState('idle'); // idle | sending | placeholder | sent | error
  const [qfPreselected, setQfPreselected] = React.useState(false);
  const qfRefs = React.useRef({});
  const qfStatusRef = React.useRef(null);
  const today = mcTodayISO();

  // A service chosen elsewhere on the page (cards, tabs) flows into the form.
  React.useEffect(() => {
    if (service && service !== qfValues.service) {
      setQfValues((current) => ({ ...current, service }));
      setQfErrors((current) => {
        const next = { ...current };
        delete next.service;
        return next;
      });
      setQfPreselected(true);
      if (qfStatus === 'placeholder') setQfStatus('idle');
    }
  }, [service]);

  React.useEffect(() => {
    if ((qfStatus === 'placeholder' || qfStatus === 'sent' || qfStatus === 'error') && qfStatusRef.current) {
      qfStatusRef.current.focus();
    }
  }, [qfStatus]);

  const showError = (key) => (qfTouched[key] || qfAttempted ? qfErrors[key] : undefined);

  const handleChange = (key) => (event) => {
    const value = event.target.value;
    const next = { ...qfValues, [key]: value };
    setQfValues(next);
    if (key === 'service') {
      setQfPreselected(false);
      if (onServiceChange) onServiceChange(value);
    }
    if (qfTouched[key] || qfAttempted) setQfErrors(mcValidateQuote(next));
    if (qfStatus !== 'idle' && qfStatus !== 'sending') setQfStatus('idle');
  };

  const handleBlur = (key) => () => {
    if (!qfValues[key]) return; // empty fields are only flagged after a submit attempt
    setQfTouched((current) => ({ ...current, [key]: true }));
    setQfErrors(mcValidateQuote(qfValues));
  };

  const fieldProps = (key) => {
    const error = showError(key);
    const describedBy = [MC_FORM_HINTS[key] ? `mc-f-${key}-hint` : null, error ? `mc-f-${key}-err` : null]
      .filter(Boolean)
      .join(' ');
    return {
      id: `mc-f-${key}`,
      name: key,
      value: qfValues[key],
      onChange: handleChange(key),
      onBlur: handleBlur(key),
      ref: (el) => {
        qfRefs.current[key] = el;
      },
      'aria-invalid': error ? 'true' : undefined,
      'aria-describedby': describedBy || undefined,
      className: 'mc-input',
    };
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    const errors = mcValidateQuote(qfValues);
    setQfErrors(errors);
    setQfAttempted(true);
    const firstInvalid = MC_FORM_ORDER.find((key) => errors[key]);
    if (firstInvalid) {
      setQfStatus('idle');
      const el = qfRefs.current[firstInvalid];
      if (el) el.focus();
      return;
    }

    if (!MC_CONFIG.formEndpoint) {
      setQfStatus('placeholder');
      return;
    }

    setQfStatus('sending');
    try {
      const chosen = MC_SERVICES.find((s) => s.id === qfValues.service);
      const response = await fetch(MC_CONFIG.formEndpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          ...qfValues,
          serviceName: chosen ? chosen.name : qfValues.service,
          intent,
          source: 'dusty-cleaning-landing-page',
        }),
      });
      if (!response.ok) throw new Error(`Request failed with status ${response.status}`);
      setQfStatus('sent');
    } catch (err) {
      setQfStatus('error');
    }
  };

  const errorCount = qfAttempted ? MC_FORM_ORDER.filter((key) => qfErrors[key]).length : 0;
  const submitLabel = intent === 'book' ? 'Request a booking' : 'Request my free quote';
  const firstName = qfValues.name.trim().split(/\s+/)[0];

  if (qfStatus === 'sent') {
    return (
      <div className="mc-form__status is-sent" role="status" tabIndex={-1} ref={qfStatusRef}>
        <p className="mc-form__status-title">
          <MCIcon name="check" />
          Thanks{firstName ? `, ${firstName}` : ''}. Your enquiry has been sent.
        </p>
        <p>We’ll be in touch using the details you gave us.</p>
      </div>
    );
  }

  return (
    <form className="mc-form" onSubmit={handleSubmit} noValidate aria-labelledby="mc-form-title">
      <h3 className="mc-form__title" id="mc-form-title">
        Tell us about your space
      </h3>
      <p className="mc-form__intro">All fields are required unless marked optional.</p>

      <fieldset className="mc-form__intent">
        <legend className="mc-sr">What would you like to do?</legend>
        {[
          ['quote', 'Get a free quote'],
          ['book', 'Book a clean'],
        ].map(([value, label]) => (
          <label key={value} className={intent === value ? 'is-checked' : ''}>
            <input
              type="radio"
              name="mc-intent"
              value={value}
              checked={intent === value}
              onChange={() => onIntentChange(value)}
            />
            <span>{label}</span>
          </label>
        ))}
      </fieldset>

      {errorCount > 0 ? (
        <p className="mc-form__summary" role="alert">
          {errorCount === 1 ? 'One field needs attention before you can send this.' : `${errorCount} fields need attention before you can send this.`}
        </p>
      ) : null}

      <div className="mc-form__grid">
        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-name">
            Full name
          </label>
          <input {...fieldProps('name')} type="text" autoComplete="name" aria-required="true" />
          <MCFieldError id="mc-f-name-err" message={showError('name')} />
        </div>

        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-email">
            Email address
          </label>
          <input {...fieldProps('email')} type="email" autoComplete="email" inputMode="email" aria-required="true" />
          <MCFieldError id="mc-f-email-err" message={showError('email')} />
        </div>

        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-phone">
            Phone number
          </label>
          <input {...fieldProps('phone')} type="tel" autoComplete="tel" inputMode="tel" aria-required="true" />
          <MCFieldError id="mc-f-phone-err" message={showError('phone')} />
        </div>

        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-suburb">
            Suburb
          </label>
          <input {...fieldProps('suburb')} type="text" autoComplete="address-level2" aria-required="true" />
          <MCFieldError id="mc-f-suburb-err" message={showError('suburb')} />
        </div>

        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-service">
            Service required
          </label>
          <div className="mc-select">
            <select {...fieldProps('service')} aria-required="true">
              <option value="">Choose a service</option>
              {MC_SERVICES.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
            </select>
            <MCIcon name="chevron" className="mc-select__icon" />
          </div>
          {qfPreselected && qfValues.service ? (
            <p className="mc-field__notice">
              <MCIcon name="sparkle" />
              Selected from the page. You can change it here.
            </p>
          ) : null}
          <MCFieldError id="mc-f-service-err" message={showError('service')} />
        </div>

        <div className="mc-field">
          <label className="mc-field__label" htmlFor="mc-f-property">
            Property type
          </label>
          <div className="mc-select">
            <select {...fieldProps('property')} aria-required="true">
              <option value="">Choose a type</option>
              {MC_PROPERTY_TYPES.map((type) => (
                <option key={type} value={type}>
                  {type}
                </option>
              ))}
            </select>
            <MCIcon name="chevron" className="mc-select__icon" />
          </div>
          <MCFieldError id="mc-f-property-err" message={showError('property')} />
        </div>

        <div className="mc-field mc-field--full">
          <label className="mc-field__label" htmlFor="mc-f-date">
            Preferred cleaning date <span className="mc-field__opt">(optional)</span>
          </label>
          <input {...fieldProps('date')} type="date" min={today} />
          <p className="mc-field__hint" id="mc-f-date-hint">
            {MC_FORM_HINTS.date}
          </p>
          <MCFieldError id="mc-f-date-err" message={showError('date')} />
        </div>

        <div className="mc-field mc-field--full">
          <label className="mc-field__label" htmlFor="mc-f-details">
            Additional details <span className="mc-field__opt">(optional)</span>
          </label>
          <textarea {...fieldProps('details')} rows={4} maxLength={1200} />
          <p className="mc-field__hint" id="mc-f-details-hint">
            {MC_FORM_HINTS.details}
          </p>
          <MCFieldError id="mc-f-details-err" message={showError('details')} />
        </div>
      </div>

      <button type="submit" className="mc-btn mc-form__submit" disabled={qfStatus === 'sending'}>
        {qfStatus === 'sending' ? 'Sending…' : submitLabel}
        <MCIcon name="sparkle" className="mc-btn__spark" />
      </button>

      <p className="mc-form__fine">
        We use your details to reply to your enquiry and arrange your clean. Read our{' '}
        <MCPrivacyLink className="mc-link">privacy policy</MCPrivacyLink>.
      </p>

      {qfStatus === 'placeholder' ? (
        <div className="mc-form__status" role="status" tabIndex={-1} ref={qfStatusRef}>
          <p className="mc-form__status-title">
            <MCIcon name="info" />
            Not sent: this form isn’t connected yet
          </p>
          <p>
            Your details passed every check, but no booking system or backend is connected, so nothing has been sent
            and no one has been notified.
          </p>
          <p>
            <MCPh>Submission placeholder: set MC_CONFIG.formEndpoint in components/Shared.jsx or connect a booking platform</MCPh>
          </p>
        </div>
      ) : null}

      {qfStatus === 'error' ? (
        <div className="mc-form__status is-error" role="alert" tabIndex={-1} ref={qfStatusRef}>
          <p className="mc-form__status-title">
            <MCIcon name="alert" />
            Your enquiry wasn’t sent
          </p>
          <p>Check your connection and try again. Your details are still in the form.</p>
        </div>
      ) : null}
    </form>
  );
}

Object.assign(window, { MCQuoteForm, MCFieldError, mcValidateQuote, mcTodayISO, MC_PROPERTY_TYPES });
