function LoginPage({ onGo, onAuth }) {
  const [user, setUser] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState(null);

  async function handleSubmit(e) {
    e.preventDefault();
    setMsg(null);
    setLoading(true);
    try {
      const res = await fetch('/api/admin-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user, password })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Login failed');
      window.setAdminToken(data.token);
      onAuth?.();
      onGo('publish');
    } catch (err) {
      console.error(err);
      setMsg({ type: 'error', text: err.message || 'Login failed' });
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="wrap" style={{padding: '48px 0', maxWidth: 760}}>
      <h1>Admin login</h1>
      <p style={{color: 'var(--fg-2)'}}>Sign in to access the publish admin page.</p>
      <form onSubmit={handleSubmit}>
        <label style={{display: 'block', marginBottom: 8}}>Username</label>
        <input value={user} onChange={e => setUser(e.target.value)} style={{width: '100%', padding: 12, marginBottom: 12}} />
        <label style={{display: 'block', marginBottom: 8}}>Password</label>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)} style={{width: '100%', padding: 12, marginBottom: 12}} />
        <div style={{display: 'flex', gap: 12}}>
          <button className="btn btn--primary" disabled={loading || !user || !password} type="submit">{loading ? 'Signing in…' : 'Sign in'}</button>
          <button className="btn btn--ghost" type="button" onClick={() => onGo('insights')}>Back</button>
        </div>
        {msg && <div style={{marginTop: 12, color: msg.type === 'error' ? 'crimson' : 'green'}}>{msg.text}</div>}
      </form>
    </section>
  );
}

window.LoginPage = LoginPage;

function PublishPage({ onGo }) {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState(null);

  async function handleSubmit(e) {
    e.preventDefault();
    setMsg(null);
    setLoading(true);
    try {
      // default proxy path assumes Vercel deployment at project root
      const res = await publishViaProxy({ title, content }, '/api/publish');
      setMsg({ type: 'success', text: `Published (ID ${res.id})` });
      setTitle(''); setContent('');
    } catch (err) {
      console.error(err);
      setMsg({ type: 'error', text: err.message || 'Publish failed' });
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="wrap" style={{padding: '48px 0'}}>
      <h1>Publish (Admin)</h1>
      <p style={{color: 'var(--fg-2)'}}>This form posts to `/api/publish` and requires an admin session token.</p>
      <form onSubmit={handleSubmit} style={{maxWidth: 760}}>
        <label style={{display: 'block', marginBottom: 8}}>Title</label>
        <input value={title} onChange={e => setTitle(e.target.value)} style={{width: '100%', padding: 12, marginBottom: 12}} />
        <label style={{display: 'block', marginBottom: 8}}>Content (HTML allowed)</label>
        <textarea value={content} onChange={e => setContent(e.target.value)} rows={12} style={{width: '100%', padding: 12, marginBottom: 12}} />
        <div style={{display: 'flex', gap: 12}}>
          <button className="btn btn--primary" disabled={loading || !title || !content} type="submit">{loading ? 'Publishing…' : 'Publish'}</button>
          <button className="btn btn--ghost" type="button" onClick={() => onGo('insights')}>Cancel</button>
        </div>
        {msg && <div style={{marginTop: 12, color: msg.type === 'error' ? 'crimson' : 'green'}}>{msg.text}</div>}
      </form>
    </section>
  );
}

window.PublishPage = PublishPage;
