/* Keen Flows website, contact dialog. The single shared "Get in touch" form —
   opened from the nav button and the CTA band. Submits to api/contact.js
   (a Vercel serverless function that emails the submission via Gmail OAuth2). */
const { useState: useStateDlg } = React;
const KF_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function KFContactDialog({ open, onClose }) {
  const { Button, Input, Badge } = window.KeenFlowsDesignSystem_019e96;
  const [sent, setSent] = useStateDlg(false);
  const [busy, setBusy] = useStateDlg(false);
  const [error, setError] = useStateDlg('');
  const [email, setEmail] = useStateDlg('');
  const [company, setCompany] = useStateDlg('');
  const [automate, setAutomate] = useStateDlg('');
  const [website, setWebsite] = useStateDlg(''); // honeypot, must stay empty

  if (!open) return null;

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!KF_EMAIL_RE.test(email)) {
      setError('Enter a valid work email.');
      return;
    }
    setError('');
    setBusy(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, company, automate, website }),
      });
      if (!res.ok) throw new Error('request failed');
      setSent(true);
    } catch (err) {
      setError("That didn't go through, email us directly or try again.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="kfsite-modal" onClick={onClose}>
      <div className="kfsite-modal__panel" onClick={(e) => e.stopPropagation()}>
        <button className="kfsite-modal__close" onClick={onClose} aria-label="Close"><span className="kfsite-x"></span></button>

        {!sent ? (
          <form onSubmit={onSubmit}>
            <h3 className="kfsite-modal__title">Tell us what's slowing you down</h3>
            <p className="kfsite-modal__sub">Send us one workflow that's eating your time. We'll reply within one business day and tell you straight whether it's worth building.</p>
            <div className="kfsite-modal__form">
              <Input label="Work email" type="email" required placeholder="you@company.com" value={email} onChange={(e) => setEmail(e.target.value)} />
              <Input label="Company" placeholder="Acme Inc." value={company} onChange={(e) => setCompany(e.target.value)} />
              <Input label="What would you automate first?" placeholder="e.g. invoice triage, lead routing" value={automate} onChange={(e) => setAutomate(e.target.value)} />
              <input
                type="text"
                name="website"
                value={website}
                onChange={(e) => setWebsite(e.target.value)}
                autoComplete="off"
                tabIndex={-1}
                aria-hidden="true"
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
              />
            </div>
            <Button variant="primary" block type="submit" disabled={busy}>
              {busy ? 'Sending…' : 'Send message'}
            </Button>
            {error && <p className="kfsite-modal__fine" style={{ color: 'var(--color-danger)' }}>{error}</p>}
            {!error && <p className="kfsite-modal__fine">No pitch deck. No spam. A real engineer replies within one business day.</p>}
          </form>
        ) : (
          <div className="kfsite-modal__done">
            <div className="kfsite-modal__check"><img src="assets/keen-logo-mark-trim.png" alt="" /></div>
            <h3 className="kfsite-modal__title">Message sent</h3>
            <p className="kfsite-modal__sub">Thanks. We'll be in touch within one business day.</p>
            <Badge variant="success" dot>Message received</Badge>
            <div style={{ height: 16 }}></div>
            <Button variant="secondary" onClick={onClose}>Close</Button>
          </div>
        )}
      </div>
    </div>
  );
}

window.KFContactDialog = KFContactDialog;
