/* global React, Icon, Eyebrow, Flourish, Button, Section, Reveal, Avatar, Tag, Stars, CourseThumb, CourseCard, courseById, expertById, COURSES */
const { useState: useDetailState } = React;

const LEARN = [
  "Construir un proceso de venta consultiva paso a paso",
  "Calificar prospectos antes de invertir tu tiempo",
  "Técnicas de cierre sin presión emocional",
  "Manejar objeciones como una conversación, no una batalla",
  "Diseñar un follow-up que no se siente acoso",
  "Fidelizar para que el cliente vuelva y te recomiende",
];

const MODULES = [
  { t: "El mindset del vendedor moderno", lessons: 3, min: 28, items: ["Por qué la venta agresiva ya no funciona", "Vender desde el valor, no desde la necesidad", "Tu primera reprogramación mental"] },
  { t: "Prospección inteligente", lessons: 4, min: 35, items: ["Dónde está realmente tu cliente ideal", "Calificación en 2 minutos", "El primer mensaje que sí abre puertas", "Construir tu pipeline sin quemarte"] },
  { t: "La conversación de ventas", lessons: 4, min: 32, items: ["Preguntas que venden solas", "Escucha activa aplicada", "Presentar precio sin miedo", "Leer señales de compra"] },
  { t: "Técnicas de cierre sin presión", lessons: 3, min: 25, items: ["El cierre consultivo", "Manejo de objeciones reales", "Cuándo (y cómo) retirarte"] },
  { t: "Seguimiento y fidelización", lessons: 2, min: 20, items: ["El follow-up que no incomoda", "Convertir clientes en referidores"] },
];

const REVIEWS = [
  { name: "Mauricio T.", date: "Hace 2 semanas", hue: 28, r: 5, q: "Apliqué la técnica de calificación el mismo día y dejé de perder tiempo con prospectos que nunca iban a comprar. Oro puro." },
  { name: "Gabriela S.", date: "Hace 1 mes", hue: 160, r: 5, q: "Por fin entiendo cómo vender sin sentir que estoy persiguiendo a la gente. Antonio explica con ejemplos reales, no teoría." },
  { name: "Esteban V.", date: "Hace 1 mes", hue: 268, r: 4, q: "El módulo de cierre cambió mi forma de cerrar reuniones. Subí mi tasa de cierre notablemente en pocas semanas." },
  { name: "Paola R.", date: "Hace 2 meses", hue: 130, r: 5, q: "Conciso y aplicable. Nada de relleno. Lo recomiendo a cualquiera que venda servicios de alto valor." },
];

