// ============================================================
// LGM — Modal, contacto, favoritos, tweaks, footer
// ============================================================
const { useState: uS, useEffect: uE, useRef: uR, useMemo: uM } = React;

// ============================================================
// PROPERTY MODAL
// ============================================================
function PropertyModal({ t, property, onClose, isFav, onFav, waNumber }) {
  const overlayRef = uR(null);
  const [sent, setSent] = uS(false);
  const [form, setForm] = uS({ name: "", email: "", phone: "", msg: "" });
  const [lightboxIdx, setLightboxIdx] = uS(null);
  const touchStartX = uR(0);
  const touchStartY = uR(0);

  uE(() => {
    if (property) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [property]);

  uE(() => {
    if (!property) return;
    const onKey = (e) => {
      if (e.key === "Escape") {
        if (lightboxIdx !== null) setLightboxIdx(null);
        else onClose();
        return;
      }
      if (lightboxIdx === null || !property) return;
      const n = property.images.length;
      if (e.key === "ArrowLeft") setLightboxIdx(i => (i - 1 + n) % n);
      else if (e.key === "ArrowRight") setLightboxIdx(i => (i + 1) % n);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [property, onClose, lightboxIdx]);

  if (!property) return null;
  const p = property;

  const lbPrev = () => setLightboxIdx(i => (i - 1 + p.images.length) % p.images.length);
  const lbNext = () => setLightboxIdx(i => (i + 1) % p.images.length);
  const onTouchStart = (e) => {
    touchStartX.current = e.touches[0].clientX;
    touchStartY.current = e.touches[0].clientY;
  };
  const onTouchEnd = (e) => {
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    const dy = e.changedTouches[0].clientY - touchStartY.current;
    if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 50) {
      if (dx > 0) lbPrev(); else lbNext();
    }
  };

  const submit = (e) => {
    e.preventDefault();
    setSent(true);
    setTimeout(() => { setSent(false); onClose(); }, 2500);
  };

  const share = () => {
    const url = `${location.origin}${location.pathname}#p-${p.id}`;
    if (navigator.share) navigator.share({ title: p.name, url });
    else navigator.clipboard?.writeText(url);
  };

  return (
    <>
    <div ref={overlayRef} className={`modal-overlay${p ? " open" : ""}`}
      onClick={(e) => e.target === overlayRef.current && onClose()}>
      <button className="modal__close" onClick={onClose}><Icon.Close /></button>
      <div className="modal">
        <div className="modal__gallery">
          {p.images.slice(0, 6).map((src, i) => (
            <img key={i} src={src} alt={`${p.name} ${i+1}`} loading="lazy"
              onClick={() => setLightboxIdx(i)}
              style={{ cursor: "zoom-in" }} />
          ))}
        </div>
        <div className="modal__body">
          <div className="modal__main">
            <div className="modal__head-row">
              <div>
                <div className="modal__ref">{t.prop.ref} · {p.ref}</div>
                <h2 className="modal__title">{p.name}</h2>
                <div className="modal__zone">{[p.zone, p.city].filter(Boolean).join(" · ")}, {t.contact.officeValue.includes("R.D") ? "República Dominicana" : "Dominican Republic"}</div>
              </div>
            </div>

            <div className="modal__alerts">
              {p.title && <span className="modal__alert"><Icon.Check /> {t.prop.titled}</span>}
              {p.deslinde && <span className="modal__alert"><Icon.Check /> {t.prop.delisted}</span>}
              <span className="modal__alert" style={{ color: "var(--text)", borderColor: "var(--border-strong)" }}>
                <Icon.Pin /> {p.year}
              </span>
            </div>

            <div className="modal__price-row">
              {p.price && (
                <div className="modal__price-item">
                  <span className="modal__price-label">{t.prop.price}</span>
                  <span className="modal__price-value">{formatPrice(p.price)}</span>
                </div>
              )}
              {p.rent && (
                <div className="modal__price-item">
                  <span className="modal__price-label">{t.prop.rent}</span>
                  <span className="modal__price-value">{formatRent(p.rent)}</span>
                </div>
              )}
            </div>

            <p className="modal__description">{p.description}</p>

            <div className="modal__specs">
              <div className="modal__spec"><span className="modal__spec-val">{p.beds}</span><span className="modal__spec-label">{t.prop.beds}</span></div>
              <div className="modal__spec"><span className="modal__spec-val">{p.baths}</span><span className="modal__spec-label">{t.prop.baths}</span></div>
              <div className="modal__spec"><span className="modal__spec-val">{p.parking}</span><span className="modal__spec-label">{t.prop.parking}</span></div>
              <div className="modal__spec"><span className="modal__spec-val">{p.area}</span><span className="modal__spec-label">{t.prop.area}</span></div>
              {p.lotArea && <div className="modal__spec"><span className="modal__spec-val">{p.lotArea}</span><span className="modal__spec-label">{t.prop.lot}</span></div>}
              <div className="modal__spec"><span className="modal__spec-val">{p.year}</span><span className="modal__spec-label">{t.prop.year}</span></div>
            </div>

            {p.features && p.features.length > 0 && (
              <>
                <div className="modal__features-title">{t.prop.features}</div>
                <ul className="modal__features">
                  {p.features.map((f, i) => <li key={i}>{f}</li>)}
                </ul>
              </>
            )}

            {Array.isArray(p.amenities) && p.amenities.length > 0 && (() => {
              const cat = (window.LGM_AMENITIES && window.LGM_AMENITIES.categories) || [];
              const items = (window.LGM_AMENITIES && window.LGM_AMENITIES.items) || [];
              const amenLabels = (t && t.amenities) || {};
              const catLabels = amenLabels._categories || {};
              const set = new Set(p.amenities);
              const groups = cat.map(c => ({
                key: c.key,
                label: catLabels[c.key] || c.key,
                slugs: items.filter(a => a.category === c.key && set.has(a.slug)).map(a => a.slug),
              })).filter(g => g.slugs.length > 0);
              if (!groups.length) return null;
              return (
                <>
                  <div className="modal__amenities-title">{amenLabels._title || "Amenities"}</div>
                  {groups.map(g => (
                    <div key={g.key} className="modal__amen-group">
                      <div className="modal__amen-group-label">{g.label}</div>
                      <div className="modal__amen-chips">
                        {g.slugs.map(s => (
                          <span key={s} className="modal__amen-chip">{amenLabels[s] || s}</span>
                        ))}
                      </div>
                    </div>
                  ))}
                </>
              );
            })()}

            <div className="modal__actions">
              <button onClick={() => onFav(p.id)}>
                <Icon.Heart fill={isFav ? "currentColor" : "none"} />
                {isFav ? t.prop.removeFav : t.prop.addFav}
              </button>
              <button onClick={share}><Icon.Share /> {t.prop.share}</button>
              <a href={`https://wa.me/${waNumber}?text=${encodeURIComponent(`Hola Luis, me interesa la propiedad ${p.ref} — ${p.name}`)}`}
                target="_blank" rel="noopener"
                style={{ background: "var(--gold)", color: "#14120e", borderColor: "var(--gold)", flex: 1.5, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: 14 }}>
                <Icon.WhatsApp /> WhatsApp
              </a>
            </div>
          </div>

          <aside className="modal__side">
            <h4>{t.prop.inquire}</h4>
            {sent ? (
              <div className="form-success">✓ {t.contact.sent}</div>
            ) : (
              <form onSubmit={submit}>
                <div className="form-row">
                  <label>{t.contact.name}</label>
                  <input required type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
                </div>
                <div className="form-row">
                  <label>{t.contact.email}</label>
                  <input required type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                </div>
                <div className="form-row">
                  <label>{t.contact.phone}</label>
                  <input type="tel" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} />
                </div>
                <div className="form-row">
                  <label>{t.contact.message}</label>
                  <textarea rows="3" placeholder={`Ref: ${p.ref}`} value={form.msg} onChange={e => setForm({...form, msg: e.target.value})}></textarea>
                </div>
                <button type="submit" className="btn-gold" style={{ width: "100%", justifyContent: "center" }}>
                  {t.contact.send} <Icon.Arrow />
                </button>
              </form>
            )}
          </aside>
        </div>
      </div>
    </div>
    {lightboxIdx !== null && (
      <div className="lightbox open" onClick={(e) => { if (e.target === e.currentTarget) setLightboxIdx(null); }}>
        <button className="lightbox__close" onClick={() => setLightboxIdx(null)} aria-label="Cerrar">
          <Icon.Close />
        </button>
        <button className="lightbox__nav lightbox__nav--prev" onClick={lbPrev} aria-label="Anterior">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
        </button>
        <button className="lightbox__nav lightbox__nav--next" onClick={lbNext} aria-label="Siguiente">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
        </button>
        <div className="lightbox__stage" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
          <img className="lightbox__img" src={p.images[lightboxIdx]} alt={`${p.name} ${lightboxIdx+1}`} />
          <div className="lightbox__counter">{lightboxIdx+1} / {p.images.length}</div>
        </div>
        <div className="lightbox__thumbs">
          {p.images.map((src, i) => (
            <button key={i}
              className={`lightbox__thumb${i === lightboxIdx ? " active" : ""}`}
              onClick={() => setLightboxIdx(i)}
              aria-label={`Imagen ${i+1}`}>
              <img src={src} alt="" loading="lazy" />
            </button>
          ))}
        </div>
      </div>
    )}
    </>
  );
}

// ============================================================
// CONTACT SECTION
// ============================================================
function Contact({ t, waNumber }) {
  const [sent, setSent] = uS(false);
  const [form, setForm] = uS({ name: "", email: "", phone: "", interest: "", msg: "" });
  const submit = (e) => {
    e.preventDefault();
    setSent(true);
    setForm({ name: "", email: "", phone: "", interest: "", msg: "" });
    setTimeout(() => setSent(false), 5000);
  };

  // Prefill interest/msg desde sessionStorage (ServicesPage / SellPage deep-link)
  uE(() => {
    const applyPrefill = () => {
      try {
        const pre = sessionStorage.getItem("lgm_contact_prefill");
        if (!pre) return;
        const data = JSON.parse(pre);
        sessionStorage.removeItem("lgm_contact_prefill");
        const opts = t.contact.interestOptions || [];
        const interest = (typeof data.interestIdx === "number" && opts[data.interestIdx]) || data.interest || "";
        setForm(f => ({
          ...f,
          interest: interest || f.interest,
          msg: data.msg || f.msg,
        }));
      } catch (_) { /* ignore */ }
    };
    applyPrefill();
    window.addEventListener("lgm_contact_prefill", applyPrefill);
    return () => window.removeEventListener("lgm_contact_prefill", applyPrefill);
  }, [t]);

  return (
    <section className="contact" id="contact">
      <div className="contact__wrap">
        <div className="contact__left reveal">
          <span className="eyebrow">{t.contact.eyebrow}</span>
          <h2>{t.contact.title}</h2>
          <p className="contact__sub">{t.contact.sub}</p>

          <div className="contact__channels">
            <a className="contact__channel" href={`tel:${waNumber}`}>
              <span className="contact__channel-label">{t.contact.phoneLabel}</span>
              <span className="contact__channel-value">+1 (829) 483-2697</span>
            </a>
            <a className="contact__channel" href={`https://wa.me/${waNumber}`} target="_blank" rel="noopener">
              <span className="contact__channel-label">{t.contact.waLabel}</span>
              <span className="contact__channel-value">+1 (829) 483-2697</span>
            </a>
            <a className="contact__channel" href="mailto:luis@lgmrealestate.do">
              <span className="contact__channel-label">{t.contact.emailLabel}</span>
              <span className="contact__channel-value">luis@lgmrealestate.do</span>
            </a>
            <div className="contact__channel">
              <span className="contact__channel-label">{t.contact.hoursLabel}</span>
              <span className="contact__channel-value">{t.contact.hoursValue}</span>
            </div>
            <div className="contact__channel">
              <span className="contact__channel-label">{t.contact.officeLabel}</span>
              <span className="contact__channel-value">{t.contact.officeValue}</span>
            </div>
          </div>
        </div>

        <div className="contact__form reveal">
          <h3>{t.contact.send}</h3>
          {sent ? (
            <div className="form-success">✓ {t.contact.sent}</div>
          ) : (
            <form onSubmit={submit}>
              <div className="form-row">
                <label>{t.contact.name}</label>
                <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
              </div>
              <div className="form-row">
                <label>{t.contact.email}</label>
                <input required type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
              </div>
              <div className="form-row">
                <label>{t.contact.phone}</label>
                <input type="tel" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} />
              </div>
              <div className="form-row">
                <label>{t.contact.interest}</label>
                <Dropdown ariaLabel={t.contact.interest}
                  value={form.interest}
                  placeholder="—"
                  onChange={e => setForm({...form, interest: e.target.value})}
                  options={t.contact.interestOptions.map(o => ({ value: o, label: o }))} />
              </div>
              <div className="form-row">
                <label>{t.contact.message}</label>
                <textarea rows="4" value={form.msg} onChange={e => setForm({...form, msg: e.target.value})}></textarea>
              </div>
              <button type="submit" className="btn-gold" style={{ width: "100%", justifyContent: "center" }}>
                {t.contact.send} <Icon.Arrow />
              </button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// FOOTER
// ============================================================
function Footer({ t, onNav }) {
  const nav = (e, to) => { e.preventDefault(); onNav ? onNav(to) : (location.hash = "#" + to); };
  return (
    <footer className="footer">
      <div className="footer__inner">
        <div className="footer__brand">
          <img src="assets/lgm-logo-cream.png" alt="LGM Real Estate" />
          <p className="footer__tagline">{t.footer.tagline}</p>
        </div>
        <div>
          <h5>{t.nav.properties}</h5>
          <ul>
            <li><a href="#/propiedades" onClick={(e) => nav(e, "/propiedades")}>{t.nav.properties}</a></li>
            <li><a href="#/propiedades?op=sale" onClick={(e) => nav(e, "/propiedades")}>{t.editorial.sale}</a></li>
            <li><a href="#/propiedades?op=rent" onClick={(e) => nav(e, "/propiedades")}>{t.editorial.rent}</a></li>
          </ul>
        </div>
        <div>
          <h5>{t.nav.services}</h5>
          <ul>
            <li><a href="#/servicios" onClick={(e) => nav(e, "/servicios")}>{t.nav.services}</a></li>
            <li><a href="#/sobre-mi" onClick={(e) => nav(e, "/sobre-mi")}>{t.nav.about}</a></li>
          </ul>
        </div>
        <div>
          <h5>{t.nav.contact}</h5>
          <ul>
            <li><a href="tel:+18294832697">+1 (829) 483-2697</a></li>
            <li><a href="mailto:luis@lgmrealestate.do">luis@lgmrealestate.do</a></li>
            <li><a href="https://wa.me/18294832697" target="_blank" rel="noopener">WhatsApp</a></li>
          </ul>
        </div>
      </div>
      <div className="footer__bottom">
        <span>{t.footer.cr}</span>
        <span>{t.footer.legal}</span>
      </div>
      <div className="footer__vertix">
        <span>Hecho bajo la marca </span>
        <a href="https://vertix.lat" target="_blank" rel="noopener noreferrer">Vertix</a>
      </div>
    </footer>
  );
}

// ============================================================
// FAVORITES DRAWER
// ============================================================
function FavDrawer({ t, open, onClose, favorites, visited, properties, onOpen, onToggleFav }) {
  const [tab, setTab] = uS("fav");
  const favProps = properties.filter(p => favorites.includes(p.id));
  const visitedProps = properties.filter(p => visited.includes(p.id));
  const list = tab === "fav" ? favProps : visitedProps;

  uE(() => {
    if (open) document.body.style.overflow = "hidden";
    else if (!window.__modalOpen) document.body.style.overflow = "";
  }, [open]);

  return (
    <>
      {open && <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 180, background: "rgba(0,0,0,0.5)" }}></div>}
      <aside className={`fav-drawer${open ? " open" : ""}`}>
        <div className="fav-drawer__head">
          <h3>
            {tab === "fav" ? t.fav.title : t.fav.visited}
          </h3>
          <button onClick={onClose} style={{ color: "var(--text)" }}><Icon.Close /></button>
        </div>
        <div className="fav-drawer__tabs">
          <button className={`fav-drawer__tab${tab === "fav" ? " active" : ""}`} onClick={() => setTab("fav")}>
            {t.fav.title} · {favProps.length}
          </button>
          <button className={`fav-drawer__tab${tab === "visited" ? " active" : ""}`} onClick={() => setTab("visited")}>
            {t.fav.visited} · {visitedProps.length}
          </button>
        </div>
        <div className="fav-drawer__body">
          {list.length === 0 && <div className="fav-drawer__empty">{t.fav.empty}</div>}
          {list.map(p => (
            <div key={p.id} className="fav-item" onClick={() => { onClose(); onOpen(p); }}>
              <img src={p.images[0]} alt={p.name} />
              <div className="fav-item__info">
                <span className="fav-item__name">{p.name}</span>
                <span className="fav-item__zone">{p.zone}</span>
                <span className="fav-item__price">{p.price ? formatPrice(p.price) : formatRent(p.rent)}</span>
              </div>
              {tab === "fav" && (
                <button onClick={(e) => { e.stopPropagation(); onToggleFav(p.id); }}
                  style={{ color: "var(--gold)", alignSelf: "flex-start", padding: 6 }}>
                  <Icon.Close />
                </button>
              )}
            </div>
          ))}
        </div>
      </aside>
    </>
  );
}

// ============================================================
// TWEAKS PANEL
// ============================================================
function TweaksPanel({ visible, tweaks, setTweaks }) {
  const palettes = [
    { id: "dark", label: "Dark Luxe", c1: "#0e0e0c", c2: "#c9a876" },
    { id: "light", label: "Cream", c1: "#f5f0e6", c2: "#9a7a42" },
    { id: "coastal", label: "Coastal", c1: "#0a1620", c2: "#d9be8e" },
  ];

  return (
    <div className={`tweaks-panel${visible ? " visible" : ""}`}>
      <h3>Tweaks</h3>
      <div className="tweak-row">
        <label>Paleta</label>
        <div className="tweak-swatches">
          {palettes.map(p => (
            <div key={p.id}
              className={`tweak-swatch${tweaks.palette === p.id ? " active" : ""}`}
              style={{ background: `linear-gradient(135deg, ${p.c1} 60%, ${p.c2} 60%)` }}
              onClick={() => setTweaks(t => ({ ...t, palette: p.id }))}
              title={p.label}
            />
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <label>Estilo del hero</label>
        <Dropdown ariaLabel="Estilo del hero"
          value={tweaks.hero}
          onChange={e => setTweaks(t => ({ ...t, hero: e.target.value }))}
          options={[
            { value: "fullbleed", label: "Full-bleed" },
            { value: "typographic", label: "Tipográfico (sin imagen)" },
            { value: "split", label: "Dividido (imagen lateral)" },
          ]} />
      </div>
      <div className="tweak-row">
        <label>Tarjetas de propiedad</label>
        <Dropdown ariaLabel="Tarjetas de propiedad"
          value={tweaks.cards}
          onChange={e => setTweaks(t => ({ ...t, cards: e.target.value }))}
          options={[
            { value: "editorial", label: "Mosaico editorial" },
            { value: "uniform", label: "Grid uniforme" },
            { value: "list", label: "Listado" },
          ]} />
      </div>
      <div className="tweak-row">
        <label>Tipografía display</label>
        <Dropdown ariaLabel="Tipografía display"
          value={tweaks.display}
          onChange={e => setTweaks(t => ({ ...t, display: e.target.value }))}
          options={[
            { value: "cormorant", label: "Cormorant Garamond" },
            { value: "playfair", label: "Playfair Display" },
            { value: "italiana", label: "Italiana" },
            { value: "canela", label: "DM Serif Display" },
          ]} />
      </div>
      <div className="tweak-row">
        <label>Navegación</label>
        <Dropdown ariaLabel="Navegación"
          value={tweaks.nav}
          onChange={e => setTweaks(t => ({ ...t, nav: e.target.value }))}
          options={[
            { value: "top", label: "Top fija" },
            { value: "minimal", label: "Minimal (solo logo + WA)" },
          ]} />
      </div>
    </div>
  );
}

Object.assign(window, { PropertyModal, Contact, Footer, FavDrawer, TweaksPanel });
