
// CourseLandingPage.jsx — Landing page individual por curso
const COURSE_DETAIL = {
  "humanidad": {
    tagEs: "Curso grabado · Disponible ahora",
    tagEn: "Recorded course · Available now",
    titleEs: "Humanidad en transformación",
    titleEn: "Humanity in Transformation",
    subtitleEs: "Del cazador a la Revolución Industrial",
    subtitleEn: "From hunter-gatherer to the Industrial Revolution",
    descEs: "Un viaje por los grandes momentos que transformaron la humanidad, desde los primeros asentamientos hasta la revolución que cambió el trabajo, la ciudad y la vida cotidiana.",
    descEn: "A journey through the great moments that transformed humanity, from the first settlements to the revolution that changed work, the city and daily life.",
    type: "recorded",
    platform: "Grabación",
    priceComplete: 36000,
    priceSession: 12000,
    urlCompleto: 'https://mpago.la/15snY53',
    urlSesion: 'https://mpago.la/2TccweY',
    sessions: [
      { dateEs:"Sesión 1", dateEn:"Session 1", titleEs:"Del nómade al agricultor", titleEn:"From nomad to farmer", descEs:"La revolución neolítica y los primeros asentamientos humanos permanentes.", descEn:"The Neolithic revolution and the first permanent human settlements.", youtubeUrl:"https://youtu.be/paev8EkkOKM" },
      { dateEs:"Sesión 2", dateEn:"Session 2", titleEs:"Ciudades, imperios y escritura", titleEn:"Cities, empires and writing", descEs:"El surgimiento de las primeras civilizaciones urbanas y la invención de la escritura.", descEn:"The rise of the first urban civilizations and the invention of writing.", youtubeUrl:"https://youtu.be/R3J1k7GFERQ" },
      { dateEs:"Sesión 3", dateEn:"Session 3", titleEs:"La Revolución Industrial", titleEn:"The Industrial Revolution", descEs:"El momento que cambió la relación del ser humano con el trabajo, el tiempo y el espacio.", descEn:"The moment that changed humanity's relationship with work, time and space.", youtubeUrl:"https://youtu.be/o4bUX1Ibd54" },
    ],
    whyEs: ["Acceso inmediato a las 3 grabaciones", "Aprende a tu propio ritmo", "Material de apoyo incluido"],
    whyEn: ["Immediate access to all 3 recordings", "Learn at your own pace", "Support material included"],
  },
  "trincheras": {
    tagEs: "Curso de Historia · Junio 2026",
    tagEn: "History Course · June 2026",
    titleEs: "De los Imperios a las Trincheras",
    titleEn: "From Empires to Trenches",
    subtitleEs: "Historia de la Primera Guerra Mundial",
    subtitleEn: "History of the First World War",
    descEs: "Un recorrido por los nacionalismos e imperialismos que transformaron la Europa del siglo XIX y condujeron a la Primera Guerra Mundial, culminando en el Tratado de Versalles.",
    descEn: "A journey through the nationalisms and imperialisms that transformed 19th-century Europe and led to World War I, culminating in the Treaty of Versailles.",
    type: "live",
    dates: "10, 17 y 24 de junio 2026",
    time: "19:00 hrs",
    platform: "Zoom en vivo",
    priceComplete: 45000,
    priceSession: 15000,
    urlCompleto: 'https://mpago.la/1LFMkuV',
    urlSesion: 'https://mpago.la/2GCvq4q',
    sessions: [
      { dateEs:"Miércoles 10 de junio", dateEn:"Wednesday June 10", titleEs:"Sesión 1 — Nacionalismos e Imperialismos", titleEn:"Session 1 — Nationalisms and Imperialisms", descEs:"", descEn:"" },
      { dateEs:"Miércoles 17 de junio", dateEn:"Wednesday June 17", titleEs:"Sesión 2 — La Gran Guerra", titleEn:"Session 2 — The Great War", descEs:"", descEn:"" },
      { dateEs:"Miércoles 24 de junio", dateEn:"Wednesday June 24", titleEs:"Sesión 3 — Versalles y sus consecuencias", titleEn:"Session 3 — Versailles and its consequences", descEs:"", descEn:"" },
    ],
    whyEs: ["Clases en vivo por Zoom con Pilar Ducci", "Análisis de fuentes primarias y contexto geopolítico riguroso"],
    whyEn: ["Live Zoom classes with Pilar Ducci", "Primary source analysis and rigorous geopolitical context"],
  },
  "aquiles": {
    tagEs: "Curso de Historia · Agosto 2026",
    tagEn: "History Course · August 2026",
    titleEs: "Aquiles y Odiseo – El Mundo detrás de Troya",
    titleEn: "Achilles & Odysseus – The World Behind Troy",
    subtitleEs: "Dos sesiones en vivo por Zoom",
    subtitleEn: "Two live sessions via Zoom",
    descEs: "La Guerra de Troya, sus héroes y el mundo antiguo que la hizo posible. Dos sesiones para explorar la épica griega como espejo de la historia.",
    descEn: "The Trojan War, its heroes and the ancient world that made it possible. Two sessions to explore Greek epic as a mirror of history.",
    type: "live",
    dates: "8 y 15 de agosto 2026",
    time: "19:00 hrs",
    platform: "Zoom en vivo",
    priceComplete: 30000,
    priceSession: 15000,
    urlCompleto: 'https://mpago.la/2zBd4dw',
    urlSesion: 'https://mpago.la/2GCvq4q',
    sessions: [
      { dateEs:"Miércoles 8 de agosto", dateEn:"Wednesday August 8", titleEs:"Aquiles y la Ilíada", titleEn:"Achilles and the Iliad", descEs:"", descEn:"" },
      { dateEs:"Miércoles 15 de agosto", dateEn:"Wednesday August 15", titleEs:"Odiseo y la Odisea", titleEn:"Odysseus and the Odyssey", descEs:"", descEn:"" },
    ],
    whyEs: ["Clases en vivo por Zoom con Pilar Ducci"],
    whyEn: ["Live Zoom classes with Pilar Ducci"],
  },
  "vikingos": {
    tagEs: "Curso de Historia · Agosto 2026",
    tagEn: "History Course · August 2026",
    titleEs: "La Ruta de los Vikingos",
    titleEn: "The Viking Route",
    subtitleEs: "Una sesión en vivo por Zoom",
    subtitleEn: "One live session via Zoom",
    descEs: "Rutas, cultura, mitología y legado vikingo en la historia europea. Una sesión para descubrir el mundo nórdico medieval.",
    descEn: "Routes, culture, mythology and Viking legacy in European history. One session to discover the medieval Nordic world.",
    type: "live",
    dates: "12 de agosto 2026",
    time: "19:00 hrs",
    platform: "Zoom en vivo",
    priceComplete: 15000,
    priceSession: 15000,
    urlCompleto: 'https://mpago.la/2GCvq4q',
    urlSesion: 'https://mpago.la/2GCvq4q',
    sessions: [
      { dateEs:"Miércoles 12 de agosto", dateEn:"Wednesday August 12", titleEs:"La Ruta de los Vikingos", titleEn:"The Viking Route", descEs:"", descEn:"" },
    ],
    whyEs: ["Clase en vivo por Zoom con Pilar Ducci"],
    whyEn: ["Live Zoom class with Pilar Ducci"],
  },
};

