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

function Modal() {
  const ui = useUI();
  const wl = useWishlist();
  const p = ui.modal;

  useEffect(() => {
    if (!p) return;
    const onKey = (e) => { if (e.key === "Escape") ui.closeModal(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [p]);

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

  // Handle both raw catalog format (nombre/foto/precio) and transformed format (name/photo/price)
  const name = p.name || p.nombre || "";
  const photo = 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">
          {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
            />
          )}
        </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;
