// careers.jsx — Únete a nuestro equipo: list, detail, apply
// Each HTML entry sets window.PAGE = "careers" | "vacante" | "aplicar"
const { useState, useEffect, useRef } = React;

// =====================================================================
// LIST PAGE
// =====================================================================
function CareersListPage() {
  const [data, setData] = useState({ items: [], total: 0, facets: { departments: [], locations: [] } });
  const [loaded, setLoaded] = useState(false);
  const [filters, setFilters] = useState({ dept: "", location: "", modality: "", q: "" });

  const refetch = (f) => {
    const qs = new URLSearchParams();
    if (f.dept)     qs.set("dept", f.dept);
    if (f.location) qs.set("location", f.location);
    if (f.modality) qs.set("modality", f.modality);
    if (f.q)        qs.set("q", f.q);
    fetch(`/api/careers/jobs_list?${qs.toString()}`)
      .then(r => r.json())
      .then(d => { if (d.ok) { setData(d); setLoaded(true); } });
  };

  useEffect(() => { refetch(filters); }, []);

  const setF = (k, v) => {
    const next = { ...filters, [k]: v };
    setFilters(next);
    refetch(next);
  };

  const MODALITY = { presencial: "Presencial", remoto: "Remoto", hibrido: "Híbrido" };
  const CONTRACT = { tiempo_completo: "Tiempo completo", medio_tiempo: "Medio tiempo", temporal: "Temporal", pasantia: "Pasantía", freelance: "Freelance" };

  return (
    <window.PageScaffold active="careers">
      {/* Hero */}
      <section style={{
        padding: "120px 0 60px", position: "relative", overflow: "hidden",
        background: `
          radial-gradient(ellipse 65% 50% at 5% -5%, rgba(237,15,68,0.24), transparent 55%),
          radial-gradient(ellipse 55% 60% at 100% 105%, rgba(255,122,77,0.20), transparent 55%),
          linear-gradient(180deg, var(--paper) 0%, var(--paper-2) 100%)
        `,
      }}>
        <div aria-hidden="true" style={{
          position: "absolute", top: "-18%", right: "-8%",
          width: 500, height: 500, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(237,15,68,0.26) 0%, transparent 65%)",
          filter: "blur(56px)", pointerEvents: "none",
        }} />
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 20 }}>Únete a nuestro equipo · {data.total} {data.total === 1 ? "vacante abierta" : "vacantes abiertas"}</div>
          <h1 className="display reveal" style={{ margin: 0, maxWidth: 880 }}>
            Construye tu carrera <span className="italic-display" style={{ color: "var(--brand)" }}>conectando dominicanos.</span>
          </h1>
          <p className="lead reveal" style={{ maxWidth: 620, marginTop: 28, color: "var(--ink-2)" }}>
            En Baldera trabajamos en equipo, con propósito y pasión por el cliente. Si te apasiona la tecnología,
            las ventas o el servicio, este es tu lugar.
          </p>
        </div>
      </section>

      {/* Filters + listing */}
      <section style={{ background: "var(--paper-2)", paddingTop: 40, paddingBottom: 80 }}>
        <div className="container">
          {/* Filter bar */}
          <div className="reveal" style={{
            background: "#fff", borderRadius: 18, padding: 14, border: "1px solid var(--line)",
            display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center",
            boxShadow: "0 6px 16px -8px rgba(20,17,15,0.08)",
          }}>
            <input
              type="search" placeholder="Buscar por título, departamento…"
              value={filters.q} onChange={e => setF("q", e.target.value)}
              style={{
                flex: "1 1 240px", padding: "10px 14px", borderRadius: 12,
                border: "1px solid var(--line)", fontSize: 14, fontFamily: "inherit",
              }}
            />
            <select value={filters.dept} onChange={e => setF("dept", e.target.value)} style={selectS}>
              <option value="">Todos los departamentos</option>
              {data.facets.departments.map(d => <option key={d} value={d}>{d}</option>)}
            </select>
            <select value={filters.location} onChange={e => setF("location", e.target.value)} style={selectS}>
              <option value="">Todas las ubicaciones</option>
              {data.facets.locations.map(l => <option key={l} value={l}>{l}</option>)}
            </select>
            <select value={filters.modality} onChange={e => setF("modality", e.target.value)} style={selectS}>
              <option value="">Todas las modalidades</option>
              <option value="presencial">Presencial</option>
              <option value="hibrido">Híbrido</option>
              <option value="remoto">Remoto</option>
            </select>
          </div>

          {/* Grid */}
          <div className="reveal" style={{ marginTop: 28 }}>
            {!loaded ? (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 20 }}>
                {[1, 2, 3].map(i => (
                  <div key={i} style={{
                    background: "#fff", borderRadius: 22, padding: 28, border: "1px solid var(--line)",
                    minHeight: 260, animation: `balCareersSkel 1.4s ease-in-out ${i * 0.1}s infinite`,
                    opacity: 0.6,
                  }} />
                ))}
              </div>
            ) : data.items.length === 0 ? (
              <div style={{ background: "#fff", borderRadius: 22, padding: 60, textAlign: "center", border: "1px solid var(--line)" }}>
                <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>No hay vacantes abiertas con esos filtros.</div>
                <p className="caption" style={{ color: "var(--ink-3)" }}>
                  Prueba quitar algún filtro, o vuelve pronto — publicamos posiciones nuevas cada mes.
                </p>
              </div>
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: 20 }} className="grid-careers">
                {data.items.map(j => (
                  <a key={j.id} href={window.balUrl(`vacante.html?slug=${encodeURIComponent(j.slug)}`)}
                     style={{
                       display: "flex", flexDirection: "column",
                       background: "#fff", borderRadius: 22, padding: 28,
                       border: "1px solid var(--line)", color: "var(--ink)",
                       transition: "transform 240ms cubic-bezier(0.32,0.72,0,1), box-shadow 240ms, border-color 240ms",
                     }}
                     onMouseOver={e => {
                       e.currentTarget.style.transform = "translateY(-4px)";
                       e.currentTarget.style.boxShadow = "0 20px 44px -16px rgba(20,17,15,0.18)";
                       e.currentTarget.style.borderColor = "rgba(237,15,68,0.22)";
                     }}
                     onMouseOut={e => {
                       e.currentTarget.style.transform = "";
                       e.currentTarget.style.boxShadow = "";
                       e.currentTarget.style.borderColor = "var(--line)";
                     }}
                  >
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
                      <span className="mini" style={{ color: "var(--brand)", letterSpacing: "0.08em" }}>{j.department || "Vacante"}</span>
                    </div>
                    <h3 style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.018em", lineHeight: 1.2, margin: 0 }}>{j.title}</h3>
                    {j.short_summary && (
                      <p style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-2)", marginTop: 12, marginBottom: 18, flex: 1 }}>{j.short_summary}</p>
                    )}
                    <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: "auto", paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                      <Tag>{j.location || "RD"}</Tag>
                      <Tag>{MODALITY[j.modality]}</Tag>
                      <Tag>{CONTRACT[j.contract_type]}</Tag>
                    </div>
                    <div style={{ marginTop: 16, color: "var(--brand)", fontSize: 13, fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}>
                      Ver detalles <window.Icon.Arrow />
                    </div>
                  </a>
                ))}
              </div>
            )}
          </div>
        </div>
      </section>

      <style>{`
        @keyframes balCareersSkel {
          0%, 100% { opacity: 0.4; }
          50%      { opacity: 0.75; }
        }
      `}</style>
    </window.PageScaffold>
  );
}

