/* global React, LINKS, Icon */
const { useState, useEffect, useRef } = React;

/* ============== Modal shell ============== */
function Modal({ open, onClose, children, className = "", labelClose = "Cerrar" }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") 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 className="mdl-overlay" onClick={onClose}>
      <div className={`mdl-card ${className}`} onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="mdl-close" onClick={onClose} aria-label={labelClose}>{Icon.close(18)}</button>
        {children}
      </div>
    </div>);
}

/* ============== About modal (sells) ============== */
function AboutModal({ t, lang, open, onClose }) {
  const m = t.modals.about;
  const waHref = `https://wa.me/${LINKS.whatsapp}?text=${encodeURIComponent(
    lang === "es" ? "Hola Guillermina, me gustaría agendar mi primera cita." : "Hi Guillermina, I'd like to book my first session.")}`;
  return (
    <Modal open={open} onClose={onClose} className="mdl-about" labelClose={t.modals.close}>
      <div className="ab-grid">
        <aside className="ab-side">
          <div className="ab-portrait">
            <img src="assets/foto guillermina con titulo.jpeg" alt="Lic. Guillermina Gómez" loading="lazy" />
          </div>
          <div className="ab-stats">
            {t.about.stats.map((s, i) =>
              <div key={i} className="ab-stat">
                <div className="n">{s.n}</div>
                <div className="l">{s.l}</div>
              </div>
            )}
          </div>
          <a className="btn btn-sage ab-cta" href={waHref} target="_blank" rel="noopener noreferrer">
            {m.cta} {Icon.arrow()}
          </a>
        </aside>

        <div className="ab-main">
          <span className="eyebrow">{m.eyebrow}</span>
          <h2 className="ab-title">{m.title.split("\n").map((l, i) => <React.Fragment key={i}>{l}<br/></React.Fragment>)}</h2>
          <p className="ab-intro">{m.intro}</p>
          <div className="ab-bio">
            <p>{t.about.p1}</p>
            <p>{t.about.p2}</p>
            <p>{t.about.p3}</p>
            <p>{t.about.p4}</p>
          </div>

          <div className="ab-cred">
            <span className="eyebrow">{m.credTitle}</span>
            <div className="ab-cred-groups">
              {t.about.credGroups.map((g, i) =>
                <div key={i} className="ab-cred-group">
                  <h4>{g.h}</h4>
                  <ul>{g.items.map((it, j) => <li key={j}>{it}</li>)}</ul>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </Modal>);
}

/* ============== Testimonials modal (3 moving) ============== */
function TestimonialsModal({ t, open, onClose }) {
  const items = t.testimonials.items;
  const m = t.modals.testimonials;
  const [idx, setIdx] = useState(0);
  const [perView, setPerView] = useState(1);

  useEffect(() => {
    const calc = () => {
      const w = window.innerWidth;
      setPerView(w < 600 ? 1 : 1.08);
    };
    calc();
    window.addEventListener("resize", calc);
    return () => window.removeEventListener("resize", calc);
  }, []);

  const maxIdx = Math.max(0, Math.ceil(items.length - perView));
  useEffect(() => { setIdx((i) => Math.min(i, maxIdx)); }, [maxIdx]);
  useEffect(() => {
    if (!open) return;
    const id = setInterval(() => setIdx((i) => (i >= maxIdx ? 0 : i + 1)), 4500);
    return () => clearInterval(id);
  }, [open, maxIdx]);

  return (
    <Modal open={open} onClose={onClose} className="mdl-tst" labelClose={t.modals.close}>
      <div className="mdl-head">
        <span className="eyebrow">{m.eyebrow}</span>
        <h2>{m.title}</h2>
        <p className="lead">{m.sub}</p>
      </div>

      <div className="tcar2">
        <div className="tcar2-viewport">
          <div className="tcar2-track" style={{ transform: `translateX(calc(-${idx} * (100% / ${perView})))` }}>
            {items.map((tt, i) =>
              <div key={i} className="tcar2-slide" style={{ flexBasis: `calc(100% / ${perView})` }}>
                <div className="testimonial">
                  <div className="t-top">
                    <span className="qmark">"</span>
                    {tt.tag && <span className="t-tag">{tt.tag}</span>}
                  </div>
                  <p className="quote">{tt.q}</p>
                  <div className="att">
                    <div className="att-avatar">{tt.a.slice(0, 1)}</div>
                    <div className="att-meta"><strong>{tt.a}</strong><span>{tt.loc}</span></div>
                    <div className="att-stars">{"★★★★★"}</div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="tcar-controls">
          <div className="tcar-dots">
            {Array.from({ length: maxIdx + 1 }).map((_, i) =>
              <button key={i} className={`tcar-dot ${i === idx ? "active" : ""}`} onClick={() => setIdx(i)} aria-label={`Slide ${i + 1}`}></button>
            )}
          </div>
          <div className="tcar-arrows">
            <button className="c-arr" onClick={() => setIdx((i) => Math.max(0, i - 1))} disabled={idx === 0}>{Icon.chev("left")}</button>
            <button className="c-arr" onClick={() => setIdx((i) => Math.min(maxIdx, i + 1))} disabled={idx === maxIdx}>{Icon.chev("right")}</button>
          </div>
        </div>
      </div>
    </Modal>);
}

/* ============== Credentials / Formación modal ============== */
function CredentialsModal({ t, open, onClose }) {
  const m = t.modals.credentials;
  return (
    <Modal open={open} onClose={onClose} className="mdl-cred" labelClose={t.modals.close}>
      <div className="mdl-head">
        <span className="eyebrow">{m.eyebrow}</span>
        <h2>{m.title}</h2>
        <p className="lead">{m.sub}</p>
      </div>

      <div className="cred-section">
        <h4 className="cred-h">{m.institutionsTitle}</h4>
        <div className="inst-grid">
          {t.trust.items.map((it, i) =>
            <div key={i} className="inst-chip">{it}</div>
          )}
        </div>
      </div>

      <div className="cred-section">
        <h4 className="cred-h">{t.modals.about.credTitle}</h4>
        <div className="ab-cred-groups">
          {t.about.credGroups.map((g, i) =>
            <div key={i} className="ab-cred-group">
              <h4>{g.h}</h4>
              <ul>{g.items.map((it, j) => <li key={j}>{it}</li>)}</ul>
            </div>
          )}
        </div>
      </div>
    </Modal>);
}

Object.assign(window, { Modal, AboutModal, TestimonialsModal, CredentialsModal });