// Generic recorded course template
const GRABADOS_URLS = {1: 'https://mpago.la/2TccweY', 2: 'https://mpago.la/2fd6Tvt', 3: 'https://mpago.la/15snY53', 4: 'https://mpago.la/25mS66j'};
const makeRecorded = (id, titleEs, titleEn, descEs, descEn, sessions, price, sessionTitlesEs = []) => ({
  tagEs: "Curso grabado · Disponible ahora",
  tagEn: "Recorded course · Available now",
  titleEs, titleEn,
  subtitleEs: "Acceso inmediato al comprar",
  subtitleEn: "Immediate access upon purchase",
  descEs, descEn,
  type: "recorded",
  dates: "",
  time: "",
  platform: "Grabación online",
  priceComplete: price,
  priceSession: 12000,
  urlCompleto: GRABADOS_URLS[sessions] || '#',
  urlSesion: 'https://mpago.la/2TccweY',
  sessions: Array.from({ length: sessions }, (_, i) => ({
    dateEs: `Sesión ${i + 1}`,
    dateEn: `Session ${i + 1}`,
    titleEs: sessionTitlesEs[i] || `Sesión ${i + 1}`,
    titleEn: sessionTitlesEs[i] || `Session ${i + 1}`,
    descEs: "",
    descEn: "",
  })),
  whyEs: ["Acceso inmediato a las grabaciones", "Contenido riguroso y apasionante", "Ve las clases a tu propio ritmo"],
  whyEn: ["Immediate access to recordings", "Rigorous and passionate content", "Watch classes at your own pace"],
});

const makeFreeCourse = (titleEs, titleEn, descEs, descEn, youtubeUrl) => ({
  tagEs: "Clase gratuita · Acceso inmediato",
  tagEn: "Free class · Immediate access",
  titleEs, titleEn,
  subtitleEs: "Clase gratuita en YouTube",
  subtitleEn: "Free class on YouTube",
  descEs, descEn,
  type: "recorded",
  free: true,
  dates: "",
  time: "",
  platform: "YouTube",
  priceComplete: 0,
  priceSession: 0,
  urlCompleto: youtubeUrl,
  urlSesion: youtubeUrl,
  sessions: [
    { dateEs: "Clase gratuita", dateEn: "Free class", titleEs, titleEn, descEs: "", descEn: "", youtubeUrl },
  ],
  whyEs: ["Acceso gratuito e inmediato", "Clase introductoria para explorar el tema"],
  whyEn: ["Free immediate access", "Introductory class to explore the topic"],
});

