const { useState: useStateCTA } = React;

const WEBHOOK_URL = 'https://backend.production.portal.amalaxis.ai/api/v1/crm/webhooks/generic/?source_id=50cdffa9-cd9a-4bc5-8425-4e4808cd0c68&secret=5365889d-3e5a-4b18-9622-3be2bdb7ea32';

function CTA() {
  const [form, setForm] = useStateCTA({ name: '', email: '', phone: '', company: '', message: '' });
  const [status, setStatus] = useStateCTA('idle');
  const [errorMsg, setErrorMsg] = useStateCTA('');

  const update = (field) => (e) => setForm((f) => ({ ...f, [field]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'submitting') return;

    if (!form.name.trim() || !form.email.trim() || !form.phone.trim()) {
      setErrorMsg('Please fill in your name, email and phone.');
      setStatus('error');
      return;
    }

    setStatus('submitting');
    setErrorMsg('');

    const payload = {
      name: form.name.trim(),
      email: form.email.trim(),
      phone: form.phone.trim(),
      company: form.company.trim(),
      message: form.message.trim(),
      source: 'CallAxis Landing — Book Now',
      submitted_at: new Date().toISOString(),
    };

    try {
      const res = await fetch(WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const text = await res.text().catch(() => '');
        throw new Error(text || ('Request failed (' + res.status + ')'));
      }
      setStatus('success');
      setForm({ name: '', email: '', phone: '', company: '', message: '' });
    } catch (err) {
      try {
        await fetch(WEBHOOK_URL, {
          method: 'POST',
          mode: 'no-cors',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        setStatus('success');
        setForm({ name: '', email: '', phone: '', company: '', message: '' });
      } catch (err2) {
        setErrorMsg((err && err.message) || 'Could not submit. Please try again.');
        setStatus('error');
      }
    }
  };

  return (
    <section id="cta" style={{
      padding: '0 48px 120px',
      maxWidth: 1440, margin: '0 auto',
    }}>
      <div style={{
        background: 'var(--ink)',
        color: 'var(--bg)',
        borderRadius: 28,
        padding: '72px 64px',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute',
          right: -60, top: '50%',
          transform: 'translateY(-50%)',
          opacity: 0.35,
          pointerEvents: 'none',
        }}>
          <svg width="380" height="460" viewBox="0 0 380 460" fill="none">
            <defs>
              <radialGradient id="dialGrad" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4"/>
                <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
              </radialGradient>
            </defs>
            <circle cx="190" cy="230" r="200" fill="url(#dialGrad)"/>
            {Array.from({ length: 12 }).map((_, i) => {
              const row = Math.floor(i / 3);
              const col = i % 3;
              const x = 80 + col * 80;
              const y = 100 + row * 80;
              const labels = ['1','2','3','4','5','6','7','8','9','*','0','#'];
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r="28" fill="none" stroke="oklch(0.32 0.01 60)" strokeWidth="1"/>
                  <text x={x} y={y + 6} textAnchor="middle" fill="oklch(0.55 0.01 60)" fontSize="20" fontFamily="Instrument Serif">{labels[i]}</text>
                </g>
              );
            })}
          </svg>
        </div>

        <div style={{
          position: 'relative',
          display: 'grid',
          gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)',
          gap: 56,
          alignItems: 'start',
        }}>
          <div>
            <div className="mono" style={{
              fontSize: 11, color: 'oklch(0.7 0.01 60)',
              letterSpacing: '0.1em', marginBottom: 24,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span className="live-dot" style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--accent)' }}/>
              05 — GET STARTED
            </div>

            <h2 style={{
              fontSize: 'clamp(40px, 4.6vw, 64px)',
              lineHeight: 1.04,
              letterSpacing: '-0.03em',
              marginBottom: 24,
              paddingBottom: 4,
            }}>
              <span className="serif">Your phone line, </span>
              <span className="serif italic">powered by AI.</span>
            </h2>

            <p style={{ fontSize: 17, color: 'oklch(0.78 0.01 60)', lineHeight: 1.5, marginBottom: 32, maxWidth: 480 }}>
              Setup in 48 hours. Works on your existing number. Cancel anytime.
            </p>

            <div style={{
              display: 'grid', gridTemplateColumns: '1fr', gap: 14,
              paddingTop: 24, borderTop: '1px solid oklch(0.28 0.01 60)',
              color: 'oklch(0.78 0.01 60)', fontSize: 13,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Check/> No long-term contracts
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Check/> Live in 48 hours
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Check/> Onboarding handled by us
              </div>
            </div>
          </div>

          <BookForm
            form={form}
            update={update}
            status={status}
            errorMsg={errorMsg}
            onSubmit={handleSubmit}
          />
        </div>
      </div>
    </section>
  );
}

function Check() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" style={{ flexShrink: 0 }}>
      <path d="M3 8 6 11 13 4" stroke="var(--accent)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
    </svg>
  );
}

function BookForm({ form, update, status, errorMsg, onSubmit }) {
  const submitting = status === 'submitting';
  const success = status === 'success';

  return (
    <form
      onSubmit={onSubmit}
      style={{
        background: 'oklch(0.22 0.008 60)',
        border: '1px solid oklch(0.32 0.01 60)',
        borderRadius: 20,
        padding: 28,
        display: 'flex',
        flexDirection: 'column',
        gap: 14,
        position: 'relative',
      }}
    >
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 4,
      }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--bg)', letterSpacing: '-0.01em' }}>
          Book Now
        </div>
        <span className="mono" style={{
          fontSize: 10, color: 'oklch(0.65 0.01 60)',
          letterSpacing: '0.1em',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          <span className="live-dot" style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent)' }}/>
          REPLY IN 24H
        </span>
      </div>

      <Field
        label="Full name"
        value={form.name}
        onChange={update('name')}
        placeholder="Hassan Ali"
        required
        autoComplete="name"
        disabled={submitting}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field
          label="Email"
          type="email"
          value={form.email}
          onChange={update('email')}
          placeholder="you@business.com"
          required
          autoComplete="email"
          disabled={submitting}
        />
        <Field
          label="Phone"
          type="tel"
          value={form.phone}
          onChange={update('phone')}
          placeholder="+92 300 0000000"
          required
          autoComplete="tel"
          disabled={submitting}
        />
      </div>

      <Field
        label="Business / Company"
        value={form.company}
        onChange={update('company')}
        placeholder="Optional"
        autoComplete="organization"
        disabled={submitting}
      />

      <FieldArea
        label="What would you like to automate?"
        value={form.message}
        onChange={update('message')}
        placeholder="Optional — bookings, FAQs, after-hours, etc."
        disabled={submitting}
      />

      <button
        type="submit"
        disabled={submitting}
        style={{
          marginTop: 6,
          background: success ? 'var(--accent)' : 'var(--accent)',
          color: 'white',
          padding: '14px 22px',
          borderRadius: 999,
          fontSize: 15, fontWeight: 500,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          cursor: submitting ? 'wait' : 'pointer',
          opacity: submitting ? 0.7 : 1,
          transition: 'opacity 0.2s, background 0.2s',
        }}
      >
        {submitting ? 'Sending…' : success ? 'Sent — we’ll be in touch' : 'Book Now'}
        {!submitting && !success && (
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3 7h8m-3-3 3 3-3 3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        )}
      </button>

      {status === 'error' && errorMsg && (
        <div className="mono" style={{
          fontSize: 11, color: 'var(--warn)',
          letterSpacing: '0.04em',
          marginTop: 2,
        }}>
          {errorMsg}
        </div>
      )}
      {status === 'success' && (
        <div className="mono" style={{
          fontSize: 11, color: 'var(--accent)',
          letterSpacing: '0.04em',
          marginTop: 2,
        }}>
          THANKS — A SPECIALIST WILL REACH OUT SHORTLY.
        </div>
      )}

      <div style={{
        fontSize: 11, color: 'oklch(0.6 0.01 60)',
        marginTop: 4,
      }}>
        By submitting, you agree to be contacted about CallAxis.
      </div>
    </form>
  );
}

function Field({ label, ...props }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span className="mono" style={{
        fontSize: 10, color: 'oklch(0.7 0.01 60)',
        letterSpacing: '0.1em',
      }}>
        {label.toUpperCase()}
      </span>
      <input
        {...props}
        style={{
          background: 'oklch(0.18 0.008 60)',
          border: '1px solid oklch(0.32 0.01 60)',
          borderRadius: 10,
          padding: '11px 14px',
          color: 'var(--bg)',
          fontSize: 14,
          fontFamily: 'inherit',
          outline: 'none',
          width: '100%',
          transition: 'border-color 0.15s',
        }}
        onFocus={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; }}
        onBlur={(e) => { e.currentTarget.style.borderColor = 'oklch(0.32 0.01 60)'; }}
      />
    </label>
  );
}

function FieldArea({ label, ...props }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span className="mono" style={{
        fontSize: 10, color: 'oklch(0.7 0.01 60)',
        letterSpacing: '0.1em',
      }}>
        {label.toUpperCase()}
      </span>
      <textarea
        {...props}
        rows={3}
        style={{
          background: 'oklch(0.18 0.008 60)',
          border: '1px solid oklch(0.32 0.01 60)',
          borderRadius: 10,
          padding: '11px 14px',
          color: 'var(--bg)',
          fontSize: 14,
          fontFamily: 'inherit',
          outline: 'none',
          width: '100%',
          resize: 'vertical',
          minHeight: 72,
          transition: 'border-color 0.15s',
        }}
        onFocus={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; }}
        onBlur={(e) => { e.currentTarget.style.borderColor = 'oklch(0.32 0.01 60)'; }}
      />
    </label>
  );
}

window.CTA = CTA;
