/** MissionForm.jsx — "Submit a Royal Decree" */
const { useState: useStateMF } = React;

function MissionForm() {
  const [sent, setSent] = useStateMF(false);
  const [title, setTitle] = useStateMF('');
  const [decree, setDecree] = useStateMF('');
  
  // 1. We added two new memories to keep track of loading and errors!
  const [loading, setLoading] = useStateMF(false);
  const [error, setError] = useStateMF('');

  // 2. The real connection to your Vercel engine
  async function handleSubmit(e) {
    e.preventDefault(); // Stop the page from reloading
    if (!title.trim() || !decree.trim()) return;
    
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/decree', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title, decree: decree })
      });

      const data = await response.json();

      if (response.ok) {
        setSent(true); // Only show success if the database says YES!
      } else {
        setError(data.error || 'The vault is currently sealed.');
      }
    } catch (err) {
      setError('Network error. His Fluffiness tripped over the router cord.');
    } finally {
      setLoading(false);
    }
  }

  if (sent) {
    return (
      <div style={{padding: 40, textAlign:'center', background:'var(--parchment-50)', border:'3px solid var(--ink-900)', borderRadius:22, boxShadow:'6px 6px 0 var(--ink-900)'}}>
        <div style={{fontSize: 56, color:'var(--royal-gold-500)', lineHeight: 1}}>♛</div>
        <div style={{fontFamily:'var(--font-display)', fontWeight:800, fontSize:28, color:'var(--emerald-700)', marginTop: 12}}>Decree Received</div>
        <div style={{fontFamily:'var(--font-serif)', fontStyle:'italic', color:'var(--fg-2)', marginTop:6}}>His Fluffiness will consider it after his nap.</div>
        <button className="btn btn-ghost" style={{marginTop: 20}} onClick={() => { setSent(false); setTitle(''); setDecree(''); }}>Submit another</button>
      </div>
    );
  }

  return (
    // 3. We connect the form to our new handleSubmit function
    <form className="mission-form" onSubmit={handleSubmit}>
      {error && <div style={{color: 'red', marginBottom: '12px', fontStyle: 'italic', fontFamily:'var(--font-serif)'}}>{error}</div>}
      
      <div className="field">
        <label>Title of your decree</label>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="e.g. Mandatory tummy rubs, thrice daily" disabled={loading} />
      </div>
      
      <div className="field">
        <label>Your petition to the throne</label>
        <textarea rows={4} value={decree} onChange={e => setDecree(e.target.value)} placeholder="Speak, loyal subject. His Fluffiness is listening (barely)." disabled={loading} />
      </div>
      
      <div style={{display:'flex', gap: 10, alignItems:'center', justifyContent:'space-between'}}>
        <span style={{fontFamily:'var(--font-ui)', fontSize:11, color:'var(--fg-3)', letterSpacing:'0.1em', textTransform:'uppercase'}}>{decree.length}/500 scrolls</span>
        <div style={{display:'flex', gap: 8}}>
          <button type="button" className="btn btn-ghost" onClick={() => {setTitle(''); setDecree('');}} disabled={loading}>Beg Pardon</button>
          
          {/* 4. The button now changes text while it's thinking! */}
          <button type="submit" className="btn btn-gold" disabled={loading || !title.trim() || !decree.trim()}>
            {loading ? 'Dispatching... ♛' : 'By Royal Decree ♛'}
          </button>
        </div>
      </div>
    </form>
  );
}

window.MissionForm = MissionForm;