// Merge all recorded courses into COURSE_DETAIL
Object.assign(COURSE_DETAIL, {
  'damnatio': makeRecorded('damnatio', 'Damnatio Memoriae', 'Damnatio Memoriae', 'El arte de borrar personas de la historia. Análisis de casos desde Roma hasta el siglo XX.', 'The art of erasing people from history. Case studies from Rome to the 20th century.', 3, 36000, ['Invisibilización y demonización', 'Antigüedad y mundo clásico', 'Revolución científica y modernidad']),
  'mujeres': makeRecorded('mujeres', 'Sobre Mujeres y Otras Monstruosidades', 'On Women and Other Monstrosities', 'Historia de la mujer a través de los siglos. Cómo el poder construyó la idea de lo \'femenino\'.', 'History of women through the centuries. How power constructed the idea of the \'feminine\'.', 4, 48000),
  'migraciones': makeRecorded('migraciones', 'Fuera del Edén — Migraciones Humanas', 'Out of Eden — Human Migrations', 'Historia de las grandes migraciones humanas desde la prehistoria hasta el presente.', 'History of great human migrations from prehistory to the present.', 4, 48000),
  'troya-roma': makeRecorded('troya-roma', 'De Troya a Roma', 'From Troy to Rome', 'La Ilíada, la Odisea, la Eneida y la Divina Comedia. Literatura épica como espejo de la historia.', 'The Iliad, the Odyssey, the Aeneid and the Divine Comedy. Epic literature as a mirror of history.', 4, 48000, ['La Ilíada', 'La Odisea', 'La Eneida', 'La Divina Comedia']),
  'civilizacion': makeRecorded('civilizacion', 'La Cuna de la Civilización', 'The Cradle of Civilization', 'Sumeria, Asiria, Babilonia, los Fenicios y Egipto. Los orígenes de la vida urbana y la escritura.', 'Sumer, Assyria, Babylon, the Phoenicians and Egypt. The origins of urban life and writing.', 4, 48000, ['Sumeria y Acadia', 'Asiria y Babilonia', 'Los Persas', 'Egipto']),
  'catacumbas': makeRecorded('catacumbas', 'De las Catacumbas a la Modernidad', 'From the Catacombs to Modernity', 'Historia del Cristianismo desde sus orígenes perseguidos hasta su dominio global.', 'History of Christianity from its persecuted origins to global dominance.', 3, 36000, ['Orígenes', 'El Cristianismo Imperial y Medieval', 'Reforma, Contrarreforma y expansión']),
  'evolucion': makeRecorded('evolucion', 'Historia de la Evolución de la Humanidad', 'History of Human Evolution', 'De los primeros homínidos al Homo sapiens. Evolución biológica y cultural de nuestra especie.', 'From the first hominids to Homo sapiens. Biological and cultural evolution of our species.', 3, 36000, ['El origen de la vida y el surgimiento del bipedalismo', 'Selección natural, Homo erectus y los cimientos de la humanidad', 'Homo sapiens en su salida de África']),
  'iran': makeRecorded('iran', 'Irán: Poder, Colonialismo, Revolución y Religión', 'Iran: Power, Colonialism, Revolution and Religion', 'De la Persia imperial a la República Islámica. Historia de un país bajo presión constante.', 'From imperial Persia to the Islamic Republic. History of a country under constant pressure.', 1, 12000, ['Irán: poder, colonialismo, religión y revolución']),
  'corses': {
    tagEs: 'Curso grabado · Disponible ahora',
    tagEn: 'Recorded course · Available now',
    titleEs: 'Corsés, tacones y Revolución',
    titleEn: 'Corsets, Heels and Revolution',
    subtitleEs: 'Moda, género y poder en la historia',
    subtitleEn: 'Fashion, gender and power in history',
    descEs: 'Moda, género y poder a través de la historia. Cómo la ropa refleja los cambios sociales y políticos.',
    descEn: 'Fashion, gender and power through history. How clothing reflects social and political changes.',
    type: 'recorded',
    platform: 'Grabación',
    priceComplete: 12000,
    priceSession: 12000,
    urlCompleto: 'https://mpago.la/2TccweY',
    urlSesion: 'https://mpago.la/2TccweY',
    sessions: [
      { dateEs:'Sesión 1', dateEn:'Session 1', titleEs:'Corsés, tacones y Revolución', titleEn:'Corsets, Heels and Revolution', descEs:'Moda como reflejo del poder y la resistencia femenina a lo largo de la historia.', descEn:'Fashion as a reflection of power and female resistance throughout history.' },
    ],
    whyEs: ['Acceso inmediato a la grabación', 'Aprende a tu propio ritmo'],
    whyEn: ['Immediate access to the recording', 'Learn at your own pace'],
  },
  'chiloe': makeRecorded('chiloe', 'Historia de la Anexión de Chiloé', 'History of the Annexation of Chiloé', 'Bicentenario 1826–2026. Cómo y por qué Chiloé fue el último territorio en unirse a Chile.', 'Bicentennial 1826–2026. How and why Chiloé was the last territory to join Chile.', 2, 24000, ['Chiloé antes de Chile: una comunidad entre el mar y sus mitos', 'El Tratado de Tantauco y la incorporación de Chiloé']),
  'chile-mestizo': makeRecorded('chile-mestizo', 'Chile Mestizo', 'Mestizo Chile', 'La formación racial y cultural de Chile. Herencias indígenas, españolas y africanas entrelazadas.', 'The racial and cultural formation of Chile. Indigenous, Spanish and African heritages intertwined.', 1, 12000, ['La Conquista y el Chile Colonial']),
  'independencia': makeRecorded('independencia', 'Del Rey al Pueblo — Independencia de Chile', 'From King to People — Chilean Independence', 'Cómo Chile pasó de colonia a nación. El proceso más allá de los héroes del texto escolar.', 'How Chile went from colony to nation. The process beyond the heroes of the school textbook.', 1, 12000, ['Independencia de Chile: Entre Revolución e Intrigas']),
  'risas-rebeldias': makeRecorded('risas-rebeldias', 'Entre Risas y Rebeldías', 'Between Laughter and Rebellion', 'Historia de la sociabilidad popular en Chile. Fiestas, protestas y resistencia cultural.', 'History of popular sociability in Chile. Festivals, protests and cultural resistance.', 4, 48000, ['Juegos y Entretenciones: el humor y la fiesta', 'Bandidaje en Chile: de forajidos a héroes populares', 'Espiritismo y Brujería', 'Prensa Satírica: la risa como arma política en papel y tinta']),
  'mistral': makeRecorded('mistral', 'A 80 años del Nobel de Gabriela Mistral', '80 Years of Gabriela Mistral\'s Nobel', 'Vida, obra y legado de Gabriela Mistral. La primera latinoamericana en ganar el Nobel de Literatura.', 'Life, work and legacy of Gabriela Mistral. The first Latin American to win the Nobel Prize in Literature.', 2, 24000, ['La maestra, la pedagoga, la mujer que abrió caminos', 'De Lucila Godoy a Gabriela Mistral: poesía, diplomacia y Nobel']),
  'grecia': makeFreeCourse('Grecia: Clase Gratuita', 'Greece: Free Class', 'Una introducción a la historia y cultura de la Grecia antigua. Acceso gratuito.', 'An introduction to the history and culture of ancient Greece. Free access.', 'https://youtu.be/ChFh0hMF0Ws'),
  'roma': makeFreeCourse('Roma: Clase Gratuita', 'Rome: Free Class', 'Una introducción a la historia del Imperio Romano. Acceso gratuito.', 'An introduction to the history of the Roman Empire. Free access.', 'https://youtu.be/z3n-Xiulbq0'),
});