const selectS = {
  padding: "10px 14px", borderRadius: 12, border: "1px solid var(--line)",
  fontSize: 14, fontFamily: "inherit", background: "#fff", cursor: "pointer",
};

function Tag({ children }) {
  return (
    <span style={{
      fontSize: 12, fontWeight: 500, padding: "4px 10px",
      background: "var(--paper-2)", color: "var(--ink-2)",
      borderRadius: 999, border: "1px solid var(--line)",
    }}>{children}</span>
  );
}

// =====================================================================
// JOB DETAIL PAGE
// =====================================================================
function JobDetailPage() {
  const [job, setJob] = useState(null);
  const [error, setError] = useState(false);
  const slug = new URLSearchParams(location.search).get("slug") || "";

  useEffect(() => {
    if (!slug) { setError(true); return; }
    fetch(`/api/careers/job_get?slug=${encodeURIComponent(slug)}`)
      .then(r => r.json())
      .then(d => { if (d.ok) { setJob(d.job); document.title = `${d.job.title} — Únete a nuestro equipo · Baldera`; } else setError(true); });
  }, [slug]);

  if (error) {
    return (
      <window.PageScaffold active="careers">
        <section style={{ padding: "160px 0", textAlign: "center" }}>
          <div className="container">
            <h1 className="h1">Vacante no encontrada</h1>
            <p className="lead" style={{ color: "var(--ink-2)", marginTop: 16 }}>Puede haber sido cerrada o el enlace está incorrecto.</p>
            <a href={window.balUrl("unete.html")} className="btn btn-brand" style={{ marginTop: 32 }}>Ver todas las vacantes</a>
          </div>
        </section>
      </window.PageScaffold>
    );
  }

  if (!job) {
    return (
      <window.PageScaffold active="careers">
        <section style={{ padding: "160px 0", textAlign: "center", color: "var(--ink-3)" }}>Cargando…</section>
      </window.PageScaffold>
    );
  }

  const MODALITY = { presencial: "Presencial", remoto: "Remoto", hibrido: "Híbrido" };
  const CONTRACT = { tiempo_completo: "Tiempo completo", medio_tiempo: "Medio tiempo", temporal: "Temporal", pasantia: "Pasantía", freelance: "Freelance" };

  const hasCover = job.cover_image && job.cover_image.length > 0;
  const heroBg = hasCover
    ? `linear-gradient(180deg, rgba(15,10,26,0.55) 0%, rgba(20,16,36,0.85) 100%), url(${job.cover_image}) center/cover no-repeat`
    : `radial-gradient(ellipse 70% 60% at 0% -10%, rgba(237,15,68,0.32), transparent 55%),
       radial-gradient(ellipse 60% 70% at 100% 110%, rgba(255,122,77,0.22), transparent 55%),
       linear-gradient(160deg, #1a1024 0%, #2a1538 60%, #3a2050 100%)`;

  return (
    <window.PageScaffold active="careers">
      {/* HERO — cover image as background OR brand gradient */}
      <section className="bal-job-hero" style={{
        padding: "112px 0 64px", position: "relative", overflow: "hidden",
        background: heroBg,
        color: "#fff",
      }}>
        {/* Decorative dots overlay */}
        <div aria-hidden="true" style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          backgroundImage: "radial-gradient(rgba(255,255,255,0.05) 1px, transparent 1px)",
          backgroundSize: "22px 22px",
        }} />
        <div className="container" style={{ position: "relative", maxWidth: 920 }}>
          <a href={window.balUrl("unete.html")} style={{
            display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 500,
            color: "rgba(255,255,255,0.85)", marginBottom: 20,
          }}>
            ← Todas las vacantes
          </a>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "5px 12px", borderRadius: 999,
            background: "rgba(255,255,255,0.12)", color: "#fff",
            fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase",
            marginBottom: 16,
            border: "1px solid rgba(255,255,255,0.18)",
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 999, background: "var(--brand-coral)" }} />
            {job.department || "Vacante"}
          </div>
          <h1 style={{
            margin: 0, maxWidth: 800,
            fontSize: "clamp(30px, 4.6vw, 52px)",
            fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1.08,
            color: "#fff",
          }}>{job.title}</h1>
          {job.short_summary && (
            <p style={{ maxWidth: 680, marginTop: 16, marginBottom: 0, color: "rgba(255,255,255,0.82)", fontSize: 17, lineHeight: 1.5 }}>{job.short_summary}</p>
          )}
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 22 }}>
            {job.location && <ChipBadge dark>📍 {job.location}</ChipBadge>}
            <ChipBadge dark>{MODALITY[job.modality]}</ChipBadge>
            <ChipBadge dark>{CONTRACT[job.contract_type]}</ChipBadge>
            {job.salary_visible && job.salary_min && (
              <ChipBadge dark>RD${Math.round(job.salary_min).toLocaleString()}{job.salary_max ? ` – ${Math.round(job.salary_max).toLocaleString()}` : "+"}</ChipBadge>
            )}
          </div>
          <div style={{ marginTop: 28, display: "flex", gap: 10, flexWrap: "wrap" }}>
            <a href={window.balUrl(`aplicar.html?slug=${encodeURIComponent(job.slug)}`)} className="btn btn-brand"
               style={{ padding: "13px 26px", fontSize: 14.5, fontWeight: 600, boxShadow: "0 12px 32px -8px rgba(237,15,68,0.55)" }}>
              Aplicar a esta vacante <window.Icon.Arrow />
            </a>
            <button onClick={() => navigator.share ? navigator.share({ title: job.title, url: location.href }) : navigator.clipboard.writeText(location.href).then(() => alert("Enlace copiado"))}
              style={{
                padding: "13px 22px", fontSize: 13.5, fontWeight: 500,
                background: "rgba(255,255,255,0.10)", color: "#fff",
                borderRadius: 999, border: "1px solid rgba(255,255,255,0.22)",
                cursor: "pointer", backdropFilter: "blur(8px)",
              }}>
              Compartir
            </button>
          </div>
        </div>
      </section>

      {/* BODY — single centered column (no sidebar = no phantom gaps) */}
      <section style={{ background: "var(--paper)", paddingTop: 56, paddingBottom: 64 }}>
        <div className="container" style={{ maxWidth: 760 }}>
          <article>
            {job.description     && <Block title="Sobre el puesto"     html={job.description} />}
            {job.responsibilities && <Block title="Responsabilidades" html={job.responsibilities} />}
            {job.requirements    && <Block title="Requisitos"          html={job.requirements} />}
            {job.benefits        && <Block title="Beneficios"          html={job.benefits} />}
          </article>

          {/* In-flow Apply card (after content, at natural reading end) */}
          <div style={{
            marginTop: 40,
            background: "linear-gradient(135deg, var(--brand) 0%, var(--brand-deep) 100%)",
            borderRadius: 24, padding: "32px 28px",
            color: "#fff", textAlign: "center",
            boxShadow: "0 20px 48px -20px rgba(237,15,68,0.45)",
            position: "relative", overflow: "hidden",
          }}>
            <div aria-hidden="true" style={{
              position: "absolute", inset: 0,
              backgroundImage: "radial-gradient(rgba(255,255,255,0.12) 1.5px, transparent 1.5px)",
              backgroundSize: "20px 20px",
            }} />
            <div style={{ position: "relative" }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase", opacity: 0.88, marginBottom: 10 }}>
                ¿TE INTERESA?
              </div>
              <h3 style={{ fontSize: "clamp(22px, 3vw, 28px)", fontWeight: 700, letterSpacing: "-0.018em", margin: 0, color: "#fff", lineHeight: 1.2 }}>
                Aplica en menos de 5 minutos
              </h3>
              <p style={{ fontSize: 14, opacity: 0.85, marginTop: 8, marginBottom: 20, maxWidth: 440, marginLeft: "auto", marginRight: "auto", lineHeight: 1.5 }}>
                Sube tu CV, llena el form y recibe confirmación inmediata por correo. Tu data está segura (Ley 172-13).
              </p>
              <a href={window.balUrl(`aplicar.html?slug=${encodeURIComponent(job.slug)}`)}
                 className="btn" style={{
                   background: "#fff", color: "var(--brand)",
                   padding: "14px 32px", fontSize: 15, fontWeight: 700, borderRadius: 999,
                 }}>
                Aplicar ahora <window.Icon.Arrow />
              </a>
            </div>
          </div>
        </div>
      </section>

    </window.PageScaffold>
  );
}

