/* =====================================================================
   ed-ui.jsx — primitivas visuales compartidas.
   ===================================================================== */
const { useState: useS, useEffect: useE, useRef: useR } = React;

/* Icono Lucide */
function Icon({ name, size = 20, color = "currentColor", strokeWidth = 1.75, style }) {
  const ref = useR(null);
  useE(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = "";
      const i = document.createElement("i");
      i.setAttribute("data-lucide", name);
      ref.current.appendChild(i);
      try {
        window.lucide.createIcons({ attrs: { width: size, height: size, "stroke-width": strokeWidth, stroke: color }, nameAttr: "data-lucide" });
      } catch (e) {}
    }
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} aria-hidden="true" style={Object.assign({ display: "inline-flex", lineHeight: 0 }, style)} />;
}

/* Botón que puede ser <a> o <button> */
function Btn({ kind = "navy", size, href, onClick, children, icon, iconRight, type, disabled, style }) {
  const cls = "ed-btn ed-btn-" + kind + (size ? " ed-btn-" + size : "");
  const iconColor = kind === "gold" ? "var(--navy-900)" : (kind === "navy" ? "var(--white)" : "var(--navy-900)");
  const inner = (
    <React.Fragment>
      {icon && <Icon name={icon} size={size === "lg" ? 19 : 17} color={iconColor} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "lg" ? 19 : 17} color={iconColor} />}
    </React.Fragment>
  );
  if (href) return <a className={cls} href={href} onClick={onClick} style={style}>{inner}</a>;
  return <button className={cls} onClick={onClick} type={type || "button"} disabled={disabled} style={style}>{inner}</button>;
}

/* Eyebrow */
function Eyebrow({ children, style }) {
  return <div className="ed-eyebrow" style={style}>{children}</div>;
}

/* Badge de confianza / chip */
function Badge({ icon, children, tone = "default" }) {
  const map = {
    default: { bg: "var(--surface)", bd: "var(--border)", fg: "var(--fg-secondary)", ic: "var(--success)" },
    gold: { bg: "var(--gold-50)", bd: "var(--gold-100)", fg: "var(--gold-700)", ic: "var(--gold-700)" },
    navy: { bg: "var(--navy-50)", bd: "var(--navy-100)", fg: "var(--navy-700)", ic: "var(--navy-700)" },
  };
  const c = map[tone] || map.default;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13.5, fontWeight: 500, color: c.fg, background: c.bg, border: "1px solid " + c.bd, borderRadius: "var(--r-pill)", padding: "8px 15px" }}>
      {icon && <Icon name={icon} size={15} color={c.ic} />}{children}
    </span>
  );
}

/* Bloque de "dolor" — cita destacada con barra dorada */
function PainQuote({ children, style }) {
  return (
    <div style={Object.assign({
      display: "flex", gap: 14, alignItems: "flex-start", padding: "18px 20px",
      background: "var(--surface)", border: "1px solid var(--border)", borderLeft: "3px solid var(--gold)",
      borderRadius: "var(--r-md)", boxShadow: "var(--shadow-xs)",
    }, style)}>
      <Icon name="alert-circle" size={20} color="var(--gold-700)" style={{ marginTop: 1, flex: "none" }} />
      <p style={{ fontSize: 16, lineHeight: "24px", color: "var(--fg-secondary)", fontStyle: "italic" }}>{children}</p>
    </div>
  );
}

/* Lista con bullets de check */
function CheckList({ items, color = "var(--success)", style }) {
  return (
    <ul style={Object.assign({ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }, style)}>
      {items.map((it, i) => (
        <li key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 15, lineHeight: "22px", color: "var(--fg-secondary)" }}>
          <Icon name="check" size={17} color={color} strokeWidth={2.5} style={{ marginTop: 2, flex: "none" }} />
          <span>{it}</span>
        </li>
      ))}
    </ul>
  );
}

/* Breadcrumb */
function Breadcrumb({ trail }) {
  // trail: [{label, href?}] — el último sin href = actual
  return (
    <nav aria-label="Ruta" style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", fontSize: 13.5 }}>
      {trail.map((node, i) => {
        const last = i === trail.length - 1;
        return (
          <React.Fragment key={i}>
            {node.href && !last
              ? <a href={node.href} style={{ color: "var(--fg-tertiary)", fontWeight: 500 }} className="ed-crumb">{node.label}</a>
              : <span style={{ color: last ? "var(--navy-900)" : "var(--fg-tertiary)", fontWeight: last ? 600 : 500 }}>{node.label}</span>}
            {!last && <span style={{ color: "var(--fg-muted)" }} aria-hidden="true">/</span>}
          </React.Fragment>
        );
      })}
    </nav>
  );
}

/* Botón Volver */
function BackBtn({ href, label = "Volver" }) {
  return (
    <a href={href} className="ed-btn ed-btn-quiet ed-btn-sm" style={{ paddingLeft: 10 }}>
      <Icon name="arrow-left" size={16} /> {label}
    </a>
  );
}

