// modals.jsx — ShareModal (IG story) + CartModal + checkout
// exposes: ShareModal, CartModal

function Backdrop({ onClose, children, align = "center" }) {
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200, background: "rgba(6,4,18,0.62)",
      backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: align === "right" ? "flex-end" : "center",
      padding: align === "right" ? 0 : 24,
    }}>
      <style>{`@keyframes fadeBg{from{opacity:0}to{opacity:1}}@keyframes slideR{from{transform:translateX(40px)}to{transform:translateX(0)}}@keyframes popIn{from{transform:scale(0.95)}to{transform:scale(1)}}`}</style>
      <div onClick={(e) => e.stopPropagation()}>{children}</div>
    </div>
  );
}

// ---------- SHARE (Instagram story) ----------
function ShareModal({ model, design, onClose, onPublish }) {
  const [caption, setCaption] = React.useState("Mi nueva Coolcase ✨");
  const [published, setPublished] = React.useState(false);
  const backdrop = design.design || `linear-gradient(160deg, ${design.base || "#241a52"}, #0d0a22)`;

  const publish = () => {
    onPublish({ caption, backdrop: `linear-gradient(160deg,#2a1c5e,#0d0a22)` });
    setPublished(true);
  };

  return (
    <Backdrop onClose={onClose}>
      <div className="glass-strong" style={{ borderRadius: 30, padding: 24, width: "min(420px, 92vw)", maxHeight: "94vh", overflowY: "auto", animation: "popIn 0.3s cubic-bezier(0.2,0.8,0.2,1)" }}>
        <div className="row" style={{ justifyContent: "space-between", marginBottom: 18 }}>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 19 }}>{published ? "¡Compartido!" : "Compartir con la comunidad"}</span>
          <button onClick={onClose} style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: "50%", width: 32, height: 32, cursor: "pointer", color: "var(--ink-70)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="close" size={16} /></button>
        </div>

        {/* story preview 9:16 */}
        <div style={{ position: "relative", height: "min(50vh, 440px)", aspectRatio: "9 / 16", margin: "0 auto", borderRadius: 22, overflow: "hidden", background: backdrop, marginBottom: 18, boxShadow: "0 20px 50px -16px rgba(0,0,0,0.6)" }}>
          <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 50% 35%, rgba(255,255,255,0.14), transparent 60%)" }}/>
          {/* IG story top bar */}
          <div style={{ position: "absolute", top: 12, left: 12, right: 12, display: "flex", alignItems: "center", gap: 8, zIndex: 2 }}>
            <div style={{ flex: 1, height: 3, borderRadius: 3, background: "rgba(255,255,255,0.45)" }}/>
            <div style={{ display: "flex", alignItems: "center", gap: 7, color: "#fff" }}>
              <Logo size={20} withWord={false} /><span style={{ fontSize: 12.5, fontWeight: 600 }}>cool.case.cl</span>
            </div>
          </div>
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <div style={{ transform: "rotate(-7deg)", filter: "drop-shadow(0 24px 44px rgba(0,0,0,0.55))" }}>
              <PhoneCase model={model} design={design} scale={0.46} />
            </div>
          </div>
          <div style={{ position: "absolute", bottom: 18, left: 0, right: 0, textAlign: "center", color: "#fff", zIndex: 2 }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, textShadow: "0 2px 12px rgba(0,0,0,0.5)" }}>{caption}</div>
            <div style={{ fontSize: 12.5, opacity: 0.85, marginTop: 4 }}>diseñada en coolcase.cl</div>
          </div>
        </div>

        {!published ? (
          <>
            <input value={caption} onChange={(e) => setCaption(e.target.value)} maxLength={48} style={{
              width: "100%", background: "rgba(0,0,0,0.25)", border: "1px solid var(--glass-border)", borderRadius: 12, padding: "12px 14px", color: "#fff", fontSize: 14.5, fontFamily: "var(--font-ui)", outline: "none", marginBottom: 14,
            }} placeholder="Escribe un pie de foto…" />
            <button className="btn btn-neon" onClick={publish} style={{ width: "100%", justifyContent: "center", padding: "14px 0", fontSize: 15.5 }}>
              <Icon name="instagram" size={19} /> Publicar en la comunidad
            </button>
          </>
        ) : (
          <div className="col" style={{ alignItems: "center", gap: 14, textAlign: "center" }}>
            <p style={{ color: "var(--ink-70)", fontSize: 14.5, margin: 0 }}>Tu carcasa ya aparece en la pestaña <b style={{ color: "#fff" }}>Comunidad</b> y sumó +1 al contador.</p>
            <button className="btn btn-ghost" onClick={onClose} style={{ width: "100%", justifyContent: "center", padding: "13px 0" }}>Listo</button>
          </div>
        )}
      </div>
    </Backdrop>
  );
}

