/* ============================================================
   CAREERS — work at Pink Pony (non-performer roles).
   Hero + open positions + application form. Saves to PPDB.careers
   (status: new) and sends a WhatsApp summary to the team.
   Performer/dancer roles live on the Entertainment page (casting).
   ============================================================ */
const JOB_INPUT =
  "w-full bg-white/[.04] border border-white/15 rounded-xl px-4 py-3.5 text-[15px] text-white focus:outline-none focus:border-coral focus:bg-white/[.06] transition-colors placeholder:text-white/30";
const JOB_LABEL = "label text-white/50 text-[10px] block mb-2";

/* the 13 roles from the brief (id · icon · en · es) */
const POSITIONS = [
  ["bartender", "wine", "Bartender", "Bartender"],
  ["server", "utensils", "Server", "Mesero(a)"],
  ["host", "smile", "Host / Hostess", "Host / Hostess"],
  ["security", "shield", "Security", "Seguridad"],
  ["barback", "box", "Barback", "Barback"],
  ["kitchen", "chef-hat", "Kitchen Staff", "Cocina"],
  ["cleaning", "spray-can", "Cleaning", "Limpieza"],
  ["dj", "disc-3", "DJ", "DJ"],
  ["manager", "briefcase", "Manager", "Gerente"],
  ["cashier", "calculator", "Cashier", "Cajero(a)"],
  ["marketing", "megaphone", "Marketing", "Marketing"],
  ["valet", "car", "Valet", "Valet"],
  ["other", "ellipsis", "Other", "Otro"],
];
function positionLabel(id, lang) {
  const p = POSITIONS.find((x) => x[0] === id);
  return p ? (lang === "es" ? p[3] : p[2]) : id;
}