/* Encabezado de sección interna (eyebrow + h2 + lead) */
function SectionHead({ eyebrow, title, lead, align = "left", max = 680 }) {
  return (
    <div style={{ maxWidth: max, margin: align === "center" ? "0 auto" : undefined, textAlign: align }}>
      {eyebrow && <Eyebrow style={{ marginBottom: 14 }}>{eyebrow}</Eyebrow>}
      <h2 style={{ fontSize: 38, lineHeight: "44px", fontWeight: 600 }}>{title}</h2>
      {lead && <p style={{ marginTop: 16, fontSize: 18, lineHeight: "27px", color: "var(--fg-secondary)" }}>{lead}</p>}
    </div>
  );
}

/* Tarjeta de paquete / precio */
function PriceCard({ label, detail, price, unit, featured, cta, onCta }) {
  return (
    <div style={{
      position: "relative", background: "var(--surface)", borderRadius: "var(--r-lg)", padding: "26px 24px",
      border: "1.5px solid " + (featured ? "var(--navy-700)" : "var(--border)"),
      boxShadow: featured ? "var(--shadow-lg)" : "var(--shadow-sm)",
      display: "flex", flexDirection: "column",
    }}>
      {featured && (
        <span style={{ position: "absolute", top: -11, left: 24, fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--navy-900)", background: "var(--gold)", borderRadius: "var(--r-pill)", padding: "4px 12px" }}>Más elegido</span>
      )}
      <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600, color: "var(--navy-900)" }}>{label}</div>
      {detail && <div style={{ fontSize: 13.5, color: "var(--fg-tertiary)", marginTop: 4 }}>{detail}</div>}
      <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 18 }}>
        <span className="ed-tnum" style={{ fontFamily: "var(--font-display)", fontSize: 34, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--navy-900)" }}>${price.toLocaleString("en-US")}</span>
        <span style={{ fontSize: 14, color: "var(--fg-tertiary)", fontWeight: 500 }}>USD{unit || ""}</span>
      </div>
      {cta && <Btn kind={featured ? "gold" : "ghost"} onClick={onCta} style={{ marginTop: 20, width: "100%" }} iconRight="arrow-right">{cta}</Btn>}
    </div>
  );
}

/* Modal accesible */
function Modal({ open, onClose, children, maxWidth = 520, labelledBy }) {
  useE(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div role="dialog" aria-modal="true" aria-labelledby={labelledBy}
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(20,24,42,0.40)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, animation: "ed-overlay 200ms var(--ease-out)" }}>
      <div style={{ background: "var(--surface)", borderRadius: "var(--r-xl)", boxShadow: "var(--shadow-xl)", maxWidth, width: "100%", maxHeight: "90vh", overflow: "auto", animation: "ed-pop 240ms var(--ease-out)" }}>
        {children}
      </div>
    </div>
  );
}

/* Modal Calendly (mock reutilizable) */
function CalendlyModal({ open, onClose, context }) {
  const [day, setDay] = useS(null), [slot, setSlot] = useS(null), [done, setDone] = useS(false);
  useE(() => { if (open) { setDay(null); setSlot(null); setDone(false); } }, [open]);
  const days = []; const base = new Date();
  const dow = ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"];
  const mon = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
  let added = 0, cur = 1;
  while (added < 8) { const d = new Date(base.getTime() + cur * 86400000); if (d.getDay() !== 0 && d.getDay() !== 6) { days.push(d); added++; } cur++; }
  const slots = ["9:00", "10:30", "12:00", "14:00", "15:30", "17:00"];
  return (
    <Modal open={open} onClose={onClose} maxWidth={560} labelledBy="ed-cal-title">
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 24px", borderBottom: "1px solid var(--border)" }}>
        <span style={{ width: 36, height: 36, borderRadius: "var(--r-md)", background: "var(--navy-900)", color: "var(--white)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="calendar-clock" size={18} color="var(--white)" /></span>
        <div style={{ flex: 1 }}>
          <h3 id="ed-cal-title" style={{ fontSize: 17, fontWeight: 600 }}>Agenda una llamada · 30 min</h3>
          <div style={{ fontSize: 12.5, color: "var(--fg-tertiary)" }}>{context ? context + " · " : ""}Con un especialista de Sell-U</div>
        </div>
        <button type="button" aria-label="Cerrar" className="ed-btn ed-btn-quiet" style={{ padding: 8 }} onClick={onClose}><Icon name="x" size={18} /></button>
      </div>
      {!done ? (
        <div style={{ padding: 24 }}>
          <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-tertiary)", marginBottom: 12 }}>Elige un día</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
            {days.map((d, i) => {
              const sel = day === i;
              return <button key={i} type="button" onClick={() => { setDay(i); setSlot(null); }} style={{ cursor: "pointer", borderRadius: "var(--r-md)", padding: "10px 4px", textAlign: "center", border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border)"), background: sel ? "var(--navy-900)" : "var(--surface)", color: sel ? "var(--white)" : "var(--navy-900)", transition: "all 160ms var(--ease-out)" }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", opacity: 0.7 }}>{dow[d.getDay()]}</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600 }}>{d.getDate()}</div>
                <div style={{ fontSize: 11, opacity: 0.7 }}>{mon[d.getMonth()]}</div>
              </button>;
            })}
          </div>
          {day !== null && (
            <div style={{ marginTop: 22 }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-tertiary)", marginBottom: 12 }}>Elige un horario</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                {slots.map(s => { const sel = slot === s; return <button key={s} type="button" onClick={() => setSlot(s)} style={{ cursor: "pointer", borderRadius: "var(--r-md)", padding: "11px 4px", fontWeight: 600, fontSize: 14, border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border-strong)"), background: sel ? "var(--navy-900)" : "var(--surface)", color: sel ? "var(--white)" : "var(--navy-900)", transition: "all 160ms var(--ease-out)" }}>{s}</button>; })}
              </div>
            </div>
          )}
          <Btn kind="gold" disabled={slot === null} onClick={() => setDone(true)} style={{ width: "100%", marginTop: 24 }}>Confirmar llamada</Btn>
          <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--fg-muted)", textAlign: "center" }}>Demo · integración Calendly simulada</div>
        </div>
      ) : (
        <div style={{ padding: "36px 24px", textAlign: "center" }}>
          <span style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-bg)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}><Icon name="calendar-check" size={26} color="var(--success)" /></span>
          <h3 style={{ fontSize: 21, fontWeight: 600 }}>Llamada agendada</h3>
          <p style={{ marginTop: 10, fontSize: 14.5, color: "var(--fg-secondary)" }}>{dow[days[day].getDay()]} {days[day].getDate()} de {mon[days[day].getMonth()]} · {slot} h.<br />Te enviamos la invitación por correo.</p>
          <Btn kind="ghost" onClick={onClose} style={{ marginTop: 20 }}>Listo</Btn>
        </div>
      )}
    </Modal>
  );
}

