/* global React */
const { useEffect, useCallback } = React;

// Resolve bilingual { fr, en } values (mirrors the helper in sections.jsx)
const tl = (obj, lang) => (typeof obj === "string" ? obj : obj?.[lang] ?? obj?.fr ?? "");

// ─────────────────────────────────────────────────────────────────────
// Modal — generic shell. Handles overlay, close, esc, body lock.
// ─────────────────────────────────────────────────────────────────────
function Modal({ open, onClose, children, labelledBy }) {
  const handleKey = useCallback(
    (e) => { if (e.key === "Escape") onClose(); },
    [onClose]
  );

  useEffect(() => {
    if (!open) return;
    document.addEventListener("keydown", handleKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", handleKey);
      document.body.style.overflow = prev;
    };
  }, [open, handleKey]);

  if (!open) return null;

  return (
    <div
      className="modal-backdrop"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-labelledby={labelledBy}
    >
      <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        {children}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// DetailModal — renders a `details` object from data.js
// Used by both projects and experiences.
//
// Props:
//   open, onClose       — modal state
//   lang                — "fr" | "en"
//   kicker              — small label above the title (e.g. "Projet · 2025")
//   title               — main heading
//   subtitle            — optional one-liner below the title
//   stack               — optional list of tech chips (from project.stack)
//   tags                — optional list of tag chips
//   details             — the `details` object from data.js (see schema)
// ─────────────────────────────────────────────────────────────────────
function DetailModal({ open, onClose, lang, kicker, title, subtitle, stack, tags, details }) {
  const d = details || {};
  const lbl = title ? `modal-title-${String(title).replace(/\s+/g, "-").toLowerCase()}` : undefined;

  return (
    <Modal open={open} onClose={onClose} labelledBy={lbl}>
      {/* HERO */}
      {d.cover ? (
        <div className="modal-cover">
          <img src={d.cover} alt="" />
        </div>
      ) : null}

      <div className="modal-head">
        {kicker ? <div className="modal-kicker">{kicker}</div> : null}
        {title ? <h2 id={lbl} className="modal-title">{title}</h2> : null}
        {subtitle ? <p className="modal-subtitle">{subtitle}</p> : null}

        {(stack && stack.length) || (tags && tags.length) ? (
          <div className="modal-chips">
            {stack && stack.map((s) => (
              <span key={`s-${s}`} className="chip-stack">{s}</span>
            ))}
            {tags && tags.map((t) => (
              <span key={`t-${t}`} className="chip-tag">#{t}</span>
            ))}
          </div>
        ) : null}

        {d.links && d.links.length ? (
          <div className="modal-cta">
            {d.links.map((l, i) => (
              <a
                key={i}
                href={l.url}
                target={l.url && l.url !== "#" ? "_blank" : undefined}
                rel="noreferrer"
                className={`btn ${l.primary ? "primary" : ""}`}
              >
                {tl(l.label, lang)}
                <span className="arr">↗</span>
              </a>
            ))}
          </div>
        ) : null}
      </div>

      <div className="modal-body">
        {/* META FACTS */}
        {d.meta && d.meta.length ? (
          <dl className="modal-facts">
            {d.meta.map((f, i) => (
              <div key={i}>
                <dt>{tl(f.k, lang)}</dt>
                <dd>{tl(f.v, lang)}</dd>
              </div>
            ))}
          </dl>
        ) : null}

        {/* SECTIONS (heading + paragraphs) */}
        {d.sections && d.sections.map((sec, i) => (
          <section key={`sec-${i}`} className="modal-section">
            {sec.heading ? <h3>{tl(sec.heading, lang)}</h3> : null}
            {(sec.body || []).map((p, j) => (
              <p key={j}>{tl(p, lang)}</p>
            ))}
          </section>
        ))}

        {/* BULLETS (heading + list) */}
        {d.bullets && d.bullets.map((b, i) => (
          <section key={`b-${i}`} className="modal-section">
            {b.heading ? <h3>{tl(b.heading, lang)}</h3> : null}
            <ul className="modal-list">
              {(b.items || []).map((it, j) => (
                <li key={j}>{tl(it, lang)}</li>
              ))}
            </ul>
          </section>
        ))}

        {/* GALLERY */}
        {d.gallery && d.gallery.length ? (
          <section className="modal-section">
            <div className="modal-gallery">
              {d.gallery.map((g, i) => (
                <figure key={i}>
                  <img src={g.src} alt={tl(g.alt, lang)} />
                  {g.alt ? <figcaption>{tl(g.alt, lang)}</figcaption> : null}
                </figure>
              ))}
            </div>
          </section>
        ) : null}

        {/* Empty-state fallback (no details object on this entry) */}
        {!details ? (
          <p className="modal-empty">
            {lang === "fr"
              ? "Plus de détails à venir bientôt — en attendant, n'hésite pas à me contacter."
              : "More details coming soon — in the meantime, feel free to reach out."}
          </p>
        ) : null}
      </div>
    </Modal>
  );
}

Object.assign(window, { Modal, DetailModal });
