/* ============================================================
   ENTERTAINMENT — dancer application (form only).
   Professional multi-step flow: identity (21+ enforced) →
   experience & availability (min 3 days) → photos → entertainer
   agreement ("Ley de la Chica") with DocuSign-style signature.
   Saves to PPDB.applicants (pending approval in the Hub: ID ·
   contract · audition + manager & owner sign-off).
   ============================================================ */
const CAST_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 CAST_LABEL = "label text-white/50 text-[10px] block mb-2";

/* the latest date of birth that is 21+ today */
function maxDob21() {
  const n = new Date();
  return new Date(n.getFullYear() - 21, n.getMonth(), n.getDate()).toISOString().slice(0, 10);
}
function isAdult21(dob) {
  if (!dob) return false;
  return dob <= maxDob21();
}
/* downscale a photo to a small JPEG dataURL so it can persist */
function shrinkPhoto(file) {
  return new Promise((res, rej) => {
    const img = new Image();
    img.onload = () => {
      try {
        const sc = Math.min(1, 460 / img.width);
        const c = document.createElement("canvas");
        c.width = Math.round(img.width * sc); c.height = Math.round(img.height * sc);
        c.getContext("2d").drawImage(img, 0, 0, c.width, c.height);
        res(c.toDataURL("image/jpeg", 0.72));
      } catch (e) { rej(e); }
      URL.revokeObjectURL(img.src);
    };
    img.onerror = rej;
    img.src = URL.createObjectURL(file);
  });
}

/* ---------- DocuSign-style signature pad ---------- */
function SignaturePad({ onChange }) {
  const t = useT();
  const ref = useRef(null);
  const drawing = useRef(false);
  const [has, setHas] = useState(false);
  useEffect(() => {
    const c = ref.current; if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const w = c.offsetWidth, h = 150;
    c.width = w * dpr; c.height = h * dpr;
    const ctx = c.getContext("2d");
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = "#fff"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; ctx.lineJoin = "round";
  }, []);
  const pos = (e) => {
    const r = ref.current.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    return [p.clientX - r.left, p.clientY - r.top];
  };
  const start = (e) => { e.preventDefault(); drawing.current = true; const ctx = ref.current.getContext("2d"); const [x, y] = pos(e); ctx.beginPath(); ctx.moveTo(x, y); };
  const move = (e) => { if (!drawing.current) return; e.preventDefault(); const ctx = ref.current.getContext("2d"); const [x, y] = pos(e); ctx.lineTo(x, y); ctx.stroke(); if (!has) setHas(true); };
  const end = () => { if (!drawing.current) return; drawing.current = false; try { onChange(ref.current.toDataURL("image/png")); } catch (e) {} };
  const clear = () => {
    const c = ref.current; const ctx = c.getContext("2d");
    ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, c.width, c.height); ctx.restore();
    setHas(false); onChange(null);
  };
  return (
    <div>
      <div className="relative rounded-2xl border-2 border-dashed border-white/25 bg-white/[.03] overflow-hidden">
        <canvas ref={ref} className="sigpad block w-full" style={{ height: 150 }}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
        {!has && <div className="absolute inset-0 flex items-center justify-center pointer-events-none"><span className="text-white/30 text-sm flex items-center gap-2"><Icon name="pen-line" className="w-4 h-4" />{t("Sign here with your finger or mouse", "Firma aquí con tu dedo o mouse")}</span></div>}
        <div className="absolute bottom-3 left-4 right-4 border-t border-white/20"></div>
      </div>
      <div className="flex justify-between items-center mt-2">
        <span className="text-white/35 text-[11px]">{t("Legally binding electronic signature", "Firma electrónica con validez legal")}</span>
        {has && <button type="button" onClick={clear} className="text-coral text-[11px] font-bold uppercase tracking-wider hover:text-white">{t("Clear", "Borrar")}</button>}
      </div>
    </div>
  );
}