function formatPrice(n) {
  return "$" + n.toLocaleString("es-CL");
}

function validateRut(rut) {
  rut = rut.replace(/\./g, "").replace(/-/g, "").toUpperCase();
  if (rut.length < 2) return false;
  const body = rut.slice(0, -1);
  const dv = rut.slice(-1);
  let sum = 0, mul = 2;
  for (let i = body.length - 1; i >= 0; i--) {
    sum += parseInt(body[i]) * mul;
    mul = mul === 7 ? 2 : mul + 1;
  }
  const expected = 11 - (sum % 11);
  const expectedStr = expected === 11 ? "0" : expected === 10 ? "K" : String(expected);
  return dv === expectedStr;
}

const CourseLandingPage = ({ courseId, setPage, goToCategory, palette, t }) => {
  const P = palette;
  const isMobile = useIsMobile();
  const course = COURSE_DETAIL[courseId];

  const [mode, setMode] = React.useState(null); // 'complete' | 'session'
  const [selectedSessions, setSelectedSessions] = React.useState([]);
  const [form, setForm] = React.useState({ nombre: "", apellido: "", rut: "", email: "", emailConfirm: "" });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  if (!course) return (
    <div style={{ background: P.bg, minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <p style={{ fontFamily: "'Lato', sans-serif", color: P.muted }}>Curso no encontrado.</p>
    </div>
  );

  const titleEs = course.titleEs; const titleEn = course.titleEn;
  const title = t(titleEs, titleEn);
  const subtitle = t(course.subtitleEs, course.subtitleEn);
  const desc = t(course.descEs, course.descEn);
  const isLive = course.type === "live";
  const isFree = course.free === true;
  const total = mode === "complete" ? course.priceComplete : selectedSessions.length * course.priceSession;

  const toggleSession = (i) => {
    setSelectedSessions(prev => prev.includes(i) ? prev.filter(x => x !== i) : [...prev, i]);
  };

  const validate = () => {
    const e = {};
    if (!/^[a-zA-ZÀ-ÿ\s]{2,}$/.test(form.nombre)) e.nombre = t("Solo letras, campo requerido.", "Letters only, field required.");
    if (!/^[a-zA-ZÀ-ÿ\s]{2,}$/.test(form.apellido)) e.apellido = t("Solo letras, campo requerido.", "Letters only, field required.");
    if (!validateRut(form.rut)) e.rut = t("RUT inválido. Formato: 12.345.678-9", "Invalid RUT. Format: 12.345.678-9");
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = t("Ingresa un correo válido.", "Enter a valid email.");
    if (form.email !== form.emailConfirm) e.emailConfirm = t("Los correos no coinciden.", "Emails don't match.");
    if (mode === "session" && selectedSessions.length === 0) e.sessions = t("Selecciona al menos una sesión.", "Select at least one session.");
    if (!mode) e.mode = t("Selecciona una modalidad.", "Select a modality.");
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = () => {
    if (isFree) {
      window.location.href = course.urlCompleto;
      return;
    }
    if (validate()) {
      let url;
      if (mode === 'complete') {
        url = course.urlCompleto || '#';
      } else {
        const count = selectedSessions.length;
        if (course.type === 'recorded') {
          url = GRABADOS_URLS[count] || course.urlSesion || '#';
        } else {
          url = course.urlSesion || '#';
        }
      }
      if (url && url !== '#') {
        fetch('https://n8n.srv1641238.hstgr.cloud/webhook/pre-registro', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: form.email,
            nombre: form.nombre,
            apellido: form.apellido,
            rut: form.rut,
            curso_id: courseId,
            curso_nombre: titleEs,
            tipo: course.type,
            modo: mode,
            sesiones: JSON.stringify(mode === 'session' ? selectedSessions : []),
            monto: total,
            timestamp: new Date().toISOString()
          })
        }).catch(() => {});
        window.location.href = url;
      } else {
        setSubmitted(true);
      }
    }
  };

  const inputStyle = (field) => ({
    width: "100%",
    padding: "11px 14px",
    fontFamily: "'Lato', sans-serif",
    fontSize: 14,
    border: `1px solid ${errors[field] ? "#e85d3a" : P.accent + "44"}`,
    background: "#FFFFFF",
    color: P.text,
    outline: "none",
    marginTop: 6,
  });

  const labelStyle = {
    fontFamily: "'Lato', sans-serif",
    fontSize: 12,
    color: P.muted,
    letterSpacing: "0.05em",
    display: "block",
  };

  const errStyle = {
    fontFamily: "'Lato', sans-serif",
    fontSize: 11,
    color: "#e85d3a",
    marginTop: 4,
  };

  return (
    <div style={{ background: P.bg, color: P.text, minHeight: "100vh", paddingTop: 80 }}>
      {/* Back */}
      <div style={{ maxWidth: 820, margin: "0 auto", padding: "24px 24px 0" }}>
        <button onClick={() => {
          const cat = course.type === "recorded" ? "recorded" : "live";
          if (goToCategory) goToCategory(cat);
          else setPage("cursos");
        }} style={{
          background: "none", border: "none", cursor: "pointer",
          fontFamily: "'Lato', sans-serif", fontSize: 13,
          color: P.muted, letterSpacing: "0.05em",
          display: "flex", alignItems: "center", gap: 6,
          padding: 0,
        }}
          onMouseEnter={e => e.currentTarget.style.color = P.accent}
          onMouseLeave={e => e.currentTarget.style.color = P.muted}
        >
          ← {t("Todos los cursos", "All courses")}
        </button>
      </div>

      <div style={{ maxWidth: 820, margin: "0 auto", padding: isMobile ? "24px 16px 60px" : "32px 24px 80px", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 380px", gap: isMobile ? 32 : 48, alignItems: "start" }}>

        {/* LEFT — Info */}
        <div>
          {/* Tag */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
            <span style={{
              background: isLive ? "#e85d3a22" : P.accent + "22",
              color: isLive ? "#e85d3a" : P.accent,
              fontFamily: "'Lato', sans-serif", fontSize: 10,
              letterSpacing: "0.15em", textTransform: "uppercase",
              padding: "4px 10px",
              display: "flex", alignItems: "center", gap: 6,
            }}>
              {isLive && <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#e85d3a", display: "inline-block" }} />}
              {t(course.tagEs || course.tag, course.tagEn || course.tag)}
            </span>
          </div>

          <h1 style={{
            fontFamily: "'Playfair Display', serif",
            fontSize: "clamp(1.8rem, 4vw, 2.6rem)",
            color: P.textBold, lineHeight: 1.15, marginBottom: 8,
          }}>{title}</h1>
          <p style={{
            fontFamily: "'Playfair Display', serif", fontStyle: "italic",
            fontSize: "1.15rem", color: P.accent, marginBottom: 20,
          }}>{subtitle}</p>
          <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 15, color: P.muted, lineHeight: 1.8, marginBottom: 28 }}>{desc}</p>

          {/* Details chips */}
          {(course.dates || course.time || course.platform) && (
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 32 }}>
              {course.dates && <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.text, background: P.surface, padding: "7px 14px", border: `1px solid ${P.accent}22` }}>📅 {course.dates}</span>}
              {course.time && <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.text, background: P.surface, padding: "7px 14px", border: `1px solid ${P.accent}22` }}>🕖 {course.time}</span>}
              {course.platform && <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.text, background: P.surface, padding: "7px 14px", border: `1px solid ${P.accent}22` }}>💻 {course.platform}</span>}
            </div>
          )}

          {/* Trust badges */}
          <div style={{ display: "flex", gap: 16, flexWrap: "wrap", marginBottom: 40, padding: "16px 0", borderTop: `1px solid ${P.accent}18`, borderBottom: `1px solid ${P.accent}18` }}>
            {[
              { icon: "🔒", text: t("Pago 100% seguro", "100% secure payment") },
              { icon: "📧", text: t("Link/acceso por correo", "Link/access by email") },
              { icon: "⚡", text: t("Inscripción inmediata", "Immediate enrollment") },
            ].map((b, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ fontSize: 16 }}>{b.icon}</span>
                <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 12, color: P.muted }}>{b.text}</span>
              </div>
            ))}
          </div>

          {/* Syllabus */}
          <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.3rem", color: P.textBold, marginBottom: 20 }}>
            {t("Contenido del curso", "Course content")}
          </h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {course.sessions.map((s, i) => {
              const sTitle = t(s.titleEs, s.titleEn);
              const sDate = t(s.dateEs, s.dateEn);
              const sDesc = t(s.descEs, s.descEn);
              return (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "auto 1fr",
                  gap: "0 20px", padding: "16px 0",
                  borderBottom: `1px solid ${P.accent}14`,
                }}>
                  <div style={{
                    width: 32, height: 32, background: P.surface,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontFamily: "'Playfair Display', serif", fontSize: 13,
                    color: P.accent, fontWeight: 700, flexShrink: 0, marginTop: 2,
                  }}>{i + 1}</div>
                  <div>
                    {sDate && <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 11, color: P.accent, letterSpacing: "0.08em", marginBottom: 4 }}>{sDate}</p>}
                    <p style={{ fontFamily: "'Lato', sans-serif", fontWeight: 700, fontSize: 14, color: P.textBold, marginBottom: sDesc ? 4 : 0 }}>{sTitle}</p>
                    {sDesc && <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.muted, lineHeight: 1.6 }}>{sDesc}</p>}
                    {s.youtubeUrl && (
                      <a
                        href={s.youtubeUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          marginTop: 8,
                          fontFamily: "'Lato', sans-serif", fontSize: 12,
                          color: P.accent2, fontWeight: 700, textDecoration: 'none',
                          letterSpacing: '0.05em',
                        }}
                      >
                        ▶ {t('Ver grabación', 'Watch recording')}
                      </a>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Why */}
          <h2 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.3rem", color: P.textBold, marginTop: 36, marginBottom: 16 }}>
            {t("¿Por qué inscribirse?", "Why enroll?")}
          </h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {(t("es", "en") === "en" ? course.whyEn : course.whyEs).map((w, i) => (
              <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <span style={{ color: P.accent, marginTop: 2, flexShrink: 0 }}>✓</span>
                <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 14, color: P.muted, lineHeight: 1.6 }}>{w}</p>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT — Enrollment form */}
        <div style={{ position: isMobile ? "static" : "sticky", top: 88 }}>
          {submitted ? (
            <div style={{ background: P.surface, border: `1px solid ${P.accent}33`, padding: "40px 28px", textAlign: "center" }}>
              <div style={{ fontSize: 40, marginBottom: 16 }}>✅</div>
              <h3 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.4rem", color: P.textBold, marginBottom: 12 }}>
                {t("¡Inscripción recibida!", "Enrollment received!")}
              </h3>
              <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.muted, lineHeight: 1.7, marginBottom: 20 }}>
                {t(`Recibirás un correo en ${form.email} con los detalles de acceso y el link de pago.`, `You'll receive an email at ${form.email} with access details and payment link.`)}
              </p>
              <button onClick={() => {
                const cat = course.type === "recorded" ? "recorded" : "live";
                if (goToCategory) goToCategory(cat);
                else setPage("cursos");
              }} style={{
                background: "transparent", color: P.accent,
                border: `1px solid ${P.accent}`, padding: "10px 24px",
                fontFamily: "'Lato', sans-serif", fontSize: 12,
                letterSpacing: "0.1em", textTransform: "uppercase", cursor: "pointer",
              }}>
                {t("Ver más cursos", "See more courses")}
              </button>
            </div>
          ) : isFree ? (
            <div style={{ background: P.surface, border: `1px solid ${P.accent}22`, padding: "28px 24px", textAlign: "center" }}>
              <h3 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.1rem", color: P.textBold, marginBottom: 14 }}>
                {t("Clase gratuita", "Free class")}
              </h3>
              <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.muted, lineHeight: 1.7, marginBottom: 20 }}>
                {t("Accede directamente a la clase gratuita en YouTube.", "Go directly to the free class on YouTube.")}
              </p>
              <a
                href={course.urlCompleto}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: "inline-block",
                  background: P.accent2, color: "#FFFFFF",
                  border: "none", padding: "14px 24px",
                  fontFamily: "'Lato', sans-serif", fontWeight: 700,
                  fontSize: 13, letterSpacing: "0.1em", textTransform: "uppercase",
                  textDecoration: "none",
                }}
              >
                {t("Ver clase gratis", "Watch free class")}
              </a>
            </div>
          ) : (
            <div style={{ background: P.surface, border: `1px solid ${P.accent}22`, padding: "28px 24px" }}>
              <h3 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.1rem", color: P.textBold, marginBottom: 20 }}>
                {t("Inscríbete ahora", "Enroll now")}
              </h3>

              {/* Step 1 — Personal data */}
              <div style={{ marginBottom: 20 }}>
                <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, letterSpacing: "0.2em", color: P.accent, textTransform: "uppercase", marginBottom: 14 }}>
                  1 · {t("Tus datos", "Your details")}
                </p>
                <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10, marginBottom: 10 }}>
                  <div>
                    <label style={labelStyle}>{t("Nombre *", "First name *")}</label>
                    <input value={form.nombre} onChange={e => setForm(f => ({ ...f, nombre: e.target.value }))} style={inputStyle("nombre")} />
                    {errors.nombre && <p style={errStyle}>{errors.nombre}</p>}
                  </div>
                  <div>
                    <label style={labelStyle}>{t("Apellido *", "Last name *")}</label>
                    <input value={form.apellido} onChange={e => setForm(f => ({ ...f, apellido: e.target.value }))} style={inputStyle("apellido")} />
                    {errors.apellido && <p style={errStyle}>{errors.apellido}</p>}
                  </div>
                </div>
                <div style={{ marginBottom: 10 }}>
                  <label style={labelStyle}>{t("RUT *", "RUT *")}</label>
                  <input
                    value={form.rut}
                    onChange={e => {
                      // Auto-format: digits only + dash before last char
                      let val = e.target.value.replace(/\./g, "").replace(/[^0-9kK-]/g, "");
                      // Ensure only one dash at the right place
                      val = val.replace(/-/g, "");
                      if (val.length > 1) val = val.slice(0, -1) + "-" + val.slice(-1);
                      setForm(f => ({ ...f, rut: val.toUpperCase() }));
                    }}
                    placeholder="12345678-9"
                    maxLength={10}
                    style={{
                      ...inputStyle("rut"),
                      color: form.rut ? P.text : P.muted,
                      letterSpacing: "0.08em",
                    }}
                  />
                  {errors.rut && <p style={errStyle}>{errors.rut}</p>}
                </div>
                <div style={{ marginBottom: 10 }}>
                  <label style={labelStyle}>{t("Correo electrónico *", "Email *")}</label>
                  <input value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} style={inputStyle("email")} />
                  {errors.email && <p style={errStyle}>{errors.email}</p>}
                </div>
                <div>
                  <label style={labelStyle}>{t("Confirmar correo *", "Confirm email *")}</label>
                  <input value={form.emailConfirm} onChange={e => setForm(f => ({ ...f, emailConfirm: e.target.value }))} style={inputStyle("emailConfirm")} />
                  {errors.emailConfirm && <p style={errStyle}>{errors.emailConfirm}</p>}
                </div>
              </div>

              {/* Step 2 — Modality */}
              <div style={{ marginBottom: 20 }}>
                <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, letterSpacing: "0.2em", color: P.accent, textTransform: "uppercase", marginBottom: 14 }}>
                  2 · {t("¿Cómo quieres inscribirte?", "How do you want to enroll?")}
                </p>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 12 }}>
                  {/* Complete */}
                  <button onClick={() => { setMode("complete"); setSelectedSessions([]); }} style={{
                    background: mode === "complete" ? P.accent2 : "transparent",
                    border: `1px solid ${mode === "complete" ? P.accent2 : P.accent + "44"}`,
                    color: mode === "complete" ? "#FFFFFF" : P.text,
                    padding: "12px 10px", cursor: "pointer", textAlign: "center",
                    transition: "all 0.2s",
                  }}>
                    {mode === "complete" && <div style={{ fontFamily: "'Lato', sans-serif", fontSize: 9, letterSpacing: "0.15em", marginBottom: 4, textTransform: "uppercase", opacity: 0.8 }}>✦ {t("Mejor valor","Best value")}</div>}
                    <div style={{ fontFamily: "'Lato', sans-serif", fontWeight: 700, fontSize: 13 }}>{t("Curso completo","Full course")}</div>
                    <div style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.1rem", fontWeight: 700, marginTop: 4 }}>{formatPrice(course.priceComplete)}</div>
                    <div style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, opacity: 0.7, marginTop: 2 }}>{t(`Las ${course.sessions.length} sesiones`, `All ${course.sessions.length} sessions`)}</div>
                  </button>
                  {/* Per session */}
                  {course.sessions.length > 1 && (
                    <button onClick={() => setMode("session")} style={{
                      background: mode === "session" ? P.accent2 : "transparent",
                      border: `1px solid ${mode === "session" ? P.accent2 : P.accent + "44"}`,
                      color: mode === "session" ? "#FFFFFF" : P.text,
                      padding: "12px 10px", cursor: "pointer", textAlign: "center",
                      transition: "all 0.2s",
                    }}>
                      <div style={{ fontFamily: "'Lato', sans-serif", fontWeight: 700, fontSize: 13 }}>{t("Por sesión","Per session")}</div>
                      <div style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.1rem", fontWeight: 700, marginTop: 4 }}>{formatPrice(course.priceSession)}</div>
                      <div style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, opacity: 0.7, marginTop: 2 }}>{t("Elige las que quieras","Choose the ones you want")}</div>
                    </button>
                  )}
                </div>
                {errors.mode && <p style={errStyle}>{errors.mode}</p>}

                {/* Session selector */}
                {mode === "session" && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
                    {course.sessions.map((s, i) => {
                      const sel = selectedSessions.includes(i);
                      return (
                        <button key={i} onClick={() => toggleSession(i)} style={{
                          display: "flex", justifyContent: "space-between", alignItems: "center",
                          padding: "10px 12px",
                          border: `1px solid ${sel ? P.accent2 : P.accent + "33"}`,
                          background: sel ? P.accent2 + "18" : "transparent",
                          cursor: "pointer", textAlign: "left",
                          transition: "all 0.15s",
                        }}>
                          <div>
                            <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 12, color: P.textBold, fontWeight: sel ? 700 : 400 }}>
                              {t(s.titleEs, s.titleEn)}
                            </p>
                            {s.dateEs && <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, color: P.muted, marginTop: 2 }}>{t(s.dateEs, s.dateEn)}</p>}
                          </div>
                          <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 12, color: P.accent, flexShrink: 0, marginLeft: 8 }}>{formatPrice(course.priceSession)}</span>
                        </button>
                      );
                    })}
                    {errors.sessions && <p style={errStyle}>{errors.sessions}</p>}
                  </div>
                )}
              </div>

              {/* Summary */}
              {mode && (
                <div style={{ background: "#FFFFFF", border: `1px solid ${P.accent}33`, padding: "14px 16px", marginBottom: 16 }}>
                  <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 11, color: P.muted, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 8 }}>
                    {t("Resumen", "Summary")}
                  </p>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.text }}>
                      {mode === "complete" ? t("Curso completo", "Full course") : `${selectedSessions.length} ${t("sesión(es)", "session(s)")}`}
                    </span>
                    <span style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.2rem", color: P.accent, fontWeight: 700 }}>
                      {total > 0 ? formatPrice(total) : "—"}
                    </span>
                  </div>
                </div>
              )}

              {/* Submit */}
              <button onClick={handleSubmit} style={{
                width: "100%", background: P.accent2, color: "#FFFFFF",
                border: "none", padding: "14px",
                fontFamily: "'Lato', sans-serif", fontWeight: 700,
                fontSize: 13, letterSpacing: "0.1em", textTransform: "uppercase",
                cursor: "pointer", transition: "opacity 0.2s",
              }}
                onMouseEnter={e => e.target.style.opacity = "0.85"}
                onMouseLeave={e => e.target.style.opacity = "1"}
              >
                {t("Ir al pago →", "Proceed to payment →")}
              </button>
              <div style={{
                marginTop: 24, padding: "18px 20px",
                background: P.accent + "12",
                border: `1px solid ${P.accent}33`,
                borderRadius: 2,
                textAlign: "center",
              }}>
                <p style={{
                  fontFamily: "'Lato', sans-serif", fontSize: 13,
                  color: P.text, lineHeight: 1.75, marginBottom: 10,
                }}>
                  {t(
                    "Accede de forma ilimitada a todos los cursos y participa en foros y tertulias en vivo junto a una comunidad curiosa y apasionada por aprender",
                    "Get unlimited permanent access to all courses and join live forums and discussions with a curious community — subscribe here:"
                  )}
                </p>
                <a
                  href="https://www.skool.com/historiaconpilarducci"
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    display: "inline-block",
                    background: P.accent2, color: "#fff",
                    padding: "9px 20px",
                    fontFamily: "'Lato', sans-serif", fontSize: 11,
                    letterSpacing: "0.1em", textTransform: "uppercase",
                    fontWeight: 700, textDecoration: "none",
                  }}
                >
                  {t("Suscribirse a la comunidad", "Join the community")}
                </a>
              </div>
              <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 10, color: P.muted, textAlign: "center", marginTop: 10 }}>
                🔒 {t("Pago seguro · SSL cifrado · Mercado Pago", "Secure payment · SSL encrypted · Mercado Pago")}
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { CourseLandingPage, COURSE_DETAIL });
