// ─── Submit Modal ─────────────────────────────────────────────
// Renders over the main homepage. Opens when:
//   • window.OPEN_SUBMIT === true  (set by server when visiting /submit directly)
//   • window.location.hash === '#submit'  (in-page nav click)

function SubmitModal() {
  const user = window.CURRENT_USER;

  const [open, setOpen] = React.useState(
    !!(window.OPEN_SUBMIT || window.location.hash === '#submit')
  );

  // Form state
  const [selectedPeople, setSelectedPeople] = React.useState([]);
  const [newPeople, setNewPeople]           = React.useState([]);
  const [searchTerm, setSearchTerm]         = React.useState('');
  const [searchResults, setSearchResults]   = React.useState([]);
  const [showDropdown, setShowDropdown]     = React.useState(false);
  const [showNewPerson, setShowNewPerson]   = React.useState(false);
  const [newPerson, setNewPerson]           = React.useState({ name: '', bio: '', bioSource: '', bioLink: '' });
  const [fields, setFields]                 = React.useState({ location: '', date: '', guide: '', description: '', source: '', sourcedesc: '' });
  const [submitting, setSubmitting]         = React.useState(false);
  const [done, setDone]                     = React.useState(false);
  const [fileError, setFileError]           = React.useState('');
  const fileRef = React.useRef(null);

  // Hash / modal event / popstate listeners
  React.useEffect(() => {
    function onHash()   { if (window.location.hash === '#submit') setOpen(true); }
    function onModal(e) { if (e.detail === 'submit') setOpen(true); }
    function onPop()    { if (!window.location.pathname.includes('submit')) setOpen(false); }
    window.addEventListener('hashchange', onHash);
    window.addEventListener('not:modal',  onModal);
    window.addEventListener('popstate',   onPop);
    return () => {
      window.removeEventListener('hashchange', onHash);
      window.removeEventListener('not:modal',  onModal);
      window.removeEventListener('popstate',   onPop);
    };
  }, []);

  // ESC key
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') handleClose(); }
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);

  // People search
  React.useEffect(() => {
    if (!searchTerm) { setSearchResults([]); setShowDropdown(false); return; }
    fetch(`/api/search-names?q=${encodeURIComponent(searchTerm)}`, {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-Application-Request': 'true',
        'Accept': 'application/json'
      }
    })
      .then(r => r.json())
      .then(results => { setSearchResults(results); setShowDropdown(results.length > 0); })
      .catch(() => setShowDropdown(false));
  }, [searchTerm]);

  function handleClose() {
    setOpen(false);
    if (window.location.pathname.includes('submit')) {
      if (window.history.state && window.history.state.notModal) {
        history.back();
      } else {
        history.pushState({}, '', '/');
      }
    } else {
      history.pushState({}, '', window.location.pathname + window.location.search);
    }
  }

  function selectPerson(person) {
    if (!selectedPeople.some(p => p.name === person.name)) {
      setSelectedPeople(prev => [...prev, { name: person.name, id: person.id }]);
    }
    setSearchTerm('');
    setShowDropdown(false);
  }

  function removePerson(name) {
    setSelectedPeople(prev => prev.filter(p => p.name !== name));
  }

  function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
      const r = Math.random() * 16 | 0;
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
  }

  function saveNewPerson() {
    if (!newPerson.name || !newPerson.bio || !newPerson.bioSource) {
      alert('Please fill in Name, Bio, and Bio Source.');
      return;
    }
    const uuid = generateUUID();
    setNewPeople(prev => [...prev, { ...newPerson, uuid }]);
    setSelectedPeople(prev => [...prev, { name: newPerson.name, id: uuid }]);
    setNewPerson({ name: '', bio: '', bioSource: '', bioLink: '' });
    setShowNewPerson(false);
  }

  function handleFileChange(e) {
    const file = e.target.files[0];
    setFileError('');
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) {
      setFileError('File size must be 5MB or less.');
      e.target.value = '';
      return;
    }
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
      setFileError('Only JPG and PNG files are allowed.');
      e.target.value = '';
    }
  }

  async function handleSubmit(e) {
    e.preventDefault();
    if (selectedPeople.length === 0) { alert('Please add at least one person to the photo.'); return; }
    const file = fileRef.current?.files[0];
    if (!file) { alert('Please select a photo to upload.'); return; }

    setSubmitting(true);
    const fd = new FormData();
    fd.append('photo', file);
    fd.append('people', JSON.stringify(selectedPeople));
    fd.append('newPeople', JSON.stringify(newPeople));
    fd.append('location', fields.location);
    fd.append('date', fields.date);
    fd.append('guide', fields.guide);
    fd.append('description', fields.description);
    fd.append('source', fields.source);
    fd.append('sourcedesc', fields.sourcedesc);
    if (user?._id) fd.append('userId', user._id);

    try {
      const resp = await fetch('/api/photos/submit-photo', {
        method: 'POST',
        headers: {
          'xsrf-token': window.getCsrfToken ? window.getCsrfToken() : '',
          'X-Requested-With': 'XMLHttpRequest',
          'X-Application-Request': 'true'
        },
        body: fd
      });
      if (!resp.ok) {
        const data = await resp.json().catch(() => ({}));
        throw new Error(data.error || `HTTP ${resp.status}`);
      }
      setDone(true);
      setSelectedPeople([]);
      setNewPeople([]);
      setFields({ location: '', date: '', guide: '', description: '', source: '', sourcedesc: '' });
      if (fileRef.current) fileRef.current.value = '';
    } catch (err) {
      alert('Error submitting photo: ' + err.message);
    } finally {
      setSubmitting(false);
    }
  }

  if (!open) return null;

  return (
    <div className="abt-overlay" onClick={handleClose}>
      <div className="abt-panel sbt-panel" onClick={e => e.stopPropagation()}>

        <div className="abt-head">
          <span className="abt-label">Submit a Photo</span>
          <button className="abt-close" onClick={handleClose}>✕ close</button>
        </div>

        <div className="abt-body">

          {!user ? (
            /* ── Not logged in ── */
            <div>
              <h2 className="abt-section-head" style={{ marginTop: 0 }}>Contribute to the archive</h2>
              <p>You must be logged in to submit photos. Create an account or log in to contribute to the world's largest photo-based human connection archive.</p>
              <div className="sbt-auth-btns">
                <a href="/register.html" className="sbt-btn sbt-btn--primary">Create Account</a>
                <a href="/login.html" className="sbt-btn">Log In</a>
              </div>

              <h2 className="abt-section-head">Why join and submit?</h2>
              <ul>
                <li><strong>Track your connections</strong> — see how you connect to historical figures and modern celebrities.</li>
                <li><strong>Join the Leaderboard</strong> — could you be among the 1,000 most-connected people in history?</li>
                <li><strong>Build your legacy</strong> — ensure your place in this visual record of human connections.</li>
                <li><strong>Preserve memories</strong> — document meaningful encounters that might otherwise be lost.</li>
              </ul>

              <h2 className="abt-section-head">What photos can I submit?</h2>
              <ul>
                <li>Photos of yourself with other people (especially those already in our database)</li>
                <li>Historical photos showing multiple identifiable people</li>
                <li>Photos from events where notable individuals appeared together</li>
                <li>Family photos that connect to wider networks</li>
              </ul>
              <p className="sbt-muted">All submissions undergo review. Photos must show real meetings between people, with no digital manipulation.</p>
            </div>

          ) : done ? (
            /* ── Success ── */
            <div className="sbt-success">
              <h2 className="abt-section-head" style={{ marginTop: 0 }}>Photo submitted</h2>
              <p>Your photo is now pending review. Track its status on your <a href="/profile.html">profile page</a>.</p>
              <button className="sbt-btn sbt-btn--primary" onClick={() => setDone(false)}>Submit another</button>
            </div>

          ) : (
            /* ── Form ── */
            <form onSubmit={handleSubmit}>
              <p className="sbt-intro">Upload a photo and complete the form below. Your submission will be reviewed before being added to the database. You can view submission status on your <a href="/profile.html">profile page</a>.</p>

              {/* File upload */}
              <div className="sbt-field">
                <label className="sbt-label-field">Upload Photo</label>
                <input type="file" ref={fileRef} accept=".jpg,.jpeg,.png" onChange={handleFileChange} className="sbt-file-input" required />
                <p className="sbt-hint">JPG or PNG · max 5MB</p>
                {fileError && <p className="sbt-error">{fileError}</p>}
              </div>

              {/* People search */}
              <div className="sbt-field" style={{ position: 'relative' }}>
                <label className="sbt-label-field">People in Photo</label>
                <div className="sbt-search-row">
                  <input
                    type="text"
                    className="sbt-input"
                    placeholder="Search for a person…"
                    value={searchTerm}
                    onChange={e => setSearchTerm(e.target.value)}
                    onBlur={() => setTimeout(() => setShowDropdown(false), 150)}
                    autoComplete="off"
                  />
                  <button type="button" className="sbt-btn" onClick={() => setShowNewPerson(v => !v)}>
                    + New person
                  </button>
                </div>
                {showDropdown && searchResults.length > 0 && (
                  <div className="sbt-dropdown">
                    {searchResults.map(p => (
                      <button
                        type="button"
                        key={p.id}
                        className="sbt-dropdown-item"
                        onMouseDown={() => selectPerson(p)}
                      >{p.name}</button>
                    ))}
                  </div>
                )}
                {selectedPeople.length > 0 && (
                  <div className="sbt-chips">
                    {selectedPeople.map(p => (
                      <span key={p.name} className="sbt-chip">
                        {p.name} ✓
                        <button type="button" className="sbt-chip-remove" onClick={() => removePerson(p.name)}>×</button>
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* New person inline form */}
              {showNewPerson && (
                <div className="sbt-new-person">
                  <div className="sbt-field">
                    <label className="sbt-label-field">Name *</label>
                    <input className="sbt-input" value={newPerson.name} onChange={e => setNewPerson(p => ({ ...p, name: e.target.value }))} />
                  </div>
                  <div className="sbt-field">
                    <label className="sbt-label-field">Mini-Bio (100 words or less) *</label>
                    <textarea className="sbt-input" rows={2} value={newPerson.bio} onChange={e => setNewPerson(p => ({ ...p, bio: e.target.value }))} />
                  </div>
                  <div className="sbt-field">
                    <label className="sbt-label-field">Bio Source *</label>
                    <input className="sbt-input" value={newPerson.bioSource} onChange={e => setNewPerson(p => ({ ...p, bioSource: e.target.value }))} />
                  </div>
                  <div className="sbt-field">
                    <label className="sbt-label-field">Bio Link (optional)</label>
                    <input className="sbt-input" type="url" value={newPerson.bioLink} onChange={e => setNewPerson(p => ({ ...p, bioLink: e.target.value }))} />
                  </div>
                  <div className="sbt-new-person-actions">
                    <button type="button" className="sbt-btn" onClick={() => setShowNewPerson(false)}>Cancel</button>
                    <button type="button" className="sbt-btn sbt-btn--primary" onClick={saveNewPerson}>Save person</button>
                  </div>
                </div>
              )}

              {/* Location + Date */}
              <div className="sbt-row">
                <div className="sbt-field">
                  <label className="sbt-label-field">Location</label>
                  <input className="sbt-input" value={fields.location} onChange={e => setFields(f => ({ ...f, location: e.target.value }))} required />
                </div>
                <div className="sbt-field">
                  <label className="sbt-label-field">Date</label>
                  <input className="sbt-input" value={fields.date} onChange={e => setFields(f => ({ ...f, date: e.target.value }))} placeholder="YYYY-MM-DD or YYYY-MM or YYYY" required />
                </div>
              </div>

              {/* Guide */}
              <div className="sbt-field">
                <label className="sbt-label-field">Guide (left → right)</label>
                <input className="sbt-input" value={fields.guide} onChange={e => setFields(f => ({ ...f, guide: e.target.value }))} placeholder="Left-to-right guide to who appears in the photo" required />
              </div>

              {/* Description */}
              <div className="sbt-field">
                <label className="sbt-label-field">Description</label>
                <textarea className="sbt-input" rows={2} value={fields.description} onChange={e => setFields(f => ({ ...f, description: e.target.value }))} required />
              </div>

              {/* Source + Attribution */}
              <div className="sbt-row">
                <div className="sbt-field">
                  <label className="sbt-label-field">Source</label>
                  <input className="sbt-input" value={fields.source} onChange={e => setFields(f => ({ ...f, source: e.target.value }))} placeholder="URL or physical origin description" required />
                </div>
                <div className="sbt-field">
                  <label className="sbt-label-field">Photo Attribution</label>
                  <input className="sbt-input" value={fields.sourcedesc} onChange={e => setFields(f => ({ ...f, sourcedesc: e.target.value }))} required />
                </div>
              </div>

              <p className="sbt-muted">By submitting, you confirm you have the right to share this image and agree to our <a href="/terms.html">Terms of Service</a>.</p>

              <div className="sbt-submit-row">
                <button type="submit" className="sbt-btn sbt-btn--primary" disabled={submitting}>
                  {submitting ? 'Submitting…' : 'Submit Photo'}
                </button>
              </div>
            </form>
          )}

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SubmitModal });
