// MISLAK — Careers (الوظائف)
const { useState: useXS, useRef: useXR } = React;

if (!window.submitMislakForm) {
  window.MISLAK_FORMS_ENDPOINT = "https://mislak-forms.mislak.workers.dev";
  window.submitMislakForm = async function (formName, data) {
    try {
      const res = await fetch(window.MISLAK_FORMS_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ form: formName, data }),
      });
      return res.ok;
    } catch (err) {
      return false;
    }
  };
}

/* =================== CAREERS =================== */
function CareersPage() {
  window.useLang();
  const ROLES = [
    { id: "ai-eng", title: window.L("مهندس ذكاء اصطناعي", "AI Engineer"), dept: window.L("الهندسة", "Engineering"), loc: window.L("الرياض · دوام كامل", "Riyadh · Full-time") },
    { id: "voip", title: window.L("مهندس اتصالات و VoIP", "Telecom & VoIP Engineer"), dept: window.L("الهندسة", "Engineering"), loc: window.L("الرياض · دوام كامل", "Riyadh · Full-time") },
    { id: "fullstack", title: window.L("مطوّر Full-Stack أول", "Senior Full-Stack Developer"), dept: window.L("الهندسة", "Engineering"), loc: window.L("عن بُعد", "Remote") },
    { id: "cs", title: window.L("أخصائي نجاح العملاء", "Customer Success Specialist"), dept: window.L("العمليات", "Operations"), loc: window.L("الرياض · دوام كامل", "Riyadh · Full-time") },
    { id: "sales", title: window.L("مدير مبيعات المؤسسات", "Enterprise Sales Manager"), dept: window.L("المبيعات", "Sales"), loc: window.L("الرياض / جدة", "Riyadh / Jeddah") },
    { id: "design", title: window.L("مصمم منتج (UX/UI)", "Product Designer (UX/UI)"), dept: window.L("المنتج", "Product"), loc: window.L("عن بُعد", "Remote") },
  ];
  const [form, setForm] = useXS({ first: "", last: "", email: "", position: "" });
  const [fileName, setFileName] = useXS("");
  const [sent, setSent] = useXS(false);
  const [sending, setSending] = useXS(false);
  const [sendError, setSendError] = useXS(false);
  const fileRef = useXR(null);
  const upd = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const onSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setSending(true);
    setSendError(false);
    const role = ROLES.find((r) => r.id === form.position);
    const ok = await window.submitMislakForm("careers", {
      firstName: form.first,
      lastName: form.last,
      email: form.email,
      position: role ? role.title : form.position,
      cvUrl: fileName,
    });
    setSending(false);
    if (ok) setSent(true);
    else setSendError(true);
  };

  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    setFileName(f ? f.name : "");
  };
  const pickRole = (id) => {
    setForm({ ...form, position: id });
    const el = document.getElementById("apply-form");
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.pageYOffset - 90, behavior: "smooth" });
  };
  const reset = () => { setForm({ first: "", last: "", email: "", position: "" }); setFileName(""); if (fileRef.current) fileRef.current.value = ""; };

  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("انضمّ إلينا · الوظائف", "Join Us · Careers")}
        title={window.L(<>ابنِ مستقبل الاتصال<br/>الذكي في السعودية.</>, <>Build the future of smart<br/>communication in Saudi Arabia.</>)}
        sub={window.L("نبحث دائماً عن أشخاص شغوفين يصنعون منتجاً يخدم آلاف الشركات. استعرض الفرص المتاحة وقدّم سيرتك الذاتية.", "We're always looking for passionate people who build a product that serves thousands of companies. Browse the open roles and submit your CV.")}
      />
      <section style={{ paddingTop: 16, paddingBottom: 48 }}>
        <div className="container">
          <div className="contact-board">
            <div className="contact-form" id="apply-form">
              {sent ? (
                <div className="form-success">
                  <div className="mono" style={{ fontSize: 12, color: "var(--accent)", letterSpacing: ".1em", marginBottom: 12 }}>{window.L("✓ تم الاستلام", "✓ Received")}</div>
                  <h3>{window.L("شكراً لاهتمامك بالانضمام إلينا.", "Thank you for your interest in joining us.")}</h3>
                  <p style={{ color: "var(--muted)", marginTop: 14 }}>{window.L("استلمنا طلبك وسيراجعه فريق التوظيف. سنتواصل معك إذا كانت مؤهلاتك مناسبة للدور.", "We received your application and our recruitment team will review it. We'll contact you if your qualifications match the role.")}</p>
                  <button className="btn btn-ghost" style={{ marginTop: 18 }} onClick={() => { setSent(false); reset(); }}>{window.L("تقديم طلب آخر", "Submit another application")}</button>
                </div>
              ) : (
                <form onSubmit={onSubmit}>
                  <div className="sec-eyebrow">{window.L("نموذج التقديم", "Application form")}</div>
                  <h3 style={{ marginTop: 6, marginBottom: 24 }}>{window.L("قدّم سيرتك الذاتية.", "Submit your CV.")}</h3>
                  <div className="form-grid">
                    <label>
                      <span>{window.L("الاسم الأول", "First name")}</span>
                      <input value={form.first} onChange={upd("first")} required placeholder={window.L("عبدالله", "Abdullah")} />
                    </label>
                    <label>
                      <span>{window.L("اسم العائلة", "Last name")}</span>
                      <input value={form.last} onChange={upd("last")} required placeholder={window.L("السعيد", "Al-Saeed")} />
                    </label>
                    <label className="span-2">
                      <span>{window.L("البريد الإلكتروني", "Email")}</span>
                      <input type="email" dir="ltr" value={form.email} onChange={upd("email")} required placeholder="you@example.com" />
                    </label>
                    <label className="span-2">
                      <span>{window.L("الوظيفة المتقدَّم لها", "Position applied for")}</span>
                      <select value={form.position} onChange={upd("position")} required>
                        <option value="">{window.L("اختر الوظيفة", "Choose a position")}</option>
                        {ROLES.map((r) => <option key={r.id} value={r.id}>{r.title} — {r.dept}</option>)}
                      </select>
                    </label>
                    <label className="span-2">
                      <span>{window.L("السيرة الذاتية (CV)", "CV / Resume")}</span>
                      <div className={"file-drop" + (fileName ? " has-file" : "")} onClick={() => fileRef.current && fileRef.current.click()}>
                        <input ref={fileRef} type="file" accept=".pdf,.doc,.docx" onChange={onFile} required hidden />
                        <span className="file-ic mono">{fileName ? "✓" : "↑"}</span>
                        <span className="file-text">
                          {fileName
                            ? <strong dir="ltr">{fileName}</strong>
                            : <>{window.L("اسحب الملف هنا أو ", "Drag the file here or ")}<em>{window.L("اضغط للرفع", "click to upload")}</em></>}
                          <span className="file-sub">{window.L("PDF أو DOC · حتى 10MB", "PDF or DOC · up to 10MB")}</span>
                        </span>
                      </div>
                    </label>
                  </div>
                  <button type="submit" disabled={sending} className="btn btn-primary" style={{ marginTop: 8, width: "100%", justifyContent: "center", opacity: sending ? 0.6 : 1 }}>{sending ? window.L("جارٍ الإرسال…", "Sending…") : <>{window.L("إرسال الطلب", "Submit application")} <span className="mono">{window.ARR()}</span></>}</button>
                  {sendError && <p style={{ fontSize: 13, color: "#d33", marginTop: 12, textAlign: "center" }}>{window.L("حدث خطأ أثناء الإرسال. حاول مرة أخرى.", "Something went wrong. Please try again.")}</p>}
                  <p className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 14, textAlign: "center" }}>{window.L("بتقديم هذا النموذج فإنك توافق على معالجة بياناتك وفق سياسة الخصوصية.", "By submitting this form you agree to the processing of your data under the Privacy Policy.")}</p>
                </form>
              )}
            </div>

            <aside className="contact-side">
              <div className="sec-eyebrow">{window.L("الفرص المتاحة", "Open roles")}</div>
              <div className="role-list">
                {ROLES.map((r) => (
                  <button
                    key={r.id}
                    type="button"
                    className={"role-item" + (form.position === r.id ? " active" : "")}
                    onClick={() => pickRole(r.id)}
                  >
                    <div className="role-top">
                      <span className="role-title">{r.title}</span>
                      <span className="role-arrow mono">←</span>
                    </div>
                    <div className="role-meta">
                      <span className="role-dept">{r.dept}</span>
                      <span className="role-dot"></span>
                      <span>{r.loc}</span>
                    </div>
                  </button>
                ))}
              </div>
              <div className="contact-note">
                <div className="mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: ".1em", marginBottom: 6 }}>{window.L("● لا ترى دوراً مناسباً؟", "● Don't see a fitting role?")}</div>
                <p style={{ margin: 0, fontSize: 14 }}>{window.L("أرسل سيرتك على ", "Send your CV to ")}<strong dir="ltr">Contact@mislakcloud.com</strong>{window.L(" وسنعود إليك عند توفّر فرصة تناسب مهاراتك.", " and we'll reach out when a role matching your skills opens up.")}</p>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

Object.assign(window, { CareersPage });