/* Espacio para video VSL — marco navy 16:9 con botón de play; abre reproductor mock */
function VslSlot({ label = "VSL", duration = "2 min", caption, title }) {
  const [open, setOpen] = useS(false);
  return (
    <React.Fragment>
      <figure style={{ margin: 0 }}>
        <button type="button" onClick={() => setOpen(true)} aria-label={"Reproducir video" + (title ? ": " + title : "")}
          style={{ position: "relative", display: "block", width: "100%", aspectRatio: "16 / 9", border: "none", cursor: "pointer",
            background: "var(--navy-900)", borderRadius: "var(--r-2xl)", boxShadow: "var(--shadow-xl)", overflow: "hidden", padding: 0 }}>
          {/* motivo puzzle tenue */}
          <span aria-hidden="true" style={{ position: "absolute", right: -40, bottom: -40, width: 240, height: 240, background: "var(--gold)", opacity: 0.10, borderRadius: "var(--r-2xl)", transform: "rotate(12deg)" }} />
          <span aria-hidden="true" style={{ position: "absolute", top: 16, left: 18, display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--gold)", background: "rgba(245,166,35,0.12)", border: "1px solid rgba(245,166,35,0.3)", borderRadius: "var(--r-pill)", padding: "5px 11px" }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--gold)", display: "inline-block" }} />{label}
          </span>
          <span style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14 }}>
            <span className="ed-vsl-play" style={{ width: 76, height: 76, borderRadius: 999, background: "var(--gold)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 24px rgba(0,0,0,0.28)", transition: "transform 200ms var(--ease-out)" }}>
              <Icon name="play" size={30} color="var(--navy-900)" strokeWidth={2.5} style={{ marginLeft: 4 }} />
            </span>
            <span style={{ fontSize: 14, fontWeight: 500, color: "rgba(238,241,246,0.82)" }}>{caption || "Ver video"} · {duration}</span>
          </span>
        </button>
      </figure>
      <Modal open={open} onClose={() => setOpen(false)} maxWidth={860} labelledBy="ed-vsl-title">
        <div style={{ position: "relative", width: "100%", aspectRatio: "16 / 9", background: "#0c1322", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 16 }}>
          <button type="button" aria-label="Cerrar" onClick={() => setOpen(false)} style={{ position: "absolute", top: 14, right: 14, width: 38, height: 38, borderRadius: 999, border: "none", background: "rgba(255,255,255,0.12)", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={18} color="#fff" /></button>
          <span style={{ width: 72, height: 72, borderRadius: 999, background: "var(--gold)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="play" size={28} color="var(--navy-900)" strokeWidth={2.5} style={{ marginLeft: 4 }} /></span>
          <h3 id="ed-vsl-title" style={{ fontSize: 18, fontWeight: 600, color: "#fff", textAlign: "center", padding: "0 24px" }}>{title || "Video VSL"}</h3>
          <p style={{ fontSize: 13.5, color: "rgba(255,255,255,0.6)", textAlign: "center", maxWidth: 420, padding: "0 24px" }}>Este es el espacio reservado para tu video de ventas (VSL). Aquí se incrustará el reproductor real. Demo.</p>
        </div>
      </Modal>
    </React.Fragment>
  );
}

Object.assign(window, { Icon, Btn, Eyebrow, Badge, PainQuote, CheckList, Breadcrumb, BackBtn, SectionHead, PriceCard, Modal, CalendlyModal, VslSlot });