/* ---------- the entertainer agreement ("Ley de la Chica") — fillable ---------- */
function AgreementText({ name, dob, days, today }) {
  const t = useT(); const { lang } = useLang();
  const fill = (v) => <span className="text-coral font-bold border-b border-coral/40 px-0.5">{v || "________"}</span>;
  const C = [
    [t("1. Independent entertainer", "1. Entertainer independiente"), t("You perform at Club Pink Pony (7971 NW 33rd St, Doral, FL) as an independent entertainer, not an employee. You control your schedule within the availability you commit to.", "Actúas en Club Pink Pony (7971 NW 33rd St, Doral, FL) como entertainer independiente, no como empleada. Controlas tu horario dentro de la disponibilidad que comprometas.")],
    [t("2. Age & identity", "2. Edad e identidad"), t("You certify you are 21 or older and will present a valid government-issued photo ID before your first shift. False information voids this application.", "Certificas que eres mayor de 21 años y presentarás una identificación oficial vigente con foto antes de tu primer turno. Información falsa anula esta aplicación.")],
    [t("3. Commitment", "3. Compromiso"), t("You commit to a minimum of three (3) work days per week as selected in this application. Schedule changes are coordinated with management with at least 48 hours notice.", "Te comprometes a un mínimo de tres (3) días de trabajo por semana según lo seleccionado en esta aplicación. Los cambios de horario se coordinan con gerencia con al menos 48 horas de aviso.")],
    [t("4. House policies", "4. Políticas de la casa"), t("A $0 house fee currently applies (promotional). Payout structure, dress code and conduct standards are reviewed and accepted at onboarding. Zero tolerance for illegal substances or solicitation.", "Actualmente aplica un house fee de $0 (promocional). La estructura de pagos, código de vestimenta y normas de conducta se revisan y aceptan en el onboarding. Cero tolerancia a sustancias ilegales o solicitación.")],
    [t("5. Audition & approval", "5. Audición y aprobación"), t("Final acceptance requires: (a) ID verification, (b) this signed agreement, and (c) a passed in-person audition, approved by both a manager and the owner.", "La aceptación final requiere: (a) verificación de ID, (b) este acuerdo firmado, y (c) una audición presencial aprobada, con visto bueno de un gerente y del dueño.")],
    [t("6. Image & privacy", "6. Imagen y privacidad"), t("Your application data is kept private and used only for hiring. Promotional photography is always agreed in writing separately.", "Tus datos de aplicación se mantienen privados y se usan solo para contratación. La fotografía promocional siempre se acuerda por escrito por separado.")],
    [t("7. Termination", "7. Terminación"), t("Either party may end the relationship at any time. Florida law governs this agreement (Miami-Dade County).", "Cualquiera de las partes puede terminar la relación en cualquier momento. La ley de Florida rige este acuerdo (Condado de Miami-Dade).")],
  ];
  return (
    <div className="max-h-72 overflow-y-auto rounded-2xl border border-white/12 bg-white/[.03] p-5 space-y-4 text-left">
      <div className="text-center pb-3 border-b border-white/10">
        <div className="font-black uppercase tracking-wide text-[13px] leading-tight">{CONTRACT.title[lang === "es" ? "es" : "en"]}</div>
        <div className="text-white/40 text-[11px] mt-1">Club Pink Pony · 7971 NW 33rd St, Doral, FL 33122</div>
        <div className="text-white/35 text-[10px] mt-0.5">{CONTRACT.version} · {t("Exhibits", "Anexos")} {CONTRACT.exhibits}</div>
      </div>
      {/* fillable preamble */}
      <p className="text-white/65 text-[12.5px] leading-relaxed">
        {t("This Entertainer Agreement is entered into on ", "Este Acuerdo de Entertainer se celebra el ")}{fill(today)}{t(" by and between Club Pink Pony and ", " entre Club Pink Pony y ")}{fill(name)}{t(" (date of birth ", " (fecha de nacimiento ")}{fill(dob)}{t("), who confirms availability of at least ", "), quien confirma disponibilidad de al menos ")}{fill((days && days.length) || 0)}{t(" days per week.", " días por semana.")}
      </p>
      {C.map(([h, b], i) => (
        <div key={i}><div className="font-bold text-[13px] mb-1">{h}</div><p className="text-white/55 text-[12.5px] leading-relaxed">{b}</p></div>
      ))}
    </div>
  );
}

/* ---------- multi-select pill ---------- */
function CastPill({ active, children, onClick }) {
  return (
    <button type="button" onClick={onClick}
      className={"px-4 py-3 rounded-xl border text-[13.5px] font-semibold transition-all text-left active:scale-95 " +
        (active ? "border-coral bg-coral/12 text-white shadow-[0_0_22px_-8px_rgba(255,107,91,.8)]" : "border-white/14 bg-white/[.03] text-white/75 hover:border-white/30")}>
      {children}
    </button>
  );
}