function AccordionItem({ m, index, open, onToggle }) {
  return (
    <div style={{ borderBottom: "1px solid var(--mp-border)" }}>
      <button onClick={onToggle} style={{
        width: "100%", display: "flex", alignItems: "center", gap: 16, padding: "20px 4px", cursor: "pointer",
        background: "transparent", border: 0, fontFamily: "var(--mp-font-sans)", textAlign: "left",
      }}>
        <span style={{ fontSize: 13, fontWeight: 800, color: "var(--mp-mint-deep)", flex: "0 0 auto", width: 28 }}>{String(index + 1).padStart(2, "0")}</span>
        <span style={{ flex: 1, fontWeight: 700, fontSize: 17, color: "var(--mp-ink)", letterSpacing: "-0.01em" }}>Módulo {index + 1}: {m.t}</span>
        <span style={{ fontSize: 12.5, color: "var(--mp-fg-subtle)", fontWeight: 600, whiteSpace: "nowrap" }} className="mp-acc-meta">{m.lessons} lecciones · {m.min}min</span>
        <span style={{ width: 30, height: 30, borderRadius: 999, background: open ? "var(--mp-ink)" : "var(--mp-cloud)", color: open ? "var(--mp-paper)" : "var(--mp-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto", transition: "all 200ms var(--mp-ease)" }}>
          <Icon name={open ? "minus" : "plus"} size={16} />
        </span>
      </button>
      <div className="mp-acc-body" style={{ maxHeight: open ? m.items.length * 48 + 16 : 0, opacity: open ? 1 : 0 }}>
        <div style={{ padding: "0 4px 20px 48px", display: "flex", flexDirection: "column", gap: 2 }}>
          {m.items.map((it) => (
            <div key={it} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", fontSize: 14.5, color: "var(--mp-fg-muted)" }}>
              <Icon name="playCircle" size={18} style={{ color: "var(--mp-mint-deep)", flex: "0 0 auto" }} /> {it}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CourseDetail({ go }) {
  const course = courseById("ventas-sin-presion");
  const instr = expertById(course.instructors[0]);
  const [open, setOpen] = useDetailState(0);
  const [enrolled, setEnrolled] = useDetailState(false);
  const [preview, setPreview] = useDetailState(false);
  const totalLessons = MODULES.reduce((a, m) => a + m.lessons, 0);

  const includes = [
    ["layers", "5 módulos · 16 lecciones"], ["clock", "2.5h de contenido"], ["award", "Certificado digital"],
    ["infinity", "Acceso de por vida"], ["download", "Recursos descargables"], ["shield", "Garantía de 7 días"],
  ];

  return (
    <main>
      {/* Hero */}
      <section style={{ background: "var(--mp-ink)", color: "var(--mp-paper)", padding: "140px 28px 80px", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: "-20%", left: "20%", width: 480, height: 480, borderRadius: 999, background: "radial-gradient(circle, rgba(70,87,101,0.5), transparent 64%)", filter: "blur(28px)" }} />
        <div style={{ maxWidth: 1240, margin: "0 auto", position: "relative", display: "grid", gridTemplateColumns: "1.5fr 0.9fr", gap: 44, alignItems: "start" }} className="mp-detail-grid">
          <Reveal>
            <button onClick={() => go("cursos")} style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "transparent", border: 0, color: "rgba(255,255,255,0.6)", fontFamily: "var(--mp-font-sans)", fontSize: 13.5, fontWeight: 600, cursor: "pointer", marginBottom: 26 }}>
              <Icon name="chevronRight" size={15} style={{ transform: "rotate(180deg)" }} /> Volver a cursos
            </button>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 20 }}>
              {course.instructors.length ? ["Ventas", "Estrategia", "CRM"].map((t) => <Tag key={t} dark>{t}</Tag>) : null}
            </div>
            <h1 style={{ fontSize: "clamp(34px, 4.4vw, 60px)", fontWeight: 800, lineHeight: 1.04, letterSpacing: "-0.03em", margin: "0 0 18px", textWrap: "balance" }}>
              Ventas sin presión: cierra más sin <span style={{ fontStyle: "italic", color: "var(--mp-mint)" }}>perseguir clientes.</span>
            </h1>
            <p style={{ fontSize: 19, lineHeight: 1.55, color: "rgba(255,255,255,0.76)", maxWidth: 600, margin: "0 0 28px", textWrap: "pretty" }}>
              El sistema de venta consultiva para cerrar más, con menos fricción y sin sentir que persigues a nadie.
            </p>
            <div style={{ display: "flex", alignItems: "center", gap: 24, flexWrap: "wrap", marginBottom: 26 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <Avatar initials={instr.initials} hue={instr.hue} size={48} ring />
                <div>
                  <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)" }}>Tu instructor</div>
                  <div style={{ fontWeight: 700, fontSize: 15.5 }}>{instr.name}</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Stars value={4.8} size={16} /><span style={{ fontWeight: 700 }}>4.8</span>
                <span style={{ color: "rgba(255,255,255,0.55)", fontSize: 13.5 }}>· 234 estudiantes</span>
              </div>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 18, fontSize: 13.5, color: "rgba(255,255,255,0.7)" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name="globe" size={16} /> Español</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name="award" size={16} /> Certificado</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name="clock" size={16} /> Actualizado may 2026</span>
            </div>
          </Reveal>

          {/* Sticky purchase card */}
          <Reveal delay={120}>
            <aside style={{ position: "sticky", top: 112, background: "var(--mp-paper)", color: "var(--mp-ink)", borderRadius: "var(--mp-radius-xl)", padding: 20, boxShadow: "var(--mp-shadow-lg)" }}>
              <div style={{ position: "relative" }}>
                <CourseThumb course={course} height={180} big />
                <button type="button" onClick={() => setPreview(true)} aria-label="Ver vista previa"
                  style={{ position: "absolute", inset: 0, margin: "auto", width: 62, height: 62, borderRadius: 999, background: "var(--mp-mint)", color: "var(--mp-ink)", border: 0, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 24px rgba(129,241,200,0.4)" }}>
                  <Icon name="play" size={24} style={{ marginLeft: 3, fill: "var(--mp-ink)" }} />
                </button>
              </div>
              {enrolled ? (
                <div style={{ padding: "24px 8px 8px", textAlign: "center" }}>
                  <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--mp-mint)", color: "var(--mp-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
                    <Icon name="check" size={26} stroke={2.6} />
                  </div>
                  <h3 style={{ fontSize: 20, fontWeight: 800, letterSpacing: "-0.02em", margin: "0 0 8px" }}>¡Ya tienes acceso!</h3>
                  <p style={{ fontSize: 14, color: "var(--mp-fg-muted)", lineHeight: 1.55, margin: "0 0 16px", textWrap: "pretty" }}>
                    Gracias por inscribirte. Te enviamos un correo con tus datos de acceso; puedes empezar el curso cuando quieras.
                  </p>
                  <Button variant="ink" full icon="arrowRight" onClick={() => go("cursos")}>Ver más cursos</Button>
                </div>
              ) : (
                <div style={{ padding: "20px 8px 6px" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 18 }}>
                    <span style={{ fontSize: 38, fontWeight: 800, color: "var(--mp-mint-deep)", letterSpacing: "-0.02em" }}>${course.price}</span>
                    <span style={{ fontSize: 16, color: "var(--mp-fg-subtle)", textDecoration: "line-through" }}>$189</span>
                    <span style={{ marginLeft: "auto", fontSize: 11, fontWeight: 800, color: "var(--mp-ink)", background: "var(--mp-mint)", padding: "4px 10px", borderRadius: 999 }}>-33%</span>
                  </div>
                  <Button variant="ink" full size="lg" icon="arrowRight" onClick={() => { setEnrolled(true); window.scrollTo({ top: 0, behavior: "smooth" }); }}>Aprende ahora</Button>
                  <button type="button" onClick={() => setPreview(true)} style={{ width: "100%", background: "transparent", border: 0, color: "var(--mp-ink)", fontFamily: "var(--mp-font-sans)", fontWeight: 700, fontSize: 14, cursor: "pointer", padding: "14px 0 4px" }}>Vista previa gratis →</button>
                  {preview && (
                    <div style={{ textAlign: "center", fontSize: 12.5, color: "var(--mp-fg-subtle)", padding: "2px 0 4px" }}>
                      La vista previa estará disponible muy pronto.
                    </div>
                  )}
                  <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 2 }}>
                    {includes.map(([ic, tx]) => (
                      <div key={tx} style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 0", fontSize: 14, color: "var(--mp-fg)" }}>
                        <span style={{ color: "var(--mp-mint-deep)" }}><Icon name={ic} size={17} /></span> {tx}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </aside>
          </Reveal>
        </div>
      </section>

      {/* What you'll learn */}
      <Section bg="paper" pad="84px 28px">
        <div style={{ maxWidth: 880 }}>
          <Reveal style={{ marginBottom: 32 }}>
            <Eyebrow style={{ marginBottom: 16 }}>Lo que vas a lograr</Eyebrow>
            <h2 style={{ fontSize: "clamp(28px, 3.2vw, 42px)", fontWeight: 700, letterSpacing: "-0.03em", margin: 0, lineHeight: 1.1, textWrap: "balance" }}>
              Al terminar, sabrás <span style={{ fontStyle: "italic", color: "var(--mp-mint-deep)" }}>hacer esto.</span>
            </h2>
          </Reveal>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px 32px" }} className="mp-2col">
            {LEARN.map((l, i) => (
              <Reveal key={l} delay={(i % 2) * 60} style={{ display: "flex", gap: 13, alignItems: "flex-start" }}>
                <span style={{ width: 26, height: 26, borderRadius: 999, background: "var(--mp-mint-soft)", color: "var(--mp-mint-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto", marginTop: 2 }}>
                  <Icon name="check" size={15} stroke={2.6} />
                </span>
                <span style={{ fontSize: 16, lineHeight: 1.5, color: "var(--mp-ink)" }}>{l}</span>
              </Reveal>
            ))}
          </div>
        </div>
      </Section>

      {/* Course content accordion */}
      <Section bg="cloud" pad="84px 28px">
        <div style={{ maxWidth: 880 }}>
          <Reveal style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 28, flexWrap: "wrap" }}>
            <div>
              <Eyebrow style={{ marginBottom: 16 }}>Contenido del curso</Eyebrow>
              <h2 style={{ fontSize: "clamp(28px, 3.2vw, 42px)", fontWeight: 700, letterSpacing: "-0.03em", margin: 0, lineHeight: 1.1 }}>5 módulos para dominarlo.</h2>
            </div>
            <span style={{ fontSize: 13.5, color: "var(--mp-fg-muted)", fontWeight: 600 }}>{MODULES.length} módulos · {totalLessons} lecciones · 2.5h</span>
          </Reveal>
          <Reveal style={{ background: "var(--mp-paper)", borderRadius: "var(--mp-radius-lg)", padding: "8px 24px", border: "1px solid var(--mp-border)", boxShadow: "var(--mp-shadow-sm)" }}>
            {MODULES.map((m, i) => (
              <AccordionItem key={i} m={m} index={i} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} />
            ))}
          </Reveal>
        </div>
      </Section>

      {/* Instructor */}
      <Section bg="ink" pad="84px 28px">
        <Reveal style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 32, alignItems: "center", maxWidth: 960 }} className="mp-2col">
          <Avatar initials={instr.initials} hue={instr.hue} size={150} ring />
          <div>
            <Eyebrow onDark style={{ marginBottom: 14 }}>Tu instructor</Eyebrow>
            <h3 style={{ fontSize: "clamp(26px, 3vw, 38px)", fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 6px" }}>{instr.name}</h3>
            <div style={{ fontSize: 15, color: "var(--mp-mint)", fontWeight: 600, marginBottom: 16 }}>{instr.role}</div>
            <p style={{ fontSize: 16.5, lineHeight: 1.6, color: "rgba(255,255,255,0.78)", margin: "0 0 20px", maxWidth: 620, textWrap: "pretty" }}>
              {instr.bio} Ha entrenado equipos comerciales en banca, inmobiliaria y servicios profesionales por toda Centroamérica.
            </p>
            <div style={{ display: "flex", gap: 28, flexWrap: "wrap" }}>
              {[["4.8", "Valoración"], ["234", "Estudiantes"], ["3", "Cursos"]].map(([k, v]) => (
                <div key={v}><div style={{ fontSize: 26, fontWeight: 800, color: "var(--mp-mint)", letterSpacing: "-0.02em" }}>{k}</div><div style={{ fontSize: 12.5, color: "rgba(255,255,255,0.55)" }}>{v}</div></div>
              ))}
            </div>
          </div>
        </Reveal>
      </Section>

      {/* Reviews */}
      <Section bg="paper" pad="84px 28px">
        <Reveal style={{ marginBottom: 36 }}>
          <Eyebrow style={{ marginBottom: 16 }}>Reseñas</Eyebrow>
          <h2 style={{ fontSize: "clamp(28px, 3.2vw, 42px)", fontWeight: 700, letterSpacing: "-0.03em", margin: 0, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            4.8 de 5 <Stars value={5} size={22} /> <span style={{ fontSize: 16, fontWeight: 500, color: "var(--mp-fg-muted)" }}>· 234 valoraciones</span>
          </h2>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }} className="mp-2col">
          {REVIEWS.map((rv, i) => (
            <Reveal key={rv.name} delay={(i % 2) * 70}>
              <article style={{ background: "var(--mp-cloud)", borderRadius: "var(--mp-radius-lg)", padding: 26, height: "100%", display: "flex", flexDirection: "column", gap: 14 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <Avatar initials={rv.name.split(" ").map((w) => w[0]).join("").slice(0, 2)} hue={rv.hue} size={42} fontScale={0.36} />
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14.5 }}>{rv.name}</div><div style={{ fontSize: 12, color: "var(--mp-fg-subtle)" }}>{rv.date}</div></div>
                  <Stars value={rv.r} size={14} />
                </div>
                <p style={{ fontSize: 15, lineHeight: 1.55, color: "var(--mp-ink)", margin: 0, textWrap: "pretty" }}>"{rv.q}"</p>
              </article>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Related */}
      <Section bg="cloud" pad="84px 0 100px">
        <div style={{ maxWidth: 1240, margin: "0 auto", padding: "0 28px", marginBottom: 32 }}>
          <Reveal><h2 style={{ fontSize: "clamp(26px, 3vw, 40px)", fontWeight: 700, letterSpacing: "-0.03em", margin: 0 }}>Cursos relacionados</h2></Reveal>
        </div>
        <div className="mp-hscroll mp-hscroll-light" style={{ display: "flex", gap: 20, overflowX: "auto", padding: "8px 28px 24px", scrollSnapType: "x mandatory" }}>
          {COURSES.filter((c) => c.id !== course.id).slice(0, 4).map((c) => (
            <div key={c.id} style={{ scrollSnapAlign: "start" }}><CourseCard course={c} width={320} onOpen={() => { go("course"); window.scrollTo({ top: 0 }); }} /></div>
          ))}
        </div>
      </Section>
    </main>
  );
}

window.CourseDetail = CourseDetail;