// ---------- CART ----------
function CartModal({ items, onClose, onCheckout, onRemove }) {
  const [done, setDone] = React.useState(false);
  const total = items.reduce((s, it) => s + it.price, 0);
  const checkout = () => { onCheckout(); setDone(true); };

  return (
    <Backdrop onClose={onClose} align="right">
      <div className="glass-strong" style={{ width: "min(440px, 100vw)", height: "100vh", padding: 24, display: "flex", flexDirection: "column", animation: "slideR 0.35s cubic-bezier(0.2,0.8,0.2,1)", borderRadius: 0 }}>
        <div className="row" style={{ justifyContent: "space-between", marginBottom: 22 }}>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22 }}>{done ? "¡Pedido listo!" : "Tu carro"}</span>
          <button onClick={onClose} style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: "50%", width: 34, height: 34, cursor: "pointer", color: "var(--ink-70)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="close" size={17} /></button>
        </div>

        {done ? (
          <div className="col" style={{ flex: 1, alignItems: "center", justifyContent: "center", textAlign: "center", gap: 18 }}>
            <div style={{ width: 78, height: 78, borderRadius: "50%", background: "var(--grad-neon)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 40px rgba(255,61,240,0.5)" }}><Icon name="check" size={40} stroke="#fff" /></div>
            <h3 style={{ fontSize: 24 }}>Gracias por tu compra</h3>
            <p style={{ color: "var(--ink-70)", fontSize: 15, maxWidth: 280 }}>Tus carcasas se sumaron a la comunidad Coolcase. Te avisaremos por WhatsApp cuando estén en producción.</p>
            <button className="btn btn-neon" onClick={onClose} style={{ padding: "13px 28px" }}>Seguir creando</button>
          </div>
        ) : items.length === 0 ? (
          <div className="col" style={{ flex: 1, alignItems: "center", justifyContent: "center", textAlign: "center", gap: 14, color: "var(--ink-50)" }}>
            <Icon name="cart" size={48} stroke="var(--ink-30)" />
            <p style={{ fontSize: 15 }}>Tu carro está vacío.<br/>¡Coolcaséate una!</p>
          </div>
        ) : (
          <>
            <div className="col" style={{ flex: 1, overflowY: "auto", gap: 12, marginBottom: 16 }}>
              {items.map((it) => {
                const model = CC.models.find((m) => m.id === it.modelId) || CC.models[0];
                const accMeta = it.accessoryOnly ? CC.accessories.find((x) => x.id === it.accessories[0]) : null;
                return (
                  <div key={it.id} className="row" style={{ gap: 14, padding: 12, background: "rgba(255,255,255,0.04)", border: "1px solid var(--glass-border)", borderRadius: 16 }}>
                    {it.accessoryOnly ? (
                      <div style={{ width: 54, height: 80, borderRadius: 10, background: "var(--glass-bg-strong)", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1)" }}><Icon name={accMeta?.icon || "accessory"} size={26} stroke="var(--neon-cyan)" /></div>
                    ) : (
                      <div style={{ width: 54, height: 80, borderRadius: 10, background: it.design.design || it.design.base || "#1b1740", backgroundImage: it.design.img ? `url(${it.design.img})` : undefined, backgroundSize: "cover", backgroundPosition: "center", flexShrink: 0, boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1)" }}/>
                    )}
                    <div className="col" style={{ flex: 1, gap: 3 }}>
                      <span style={{ fontWeight: 600, fontSize: 14.5 }}>{it.name || model.name}</span>
                      <span style={{ fontSize: 12, color: "var(--ink-50)" }}>{it.accessoryOnly ? "Accesorio" : `Carcasa personalizada${it.accessories?.length ? ` · ${it.accessories.length} accesorio(s)` : ""}`}</span>
                      <span style={{ fontWeight: 700, fontSize: 15, marginTop: 2 }}>{fmt(it.price)}</span>
                    </div>
                    <button onClick={() => onRemove(it.id)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-50)", alignSelf: "flex-start" }}><Icon name="trash" size={18} /></button>
                  </div>
                );
              })}
            </div>
            <div style={{ borderTop: "1px solid var(--glass-border)", paddingTop: 18 }}>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 16 }}>
                <span style={{ color: "var(--ink-70)", fontSize: 15 }}>Total</span>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26 }}>{fmt(total)}</span>
              </div>
              <button className="btn btn-neon" onClick={checkout} style={{ width: "100%", justifyContent: "center", padding: "15px 0", fontSize: 16 }}>
                Ir a pagar <Icon name="arrow" size={19} />
              </button>
            </div>
          </>
        )}
      </div>
    </Backdrop>
  );
}

Object.assign(window, { ShareModal, CartModal });