function CareersForm({ preset }) {
  const t = useT(); const { lang } = useLang();
  const blank = { fullName: "", phone: "", email: "", position: preset || "", employment: "full", days: [], experience: "", message: "", workAuth: false };
  const [f, setF] = useState(blank);
  const [done, setDone] = useState(false);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const phoneDigits = f.phone.replace(/\D/g, "");

  const DAYS = [["mon", t("Mon", "Lun")], ["tue", t("Tue", "Mar")], ["wed", t("Wed", "Mié")], ["thu", t("Thu", "Jue")], ["fri", t("Fri", "Vie")], ["sat", t("Sat", "Sáb")], ["sun", t("Sun", "Dom")]];
  const EXP = [["entry", t("Entry / no experience", "Sin experiencia")], ["1-2", t("1–2 years", "1–2 años")], ["3-5", t("3–5 years", "3–5 años")], ["5+", t("5+ years", "5+ años")]];
  const toggleDay = (d) => set("days", f.days.includes(d) ? f.days.filter((x) => x !== d) : [...f.days, d]);

  const submit = (e) => {
    e.preventDefault();
    if (!/^[^\d]{3,}$/.test(f.fullName.trim())) return window.toast(t("Enter your full name.", "Escribe tu nombre completo."), "error");
    if (!f.position) return window.toast(t("Pick the position you're applying for.", "Elige el puesto al que aplicas."), "error");
    if (phoneDigits.length < 10) return window.toast(t("Enter a valid 10-digit phone.", "Ingresa un teléfono válido de 10 dígitos."), "error");
    if (!/.+@.+\..+/.test(f.email)) return window.toast(t("Enter a valid email.", "Ingresa un correo válido."), "error");
    if (!f.workAuth) return window.toast(t("Please confirm you're 18+ and authorized to work.", "Confirma que eres 18+ y autorizado para trabajar."), "error");

    const phoneFull = "+1" + phoneDigits.slice(-10);
    const posLabel = positionLabel(f.position, lang);
    // 1) save to Admin (PPDB.careers)
    window.PPDB.careers.add({
      fullName: f.fullName.trim(), phone: phoneFull, email: f.email.trim(),
      position: f.position, positionLabel: positionLabel(f.position, "en"),
      employment: f.employment, days: f.days, experience: f.experience,
      message: f.message.trim(),
    });
    try { window.PP.track && window.PP.track("Lead", { content_name: "career_application" }); } catch (e2) {}
    // 2) WhatsApp summary to the team
    try {
      window.PP.waOpen(
        t("New job application — Pink Pony Club", "Nueva aplicación de trabajo — Pink Pony Club"),
        [
          [t("Name", "Nombre"), f.fullName.trim()],
          [t("Position", "Puesto"), posLabel],
          [t("Phone", "Teléfono"), phoneFull],
          ["Email", f.email.trim()],
          [t("Type", "Tipo"), f.employment === "full" ? t("Full-time", "Tiempo completo") : t("Part-time", "Medio tiempo")],
          [t("Availability", "Disponibilidad"), f.days.join(", ").toUpperCase()],
          [t("Experience", "Experiencia"), (EXP.find((x) => x[0] === f.experience) || [])[1] || ""],
          [t("Message", "Mensaje"), f.message.trim()],
        ],
        t("Careers · saved to Admin · clubpinkpony.com", "Empleos · guardado en Admin · clubpinkpony.com"),
      );
    } catch (e3) {}
    window.toast(t("Application sent! We'll be in touch.", "¡Aplicación enviada! Te contactaremos."));
    setDone(true);
  };

  if (done) return (
    <div className="max-w-xl mx-auto text-center fade-view">
      <div className="rounded-3xl border border-white/10 bg-white/[.03] p-9">
        <div className="w-16 h-16 rounded-full bg-green-500/15 border border-green-500 flex items-center justify-center mx-auto mb-5"><Icon name="check" className="w-8 h-8 text-green-400" /></div>
        <h3 className="text-3xl font-black uppercase mb-3">{t("Application received", "Aplicación recibida")}</h3>
        <p className="text-white/60 text-sm leading-relaxed">{t("Thanks for applying to Pink Pony. Our team reviews every application — if it's a fit, we'll reach out by phone or email to set up an interview.", "Gracias por aplicar a Pink Pony. Nuestro equipo revisa cada aplicación — si encaja, te contactaremos por teléfono o correo para una entrevista.")}</p>
      </div>
    </div>
  );

  return (
    <form onSubmit={submit} className="max-w-2xl mx-auto rounded-3xl border border-white/10 bg-white/[.03] p-6 md:p-8 space-y-6">
      <div>
        <label className={JOB_LABEL}>{t("Position you're applying for *", "Puesto al que aplicas *")}</label>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
          {POSITIONS.map(([id, ic, en, es]) => {
            const on = f.position === id;
            return (
              <button type="button" key={id} onClick={() => set("position", id)} className={"flex items-center gap-2.5 rounded-xl border px-3 py-2.5 text-left transition-all active:scale-95 " + (on ? "border-coral bg-coral/12 text-white" : "border-white/14 bg-white/[.03] text-white/75 hover:border-white/30")}>
                <Icon name={ic} className={"w-4 h-4 shrink-0 " + (on ? "text-coral" : "text-white/45")} />
                <span className="text-[12.5px] font-semibold leading-tight">{lang === "es" ? es : en}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="grid sm:grid-cols-2 gap-4">
        <div><label className={JOB_LABEL}>{t("Full name *", "Nombre completo *")}</label><input value={f.fullName} onChange={(e) => set("fullName", e.target.value.replace(/[\d]/g, ""))} placeholder={t("Your name", "Tu nombre")} className={JOB_INPUT} /></div>
        <div>
          <label className={JOB_LABEL}>{t("Mobile (10 digits) *", "Móvil (10 dígitos) *")}</label>
          <input type="tel" inputMode="numeric" value={f.phone} onChange={(e) => set("phone", e.target.value.replace(/[^\d() \-+]/g, "").slice(0, 16))} placeholder="(305) 555-0148" className={JOB_INPUT} />
        </div>
      </div>
      <div><label className={JOB_LABEL}>Email *</label><input type="email" value={f.email} onChange={(e) => set("email", e.target.value)} placeholder="tu@email.com" className={JOB_INPUT} /></div>

      <div className="grid sm:grid-cols-2 gap-4">
        <div>
          <label className={JOB_LABEL}>{t("Employment type", "Tipo de empleo")}</label>
          <div className="flex gap-2">
            {[["full", t("Full-time", "Tiempo completo")], ["part", t("Part-time", "Medio tiempo")]].map(([id, lbl]) => (
              <button type="button" key={id} onClick={() => set("employment", id)} className={"flex-1 py-3 rounded-xl text-[13px] font-bold transition-all " + (f.employment === id ? "bg-coral text-white" : "bg-white/[.04] border border-white/12 text-white/65")}>{lbl}</button>
            ))}
          </div>
        </div>
        <div>
          <label className={JOB_LABEL}>{t("Experience", "Experiencia")}</label>
          <select value={f.experience} onChange={(e) => set("experience", e.target.value)} className={JOB_INPUT} style={{ colorScheme: "dark" }}>
            <option value="" className="bg-card">{t("Select…", "Selecciona…")}</option>
            {EXP.map(([id, lbl]) => <option key={id} value={id} className="bg-card">{lbl}</option>)}
          </select>
        </div>
      </div>

      <div>
        <label className={JOB_LABEL}>{t("Availability", "Disponibilidad")}</label>
        <div className="grid grid-cols-7 gap-1.5">
          {DAYS.map(([id, lbl]) => {
            const on = f.days.includes(id);
            return <button type="button" key={id} onClick={() => toggleDay(id)} className={"aspect-square rounded-xl text-[11px] font-bold uppercase flex items-center justify-center transition-all active:scale-90 " + (on ? "bg-coral text-white shadow-[0_6px_18px_-6px_rgba(255,107,91,.8)]" : "bg-white/[.05] border border-white/12 text-white/55 hover:text-white")}>{lbl}</button>;
          })}
        </div>
      </div>

      <div><label className={JOB_LABEL}>{t("Anything else? (optional)", "¿Algo más? (opcional)")}</label><textarea value={f.message} onChange={(e) => set("message", e.target.value)} rows={3} placeholder={t("Tell us about yourself, your experience, why Pink Pony…", "Cuéntanos sobre ti, tu experiencia, por qué Pink Pony…")} className={JOB_INPUT + " resize-none"}></textarea></div>

      <button type="button" onClick={() => set("workAuth", !f.workAuth)} className="w-full flex items-start gap-3 text-left">
        <div className={"w-5 h-5 rounded-md border flex items-center justify-center shrink-0 mt-0.5 transition-all " + (f.workAuth ? "bg-coral border-coral" : "border-white/30")}>{f.workAuth && <Icon name="check" className="w-3.5 h-3.5 text-white" />}</div>
        <span className="text-white/65 text-[13px] leading-snug">{t("I confirm I'm 18 or older and legally authorized to work in the U.S.", "Confirmo que tengo 18 años o más y estoy autorizado para trabajar legalmente en EE. UU.")}</span>
      </button>

      <button type="submit" className="gbtn w-full py-4 rounded-full text-white text-[12px] font-black uppercase tracking-[0.16em] flex items-center justify-center gap-2" style={{ background: "linear-gradient(135deg,#FF2E88,#FF6B5B)", boxShadow: "0 10px 32px rgba(255,46,136,.4)" }}><Icon name="send" className="w-4 h-4" />{t("Submit application", "Enviar aplicación")}</button>
      <p className="text-white/30 text-[11px] text-center">{t("Your application is saved privately and reviewed by our hiring team. 18+ only.", "Tu aplicación se guarda en privado y la revisa nuestro equipo. Solo 18+.")}</p>
    </form>
  );
}

function CareersPage({ go }) {
  const t = useT(); const { lang } = useLang();
  const [preset, setPreset] = useState("");
  useReveal();
  useEffect(() => { try { window.scrollTo({ top: 0, behavior: "auto" }); } catch (e) {} }, []);
  const pickRole = (id) => {
    setPreset(id);
    try { document.getElementById("apply").scrollIntoView({ behavior: "smooth", block: "start" }); } catch (e) {}
  };

  return (
    <main className="pt-28 md:pt-32 pb-24">
      {/* hero */}
      <div className="container text-center max-w-2xl mx-auto mb-12">
        <div className="reveal inline-flex items-center gap-2 rounded-full border border-coral/40 bg-coral/10 px-4 py-1.5 mb-5">
          <span className="w-1.5 h-1.5 rounded-full bg-coral pulse-dot"></span>
          <span className="label text-coral text-[10px]">{t("Careers · Now Hiring", "Empleos · Contratando")}</span>
        </div>
        <h1 className="reveal text-4xl md:text-7xl font-black uppercase leading-[0.92]" data-d="1">{t(<>Work at <span className="serif-it font-normal text-coral">Pink Pony</span></>, <>Trabaja en <span className="serif-it font-normal text-coral">Pink Pony</span></>)}</h1>
        <p className="reveal text-white/60 text-lg mt-5" data-d="2">{t("Join Miami's boldest nightlife team. Front of house, bar, kitchen, security and more — we hire for energy and train the rest.", "Únete al equipo de nightlife más atrevido de Miami. Salón, barra, cocina, seguridad y más — contratamos por actitud y entrenamos el resto.")}</p>
      </div>

      {/* positions */}
      <div className="container mb-14">
        <div className="reveal flex items-end justify-between mb-5">
          <h2 className="text-2xl md:text-3xl font-black uppercase">{t("Open positions", "Puestos disponibles")}</h2>
          <span className="text-white/40 text-[12px]">{t("Tap a role to apply", "Toca un puesto para aplicar")}</span>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
          {POSITIONS.filter((p) => p[0] !== "other").map(([id, ic, en, es], i) => (
            <button key={id} onClick={() => pickRole(id)} className="reveal group rounded-2xl border border-white/10 bg-card hover:border-coral/40 transition-all p-5 text-left" data-d={(i % 3) + 1}>
              <div className="w-11 h-11 rounded-xl bg-coral/12 flex items-center justify-center mb-3 group-hover:scale-110 transition-transform"><Icon name={ic} className="w-5 h-5 text-coral" /></div>
              <div className="font-black uppercase text-[14px] leading-tight">{lang === "es" ? es : en}</div>
              <div className="text-coral text-[11px] font-bold uppercase tracking-wider mt-2 inline-flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">{t("Apply", "Aplicar")}<Icon name="arrow-right" className="w-3 h-3" /></div>
            </button>
          ))}
        </div>
      </div>

      {/* form */}
      <div id="apply" className="container scroll-mt-28">
        <div className="reveal text-center max-w-xl mx-auto mb-7">
          <Eyebrow num="" className="justify-center">{t("Apply now", "Aplica ahora")}</Eyebrow>
          <h2 className="text-3xl md:text-4xl font-black uppercase mt-3">{t(<>Send your <span className="serif-it font-normal text-coral">application</span></>, <>Envía tu <span className="serif-it font-normal text-coral">aplicación</span></>)}</h2>
          <p className="text-white/55 mt-3">{t("One short form — it takes about a minute.", "Un formulario corto — toma cerca de un minuto.")}</p>
        </div>
        <CareersForm key={preset} preset={preset} />
      </div>

      {/* performer cross-link */}
      <div className="container mt-12">
        <div className="reveal max-w-2xl mx-auto rounded-2xl border border-white/10 bg-white/[.03] p-5 flex items-center gap-4">
          <div className="w-11 h-11 rounded-xl bg-coral/12 flex items-center justify-center shrink-0"><Icon name="sparkles" className="w-5 h-5 text-coral" /></div>
          <div className="flex-1 min-w-0">
            <div className="font-bold text-sm">{t("Looking to perform?", "¿Buscas actuar?")}</div>
            <div className="text-white/55 text-[13px]">{t("Dancers & entertainers apply on the Entertainment page.", "Bailarinas y entertainers aplican en la página de Entretenimiento.")}</div>
          </div>
          <button onClick={() => go("casting")} className="px-4 py-2 rounded-full bg-coral/15 border border-coral/40 text-coral text-[11px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all shrink-0">{t("Entertainment", "Entretenimiento")}</button>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { CareersPage, CareersForm, POSITIONS, positionLabel });
