/* eslint-disable no-undef */
// Save the date / inquiry form + Footer

function SaveDate() {
  const [form, setForm] = React.useState({
    name: '', partner: '', email: '', phone: '',
    type: 'Wedding', date: '', location: '', collection: 'The Digital — $1,000', message: ''
  });
  const [status, setStatus] = React.useState('idle');
  const [errors, setErrors] = React.useState({});

  const validateField = (k, value) => {
    if (k === 'name') return value.trim() ? null : 'Required';
    if (k === 'email') {
      if (!value.trim()) return 'Required';
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) return 'Looks off';
      return null;
    }
    if (k === 'date') return value.trim() ? null : 'Required';
    return null;
  };

  const validate = () => {
    const e = {};
    for (const k of ['name', 'email', 'date']) {
      const err = validateField(k, form[k]);
      if (err) e[k] = err;
    }
    return e;
  };

  // Re-validates only the field being edited, and only once it already has a
  // visible error — otherwise a stale "Required" lingers under a field the
  // user just fixed, right up until their next submit attempt.
  const onChange = (k) => (e) => {
    const value = e.target.value;
    setForm(f => ({ ...f, [k]: value }));
    setErrors(prev => {
      if (!(k in prev)) return prev;
      const err = validateField(k, value);
      if (!err) {
        const { [k]: _omit, ...rest } = prev;
        return rest;
      }
      return prev[k] === err ? prev : { ...prev, [k]: err };
    });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const er = validate();
    setErrors(er);
    if (Object.keys(er).length) return;
    setStatus('submitting');
    fetch('/api/inquiry', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form)
    })
      .then(res => {
        if (!res.ok) throw new Error('request failed');
        setStatus('done');
      })
      .catch(() => setStatus('error'));
  };

  // Renders a label+error pair wired to the given field id: htmlFor/id for
  // programmatic association, aria-invalid + aria-describedby so a screen
  // reader announces the error together with the input, not just the input.
  const errorId = (k) => `sd-${k}-error`;

  return (
    <section id="save" className="save">
      <div className="container save-inner">
        <div className="reveal eyebrow" style={{ color: 'var(--on-deep-soft)' }}>Ready to get started?</div>
        <h2 className="save-title reveal delay-1">Save Your Date</h2>
        <p className="save-sub reveal delay-2">
          Please fill out the form below — kindly allow 24 hours for a response. I take a limited number of dates each season so I can pour everything into yours.
        </p>

        <div className="form reveal delay-3">
          {status === 'done' ? (
            <div className="form-success">
              <div className="check"><Icon.Check /></div>
              <h3>Thank you!</h3>
              <p>Your inquiry is on its way. I'll be in touch within 24 hours — keep an eye on your inbox.</p>
            </div>
          ) : (
            <form onSubmit={onSubmit} noValidate>
              <div className="form-row">
                <div className={`field ${errors.name ? 'field-error' : ''}`}>
                  <label htmlFor="sd-name">Your name *</label>
                  <input
                    id="sd-name"
                    value={form.name}
                    onChange={onChange('name')}
                    placeholder="First & last"
                    autoComplete="name"
                    aria-invalid={!!errors.name}
                    aria-describedby={errors.name ? errorId('name') : undefined}
                  />
                  {errors.name && <small id={errorId('name')} style={{ color: '#a04848', fontStyle: 'italic' }}>{errors.name}</small>}
                </div>
                <div className="field">
                  <label htmlFor="sd-partner">Partner's name</label>
                  <input id="sd-partner" value={form.partner} onChange={onChange('partner')} placeholder="Optional" autoComplete="off" />
                </div>
              </div>

              <div className="form-row">
                <div className={`field ${errors.email ? 'field-error' : ''}`}>
                  <label htmlFor="sd-email">Email *</label>
                  <input
                    id="sd-email"
                    type="email"
                    value={form.email}
                    onChange={onChange('email')}
                    placeholder="you@email.com"
                    autoComplete="email"
                    inputMode="email"
                    aria-invalid={!!errors.email}
                    aria-describedby={errors.email ? errorId('email') : undefined}
                  />
                  {errors.email && <small id={errorId('email')} style={{ color: '#a04848', fontStyle: 'italic' }}>{errors.email}</small>}
                </div>
                <div className="field">
                  <label htmlFor="sd-phone">Phone</label>
                  <input id="sd-phone" value={form.phone} onChange={onChange('phone')} placeholder="(415) 555-0100" autoComplete="tel" inputMode="tel" />
                </div>
              </div>

              <div className="form-row">
                <div className="field">
                  <label htmlFor="sd-type">Event type</label>
                  <select id="sd-type" value={form.type} onChange={onChange('type')}>
                    <option>Wedding</option>
                    <option>Engagement</option>
                    <option>Rehearsal Dinner</option>
                    <option>Quinceañera</option>
                    <option>Corporate / Brand</option>
                    <option>Other</option>
                  </select>
                </div>
                <div className={`field ${errors.date ? 'field-error' : ''}`}>
                  <label htmlFor="sd-date">Event date *</label>
                  <input
                    id="sd-date"
                    type="date"
                    value={form.date}
                    onChange={onChange('date')}
                    aria-invalid={!!errors.date}
                    aria-describedby={errors.date ? errorId('date') : undefined}
                  />
                  {errors.date && <small id={errorId('date')} style={{ color: '#a04848', fontStyle: 'italic' }}>{errors.date}</small>}
                </div>
              </div>

              <div className="form-row">
                <div className="field">
                  <label htmlFor="sd-location">Location / venue</label>
                  <input id="sd-location" value={form.location} onChange={onChange('location')} placeholder="City, venue if known" autoComplete="off" />
                </div>
                <div className="field">
                  <label htmlFor="sd-collection">Collection of interest</label>
                  <select id="sd-collection" value={form.collection} onChange={onChange('collection')}>
                    <option>The Digital — $1,000</option>
                    <option>The Vintage — $1,500</option>
                    <option>Not sure yet</option>
                  </select>
                </div>
              </div>

              <div className="form-row">
                <div className="field full">
                  <label htmlFor="sd-message">Tell me about your day</label>
                  <textarea
                    id="sd-message"
                    value={form.message}
                    onChange={onChange('message')}
                    rows="4"
                    placeholder="Vision, vibe, where you'll be — anything you'd like me to know."
                  ></textarea>
                </div>
              </div>

              <div className="form-foot">
                <small>Kindly allow 24 hours for a thoughtful reply.</small>
                <button type="submit" className="btn" disabled={status === 'submitting'}>
                  {status === 'submitting' ? 'Sending…' : <>Send inquiry <Icon.Arrow /></>}
                </button>
              </div>
              {status === 'error' && (
                <p role="alert" style={{ color: '#a04848', fontStyle: 'italic', marginTop: '0.75rem' }}>
                  Something went wrong — please email me directly at everafterbykate@gmail.com
                </p>
              )}
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">Ever After</div>
            <p className="footer-tag">Heartfelt &amp; thoughtfully curated wedding and event content for couples in the Bay Area and Sacramento.</p>
          </div>
          <div>
            <h4>Explore</h4>
            <ul>
              {window.SITE.NAV.map(n => <li key={n.href}><a href={n.href}>{n.label}</a></li>)}
            </ul>
          </div>
          <div>
            <h4>Service Area</h4>
            <ul>
              <li><a>Bay Area</a></li>
              <li><a>Sacramento</a></li>
              <li><a>Sonoma · Napa</a></li>
              <li><a>Tahoe</a></li>
              <li><a>Available for travel</a></li>
            </ul>
          </div>
          <div>
            <h4>Stay close</h4>
            <ul>
              <li><a href="mailto:everafterbykate@gmail.com">everafterbykate@gmail.com</a></li>
              <li><a href="https://www.instagram.com/everafterbykate/reels/" target="_blank" rel="noopener">@everafterbykate</a></li>
            </ul>
            <div className="socials">
              <a className="social-btn" href="https://www.instagram.com/everafterbykate/reels/" target="_blank" rel="noopener" aria-label="Instagram"><Icon.Instagram /></a>
              <a className="social-btn" href="mailto:everafterbykate@gmail.com" aria-label="Email"><Icon.Mail /></a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Ever After by Kate · Bay Area &amp; Sacramento</span>
          <span>Site by <a className="footer-credit" href="https://builtbybijan.com/" target="_blank" rel="noopener">B3</a></span>
        </div>
      </div>
    </footer>
  );
}

window.SaveDate = SaveDate;
window.Footer = Footer;
