Object.assign(window, { RegistrationForm });

const FORM_ID = 'reg_form_sozcuplus_v1';

/* ── Turkish flag SVG ── */
const TRFlag = () => (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 20" width="26" height="18"
    style={{ display: 'block', borderRadius: '2px', flexShrink: 0 }}>
    <rect width="30" height="20" fill="#E30A17"/>
    <circle cx="10.5" cy="10" r="5.2" fill="white"/>
    <circle cx="12.2" cy="10" r="4.1" fill="#E30A17"/>
    <polygon fill="white" points="18.2,7.2 19.2,10.3 22.4,10.4 19.9,12.3 20.8,15.4 18.2,13.6 15.6,15.4 16.5,12.3 14,10.4 17.2,10.3"/>
  </svg>
);

/* ── Phone input with static +90 prefix ── */
function PhoneInput({ value, onChange, error }) {
  return (
    <div style={{ marginBottom: '10px' }}>
      <div style={{
        display: 'flex', alignItems: 'center',
        border: error ? '1.5px solid #CC0000' : '1px solid #ddd',
        borderRadius: '4px', background: '#fff', overflow: 'hidden',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: '6px',
          padding: '0 10px', borderRight: '1px solid #e0e0e0',
          background: '#f5f5f5', flexShrink: 0, height: '46px',
        }}>
          <TRFlag />
          <span style={{ fontSize: '14px', color: '#333', fontFamily: 'Arial, sans-serif', fontWeight: 500 }}>
            +90
          </span>
        </div>
        <input
          type="tel"
          placeholder="501 234 56 78"
          value={value}
          onChange={onChange}
          maxLength={10}
          style={{
            flex: 1, padding: '12px 14px', fontSize: '14px',
            border: 'none', outline: 'none',
            fontFamily: 'Arial, sans-serif', color: '#333', background: '#fff',
          }}
        />
      </div>
      {error && <div style={{ color: '#CC0000', fontSize: '11px', marginTop: '3px' }}>{error}</div>}
    </div>
  );
}

/* ── Text input ── */
function TextField({ value, placeholder, error, onChange }) {
  return (
    <div style={{ marginBottom: '10px' }}>
      <input
        type="text"
        placeholder={placeholder}
        value={value}
        onChange={onChange}
        style={{
          width: '100%', padding: '12px 14px', fontSize: '14px',
          border: error ? '1.5px solid #CC0000' : '1px solid #ddd',
          borderRadius: '4px', boxSizing: 'border-box',
          outline: 'none', fontFamily: 'Arial, sans-serif', color: '#333', background: '#fff',
        }}
      />
      {error && <div style={{ color: '#CC0000', fontSize: '11px', marginTop: '3px' }}>{error}</div>}
    </div>
  );
}

/* ── Form hook ── */
function useForm(formId) {
  const [fields, setFields] = React.useState({ nombre: '', apellido: '', email: '', phone: '', website: '' });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const set = (k, v) => setFields(f => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (fields.nombre.trim().length < 2)  e.nombre   = 'En az 2 karakter giriniz';
    if (fields.apellido.trim().length < 2) e.apellido = 'En az 2 karakter giriniz';
    if (!fields.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fields.email)) e.email = 'Geçerli e-posta girin';
    const digits = fields.phone.replace(/\D/g, '');
    if (digits.length !== 10) e.telefono = 'Geçerli telefon numarası girin';
    return e;
  };

  const submit = async ev => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    const telefono = '+90' + fields.phone.replace(/\D/g, '');
    const subid         = localStorage.getItem('sozcuplus_subid')         || '';
    const campaign_name = localStorage.getItem('sozcuplus_campaign_name') || '';
    const adset_name    = localStorage.getItem('sozcuplus_adset_name')    || '';
    const ad_name       = localStorage.getItem('sozcuplus_ad_name')       || '';
    if (/localhost|127\.0\.0\.1/.test(location.hostname)) {
      location.href = './thank-you.html';
      return;
    }
    try {
      const res = await fetch('/api/send.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...fields, telefono, form_id: formId, subid, campaign_name, adset_name, ad_name }),
      });
      const json = await res.json().catch(() => ({ ok: true }));
      if (json.errors) {
        const srv = {};
        if (Array.isArray(json.errors)) json.errors.forEach(f => { srv[f] = 'Hatalı alan'; });
        else Object.assign(srv, json.errors);
        setErrors(srv);
        setLoading(false);
        return;
      }
      if (json.redirect) {
        location.href = './thank-you.html?to=' + encodeURIComponent(json.redirect);
        return;
      }
    } catch (_) {}
    location.href = './thank-you.html';
  };

  return { fields, errors, loading, set, submit };
}

/* ── Registration form ── */
function RegistrationForm() {
  const { fields, errors, loading, set, submit } = useForm(FORM_ID);

  return (
    <div className="quiz-box" style={{
      maxWidth: '420px', margin: '0 auto',
      background: '#fff', border: '1px solid #e0e0e0',
      borderRadius: '6px', padding: '28px 24px 24px',
    }}>
      {/* İşbank logo */}
      <div style={{ textAlign: 'center', marginBottom: '24px' }}>
        <img src="./index/islg.png" alt="Türkiye İş Bankası"
          style={{ height: '56px', display: 'inline-block' }}
          onError={e => e.target.style.display = 'none'} />
      </div>

      <form onSubmit={submit}>
        <TextField
          placeholder="İlk İsim"
          value={fields.nombre}
          error={errors.nombre}
          onChange={e => set('nombre', e.target.value)}
        />
        <TextField
          placeholder="Soyadı"
          value={fields.apellido}
          error={errors.apellido}
          onChange={e => set('apellido', e.target.value)}
        />
        <div style={{ marginBottom: '10px' }}>
          <input
            type="email"
            placeholder="E-posta"
            value={fields.email}
            onChange={e => set('email', e.target.value)}
            style={{
              width: '100%', padding: '12px 14px', fontSize: '14px',
              border: errors.email ? '1.5px solid #CC0000' : '1px solid #ddd',
              borderRadius: '4px', boxSizing: 'border-box',
              outline: 'none', fontFamily: 'Arial, sans-serif', color: '#333', background: '#fff',
            }}
          />
          {errors.email && <div style={{ color: '#CC0000', fontSize: '11px', marginTop: '3px' }}>{errors.email}</div>}
        </div>
        <PhoneInput
          value={fields.phone}
          error={errors.telefono}
          onChange={e => set('phone', e.target.value.replace(/\D/g, ''))}
        />

        {/* Honeypot */}
        <input type="text" name="website" value={fields.website}
          onChange={e => set('website', e.target.value)}
          style={{ display: 'none' }} tabIndex={-1} autoComplete="off" />

        <button type="submit" disabled={loading} style={{
          width: '100%', padding: '14px',
          background: loading ? '#c0392b' : '#E30A17',
          color: '#fff', fontSize: '15px', fontWeight: 700,
          border: 'none', borderRadius: '4px',
          cursor: loading ? 'not-allowed' : 'pointer',
          textTransform: 'uppercase', letterSpacing: '0.5px',
          fontFamily: 'Arial, sans-serif', marginTop: '6px',
          opacity: loading ? 0.8 : 1,
        }}>
          {loading ? 'Gönderiliyor…' : 'ÜCRETSİZ KAYIT'}
        </button>
      </form>
    </div>
  );
}
