/* global React, useUI, useWishlist, Placeholder, HeartIcon, Arr, waLink */
const { useEffect, useState } = React;

/* Descubre fotos secundarias igual que en ficha.jsx */
function useModalFotos(p) {
  const [fotos, setFotos] = useState([]);
  useEffect(() => {
    if (!p?.foto) { setFotos(p ? [] : []); return; }
    setFotos([p.foto]);
    const base = p.foto.replace(/\.[^.]+$/, "").replace(/_\d+$/, "");
    const ext = p.foto.match(/\.([^.?]+)(\?|$)/)?.[1] || "jpg";
    const checks = Array.from({ length: 6 }, (_, i) => {
      const url = `${base}_${i + 2}.${ext}`;
      return fetch(url, { method: "HEAD" }).then(r => r.ok ? url : null).catch(() => null);
    });
    Promise.all(checks).then(results => {
      setFotos([p.foto, ...results.filter(Boolean)]);
    });
  }, [p?.id]);
  return fotos;
}

function Modal() {
  const ui = useUI();
  const wl = useWishlist();
  const p = ui.modal;
  const [imgIdx, setImgIdx] = useState(0);
  const fotos = useModalFotos(p);

  useEffect(() => { setImgIdx(0); }, [p?.id]);

  useEffect(() => {
    if (!p) return;
    const onKey = (e) => {
      if (e.key === "Escape") ui.closeModal();
      if (e.key === "ArrowRight") setImgIdx(i => Math.min(i + 1, fotos.length - 1));
      if (e.key === "ArrowLeft") setImgIdx(i => Math.max(i - 1, 0));
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [p, fotos.length]);

  if (!p) return null;
  const isOn = wl.has(p.id);

  const name = p.name || p.nombre || "";
  const photo = fotos[imgIdx] || p.photo || p.foto || null;
  const price = p.price || (p.precio ? p.precio.toLocaleString("es-CO") : "");
  const family = p.family || (p.categoria ? (window.CAT_LABELS && window.CAT_LABELS[p.categoria]) || p.categoria : "");
  const pattern = p.pattern || (typeof detectarPatron === "function" ? detectarPatron(p.variante) : null) || "";
  const variant = p.variante || "";

  const wmsg = `Hola DAVA'S, me interesa la ${name}${pattern ? ` patrón ${pattern}` : ""}${price ? ` ($${price})` : ""}. ¿Me cuentan disponibilidad?`;

  return (
    <div className={`modal-back is-open`} onClick={(e) => { if (e.target.classList.contains("modal-back")) ui.closeModal(); }}>
      <div className="modal">
        <button className="close" onClick={ui.closeModal} aria-label="Cerrar">✕</button>
        <div className="left" style={{ position: "relative" }}>
          {photo ? (
            <img src={photo} alt={name} style={{ width: "100%", height: "100%", objectFit: "contain", padding: "4%", background: "#fff", borderRadius: 14 }} />
          ) : (
            <Placeholder ratio="auto" tone={p.tone || "bone"} label={`/ASSETS/PROD-${(p.id || name).toUpperCase()}-1.JPG`} corner={family} fill />
          )}
          {/* Flechas de navegación */}
          {fotos.length > 1 && imgIdx > 0 && (
            <button onClick={() => setImgIdx(i => i - 1)} style={{ position: "absolute", left: 8, top: "50%", transform: "translateY(-50%)", background: "rgba(18,10,1,.5)", border: "none", color: "#fff", fontSize: 22, cursor: "pointer", borderRadius: 6, padding: "6px 10px", lineHeight: 1 }}>‹</button>
          )}
          {fotos.length > 1 && imgIdx < fotos.length - 1 && (
            <button onClick={() => setImgIdx(i => i + 1)} style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", background: "rgba(18,10,1,.5)", border: "none", color: "#fff", fontSize: 22, cursor: "pointer", borderRadius: 6, padding: "6px 10px", lineHeight: 1 }}>›</button>
          )}
          {/* Thumbnails */}
          {fotos.length > 1 && (
            <div style={{ display: "flex", gap: 4, justifyContent: "center", marginTop: 8 }}>
              {fotos.map((src, i) => (
                <button key={i} onClick={() => setImgIdx(i)} style={{ width: 36, height: 36, border: i === imgIdx ? "2px solid #C8901A" : "2px solid rgba(0,0,0,.1)", borderRadius: 5, overflow: "hidden", cursor: "pointer", padding: 0, background: "#fff", flexShrink: 0 }}>
                  <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="right">
          <div className="mono" style={{ color: "var(--ink-mute)" }}>
            {family}
          </div>
          <h2>{name}</h2>
          {pattern ? <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 4 }}>{pattern}</div> : null}
          {variant && variant !== pattern ? <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)", marginTop: 2 }}>{variant}</div> : null}
          <div className="price-row">
            <div className="price">$ {price}</div>
            <div className="lead">Hecha a pedido · 15 días</div>
          </div>
          <div className="actions">
            <a className="btn wa lg" href={waLink(wmsg)} target="_blank" rel="noopener">
              Pedir por WhatsApp
              <Arr />
            </a>
            <button className="btn line" onClick={() => wl.toggle({ id: p.id, name: name, family: family, pattern: pattern, price: price, tone: p.tone })}>
              <HeartIcon filled={isOn} size={13} stroke={isOn ? "var(--accent)" : "currentColor"} />
              {isOn ? "Guardada" : "Guardar"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Modal = Modal;
