// CoursesPage.jsx
const CoursesPage = ({ palette, t, goToCourse, activeCategory: initialCategory, goToCategory }) => {
  const P = palette;
  const [activeCategory, setActiveCategory] = React.useState(initialCategory || null);
  const today = new Date();
  today.setHours(23, 59, 59, 0);

  const courses = [
    { id:"humanidad", title: t("Humanidad en transformación","Humanity in Transformation"), type:"live", endDate:"2026-04-29", desc: t("Del cazador a la Revolución Industrial. Tres sesiones para comprender los grandes cambios de la humanidad.","From hunter-gatherer to the Industrial Revolution. Three sessions to understand humanity's great changes."), sessions:"3", price:"$36.000", next: t("Zoom en vivo","Live on Zoom"), discount2025:true, image:"/assets/humanidad.webp" },
    { id:"trincheras", title: t("De los Imperios a las Trincheras","From Empires to Trenches"), type:"live", endDate:"2026-06-24", desc: t("Un recorrido por los nacionalismos e imperialismos que transformaron Europa y condujeron a la Primera Guerra Mundial.","A journey through the nationalisms and imperialisms that transformed Europe and led to World War I."), sessions:"3", price:"$45.000", next: t("Miércoles 10, 17 y 24 de junio · 19:00 hrs","Wednesdays June 10, 17 & 24 · 7pm"), image:"/assets/trincheras.webp" },
    { id:"aquiles", title: t("Aquiles y Odiseo – El Mundo detrás de Troya","Achilles & Odysseus – The World Behind Troy"), type:"live", endDate:"2026-08-15", desc: t("La Guerra de Troya, sus héroes y el mundo antiguo que la hizo posible.","The Trojan War, its heroes and the ancient world that made it possible."), sessions:"2", price:"$30.000", next: t("Miércoles 8 y 15 de agosto · 19:00 hrs","Wednesdays August 8 & 15 · 7pm"), image:"/assets/aquiles.webp" },
    { id:"vikingos", title: t("La Ruta de los Vikingos","The Viking Route"), type:"live", endDate:"2026-08-12", desc: t("Rutas, cultura, mitología y legado vikingo en la historia europea.","Routes, culture, mythology and Viking legacy in European history."), sessions:"1", price:"$15.000", next: t("12 de agosto · 19:00 hrs","August 12 · 7pm"), image:"/assets/vikingos.webp" },
    { id:"damnatio", title: t("Damnatio Memoriae","Damnatio Memoriae"), type:"recorded", desc: t("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."), sessions:"3", price:"$36.000", discount2025:true, image:"https://img.youtube.com/vi/KdahzuYRHWw/hqdefault.jpg" },
    { id:"mujeres", title: t("Sobre Mujeres y Otras Monstruosidades","On Women and Other Monstrosities"), type:"recorded", desc: t("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'."), sessions:"4", price:"$48.000", discount2025:true, image:"https://img.youtube.com/vi/CSFybQuDbNM/hqdefault.jpg" },
    { id:"migraciones", title: t("Fuera del Edén — Migraciones Humanas","Out of Eden — Human Migrations"), type:"recorded", desc: t("Historia de las grandes migraciones humanas desde la prehistoria hasta el presente.","History of great human migrations from prehistory to the present."), sessions:"4", price:"$48.000", discount2025:true, image:"https://img.youtube.com/vi/0JC8ekV8lpI/hqdefault.jpg" },
    { id:"troya-roma", title: t("De Troya a Roma","From Troy to Rome"), type:"recorded", desc: t("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."), sessions:"4", price:"$48.000", discount2025:true, image:"https://img.youtube.com/vi/ZWIM1kjUnJU/hqdefault.jpg" },
    { id:"civilizacion", title: t("La Cuna de la Civilización","The Cradle of Civilization"), type:"recorded", desc: t("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."), sessions:"4", price:"$48.000", discount2025:true, image:"https://img.youtube.com/vi/Qg2ih0zY0iQ/hqdefault.jpg" },
    { id:"catacumbas", title: t("De las Catacumbas a la Modernidad","From the Catacombs to Modernity"), type:"recorded", desc: t("Historia del Cristianismo desde sus orígenes perseguidos hasta su dominio global.","History of Christianity from its persecuted origins to global dominance."), sessions:"3", price:"$36.000", discount2025:true, image:"https://img.youtube.com/vi/PoEBX_gYXm8/hqdefault.jpg" },
    { id:"evolucion", title: t("Historia de la Evolución de la Humanidad","History of Human Evolution"), type:"recorded", desc: t("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."), sessions:"3", price:"$36.000", discount2025:true, image:"https://img.youtube.com/vi/kEQiQ7LERp4/hqdefault.jpg" },
    { id:"iran", title: t("Irán: Poder, Colonialismo, Revolución y Religión","Iran: Power, Colonialism, Revolution and Religion"), type:"recorded", desc: t("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."), sessions:"1", price:"$12.000", discount2025:true, image:"https://img.youtube.com/vi/CNLWpEjLHrk/hqdefault.jpg" },
    { id:"corses", title: t("Corsés, tacones y Revolución","Corsets, Heels and Revolution"), type:"recorded", desc: t("Moda, género y poder a través de la historia. Cómo la ropa refleja los cambios sociales y políticos.","Fashion, gender and power through history. How clothing reflects social and political changes."), sessions:"1", price:"$12.000", discount2025:true, image:"https://img.youtube.com/vi/YaByuh74GFo/hqdefault.jpg" },
    { id:"chiloe", title: t("Historia de la Anexión de Chiloé","History of the Annexation of Chiloé"), type:"recorded", desc: t("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."), sessions:"2", price:"$24.000", discount2025:true, image:"https://img.youtube.com/vi/fiFHFwOimcw/hqdefault.jpg" },
    { id:"chile-mestizo", title: t("Chile Mestizo","Mestizo Chile"), type:"recorded", desc: t("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."), sessions:"1", price:"$12.000", discount2025:true, image:"https://img.youtube.com/vi/XxMOZQgH8qc/hqdefault.jpg" },
    { id:"independencia", title: t("Del Rey al Pueblo — Independencia de Chile","From King to People — Chilean Independence"), type:"recorded", desc: t("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."), sessions:"1", price:"$12.000", discount2025:true, image:"https://img.youtube.com/vi/uhhuE0288bs/hqdefault.jpg" },
    { id:"risas-rebeldias", title: t("Entre Risas y Rebeldías","Between Laughter and Rebellion"), type:"recorded", desc: t("Historia de la sociabilidad popular en Chile. Fiestas, protestas y resistencia cultural.","History of popular sociability in Chile. Festivals, protests and cultural resistance."), sessions:"4", price:"$48.000", discount2025:true, image:"https://img.youtube.com/vi/h7ezkhTW4Pw/hqdefault.jpg" },
    { id:"mistral", title: t("A 80 años del Nobel de Gabriela Mistral","80 Years of Gabriela Mistral's Nobel"), type:"recorded", desc: t("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."), sessions:"2", price:"$24.000", discount2025:true, image:"https://img.youtube.com/vi/Xc3XAgcyNJ4/hqdefault.jpg" },
    { id:"grecia", title: t("Grecia: Clase Gratuita","Greece: Free Class"), type:"recorded", desc: t("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."), sessions:"1", price: t("Gratis","Free"), free:true, image:"https://img.youtube.com/vi/ChFh0hMF0Ws/hqdefault.jpg" },
    { id:"roma", title: t("Roma: Clase Gratuita","Rome: Free Class"), type:"recorded", desc: t("Una introducción a la historia del Imperio Romano. Acceso gratuito.","An introduction to the history of the Roman Empire. Free access."), sessions:"1", price: t("Gratis","Free"), free:true, image:"https://img.youtube.com/vi/z3n-Xiulbq0/hqdefault.jpg" },
  ];

  const getEffectiveType = (c) => {
    if (c.type === "live" && c.endDate && new Date(c.endDate) < today) return "recorded";
    return c.type;
  };

  const renderCourseCard = (c, i) => {
    const isLive = getEffectiveType(c) === "live";
    const badgeColor = isLive ? "#555555" : P.accent;
    const liveBg = isLive ? "#E8E8E8" : P.accent + "22";
    return (
      <div key={i} style={{
        background: P.surface, border: `1px solid ${P.accent}22`,
        padding: "28px 28px 24px", transition: "border-color 0.2s, transform 0.2s",
      }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = P.accent + "66"; e.currentTarget.style.transform = "translateY(-2px)" }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = P.accent + "22"; e.currentTarget.style.transform = "translateY(0)" }}
      >
        {c.image && (
          <div style={{ margin: "-28px -28px 16px -28px", height: 180, overflow: "hidden" }}>
            <img src={c.image} alt={c.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          </div>
        )}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <span style={{
            background: liveBg, color: badgeColor,
            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" }} />}
            {isLive ? t("En Vivo","Live") : t("Grabado","Recorded")}
          </span>
          <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 11, color: P.muted }}>{c.sessions} {t("clases","lessons")}</span>
        </div>
        <h3 style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.15rem", color: P.textBold, lineHeight: 1.4, marginBottom: 12 }}>{c.title}</h3>
        {c.discount2025 && (
          <span style={{
            display: "inline-block", background: P.accent + "22", color: P.accent2,
            fontFamily: "'Lato', sans-serif", fontSize: 10, letterSpacing: "0.12em",
            textTransform: "uppercase", padding: "4px 9px", marginBottom: 12,
          }}>
            {t("20% DTO. EN GRABADOS", "20% OFF RECORDED COURSES")}
          </span>
        )}
        <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 13, color: P.muted, lineHeight: 1.7, marginBottom: 16 }}>{c.desc}</p>
        {c.next && isLive && (
          <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 11, color: P.accent, marginBottom: 16, opacity: 0.8 }}>📅 {c.next}</p>
        )}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: `1px solid ${P.accent}18`, paddingTop: 16 }}>
          <div>
            <span style={{ fontFamily: "'Playfair Display', serif", fontSize: "1.3rem", color: P.accent, fontWeight: 700 }}>{c.price}</span>
          </div>
          {c.free ? (
            <button onClick={() => goToCourse && goToCourse(c.id, getEffectiveType(c))} style={{
              background: "transparent", color: P.accent, border: `1px solid ${P.accent}`,
              padding: "9px 20px", fontFamily: "'Lato', sans-serif",
              fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", cursor: "pointer",
              fontWeight: 700, transition: "background 0.2s",
            }}
              onMouseEnter={e => e.target.style.background = P.accent + "18"}
              onMouseLeave={e => e.target.style.background = "transparent"}
            >
              {t("Ver Clase","Watch Class")}
            </button>
          ) : (
            <button onClick={() => goToCourse && goToCourse(c.id, getEffectiveType(c))} style={{
              background: P.accent2, color: "#FFFFFF", border: "none",
              padding: "9px 20px", fontFamily: "'Lato', sans-serif",
              fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", cursor: "pointer",
              fontWeight: 700, transition: "opacity 0.2s",
            }}
              onMouseEnter={e => e.target.style.opacity = "0.85"}
              onMouseLeave={e => e.target.style.opacity = "1"}
            >
              {t("Inscribirse","Enroll")}
            </button>
          )}
        </div>
      </div>
    );
  };

  const categoryCards = [
    {
      id: "live",
      image: "/assets/envivo-banner.webp",
      title: t("Cursos En Vivo", "Live Courses"),
      desc: t("Clases por Zoom en fechas programadas para aprender en comunidad y participar en directo.", "Scheduled Zoom classes to learn in community and participate live."),
      count: courses.filter(c => getEffectiveType(c) === "live").length,
    },
    {
      id: "recorded",
      image: "/assets/grabados-banner.webp",
      title: t("Cursos Grabados", "Recorded Courses"),
      desc: t("Accede a clases grabadas a tu ritmo, con contenidos de historia universal y de Chile.", "Access recorded classes at your own pace, with world and Chilean history content."),
      count: courses.filter(c => getEffectiveType(c) === "recorded").length,
    },
  ];

  return (
    <div style={{ background: P.bg, color: P.text, minHeight: "100vh", paddingTop: 80 }}>
      {/* Header */}
      <div style={{ background: P.surface, padding: "64px 40px 48px", textAlign: "center" }}>
        <p style={{ fontFamily: "'Lato', sans-serif", letterSpacing: "0.2em", fontSize: 11, color: P.accent, textTransform: "uppercase", marginBottom: 12 }}>
          {t("Aprende con Pilar", "Learn with Pilar")}
        </p>
        <h1 style={{ fontFamily: "'Playfair Display', serif", fontSize: "clamp(2rem, 5vw, 3.5rem)", color: P.textBold, marginBottom: 16 }}>
          {t("Cursos de Historia", "History Courses")}
        </h1>
        <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 16, color: P.muted, maxWidth: 520, margin: "0 auto" }}>
          {t("Cursos en vivo y grabados sobre historia universal, Chile, circo, ciencia y mucho más.", "Live and recorded courses on world history, Chile, circus, science and much more.")}
        </p>
      </div>

      <section style={{ padding: "48px 40px 64px", maxWidth: 1200, margin: "0 auto" }}>
        {activeCategory === null ? (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 28 }}>
            {categoryCards.map(category => (
              <button key={category.id} onClick={() => { setActiveCategory(category.id); goToCategory && goToCategory(category.id); }} style={{
                position: "relative", minHeight: 360, overflow: "hidden", border: `1px solid ${P.accent}22`,
                background: P.surface, cursor: "pointer", padding: 0, textAlign: "left",
                transition: "transform 0.2s, border-color 0.2s, box-shadow 0.2s",
              }}
                onMouseEnter={e => {
                  e.currentTarget.style.transform = "translateY(-4px)";
                  e.currentTarget.style.borderColor = P.accent + "66";
                  e.currentTarget.style.boxShadow = "0 18px 40px rgba(0,0,0,0.12)";
                  const img = e.currentTarget.querySelector("img");
                  if (img) img.style.transform = "scale(1.04)";
                }}
                onMouseLeave={e => {
                  e.currentTarget.style.transform = "translateY(0)";
                  e.currentTarget.style.borderColor = P.accent + "22";
                  e.currentTarget.style.boxShadow = "none";
                  const img = e.currentTarget.querySelector("img");
                  if (img) img.style.transform = "scale(1)";
                }}
              >
                <div style={{ position: "relative", height: 220, overflow: "hidden" }}>
                  <img src={category.image} alt={category.title} style={{
                    width: "100%", height: "100%", objectFit: "cover",
                    transition: "transform 0.35s",
                  }} />
                  <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.42)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
                    <h2 style={{ color: "#fff", fontFamily: "'Playfair Display', serif", fontSize: "clamp(1.8rem, 4vw, 2.5rem)", margin: 0, textShadow: "0 2px 8px rgba(0,0,0,0.4)", textAlign: "center" }}>
                      {category.title}
                    </h2>
                  </div>
                </div>
                <div style={{ padding: "24px 26px 26px" }}>
                  <p style={{ fontFamily: "'Lato', sans-serif", fontSize: 14, color: P.muted, lineHeight: 1.8, marginBottom: 18 }}>
                    {category.desc}
                  </p>
                  <span style={{ fontFamily: "'Lato', sans-serif", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: P.accent, fontWeight: 700 }}>
                    {category.count} {t("cursos", "courses")}
                  </span>
                </div>
              </button>
            ))}
          </div>
        ) : (
          <div>
            <button onClick={() => { setActiveCategory(null); if (goToCategory) window.history.pushState({}, "", "/cursos"); }} style={{
              background: "transparent", color: P.accent, border: `1px solid ${P.accent}`,
              padding: "10px 18px", fontFamily: "'Lato', sans-serif",
              fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", cursor: "pointer",
              fontWeight: 700, marginBottom: 28,
            }}>
              {t("Volver a categorias", "Back to categories")}
            </button>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 24 }}>
              {courses.filter(c => getEffectiveType(c) === activeCategory).map(renderCourseCard)}
            </div>
          </div>
        )}
      </section>
    </div>
  );
};

Object.assign(window, { CoursesPage });
