// SourceRequestModal.jsx — "Add a marketplace we don't yet support".
//
// Same submit pipeline as the quote-request form: hits a dedicated public
// endpoint (POST /api/v1/source-request) that writes to a source_requests
// table; admins read it via the existing dashboard pattern. The Configurator
// renders an "Add missing source" card as the last item in the source grid;
// clicking it sets `window.AutoVizSourceRequest = true` which mounts this.
//
// Exposed globally via `window.SourceRequestModal` so the dashboard /app
// sidebar can reuse it later (Phase C — flagged TODO in the audit).

const { useState, useEffect, useRef } = React;

function SourceRequestModal({ open, onClose, defaultEmail, submittedFrom }) {
  const [form, setForm] = useState({
    source_name: '', country: '', url: '', email: defaultEmail || '', notes: '',
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const firstField = useRef(null);

  useEffect(() => {
    if (!open) return;
    setSubmitted(false);
    setErrors({});
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    // Focus the first input on open.
    setTimeout(() => firstField.current && firstField.current.focus(), 50);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  // Keep the prefill in sync if the parent changes defaultEmail (e.g. user
  // signed in between two source-request submissions).
  useEffect(() => {
    if (defaultEmail) setForm(f => f.email ? f : { ...f, email: defaultEmail });
  }, [defaultEmail]);

  if (!open) return null;

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  function validate() {
    const e = {};
    if (!form.source_name.trim()) e.source_name = 'Required';
    if (form.source_name.length > 200) e.source_name = 'Too long';
    if (form.url && form.url.length > 500) e.url = 'Too long';
    if (form.notes && form.notes.length > 2000) e.notes = 'Too long';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    if (!validate()) return;
    setSubmitting(true);
    try {
      const res = await fetch('/api/v1/source-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          source_name:    form.source_name.trim(),
          country:        form.country.trim(),
          url:            form.url.trim(),
          email:          form.email.trim(),
          notes:          form.notes.trim(),
          submitted_from: submittedFrom || 'landing',
        }),
      });
      if (!res.ok) {
        const j = await res.json().catch(() => ({}));
        setErrors({ _form: j.error || 'Could not submit. Please try again.' });
        return;
      }
      setSubmitted(true);
    } catch {
      setErrors({ _form: 'Network error. Please try again.' });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal--sm" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal__close" onClick={onClose} aria-label="Close">×</button>

        {submitted ? (
          <div className="modal__success">
            <h3>Thanks — we got it.</h3>
            <p>We'll review your suggestion and reach out if we need anything else. New sources usually go live within 2–4 weeks of being approved.</p>
            <button className="btn btn--primary" onClick={onClose}>Done</button>
          </div>
        ) : (
          <form onSubmit={onSubmit} className="modal__form">
            <h3 className="modal__title">Add a marketplace</h3>
            <p className="modal__subtitle">Don't see the site you want monitored? Tell us about it and we'll evaluate adding it.</p>

            <label className="modal__field">
              <span>Marketplace name *</span>
              <input
                ref={firstField}
                type="text"
                value={form.source_name}
                onChange={update('source_name')}
                placeholder="e.g. Hasznaltauto.hu"
                maxLength={200}
                aria-invalid={!!errors.source_name}
              />
              {errors.source_name && <em className="modal__err">{errors.source_name}</em>}
            </label>

            <div className="modal__row">
              <label className="modal__field">
                <span>Country</span>
                <input
                  type="text"
                  value={form.country}
                  onChange={update('country')}
                  placeholder="Hungary"
                  maxLength={100}
                />
              </label>
              <label className="modal__field">
                <span>URL</span>
                <input
                  type="url"
                  value={form.url}
                  onChange={update('url')}
                  placeholder="https://"
                  maxLength={500}
                  aria-invalid={!!errors.url}
                />
                {errors.url && <em className="modal__err">{errors.url}</em>}
              </label>
            </div>

            <label className="modal__field">
              <span>Your email (optional)</span>
              <input
                type="email"
                value={form.email}
                onChange={update('email')}
                placeholder="you@company.com"
              />
            </label>

            <label className="modal__field">
              <span>Anything else? (optional)</span>
              <textarea
                rows={3}
                value={form.notes}
                onChange={update('notes')}
                placeholder="What kinds of listings? Any specific filters?"
                maxLength={2000}
                aria-invalid={!!errors.notes}
              />
              {errors.notes && <em className="modal__err">{errors.notes}</em>}
            </label>

            {errors._form && <p className="modal__err modal__err--bar">{errors._form}</p>}

            <div className="modal__actions">
              <button type="button" className="btn btn--ghost" onClick={onClose}>Cancel</button>
              <button type="submit" className="btn btn--primary" disabled={submitting}>
                {submitting ? 'Sending…' : 'Send request'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SourceRequestModal });
