// ============================================================
// One Roof Labs — Home valuation lead form (top-of-homepage band)
// Posts to /api/home-value (Pages Function → D1: oneroof_leads)
// ============================================================

const HV_CSS = `
.hv-eyebrow { text-align: center; margin-bottom: 16px; }

.hv-card {
  background: #ffffff; border-radius: 14px; padding: 2.4rem 2.2rem;
  box-shadow: 0 30px 80px rgba(0,0,0,0.45);
  font-family: 'Hanken Grotesk', system-ui, sans-serif; color: #1a1a1a; line-height: 1.6;
}
.hv-card h2 { font-family: 'Cinzel', serif; font-size: 1.8rem; font-weight: 600; color: #100D09; margin: 0; letter-spacing: 0.01em; }
.hv-card .hv-sub { color: #6b6253; font-size: 1rem; margin: 0.35rem 0 1.7rem; }

.hv-group { margin-bottom: 1.2rem; }
.hv-group label { display: block; font-weight: 600; font-size: 0.92rem; color: #1a1a1a; margin-bottom: 0.5rem; }
.hv-group input {
  width: 100%; padding: 0.85rem 1rem; font-size: 1rem; font-family: inherit; color: #1a1a1a;
  background: #fff; border: 1px solid #d5d9dd; border-radius: 8px; transition: border-color .18s, box-shadow .18s;
}
.hv-group input::placeholder { color: #9aa0a6; }
.hv-group input:focus { outline: none; border-color: #0c2e3b; box-shadow: 0 0 0 3px rgba(12,46,59,0.12); }

.hv-consent { background: #eef4f7; border: 1px solid #dce6ec; border-radius: 8px; padding: 0.85rem 1rem; margin-bottom: 0.85rem; }
.hv-consent label { display: flex; gap: 0.7rem; align-items: flex-start; cursor: pointer; }
.hv-consent input[type="checkbox"] { margin-top: 0.2rem; width: 16px; height: 16px; flex-shrink: 0; accent-color: #0c2e3b; cursor: pointer; }
.hv-consent span { font-size: 0.82rem; color: #4a4f54; line-height: 1.5; }

.hv-links { display: flex; justify-content: center; gap: 1.75rem; margin: 1.1rem 0 1.35rem; }
.hv-links a { color: #b6553b; text-decoration: none; font-size: 0.92rem; font-weight: 600; }
.hv-links a:hover { text-decoration: underline; }

.hv-btn {
  width: 100%; padding: 1rem; font-size: 1.02rem; font-weight: 600; font-family: inherit; color: #F1E6CF;
  letter-spacing: 0.02em; cursor: pointer; border: none; border-radius: 8px;
  background: linear-gradient(180deg, #16384a 0%, #0c2e3b 100%); transition: filter .18s, transform .05s;
}
.hv-btn:hover { filter: brightness(1.1); }
.hv-btn:active { transform: translateY(1px); }
.hv-btn:disabled { opacity: 0.6; cursor: not-allowed; }

.hv-msg { margin-top: 1rem; font-size: 0.92rem; text-align: center; color: #c0392b; }

.hv-success { text-align: center; padding: 0.5rem 0 0.25rem; }
.hv-success .hv-check {
  width: 64px; height: 64px; margin: 0 auto 1.2rem; border-radius: 50%;
  background: #0c2e3b; color: #F1E6CF; font-size: 2rem; display: flex; align-items: center; justify-content: center;
}
.hv-success h2 { font-family: 'Cinzel', serif; font-size: 1.5rem; color: #100D09; margin-bottom: 0.6rem; }
.hv-success p { color: #6b6253; margin: 0; }

@media (max-width: 560px) {
  .hv-card { padding: 2rem 1.4rem; }
  .hv-card h2 { font-size: 1.5rem; }
  .hv-links { gap: 1.1rem; }
}
`;

function HomeValueForm() {
  const [form, setForm] = React.useState({
    address: '', name: '', email: '', phone: '', marketingConsent: false, transactionalConsent: false,
  });
  const [status, setStatus] = React.useState('idle'); // idle | submitting | done
  const [error, setError] = React.useState('');

  const set = (k) => (e) =>
    setForm((f) => ({ ...f, [k]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));

  async function onSubmit(e) {
    e.preventDefault();
    setError('');
    const address = form.address.trim(), name = form.name.trim(), email = form.email.trim();
    if (!address || !name || !email) { setError('Please fill in your address, name, and email.'); return; }
    setStatus('submitting');
    try {
      const res = await fetch('/api/home-value', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ ...form, address, name, email, phone: form.phone.trim() }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { setStatus('done'); return; }
      throw new Error(data.error || 'Request failed');
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
      setStatus('idle');
    }
  }

  return (
    <div id="home-value">
      <style>{HV_CSS}</style>
      <div className="hv-eyebrow kicker">Free Home Valuation · No Obligation</div>
      <div className="hv-card">
        {status === 'done' ? (
            <div className="hv-success">
              <div className="hv-check">&#10003;</div>
              <h2>Request received</h2>
              <p>Thanks — we&rsquo;ve got your details and a One Roof Labs specialist will be in touch with your home valuation shortly.</p>
            </div>
          ) : (
            <form onSubmit={onSubmit} noValidate>
              <h2>Get Your Home's Value</h2>
              <p className="hv-sub">Free, no-obligation home valuation</p>

              <div className="hv-group">
                <label htmlFor="hv-address">Property Address</label>
                <input id="hv-address" type="text" placeholder="Enter your property address"
                       value={form.address} onChange={set('address')} />
              </div>
              <div className="hv-group">
                <label htmlFor="hv-name">Your Name</label>
                <input id="hv-name" type="text" placeholder="Enter your full name"
                       value={form.name} onChange={set('name')} />
              </div>
              <div className="hv-group">
                <label htmlFor="hv-email">Email Address</label>
                <input id="hv-email" type="email" placeholder="Enter your email"
                       value={form.email} onChange={set('email')} />
              </div>
              <div className="hv-group">
                <label htmlFor="hv-phone">Phone Number (Optional)</label>
                <input id="hv-phone" type="tel" placeholder="Enter your phone number"
                       value={form.phone} onChange={set('phone')} />
              </div>

              <div className="hv-consent">
                <label>
                  <input type="checkbox" checked={form.marketingConsent} onChange={set('marketingConsent')} />
                  <span>By checking this box you agree to receive Marketing SMS from One Roof Labs. Message frequency varies. Message and data rates may apply. Reply HELP for help. STOP to opt out.</span>
                </label>
              </div>
              <div className="hv-consent">
                <label>
                  <input type="checkbox" checked={form.transactionalConsent} onChange={set('transactionalConsent')} />
                  <span>By checking this box you agree to receive Transactional SMS communication regarding account notifications and 2FA, from One Roof Labs. Message frequency may vary. Message and data rates may apply. Reply HELP for help or STOP to opt-out.</span>
                </label>
              </div>

              <div className="hv-links">
                <a href="/privacypolicy/">Privacy Policy</a>
                <a href="/termsofservice/">Terms of Service</a>
              </div>

              <button type="submit" className="hv-btn" disabled={status === 'submitting'}>
                {status === 'submitting' ? 'Submitting…' : 'Submit request'}
              </button>
              {error ? <p className="hv-msg">{error}</p> : null}
            </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HomeValueForm });