function ChipBadge({ children, dark }) {
  if (dark) {
    return (
      <span style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "7px 14px", borderRadius: 999,
        background: "rgba(255,255,255,0.10)", border: "1px solid rgba(255,255,255,0.18)",
        fontSize: 13, fontWeight: 500, color: "rgba(255,255,255,0.92)",
        backdropFilter: "blur(8px)",
      }}>{children}</span>
    );
  }
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "8px 16px", borderRadius: 999,
      background: "#fff", border: "1px solid var(--line)",
      fontSize: 13, fontWeight: 500, color: "var(--ink)",
      boxShadow: "0 2px 6px -3px rgba(20,17,15,0.08)",
    }}>{children}</span>
  );
}

function Block({ title, html }) {
  // Strip any leading/trailing whitespace and empty <p></p> tags from rich text
  const clean = (html || "")
    .replace(/^\s+|\s+$/g, "")
    .replace(/<p>\s*(<br\s*\/?>\s*)*\s*<\/p>/gi, "")
    .replace(/(<br\s*\/?>\s*){2,}/gi, "");
  return (
    <div className="bal-job-block">
      <h2>{title}</h2>
      <div className="careers-prose" dangerouslySetInnerHTML={{ __html: clean }} />
    </div>
  );
}

// =====================================================================
// APPLY PAGE — application form
// =====================================================================
function ApplyPage() {
  const [job, setJob] = useState(null);
  const [error, setError] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(null);
  const [serverError, setServerError] = useState(null);
  const slug = new URLSearchParams(location.search).get("slug") || "";

  const [form, setForm] = useState({
    full_name: "", email: "", phone: "", dni: "", city: "",
    cover_letter: "", consent: false,
  });

  useEffect(() => {
    if (!slug) { setError(true); return; }
    fetch(`/api/careers/job_get?slug=${encodeURIComponent(slug)}`)
      .then(r => r.json())
      .then(d => { if (d.ok) setJob(d.job); else setError(true); });
  }, [slug]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (ev) => {
    ev.preventDefault();
    setServerError(null);
    if (!form.consent) { setServerError("Debes aceptar el aviso de privacidad."); return; }
    if (!form.full_name.trim() || !form.email.trim() || !form.phone.trim()) {
      setServerError("Nombre, email y teléfono son obligatorios.");
      return;
    }
    setSubmitting(true);

    try {
      const r = await fetch("/api/careers/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          job_slug: slug,
          full_name: form.full_name.trim(),
          email: form.email.trim(),
          phone: form.phone.trim(),
          dni: form.dni.trim(),
          city: form.city.trim(),
          cover_letter: form.cover_letter.trim(),
          consent: !!form.consent,
        }),
      });
      const d = await r.json();
      if (d.ok) setSuccess({ id: d.application_id, message: d.message });
      else setServerError(d.message || d.error || "No se pudo enviar.");
    } catch (e) {
      setServerError("Error de red. Intenta de nuevo.");
    } finally {
      setSubmitting(false);
    }
  };

  if (error) {
    return (
      <window.PageScaffold active="careers">
        <section style={{ padding: "160px 0", textAlign: "center" }}>
          <div className="container">
            <h1 className="h1">Vacante no encontrada</h1>
            <a href={window.balUrl("unete.html")} className="btn btn-brand" style={{ marginTop: 32 }}>Ver vacantes abiertas</a>
          </div>
        </section>
      </window.PageScaffold>
    );
  }

  if (success) {
    return (
      <window.PageScaffold active="careers">
        <section style={{ padding: "120px 0", textAlign: "center" }}>
          <div className="container" style={{ maxWidth: 640 }}>
            <div style={{
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              width: 88, height: 88, borderRadius: 24,
              background: "linear-gradient(135deg, rgba(31,170,84,0.18), rgba(31,170,84,0.04))",
              border: "1px solid rgba(31,170,84,0.32)", marginBottom: 24,
              boxShadow: "0 12px 28px -10px rgba(31,170,84,0.32)",
            }}>
              <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#1faa54" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5" />
              </svg>
            </div>
            <h1 className="h1" style={{ marginBottom: 16 }}>¡Aplicación enviada!</h1>
            <p className="lead" style={{ color: "var(--ink-2)", marginBottom: 32 }}>
              {success.message} Revisa tu bandeja de entrada (y spam, por si acaso).
            </p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
              <a href={window.balUrl("unete.html")} className="btn btn-brand">Ver más vacantes</a>
              <a href={window.balUrl("index.html")} className="link" style={{ alignSelf: "center" }}>Volver al inicio</a>
            </div>
          </div>
        </section>
      </window.PageScaffold>
    );
  }

  return (
    <window.PageScaffold active="careers">
      <section style={{
        padding: "120px 0 60px", position: "relative", overflow: "hidden",
        background: "linear-gradient(180deg, var(--paper) 0%, var(--paper-2) 100%)",
      }}>
        <div className="container">
          <a href={window.balUrl(`vacante.html?slug=${encodeURIComponent(slug)}`)} style={{
            display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 500,
            color: "var(--ink-2)", marginBottom: 20,
          }}>
            ← Volver a la vacante
          </a>
          <div className="eyebrow" style={{ color: "var(--brand)", marginBottom: 16 }}>Aplicación</div>
          <h1 className="h1" style={{ margin: 0, maxWidth: 720 }}>
            {job ? `Aplicar a ${job.title}` : "Aplica a la vacante"}
          </h1>
        </div>
      </section>

      <section style={{ background: "var(--paper)", paddingTop: 40, paddingBottom: 80 }}>
        <div className="container" style={{ maxWidth: 720 }}>
          <form onSubmit={submit} style={{
            background: "#fff", borderRadius: 22, padding: 36, border: "1px solid var(--line)",
            boxShadow: "0 12px 32px -20px rgba(20,17,15,0.18)",
          }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, marginTop: 0, marginBottom: 20 }}>Tus datos</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="apply-grid">
              <Field label="Nombre completo *">
                <input required value={form.full_name} onChange={e => set("full_name", e.target.value)} maxLength={140} />
              </Field>
              <Field label="Email *">
                <input required type="email" value={form.email} onChange={e => set("email", e.target.value)} maxLength={160} />
              </Field>
              <Field label="Teléfono / WhatsApp *">
                <input required type="tel" value={form.phone} onChange={e => set("phone", e.target.value)} maxLength={40} placeholder="+1 809..." />
              </Field>
              <Field label="Cédula (opcional)">
                <input value={form.dni} onChange={e => set("dni", e.target.value)} maxLength={40} placeholder="000-0000000-0" />
              </Field>
              <Field label="Ciudad" full>
                <input value={form.city} onChange={e => set("city", e.target.value)} maxLength={80} placeholder="Ej: Santiago" />
              </Field>
            </div>

            <h2 style={{ fontSize: 18, fontWeight: 700, marginTop: 32, marginBottom: 20 }}>Sobre ti</h2>
            <div style={{
              padding: "12px 16px", marginBottom: 16, borderRadius: 12,
              background: "var(--paper-2)", border: "1px solid var(--line)",
              fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)",
            }}>
              📄 Envía tu <strong>CV</strong> a <a href="mailto:recursoshumanos@baldera.com.do" style={{ color: "var(--brand)", fontWeight: 600 }}>recursoshumanos@baldera.com.do</a> indicando la vacante. Recibirás confirmación tras enviar este formulario.
            </div>
            <Field label="Carta de presentación (opcional)" full>
              <textarea value={form.cover_letter} onChange={e => set("cover_letter", e.target.value)} maxLength={4000} rows={5}
                placeholder="Cuéntanos en pocas líneas por qué te interesa este puesto." />
              <div style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "right", marginTop: 4 }}>
                {form.cover_letter.length}/4000
              </div>
            </Field>

            <label style={{
              display: "flex", alignItems: "flex-start", gap: 10,
              padding: "16px", marginTop: 20, borderRadius: 14,
              background: "var(--paper-2)", border: "1px solid var(--line)", cursor: "pointer",
              fontSize: 13, lineHeight: 1.55, color: "var(--ink-2)",
            }}>
              <input type="checkbox" checked={form.consent} onChange={e => set("consent", e.target.checked)}
                style={{ marginTop: 3, accentColor: "var(--brand)" }} />
              <span>
                Acepto que Baldera Comunicaciones procese mis datos personales y CV con el único fin de
                evaluar mi candidatura para esta vacante u otras posiciones futuras de la empresa, conforme a la{" "}
                <a href={window.balUrl("privacidad.html")} target="_blank" rel="noopener" style={{ color: "var(--brand)" }}>
                  política de privacidad
                </a> y la <strong>Ley 172-13 de RD</strong> sobre protección de datos personales.
              </span>
            </label>

            {serverError && (
              <div style={{
                marginTop: 16, padding: "12px 16px", borderRadius: 12,
                background: "rgba(167,42,42,0.08)", border: "1px solid rgba(167,42,42,0.28)",
                color: "#a72a2a", fontSize: 13.5, fontWeight: 500,
              }}>
                {serverError}
              </div>
            )}

            <button type="submit" disabled={submitting} className="btn btn-brand" style={{
              marginTop: 24, width: "100%", padding: "14px 28px", fontSize: 15,
              justifyContent: "center", opacity: submitting ? 0.7 : 1,
            }}>
              {submitting ? "Enviando…" : <>Enviar aplicación <window.Icon.Arrow /></>}
            </button>
          </form>
        </div>
      </section>

      <style>{`
        @media (max-width: 720px) {
          .apply-grid { grid-template-columns: 1fr !important; }
        }
        form input[type="text"], form input[type="email"], form input[type="tel"], form input:not([type]),
        form textarea, form input[type="file"] {
          width: 100%; padding: 11px 14px; border-radius: 12px;
          border: 1px solid var(--line); background: #fff;
          font-size: 14.5px; font-family: inherit; color: var(--ink);
          transition: border-color 140ms, box-shadow 140ms;
        }
        form input:focus, form textarea:focus {
          outline: none; border-color: var(--brand);
          box-shadow: 0 0 0 3px rgba(237,15,68,0.14);
        }
        form textarea { resize: vertical; min-height: 110px; }
      `}</style>
    </window.PageScaffold>
  );
}

function Field({ label, full, children }) {
  return (
    <label style={{ display: "block", gridColumn: full ? "1 / -1" : undefined, marginBottom: full ? 14 : 0 }}>
      <span style={{
        display: "block", fontSize: 12.5, fontWeight: 600,
        color: "var(--ink-2)", marginBottom: 6, letterSpacing: "0.01em",
      }}>{label}</span>
      {children}
    </label>
  );
}

// =====================================================================
// BOOTSTRAP
// =====================================================================
window.PAGES = Object.assign({}, window.PAGES, {
  careers: CareersListPage,
  vacante: JobDetailPage,
  aplicar: ApplyPage,
});
if (!window.__BAL_ROOT) window.__BAL_ROOT = ReactDOM.createRoot(document.getElementById("root"));
window.__BAL_ROOT.render(React.createElement((window.PAGES && window.PAGES[window.PAGE]) || CareersListPage));