/* ---------- the application ---------- */
/* the contract this form captures (internal reference) */
const CONTRACT = {
  version: "v3",
  file: "Pink_Pony_Contrato_Entertainer_v3.pdf",
  title: { en: "Entertainer Performance Lease and Arbitration Agreement", es: "Contrato de Arrendamiento de Actuación y Arbitraje del Entertainer" },
  exhibits: "A–G",
};
/* a stable per-device id for the signature metadata (not personal) */
function appDeviceId() {
  try {
    var k = "pp_app_id", v = window.localStorage.getItem(k);
    if (!v) { v = "PPA-" + Math.random().toString(36).slice(2, 10).toUpperCase(); window.localStorage.setItem(k, v); }
    return v;
  } catch (e) { return "PPA-UNKNOWN"; }
}
/* SHA-256 hex of a string (document hash for tamper-evidence) */
async function sha256Hex(str) {
  try {
    var buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str));
    return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
  } catch (e) { return ""; }
}

function CastingForm() {
  const t = useT(); const { lang } = useLang();
  const [step, setStep] = useState(0);
  const [f, setF] = useState({
    legalName: "", dob: "", phone: "", email: "",
    styles: [], days: [], instagram: "",
    address: "", city: "", state: "", zip: "",
    emergencyName: "", emergencyPhone: "",
    businessStatus: "individual", // Exhibit B — individual | llc
  });
  const [photos, setPhotos] = useState([]); // dataURLs (shrunk)
  // the 7 required legal acknowledgements (brief §8). Wording is a DRAFT
  // pending attorney review — the warning below stays until a lawyer approves.
  const LEGAL = [
    ["contractor", t("I am an independent contractor, not an employee, and lease performance space (Exhibit A).", "Soy contratista independiente, no empleada, y arriendo espacio de actuación (Anexo A).")],
    ["fees", t("I accept the space-lease fee, payout and house-rule terms (Exhibit C).", "Acepto la tarifa de arrendamiento de espacio, los pagos y las reglas de la casa (Anexo C).")],
    ["arbitration", t("I agree to binding arbitration and waive class actions (Exhibit F).", "Acepto el arbitraje vinculante y renuncio a acciones colectivas (Anexo F).")],
    ["age", t("I certify I am 21+ and will present valid government photo ID.", "Certifico que tengo 21+ y presentaré identificación oficial vigente con foto.")],
    ["conduct", t("I accept the code of conduct and zero-tolerance policy (Exhibit D).", "Acepto el código de conducta y la política de cero tolerancia (Anexo D).")],
    ["image", t("I accept the image/likeness and confidentiality terms (Exhibit E).", "Acepto los términos de imagen y confidencialidad (Anexo E).")],
    ["read", t("I have read the full agreement and exhibits A–G and sign voluntarily.", "He leído el contrato completo y los anexos A–G y firmo voluntariamente.")],
  ];
  const [acks, setAcks] = useState({});
  const allAcked = LEGAL.every(([id]) => acks[id]);
  const toggleAck = (id) => setAcks((a) => ({ ...a, [id]: !a[id] }));
  const [signature, setSignature] = useState(null);
  const [typedName, setTypedName] = useState("");
  const [err, setErr] = useState("");
  const fileRef = useRef(null);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const TOTAL = 4;

  // every step change starts at the top
  useEffect(() => { try { window.scrollTo({ top: 0, behavior: "auto" }); } catch (e) {} setErr(""); }, [step]);

  const STYLE_OPTS = [
    t("Pole dance", "Pole dance"), t("Exotic", "Exótico"), t("Strip show", "Strip show"),
    t("Go-go / podium", "Go-go / podium"), t("Hosting", "Hosting"), t("Bottle service", "Servicio de botellas"), t("Other", "Otro"),
  ];
  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 toggle = (k, v) => set(k, f[k].includes(v) ? f[k].filter((x) => x !== v) : [...f[k], v]);

  const onFiles = async (e) => {
    const files = Array.from(e.target.files || []).slice(0, 3 - photos.length);
    e.target.value = "";
    for (const file of files) {
      try { const url = await shrinkPhoto(file); setPhotos((p) => p.length >= 3 ? p : [...p, url]); }
      catch (e2) { window.toast(t("Couldn't read that photo.", "No se pudo leer esa foto."), "error"); }
    }
  };

  const phoneDigits = f.phone.replace(/\D/g, "");
  const nameOk = /^[^\d]{3,}$/.test(f.legalName.trim()); // names: text only, no digits
  const validate = (s) => {
    if (s === 0) {
      if (!nameOk) return t("Enter your full legal name (letters only).", "Escribe tu nombre legal completo (solo letras).");
      if (!f.dob) return t("Enter your date of birth.", "Ingresa tu fecha de nacimiento.");
      if (!isAdult21(f.dob)) return t("You must be 21 or older to apply.", "Debes tener 21 años o más para aplicar.");
      if (phoneDigits.length < 10) return t("Enter a valid 10-digit phone number.", "Ingresa un teléfono válido de 10 dígitos.");
      if (!/.+@.+\..+/.test(f.email)) return t("Enter a valid email.", "Ingresa un correo válido.");
      return "";
    }
    if (s === 1) {
      if (f.styles.length === 0) return t("Pick at least one experience style.", "Elige al menos un estilo de experiencia.");
      if (f.days.length < 3) return t("Select at least 3 work days per week.", "Selecciona mínimo 3 días de trabajo por semana.");
      return "";
    }
    if (s === 2) return photos.length === 3 ? "" : t("Upload exactly 3 recent photos.", "Sube exactamente 3 fotos recientes.");
    if (s === 3) {
      if (!f.address.trim() || !f.city.trim() || !f.state.trim() || f.zip.replace(/\D/g, "").length < 5) return t("Complete your home address (street, city, state, ZIP).", "Completa tu dirección (calle, ciudad, estado, código postal).");
      if (!/^[^\d]{3,}$/.test(f.emergencyName.trim()) || f.emergencyPhone.replace(/\D/g, "").length < 10) return t("Add an emergency contact name and phone.", "Agrega nombre y teléfono de contacto de emergencia.");
      if (!allAcked) return t("Check all 7 legal acknowledgements.", "Marca las 7 confirmaciones legales.");
      if (!signature) return t("Sign in the signature box.", "Firma en el recuadro de firma.");
      if (typedName.trim().toLowerCase() !== f.legalName.trim().toLowerCase()) return t("Type your legal name exactly as entered.", "Escribe tu nombre legal exactamente como lo ingresaste.");
      return "";
    }
    return "";
  };
  const next = () => {
    const e = validate(step);
    if (e) { setErr(e); window.toast(e, "error"); return; }
    setStep((s) => s + 1);
  };

  const submit = async () => {
    const e = validate(3);
    if (e) { setErr(e); window.toast(e, "error"); return; }
    const signedAt = new Date().toISOString();
    const phoneFull = "+1" + phoneDigits.slice(-10);
    // tamper-evidence: hash the exact agreement payload the signer accepted
    const docPayload = JSON.stringify({
      title: CONTRACT.title.en, version: CONTRACT.version, file: CONTRACT.file,
      signer: f.legalName.trim(), dob: f.dob, acknowledgements: LEGAL.map(([id]) => id), signedAt: signedAt,
    });
    const documentHash = await sha256Hex(docPayload);
    // signature metadata (brief §9). IP is captured server-side at upload
    // (no reliable client-side source); everything else is captured here.
    const signatureMeta = {
      signedAt: signedAt,
      ip: "", // set server-side when the signed PDF is stored
      device: (typeof navigator !== "undefined" ? navigator.userAgent : "").slice(0, 240),
      appId: appDeviceId(),
      contractVersion: CONTRACT.version,
      documentHash: documentHash,
      signatureProvider: "internal_canvas_signature",
    };
    // 1) save the signed application (+ contract + metadata) to the database
    window.PPDB.applicants.add({
      legalName: f.legalName.trim(), dob: f.dob,
      phone: phoneFull, email: f.email.trim(),
      address: f.address.trim(), city: f.city.trim(), state: f.state.trim().toUpperCase(), zip: f.zip.replace(/\D/g, ""),
      emergencyName: f.emergencyName.trim(), emergencyPhone: "+1" + f.emergencyPhone.replace(/\D/g, "").slice(-10),
      businessStatus: f.businessStatus,
      styles: f.styles, days: f.days, instagram: f.instagram.trim(),
      photos: photos, signature: signature, signedName: typedName.trim(), signedAt: signedAt,
      contract: CONTRACT.title.en, contractFile: CONTRACT.file, contractVersion: CONTRACT.version,
      contractAcceptedAt: signedAt, acknowledgements: acks, signatureMeta: signatureMeta,
      contractDraft: true, // remove once the attorney approves the final wording
    });
    try { window.PP.track && window.PP.track("Lead", { content_name: "casting_application" }); } catch (e2) {}
    // 2) deliver a NON-sensitive summary to the club WhatsApp (no address /
    //    emergency contact / hash over WhatsApp — those stay in the Hub).
    try {
      window.PP.waOpen(
        t("Signed Entertainer Contract — Pink Pony Club", "Contrato de Entertainer Firmado — Pink Pony Club"),
        [
          [t("Legal name", "Nombre legal"), f.legalName.trim()],
          [t("Phone", "Teléfono"), phoneFull],
          ["Email", f.email.trim()],
          [t("Experience", "Experiencia"), f.styles.join(", ")],
          [t("Committed days", "Días comprometidos"), f.days.join(", ").toUpperCase()],
          [t("Contract", "Contrato"), CONTRACT.title[lang === "es" ? "es" : "en"] + " · " + CONTRACT.version + " — " + t("ACCEPTED", "ACEPTADO")],
          [t("7 legal acknowledgements", "7 confirmaciones legales"), t("All accepted", "Todas aceptadas")],
          [t("Signed by", "Firmado por"), typedName.trim()],
          [t("Signed at", "Firmado el"), new Date(signedAt).toLocaleString(lang === "es" ? "es" : "en")],
          [t("Document hash", "Hash del documento"), documentHash ? documentHash.slice(0, 16) + "…" : "—"],
          [t("Full record", "Registro completo"), t("In Hub → Applicants (private)", "En Hub → Aspirantes (privado)")],
        ],
        t("Sent from clubpinkpony.com · full contract & metadata on file", "Enviado desde clubpinkpony.com · contrato y metadatos en archivo"),
      );
    } catch (e3) {}
    window.toast(t("Contract signed & sent. We'll contact you soon.", "Contrato firmado y enviado. Te contactamos pronto."));
    setStep(9);
  };

  /* ===== success ===== */
  if (step === 9) 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 mb-6">{t("Your signed application is with our talent team. Next steps: ID verification and an in-person audition — we'll text you to coordinate.", "Tu aplicación firmada está con nuestro equipo de talento. Próximos pasos: verificación de ID y audición presencial — te escribiremos para coordinar.")}</p>
        <div className="grid grid-cols-3 gap-2 text-[11px] text-white/55 mb-2">
          {[[t("ID check", "Verificar ID"), "credit-card"], [t("Contract", "Contrato"), "check-circle"], [t("Audition", "Audición"), "sparkles"]].map(([l, ic], i) => (
            <div key={i} className="rounded-xl border border-white/10 bg-white/[.02] py-3 flex flex-col items-center gap-1.5"><Icon name={ic} className={"w-4 h-4 " + (i === 1 ? "text-green-400" : "text-white/40")} />{l}</div>
          ))}
        </div>
        <p className="text-white/35 text-[11px]">{t("Contract signed", "Contrato firmado")} ✓ · {new Date().toLocaleDateString(lang === "es" ? "es" : "en")}</p>
      </div>
    </div>
  );

  const stepTitles = [t("Your identity", "Tu identidad"), t("Experience & availability", "Experiencia y disponibilidad"), t("Your photos", "Tus fotos"), t("Agreement & signature", "Acuerdo y firma")];

  return (
    <div className="max-w-2xl mx-auto">
      {/* progress */}
      <div className="mb-7">
        <div className="flex items-center justify-between mb-2">
          <span className="label text-coral text-[10px]">{stepTitles[step]}</span>
          <span className="text-white/40 text-[11px]">{step + 1}/{TOTAL}</span>
        </div>
        <div className="h-1.5 rounded-full bg-white/10 overflow-hidden"><div className="h-full rounded-full bg-gradient-to-r from-coral to-coral-deep transition-all duration-500" style={{ width: ((step + 1) / TOTAL) * 100 + "%" }}></div></div>
      </div>

      <div key={step} className="fade-view rounded-3xl border border-white/10 bg-white/[.03] p-6 md:p-8">
        {/* STEP 0 — identity */}
        {step === 0 && (
          <div className="space-y-4">
            <div><label className={CAST_LABEL}>{t("Legal name *", "Nombre legal *")}</label><input value={f.legalName} onChange={(e) => set("legalName", e.target.value.replace(/[\d]/g, ""))} placeholder={t("As it appears on your ID", "Como aparece en tu ID")} className={CAST_INPUT} /></div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div>
                <label className={CAST_LABEL}>{t("Date of birth * (21+)", "Fecha de nacimiento * (21+)")}</label>
                <input type="date" max={maxDob21()} value={f.dob} onChange={(e) => set("dob", e.target.value)} className={CAST_INPUT} style={{ colorScheme: "dark" }} />
                {f.dob && !isAdult21(f.dob) && <p className="text-coral text-[11px] mt-1.5 flex items-center gap-1.5"><Icon name="alert-circle" className="w-3.5 h-3.5" />{t("You must be 21 or older.", "Debes ser mayor de 21.")}</p>}
              </div>
              <div>
                <label className={CAST_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={CAST_INPUT} />
                {f.phone && phoneDigits.length < 10 && <p className="text-white/35 text-[11px] mt-1.5">{phoneDigits.length}/10 {t("digits", "dígitos")}</p>}
              </div>
            </div>
            <div><label className={CAST_LABEL}>Email *</label><input type="email" value={f.email} onChange={(e) => set("email", e.target.value)} placeholder="tu@email.com" className={CAST_INPUT} /></div>
            <div className="flex items-start gap-2.5 rounded-xl border border-gold/20 bg-gold/5 px-4 py-3"><Icon name="shield-check" className="w-4 h-4 text-gold-soft mt-0.5 shrink-0" /><p className="text-white/55 text-[12px] leading-snug">{t("21+ only. A valid government-issued photo ID is verified in person before your first audition.", "Solo 21+. Una identificación oficial vigente con foto se verifica en persona antes de tu primera audición.")}</p></div>
          </div>
        )}

        {/* STEP 1 — experience + min 3 days */}
        {step === 1 && (
          <div className="space-y-6">
            <div>
              <label className={CAST_LABEL}>{t("Your experience (pick all that apply) *", "Tu experiencia (elige todas las que apliquen) *")}</label>
              <div className="grid grid-cols-2 gap-2">
                {STYLE_OPTS.map((s) => <CastPill key={s} active={f.styles.includes(s)} onClick={() => toggle("styles", s)}>{s}</CastPill>)}
              </div>
            </div>
            <div>
              <label className={CAST_LABEL}>{t("Work days — minimum 3 per week *", "Días de trabajo — mínimo 3 por semana *")}</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={() => toggle("days", 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>
              <p className={"text-[11px] mt-2 flex items-center gap-1.5 " + (f.days.length >= 3 ? "text-green-400" : "text-white/40")}><Icon name={f.days.length >= 3 ? "check-circle" : "info"} className="w-3.5 h-3.5" />{f.days.length}/3 {t("days selected", "días seleccionados")}</p>
            </div>
            <div><label className={CAST_LABEL}>Instagram ({t("optional", "opcional")})</label><input value={f.instagram} onChange={(e) => set("instagram", e.target.value)} placeholder="@usuario" className={CAST_INPUT} /></div>
          </div>
        )}

        {/* STEP 2 — photos */}
        {step === 2 && (
          <div className="space-y-4">
            <p className="text-white/55 text-sm leading-relaxed">{t("Upload 3 recent photos (face and full body). They're stored privately with your application and only seen by our talent team.", "Sube 3 fotos recientes (rostro y cuerpo completo). Se guardan en privado con tu aplicación y solo las ve nuestro equipo de talento.")}</p>
            <div className="grid grid-cols-3 gap-2.5">
              {[0, 1, 2].map((i) => photos[i] ? (
                <div key={i} className="relative aspect-[3/4] rounded-2xl overflow-hidden border border-green-500/40">
                  <img src={photos[i]} alt={"photo " + (i + 1)} className="w-full h-full object-cover" />
                  <button type="button" onClick={() => setPhotos((p) => p.filter((_, idx) => idx !== i))} className="absolute top-1.5 right-1.5 w-7 h-7 rounded-full bg-black/70 flex items-center justify-center text-white"><Icon name="x" className="w-3.5 h-3.5" /></button>
                </div>
              ) : (
                <button type="button" key={i} onClick={() => fileRef.current && fileRef.current.click()} className="aspect-[3/4] rounded-2xl border-2 border-dashed border-white/20 bg-white/[.03] hover:border-coral/50 flex flex-col items-center justify-center gap-2 text-white/40 transition-all">
                  <Icon name="camera" className="w-6 h-6" /><span className="text-[10px] font-bold uppercase">{t("Photo", "Foto")} {i + 1}</span>
                </button>
              ))}
            </div>
            <input ref={fileRef} type="file" accept="image/*" multiple className="hidden" onChange={onFiles} />
            <p className={"text-[11px] flex items-center gap-1.5 " + (photos.length === 3 ? "text-green-400" : "text-white/40")}><Icon name={photos.length === 3 ? "check-circle" : "info"} className="w-3.5 h-3.5" />{photos.length}/3 {t("photos", "fotos")}</p>
          </div>
        )}

        {/* STEP 3 — agreement, legal acknowledgements + signature */}
        {step === 3 && (
          <div className="space-y-5">
            {/* DRAFT — keep visible until the attorney approves the final wording */}
            <div className="rounded-xl border border-amber-500/40 bg-amber-500/10 p-3.5 flex items-start gap-2.5">
              <Icon name="alert-triangle" className="w-4 h-4 text-amber-400 mt-0.5 shrink-0" />
              <p className="text-amber-200/90 text-[12px] leading-snug">{t("DRAFT — this agreement is pending attorney review. The final wording and exhibits A–G may change before they become legally binding.", "BORRADOR — este contrato está pendiente de revisión legal. El texto final y los anexos A–G pueden cambiar antes de ser legalmente vinculantes.")}</p>
            </div>

            <AgreementText name={f.legalName.trim()} dob={f.dob} days={f.days} today={new Date().toLocaleDateString(lang === "es" ? "es" : "en", { year: "numeric", month: "long", day: "numeric" })} />

            {/* contact & legal details */}
            <div className="rounded-2xl border border-white/12 bg-white/[.02] p-4 space-y-4">
              <div className="label text-white/50 text-[10px]">{t("Contact & legal details", "Datos de contacto y legales")}</div>
              <div><label className={CAST_LABEL}>{t("Home address *", "Dirección *")}</label><input value={f.address} onChange={(e) => set("address", e.target.value)} placeholder={t("Street address", "Calle y número")} className={CAST_INPUT} /></div>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                <div><label className={CAST_LABEL}>{t("City *", "Ciudad *")}</label><input value={f.city} onChange={(e) => set("city", e.target.value)} placeholder="Doral" className={CAST_INPUT} /></div>
                <div><label className={CAST_LABEL}>{t("State *", "Estado *")}</label><input value={f.state} onChange={(e) => set("state", e.target.value.replace(/[^a-zA-Z]/g, "").slice(0, 2).toUpperCase())} placeholder="FL" className={CAST_INPUT} /></div>
                <div><label className={CAST_LABEL}>{t("ZIP *", "C.P. *")}</label><input inputMode="numeric" value={f.zip} onChange={(e) => set("zip", e.target.value.replace(/\D/g, "").slice(0, 5))} placeholder="33122" className={CAST_INPUT} /></div>
              </div>
              <div className="grid sm:grid-cols-2 gap-3">
                <div><label className={CAST_LABEL}>{t("Emergency contact name *", "Contacto de emergencia *")}</label><input value={f.emergencyName} onChange={(e) => set("emergencyName", e.target.value.replace(/[\d]/g, ""))} placeholder={t("Full name", "Nombre completo")} className={CAST_INPUT} /></div>
                <div><label className={CAST_LABEL}>{t("Emergency phone *", "Teléfono de emergencia *")}</label><input type="tel" inputMode="numeric" value={f.emergencyPhone} onChange={(e) => set("emergencyPhone", e.target.value.replace(/[^\d() \-+]/g, "").slice(0, 16))} placeholder="(305) 555-0148" className={CAST_INPUT} /></div>
              </div>
              <div>
                <label className={CAST_LABEL}>{t("Business status (Exhibit B)", "Estatus comercial (Anexo B)")}</label>
                <div className="flex gap-2">
                  {[["individual", t("Individual", "Individual")], ["llc", t("LLC / Company", "LLC / Empresa")]].map(([id, lbl]) => (
                    <button type="button" key={id} onClick={() => set("businessStatus", id)} className={"flex-1 py-2.5 rounded-xl text-[13px] font-bold transition-all " + (f.businessStatus === id ? "bg-coral text-white" : "bg-white/[.04] border border-white/12 text-white/65")}>{lbl}</button>
                  ))}
                </div>
              </div>
            </div>

            {/* 7 required legal acknowledgements */}
            <div>
              <div className="flex items-center justify-between mb-2.5">
                <label className={CAST_LABEL + " mb-0"}>{t("Legal acknowledgements — all required *", "Confirmaciones legales — todas obligatorias *")}</label>
                <span className={"text-[11px] font-bold " + (allAcked ? "text-green-400" : "text-white/40")}>{LEGAL.filter(([id]) => acks[id]).length}/7</span>
              </div>
              <div className="space-y-2">
                {LEGAL.map(([id, txt]) => (
                  <button type="button" key={id} onClick={() => toggleAck(id)} className={"w-full flex items-start gap-3 text-left rounded-xl border p-3 transition-all " + (acks[id] ? "border-coral/50 bg-coral/8" : "border-white/12 bg-white/[.02] hover:border-white/25")}>
                    <div className={"w-5 h-5 rounded-md border flex items-center justify-center shrink-0 mt-0.5 transition-all " + (acks[id] ? "bg-coral border-coral" : "border-white/30")}>{acks[id] && <Icon name="check" className="w-3.5 h-3.5 text-white" />}</div>
                    <span className="text-white/70 text-[12.5px] leading-snug">{txt}</span>
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className={CAST_LABEL}>{t("Signature *", "Firma *")}</label>
              <SignaturePad onChange={setSignature} />
            </div>
            <div>
              <label className={CAST_LABEL}>{t("Type your legal name to confirm *", "Escribe tu nombre legal para confirmar *")}</label>
              <input value={typedName} onChange={(e) => setTypedName(e.target.value.replace(/[\d]/g, ""))} placeholder={f.legalName || t("Legal name", "Nombre legal")} className={CAST_INPUT} />
            </div>
            {/* signature metadata captured on submit (brief §9) */}
            <div className="rounded-xl border border-white/10 bg-white/[.02] p-3 text-[10.5px] text-white/40 space-y-1">
              <div className="flex items-center justify-between"><span>{t("Document", "Documento")}: {CONTRACT.title[lang === "es" ? "es" : "en"]}</span><span>{CONTRACT.version}</span></div>
              <div className="flex items-center justify-between"><span>{t("Date", "Fecha")}: {new Date().toLocaleDateString(lang === "es" ? "es" : "en", { year: "numeric", month: "long", day: "numeric" })}</span><span>{t("App ID", "ID de app")}: {appDeviceId()}</span></div>
              <div className="flex items-center gap-1.5 pt-1 border-t border-white/8"><Icon name="lock" className="w-3 h-3" />{t("Timestamp, device, app ID, version & document hash are recorded with your signature.", "Se registran fecha/hora, dispositivo, ID de app, versión y hash del documento con tu firma.")}</div>
            </div>
          </div>
        )}

        {err && <p className="text-coral text-[12px] font-semibold mt-4 flex items-center gap-2"><Icon name="alert-circle" className="w-4 h-4 shrink-0" />{err}</p>}

        {/* nav */}
        <div className="flex items-center justify-between mt-7 pt-5 border-t border-white/10">
          <button type="button" onClick={() => setStep((s) => Math.max(0, s - 1))} disabled={step === 0} className={"inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-[11px] font-bold uppercase tracking-wider transition-all " + (step === 0 ? "text-white/20 cursor-not-allowed" : "text-white/65 hover:text-white")}><Icon name="arrow-left" className="w-4 h-4" />{t("Back", "Atrás")}</button>
          {step < TOTAL - 1
            ? <button type="button" onClick={next} className="gbtn inline-flex items-center gap-2 px-7 py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em]">{t("Continue", "Continuar")}<Icon name="arrow-right" className="w-4 h-4" /></button>
            : <button type="button" onClick={submit} className="gbtn inline-flex items-center gap-2 px-7 py-3.5 rounded-full text-white text-[12px] font-black uppercase tracking-[0.14em]" style={{ background: "linear-gradient(135deg,#FF2E88,#FF6B5B)", boxShadow: "0 10px 32px rgba(255,46,136,.4)" }}><Icon name="pen-line" className="w-4 h-4" />{t("Sign & submit", "Firmar y enviar")}</button>}
        </div>
      </div>
    </div>
  );
}

/* ---------- the page: form only ---------- */
function CastingPage({ go }) {
  const t = useT();
  useReveal();
  useEffect(() => { try { window.scrollTo({ top: 0, behavior: "auto" }); } catch (e) {} }, []);
  return (
    <main className="pt-28 md:pt-32 pb-24">
      <div className="container">
        <div className="text-center max-w-2xl mx-auto mb-10">
          <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("Entertainment · Now Hiring", "Entretenimiento · Contratando")}</span>
          </div>
          <h1 className="reveal text-4xl md:text-6xl font-black uppercase leading-[0.92]" data-d="1">
            {t(<>Dance at <span className="serif-it font-normal text-coral">Pink Pony</span></>, <>Baila en <span className="serif-it font-normal text-coral">Pink Pony</span></>)}
          </h1>
          {/* dancer benefits — $0 house fee leads */}
          <div className="reveal flex flex-wrap items-center justify-center gap-2.5 mt-6" data-d="2">
            {[["dollar-sign", t("$0 House Fee", "$0 House Fee")], ["utensils", t("Free daily lunch", "Almuerzo gratis")], ["calendar", t("Flexible schedule", "Horario flexible")], ["wallet", t("Keep your tips", "Tus propinas son tuyas")]].map(([ic, lbl], i) => (
              <span key={i} className={"inline-flex items-center gap-2 rounded-full border px-3.5 py-2 text-[11.5px] font-bold " + (i === 0 ? "border-coral/50 bg-coral/12 text-coral" : "border-white/12 bg-white/[.03] text-white/75")}><Icon name={ic} className="w-3.5 h-3.5" />{lbl}</span>
            ))}
          </div>
        </div>
        <CastingForm />
      </div>
    </main>
  );
}

Object.assign(window, { CastingPage, CastingForm });
