/* =========================================================
   SCHEGEN ADAM — Başvuru Formu
   ========================================================= */

const ApplyForm = ({ gold, content = {}, isModalOpen, onOpenModal, onCloseModal }) => {
  const formContent = {
    sectionEyebrow: content.sectionEyebrow || "08 · Başvuru",
    sectionTitle: content.sectionTitle || "İlk adımı",
    sectionTitleHighlight: content.sectionTitleHighlight || "şimdi atın",
    sectionCopy: content.sectionCopy || "Bilgilerinizi bırakın, size 24 saat içinde dönelim. Ücretsiz ön değerlendirme yapıyoruz.",
    openPanelTitle: content.openPanelTitle || "Ücretsiz ön değerlendirme formu",
    openPanelCopy: content.openPanelCopy || "Kısa formu doldurun, profilinizi inceleyip size en uygun başvuru yolunu netleştirelim.",
    openButtonText: content.openButtonText || "Başvuru formunu aç",
    modalEyebrow: content.modalEyebrow || "Başvuru formu",
    modalTitle: content.modalTitle || "Ön değerlendirme için bilgilerinizi bırakın.",
    modalCopy: content.modalCopy || "Formu doldurmak istemezseniz alttaki WhatsApp butonundan doğrudan yazabilirsiniz.",
    successTitle: content.successTitle || "Başvurunuz alındı.",
    successCopy: content.successCopy || "24 saat içinde sizinle iletişime geçeceğiz.",
    fullNameLabel: content.fullNameLabel || "İsim Soyisim",
    fullNamePlaceholder: content.fullNamePlaceholder || "Ad Soyad",
    phoneLabel: content.phoneLabel || "Tel No",
    phonePlaceholder: content.phonePlaceholder || "+90 5XX XXX XX XX",
    emailLabel: content.emailLabel || "E-Posta",
    emailPlaceholder: content.emailPlaceholder || "ornek@email.com",
    passportStatusLabel: content.passportStatusLabel || "Pasaport Durumu",
    activeEuropeanIdCardLabel: content.activeEuropeanIdCardLabel || "Aktif ID Avrupa kartı var mı?",
    applicationTypeLabel: content.applicationTypeLabel || "Başvuru",
    selectPlaceholder: content.selectPlaceholder || "Seçiniz",
    submitButtonText: content.submitButtonText || "Başvuruyu Gönder",
    loadingText: content.loadingText || "Gönderiliyor...",
    whatsappButtonText: content.whatsappButtonText || "WhatsApp ile yaz",
    defaultErrorMessage: content.defaultErrorMessage || "Bir hata oluştu. Lütfen tekrar deneyin.",
    networkErrorMessage: content.networkErrorMessage || "Sunucuya ulaşılamadı. Lütfen tekrar deneyin.",
    passportStatusOptions: content.passportStatusOptions && content.passportStatusOptions.length ? content.passportStatusOptions : [
      { value: "Pasaport var", label: "Pasaport var" },
      { value: "Pasaport yok", label: "Pasaport yok" },
      { value: "Aktif Şengen vizesi var", label: "Aktif Şengen vizesi var" },
      { value: "Aktif Şengen vizesi yok", label: "Aktif Şengen vizesi yok" }
    ],
    activeEuropeanIdCardOptions: content.activeEuropeanIdCardOptions && content.activeEuropeanIdCardOptions.length ? content.activeEuropeanIdCardOptions : [
      { value: "Var", label: "Var" },
      { value: "Yok", label: "Yok" }
    ],
    applicationTypeOptions: content.applicationTypeOptions && content.applicationTypeOptions.length ? content.applicationTypeOptions : [
      { value: "Bireysel", label: "Bireysel" },
      { value: "Aile", label: "Aile" },
      { value: "Aile birleşimi", label: "Aile birleşimi" },
      { value: "Şirket", label: "Şirket" }
    ]
  };

  const [form, setForm] = React.useState({
    fullName: "",
    phone: "",
    email: "",
    passportStatus: "",
    activeEuropeanIdCard: "",
    applicationType: ""
  });
  const [status, setStatus] = React.useState("idle"); // idle | loading | success | error
  const [errorMsg, setErrorMsg] = React.useState("");

  React.useEffect(() => {
    document.body.style.overflow = isModalOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [isModalOpen]);

  const handleChange = (e) => {
    setForm(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("loading");
    setErrorMsg("");

    const payload = {
      fullName: form.fullName.trim(),
      phone: form.phone.trim(),
      email: form.email.trim(),
      passportStatus: form.passportStatus,
      activeEuropeanIdCard: form.activeEuropeanIdCard,
      applicationType: form.applicationType
    };

    try {
      const res = await fetch("/api/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        setStatus("success");
        setForm({
          fullName: "",
          phone: "",
          email: "",
          passportStatus: "",
          activeEuropeanIdCard: "",
          applicationType: ""
        });
      } else {
        const data = await res.json().catch(() => ({}));
        setErrorMsg(data.error || formContent.defaultErrorMessage);
        setStatus("error");
      }
    } catch {
      setErrorMsg(formContent.networkErrorMessage);
      setStatus("error");
    }
  };

  const inputStyle = {
    width: "100%",
    padding: "9px 11px",
    border: "1px solid rgba(255,255,255,0.15)",
    borderRadius: 8,
    background: "rgba(255,255,255,0.06)",
    color: "#eef2fb",
    fontSize: 14,
    outline: "none",
    boxSizing: "border-box"
  };

  const labelStyle = {
    display: "block",
    fontFamily: "var(--f-mono)",
    fontSize: 10.5,
    letterSpacing: "0.18em",
    textTransform: "uppercase",
    color: "rgba(255,255,255,0.6)",
    marginBottom: 5
  };

  const openModal = () => {
    onOpenModal();
    setStatus("idle");
    setErrorMsg("");
  };

  const closeModal = () => {
    if (status === "loading") return;
    onCloseModal();
  };

  const stopModalClick = (e) => {
    e.stopPropagation();
  };

  return (
    <section id="apply" className="section dark" style={{
      background: "linear-gradient(180deg, #060f21 0%, #0b1e3c 100%)"
    }}>
      <div className="glow-gold" style={{ top: -160, right: -160, opacity: 0.4 }} />
      <div className="wrap" style={{ position: "relative" }}>

        <div className="reveal" style={{ maxWidth: 680, marginBottom: 48 }}>
          <span className="eyebrow">{formContent.sectionEyebrow}</span>
          <h2 className="section-title">
            {formContent.sectionTitle}<br />
            <em style={{ color: gold }}>{formContent.sectionTitleHighlight}</em>.
          </h2>
          <p className="section-lede" style={{ marginTop: 12 }}>
            {formContent.sectionCopy}
          </p>
        </div>

        <div className="reveal" style={{ maxWidth: 680 }}>
          <div className="apply-open-panel">
            <div>
              <div className="apply-open-title">{formContent.openPanelTitle}</div>
              <p className="apply-open-copy">
                {formContent.openPanelCopy}
              </p>
            </div>
            <button type="button" className="btn btn-primary" onClick={openModal}>
              {formContent.openButtonText} <span className="arr">→</span>
            </button>
          </div>

          {isModalOpen && ReactDOM.createPortal((
            <div className="apply-modal-backdrop" onClick={closeModal} role="presentation">
              <div className="apply-modal" onClick={stopModalClick} role="dialog" aria-modal="true" aria-label="Başvuru formu">
                <button type="button" className="apply-modal-close" onClick={closeModal} aria-label="Kapat">
                  ×
                </button>

                <div className="apply-modal-head">
                  <span className="eyebrow">{formContent.modalEyebrow}</span>
                  <h3>{formContent.modalTitle}</h3>
                  <p>{formContent.modalCopy}</p>
                </div>

                {status === "success" ? (
                  <div className="apply-success-box">
                    <div className="apply-success-mark">✓</div>
                    <div className="apply-success-title" style={{ color: gold }}>
                      {formContent.successTitle}
                    </div>
                    <p>{formContent.successCopy}</p>
                  </div>
                ) : (
                  <form onSubmit={handleSubmit} className="apply-grid">

              <div>
                <label style={labelStyle}>{formContent.fullNameLabel}</label>
                <input style={inputStyle} name="fullName" value={form.fullName}
                  onChange={handleChange} required placeholder={formContent.fullNamePlaceholder} />
              </div>

              <div>
                <label style={labelStyle}>{formContent.phoneLabel}</label>
                <input style={inputStyle} type="tel" name="phone" value={form.phone}
                  onChange={handleChange} required placeholder={formContent.phonePlaceholder} />
              </div>

              <div>
                <label style={labelStyle}>{formContent.emailLabel}</label>
                <input style={inputStyle} type="email" name="email" value={form.email}
                  onChange={handleChange} required placeholder={formContent.emailPlaceholder} />
              </div>

              <div>
                <label style={labelStyle}>{formContent.passportStatusLabel}</label>
                <select style={{ ...inputStyle, appearance: "none" }} name="passportStatus"
                  value={form.passportStatus} onChange={handleChange} required>
                  <option value="" disabled>{formContent.selectPlaceholder}</option>
                  {formContent.passportStatusOptions.map(option => (
                    <option key={option.value} value={option.value}>{option.label}</option>
                  ))}
                </select>
              </div>

              <div>
                <label style={labelStyle}>{formContent.activeEuropeanIdCardLabel}</label>
                <select style={{ ...inputStyle, appearance: "none" }} name="activeEuropeanIdCard"
                  value={form.activeEuropeanIdCard} onChange={handleChange} required>
                  <option value="" disabled>{formContent.selectPlaceholder}</option>
                  {formContent.activeEuropeanIdCardOptions.map(option => (
                    <option key={option.value} value={option.value}>{option.label}</option>
                  ))}
                </select>
              </div>

              <div>
                <label style={labelStyle}>{formContent.applicationTypeLabel}</label>
                <select style={{ ...inputStyle, appearance: "none" }} name="applicationType"
                  value={form.applicationType} onChange={handleChange} required>
                  <option value="" disabled>{formContent.selectPlaceholder}</option>
                  {formContent.applicationTypeOptions.map(option => (
                    <option key={option.value} value={option.value}>{option.label}</option>
                  ))}
                </select>
              </div>

              {status === "error" && (
                <div style={{ gridColumn: "1 / -1", color: "#f87171", fontSize: 14 }}>
                  {errorMsg}
                </div>
              )}

              <div style={{ gridColumn: "1 / -1" }}>
                <button type="submit" disabled={status === "loading"}
                  className="btn btn-primary"
                  style={{ width: "100%", opacity: status === "loading" ? 0.7 : 1 }}>
                  {status === "loading" ? formContent.loadingText : formContent.submitButtonText}
                  {status !== "loading" && <span className="arr"> →</span>}
                </button>
              </div>

                  </form>
                )}

                <a className="apply-whatsapp" href="https://wa.me/383048116123" target="_blank" rel="noopener noreferrer">
                  <span className="apply-whatsapp-icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="22" height="22">
                      <path fill="currentColor" d="M12.04 2C6.56 2 2.1 6.34 2.1 11.68c0 1.7.46 3.36 1.34 4.82L2 22l5.66-1.42a10.2 10.2 0 0 0 4.38.98c5.48 0 9.94-4.34 9.94-9.68C21.98 6.34 17.52 2 12.04 2Zm0 17.85c-1.45 0-2.86-.38-4.1-1.1l-.32-.18-3.35.84.86-3.18-.2-.33a7.92 7.92 0 0 1-1.2-4.22c0-4.4 3.73-7.98 8.31-7.98s8.31 3.58 8.31 7.98-3.73 8.17-8.31 8.17Zm4.55-5.95c-.25-.12-1.47-.7-1.7-.78-.23-.08-.4-.12-.56.12-.16.24-.64.78-.78.94-.14.16-.29.18-.54.06-.25-.12-1.05-.38-2-1.2-.74-.64-1.24-1.43-1.38-1.67-.14-.24-.02-.37.11-.49.11-.11.25-.29.37-.43.12-.14.16-.24.25-.4.08-.16.04-.3-.02-.43-.06-.12-.56-1.3-.76-1.78-.2-.47-.4-.4-.56-.41h-.48c-.16 0-.43.06-.66.3-.23.24-.87.83-.87 2.02s.89 2.34 1.02 2.5c.12.16 1.75 2.6 4.25 3.64.59.25 1.06.4 1.42.51.6.18 1.14.15 1.57.09.48-.07 1.47-.58 1.68-1.14.21-.56.21-1.04.15-1.14-.06-.1-.23-.16-.48-.28Z" />
                    </svg>
                  </span>
                  {formContent.whatsappButtonText}
                </a>
              </div>
            </div>
          ), document.body)}
        </div>
      </div>

      <style>{`
        .apply-open-panel {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 24px;
          padding: 26px;
          border: 1px solid rgba(255,255,255,0.12);
          border-radius: 14px;
          background: rgba(255,255,255,0.04);
        }
        .apply-open-title {
          font-family: var(--f-display);
          font-size: 22px;
          font-weight: 600;
          letter-spacing: -0.01em;
        }
        .apply-open-copy {
          margin: 8px 0 0;
          color: rgba(255,255,255,0.72);
        }
        .apply-modal-backdrop {
          position: fixed;
          inset: 0;
          z-index: 120;
          display: grid;
          place-items: center;
          padding: 20px;
          background: rgba(3,8,20,0.72);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
        }
        .apply-modal {
          position: relative;
          width: min(720px, 100%);
          max-height: min(760px, calc(100vh - 40px));
          overflow-y: auto;
          padding: 22px;
          border: 1px solid rgba(212,175,55,0.26);
          border-radius: 16px;
          background: linear-gradient(180deg, #071225 0%, #0b1e3c 100%);
          box-shadow: 0 30px 80px rgba(0,0,0,0.45);
        }
        .apply-modal-close {
          position: absolute;
          top: 12px;
          right: 12px;
          width: 34px;
          height: 34px;
          border: 1px solid rgba(255,255,255,0.18);
          border-radius: 8px;
          background: rgba(255,255,255,0.06);
          color: #fff;
          font-size: 28px;
          line-height: 1;
        }
        .apply-modal-head {
          padding-right: 48px;
          margin-bottom: 14px;
        }
        .apply-modal-head h3 {
          font-family: var(--f-display);
          font-size: 25px;
          line-height: 1.08;
          margin: 8px 0 6px;
          letter-spacing: -0.01em;
        }
        .apply-modal-head p,
        .apply-success-box p {
          margin: 0;
          color: rgba(255,255,255,0.72);
        }
        .apply-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
        }
        .apply-success-box {
          padding: 30px;
          border: 1px solid rgba(212,175,55,0.4);
          border-radius: 14px;
          background: rgba(212,175,55,0.06);
          text-align: center;
        }
        .apply-success-mark {
          font-size: 36px;
          margin-bottom: 16px;
        }
        .apply-success-title {
          font-family: var(--f-display);
          font-size: 22px;
          font-weight: 600;
        }
        .apply-whatsapp {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
          margin-top: 12px;
          padding: 11px 14px;
          border-radius: 10px;
          background: #25d366;
          color: #06121f;
          font-family: var(--f-display);
          font-weight: 700;
        }
        .apply-whatsapp-icon {
          display: inline-flex;
          color: #06121f;
        }
        @media (max-width: 560px) {
          .apply-open-panel {
            align-items: stretch;
            flex-direction: column;
          }
          .apply-modal {
            padding: 24px 18px;
          }
          .apply-modal-head {
            padding-right: 42px;
          }
          .apply-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
};

window.ApplyForm = ApplyForm;
