// Era Koleji — application form

const Form = () => {
  const [form, setForm] = React.useState({
    fullname: "",
    tc: "",
    phone: "",
    email: "",
    school: "",
    pref1: "",
    pref2: "",
    why: "",
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const filledCount = Object.values(form).filter(v => v.trim().length > 0).length;
  const progress = Math.round((filledCount / 8) * 100);

  const validate = () => {
    const e = {};
    if (!form.fullname.trim() || form.fullname.trim().split(" ").length < 2) {
      e.fullname = "Lütfen ad ve soyadınızı girin.";
    }
    if (!/^[1-9][0-9]{10}$/.test(form.tc)) {
      e.tc = "TC Kimlik No 11 haneli olmalı, 0 ile başlamamalıdır.";
    }
    if (!/^(\+90|0)?\s?5\d{2}\s?\d{3}\s?\d{2}\s?\d{2}$/.test(form.phone.replace(/\s/g, ""))) {
      e.phone = "Geçerli bir telefon numarası girin.";
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
      e.email = "Geçerli bir e-posta adresi girin.";
    }
    if (!form.school.trim()) {
      e.school = "Okul ve sınıf bilgisi gerekli.";
    }
    if (!form.pref1) {
      e.pref1 = "1. tercihinizi seçin.";
    }
    if (!form.pref2) {
      e.pref2 = "2. tercihinizi seçin.";
    }
    if (form.pref1 && form.pref2 && form.pref1 === form.pref2) {
      e.pref2 = "1. ve 2. tercih farklı komiteler olmalıdır.";
    }
    if (!form.why.trim() || form.why.trim().length < 20) {
      e.why = "En az 20 karakter ile motivasyonunuzu paylaşın.";
    }
    return e;
  };

  const handleChange = (k) => (ev) => {
    let val = ev.target.value;
    if (k === "tc") val = val.replace(/\D/g, "").slice(0, 11);
    if (k === "phone") val = val.replace(/[^\d+\s]/g, "").slice(0, 17);
    setForm({ ...form, [k]: val });
    if (errors[k]) setErrors({ ...errors, [k]: undefined });
  };

  const handleSubmit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) {
      setSubmitting(true);
      (async () => {
        const id = "EKUF-" + Math.floor(Math.random() * 9000 + 1000);
        const c1 = COMMITTEES.find(c => c.id === form.pref1);
        const c2 = COMMITTEES.find(c => c.id === form.pref2);
        const row = {
          id,
          fullname: form.fullname,
          tc: form.tc,
          phone: form.phone,
          email: form.email,
          school: form.school,
          pref1: form.pref1,
          pref2: form.pref2,
          pref1_name: c1?.name,
          pref2_name: c2?.name,
          why: form.why,
          status: "pending",
        };
        try {
          if (window.SB) {
            const { error } = await window.SB.from("applications").insert(row);
            if (error) throw error;
          }
          window._lastAppId = id;
          setSubmitting(false);
          setSubmitted(true);
        } catch (err) {
          console.error(err);
          setSubmitting(false);
          setErrors({ submit: "Başvuru gönderilemedi: " + (err.message || "Sunucu hatası") });
        }
      })();
    } else {
      const first = document.querySelector(".form-input.invalid, .form-select.invalid, .form-textarea.invalid");
      if (first) first.focus({ preventScroll: false });
    }
  };

  const findCommittee = (id) => COMMITTEES.find(c => c.id === id);

  if (submitted) {
    const p1 = findCommittee(form.pref1);
    const p2 = findCommittee(form.pref2);
    return (
      <div className="form-card">
        <div className="form-success">
          <div className="form-success-mark">
            <Icon name="check" size={42} stroke={2.4} />
          </div>
          <h3>Başvurunuz Alındı!</h3>
          <p>
            Era Koleji Ulusal Formu'na gösterdiğiniz ilgi için teşekkür ederiz.
            Başvurunuz değerlendirildikten sonra sizinle e-posta yoluyla iletişime geçeceğiz.
          </p>
          <div className="form-receipt">
            <div className="form-receipt-row">
              <div className="form-receipt-key">Ad Soyad</div>
              <div className="form-receipt-val">{form.fullname}</div>
            </div>
            <div className="form-receipt-row">
              <div className="form-receipt-key">1. Tercih</div>
              <div className="form-receipt-val">{p1?.name}</div>
            </div>
            <div className="form-receipt-row">
              <div className="form-receipt-key">2. Tercih</div>
              <div className="form-receipt-val">{p2?.name}</div>
            </div>
            <div className="form-receipt-row">
              <div className="form-receipt-key">Başvuru No</div>
              <div className="form-receipt-val">{window._lastAppId || "EKUF-0000"}</div>
            </div>
          </div>
          <button
            className="btn btn-ghost"
            onClick={() => {
              setSubmitted(false);
              setForm({ fullname: "", tc: "", phone: "", email: "", school: "", pref1: "", pref2: "", why: "" });
            }}
          >
            Yeni Başvuru
          </button>
        </div>
      </div>
    );
  }

  const inputCls = (k) => `form-input${errors[k] ? " invalid" : ""}`;
  const selectCls = (k) => `form-select${errors[k] ? " invalid" : ""}`;
  const textareaCls = (k) => `form-textarea${errors[k] ? " invalid" : ""}`;

  return (
    <form className="form-card" onSubmit={handleSubmit} noValidate>
      <div className="form-progress">
        <span>Başvuru</span>
        <div className="form-progress-bar">
          <div className="form-progress-fill" style={{ width: `${progress}%` }} />
        </div>
        <span>{progress}%</span>
      </div>

      <div className="form-row">
        <div className="form-field">
          <label>Ad Soyad<span className="req">*</span></label>
          <input
            className={inputCls("fullname")}
            type="text"
            value={form.fullname}
            onChange={handleChange("fullname")}
            placeholder="Örn. Ayşe Yılmaz"
            autoComplete="name"
          />
          {errors.fullname && <span className="form-error">{errors.fullname}</span>}
        </div>
        <div className="form-field">
          <label>TC Kimlik No<span className="req">*</span></label>
          <input
            className={inputCls("tc")}
            type="text"
            inputMode="numeric"
            value={form.tc}
            onChange={handleChange("tc")}
            placeholder="11 haneli kimlik no"
          />
          {errors.tc
            ? <span className="form-error">{errors.tc}</span>
            : <span className="form-help">Bilgileriniz gizli tutulur, üçüncü taraflarla paylaşılmaz.</span>
          }
        </div>
      </div>

      <div className="form-row">
        <div className="form-field">
          <label>Telefon<span className="req">*</span></label>
          <input
            className={inputCls("phone")}
            type="tel"
            value={form.phone}
            onChange={handleChange("phone")}
            placeholder="0 (5XX) XXX XX XX"
            autoComplete="tel"
          />
          {errors.phone && <span className="form-error">{errors.phone}</span>}
        </div>
        <div className="form-field">
          <label>E-posta<span className="req">*</span></label>
          <input
            className={inputCls("email")}
            type="email"
            value={form.email}
            onChange={handleChange("email")}
            placeholder="ornek@mail.com"
            autoComplete="email"
          />
          {errors.email && <span className="form-error">{errors.email}</span>}
        </div>
      </div>

      <div className="form-field">
        <label>Okul / Sınıf<span className="req">*</span></label>
        <input
          className={inputCls("school")}
          type="text"
          value={form.school}
          onChange={handleChange("school")}
          placeholder="Örn. Era Koleji — 11/A"
        />
        {errors.school && <span className="form-error">{errors.school}</span>}
      </div>

      <div className="form-divider" />

      <div className="form-row">
        <div className="form-field">
          <label className="form-pref-label">
            <span className="form-pref-tag">1</span>
            <span>Komite — 1. Tercih<span className="req">*</span></span>
          </label>
          <select
            className={selectCls("pref1")}
            value={form.pref1}
            onChange={handleChange("pref1")}
          >
            <option value="">Öncelikli komitenizi seçin</option>
            {COMMITTEES.map(c => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
          {errors.pref1
            ? <span className="form-error">{errors.pref1}</span>
            : <span className="form-help">Katılmak istediğiniz öncelikli komite.</span>
          }
        </div>
        <div className="form-field">
          <label className="form-pref-label">
            <span className="form-pref-tag alt">2</span>
            <span>Komite — 2. Tercih<span className="req">*</span></span>
          </label>
          <select
            className={selectCls("pref2")}
            value={form.pref2}
            onChange={handleChange("pref2")}
          >
            <option value="">Yedek komitenizi seçin</option>
            {COMMITTEES.filter(c => c.id !== form.pref1).map(c => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
          {errors.pref2
            ? <span className="form-error">{errors.pref2}</span>
            : <span className="form-help">1. tercih dolarsa atanacağınız komite.</span>
          }
        </div>
      </div>

      <div className="form-field">
        <label>Neden Katılmak İstiyorsun?<span className="req">*</span></label>
        <textarea
          className={textareaCls("why")}
          value={form.why}
          onChange={handleChange("why")}
          placeholder="Birkaç cümle ile motivasyonunuzu paylaşın..."
          rows={4}
        />
        {errors.why
          ? <span className="form-error">{errors.why}</span>
          : <span className="form-help">{form.why.length}/20+ karakter</span>
        }
      </div>

      <button type="submit" className="form-submit" disabled={submitting}>
        {submitting ? (
          <>Gönderiliyor…</>
        ) : (
          <>
            Başvuruyu Gönder
            <Icon name="arrow" size={18} stroke={2.4} />
          </>
        )}
      </button>
      {errors.submit && <span className="form-error" style={{ marginTop: 12, display: "block", textAlign: "center" }}>{errors.submit}</span>}
    </form>
  );
};

const Apply = () => (
  <section id="apply">
    <div className="container">
      <SectionHead
        eyebrow="Başvuru"
        title="Yerinizi <em>Ayırtın</em>"
        lead="Era Koleji Ulusal Formu'na katılmak için aşağıdaki formu doldurun. Başvurunuz değerlendirildikten sonra sizinle iletişime geçeceğiz."
      />
      <div className="apply-wrap">
        <aside className="apply-aside reveal">
          <div className="apply-aside-mark">★</div>
          <h3>Geleceğin liderleri arasında yerini al.</h3>
          <p>
            Başvurular değerlendirme sonrası onaylanır. Sınırlı kontenjan,
            erken başvuru avantajı sağlar.
          </p>
          <ul className="apply-perks">
            <li className="apply-perk">
              <span className="apply-perk-check"><Icon name="check" size={12} stroke={3} /></span>
              Ücretsiz katılım
            </li>
            <li className="apply-perk">
              <span className="apply-perk-check"><Icon name="check" size={12} stroke={3} /></span>
              Katılım sertifikası
            </li>
            <li className="apply-perk">
              <span className="apply-perk-check"><Icon name="check" size={12} stroke={3} /></span>
              Yemek & ikram dahil
            </li>
            <li className="apply-perk">
              <span className="apply-perk-check"><Icon name="check" size={12} stroke={3} /></span>
              Networking fırsatları
            </li>
            <li className="apply-perk">
              <span className="apply-perk-check"><Icon name="check" size={12} stroke={3} /></span>
              En iyi delege ödülleri
            </li>
          </ul>
        </aside>

        <Form />
      </div>
    </div>
  </section>
);

window.Apply = Apply;
