/* =========================================================================
   Momentum — Referencer (realiserede cases)
   2-kolonners kort-grid med 1:1 video + fakta-liste.
   ========================================================================= */

function RefHero() {
  return (
    <section className="refp-hero">
      <div className="refp-hero__bg" />
      <div className="refp-hero__veil" />
      <div className="refp-hero__center">
        <div className="refp-hero__eyebrow">Referencer</div>
        <h1 className="refp-hero__title">
          Realiserede investeringer <em>og erfaringer</em>
        </h1>
        <p className="refp-hero__lede">
          Igennem en lang årrække har vi skabt os en erfaring, hvor vi har faciliteret, struktureret og eksekveret investeringer indenfor fast ejendom. Herunder kan du se et udpluk af de referencer og erfaringer, som vi tidligere har introduceret til vores investorkreds.
        </p>
      </div>
    </section>);

}

const TYPE_FILTERS = [
{ id: "alle", label: "Alle" },
{ id: "Udvikling", label: "Udvikling" },
{ id: "Lån", label: "Lån" },
{ id: "Investeringsejendom", label: "Investeringsejendom" },
{ id: "Lokalplan", label: "Lokalplan" },
{ id: "Renovering", label: "Renovering" }];


function RefFilters({ active, setActive, count }) {
  return (
    <div className="refp-filters">
      <div className="refp-filters__inner">
        <div className="refp-filters__count">
          <strong>{String(count).padStart(2, "0")}</strong>
          <span>{count === 1 ? "case vist" : "cases vist"}</span>
        </div>
        <div className="refp-filters__pills">
          {TYPE_FILTERS.map((f) =>
          <button
            key={f.id}
            className={"refp-pill" + (active === f.id ? " is-active" : "")}
            onClick={() => setActive(f.id)}>
            
              {f.label}
            </button>
          )}
        </div>
      </div>
    </div>);

}

function RefCard({ c, onPlay }) {
  return (
    <article className="refp-card">
      <button className="refp-video" onClick={() => onPlay(c)} aria-label={`Afspil videogennemgang af ${c.title}`}>
        <div className="refp-video__poster" style={{ backgroundImage: `url('${c.videoPoster}')` }} />
        <div className="refp-video__chrome">
          <div className="refp-video__tl">
            <span className="refp-video__length">{c.videoLength}</span>
            <span className="refp-video__chip">{c.type}</span>
          </div>
          <div className="refp-video__play-wrap">
            <div className="refp-video__play">
              <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8 5v14l11-7z" />
              </svg>
            </div>
          </div>
          <div className="refp-video__bl">
            <span className="refp-video__hint">
              Se gennemgang
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path d="M5 12h14M13 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
          </div>
        </div>
      </button>

      <div className="refp-card__body">
        <h2 className="refp-card__title">{c.title}</h2>
        <p className="refp-card__summary">{c.summary}</p>

        <div className="refp-card__divider" />

        <ul className="refp-facts">
          {c.facts.map((f, i) =>
          <li key={i} className="refp-facts__row">
              <span className="refp-facts__label">{f.label}</span>
              <span className="refp-facts__value">{f.value}</span>
            </li>
          )}
        </ul>

        <button className="refp-card__btn" onClick={() => onPlay(c)}>
          Læs mere
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M5 12h14M13 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>
    </article>);

}

function RefModal({ openCase, onClose }) {
  const videoRef = React.useRef(null);
  const hlsRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);

  React.useEffect(() => {
    if (!openCase) return;
    // Esc lukker modal — men kun når vi ikke er i fuldskærm (der lukker Esc fuldskærm)
    const onKey = (e) => { if (e.key === "Escape" && !document.fullscreenElement && !document.webkitFullscreenElement) onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [openCase, onClose]);

  // Nulstil afspilning + ryd HLS-stream op, når casen skifter eller modal lukkes
  React.useEffect(() => {
    setPlaying(false);
    return () => {
      if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
      const v = videoRef.current;
      if (v) {
        try { v.pause(); } catch (e) {}
        v.removeAttribute("src");
        delete v.dataset.srcAttached;
        try { v.load(); } catch (e) {}
      }
    };
  }, [openCase && openCase.id]);

  if (!openCase) return null;
  const c = openCase;

  const attachStream = () => {
    const v = videoRef.current;
    if (!v || !c.videoUrl || v.dataset.srcAttached) return;
    if (v.canPlayType("application/vnd.apple.mpegurl")) {
      // Native HLS (Safari / iOS)
      v.src = c.videoUrl;
      v.dataset.srcAttached = "1";
    } else if (window.Hls && window.Hls.isSupported()) {
      const hls = new window.Hls({ enableWorker: true });
      hls.loadSource(c.videoUrl);
      hls.attachMedia(v);
      hlsRef.current = hls;
      v.dataset.srcAttached = "1";
    } else {
      v.src = c.videoUrl; // sidste udvej
      v.dataset.srcAttached = "1";
    }
  };

  const handlePlay = () => {
    setPlaying(true);
    attachStream();
    const v = videoRef.current;
    if (v) {
      try { const p = v.play(); if (p && p.catch) p.catch(() => {}); } catch (e) {}
    }
  };

  return (
    <div className={"refp-modal" + (openCase ? " is-open" : "")} role="dialog" aria-modal="true" onClick={(e) => { if (e.target.classList.contains("refp-modal")) onClose(); }}>
      <div className="refp-modal__inner">
        <button className="refp-modal__close" onClick={onClose} aria-label="Luk">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M6 6l12 12M18 6L6 18" strokeLinecap="round" />
          </svg>
        </button>

        <div className="refp-modal__video">
          <video
            ref={videoRef}
            poster={c.videoPoster}
            controls={playing}
            playsInline
            preload="none" />

          <span className={"refp-modal__videolen" + (playing ? " is-hidden" : "")}>{c.videoLength}</span>
          <button className={"refp-modal__playbtn" + (playing ? " is-hidden" : "")} onClick={handlePlay} aria-label="Afspil">
            <span className="core">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8 5v14l11-7z" />
              </svg>
            </span>
          </button>
        </div>

        <div className="refp-modal__side">
          <div className="refp-modal__eyebrow"><span className="dot" />{c.type}</div>
          <h3 className="refp-modal__title">{c.title}</h3>
          <p className="refp-modal__summary">{c.summary}</p>

          <ul className="refp-modal__facts">
            {c.facts.map((f, i) =>
            <li key={i} className="refp-modal__factrow">
                <span className="refp-modal__factlabel">{f.label}</span>
                <span className="refp-modal__factvalue">{f.value}</span>
              </li>
            )}
          </ul>
        </div>
      </div>
    </div>);

}

function ReferencerPage() {
  const all = (window.BJG_CLOSED_CASES || []).filter((c) => !c.hidden);
  const [filter, setFilter] = React.useState("alle");
  const [openCase, setOpenCase] = React.useState(null);

  const filtered = filter === "alle" ? all : all.filter((c) => c.type === filter);

  return (
    <>
      <SiteNav />
      <RefHero />
      <RefFilters active={filter} setActive={setFilter} count={filtered.length} />

      <section className="refp-list">
        <div className="refp-list__inner">
          {filtered.length === 0 ?
          <div className="refp-empty">Ingen cases under dette filter.</div> :

          <div className="refp-grid">
              {filtered.map((c) =>
            <RefCard key={c.id} c={c} onPlay={setOpenCase} />
            )}
            </div>
          }
        </div>
      </section>

      <Signup />
      <Footer />

      <RefModal openCase={openCase} onClose={() => setOpenCase(null)} />
    </>);

}

Object.assign(window, { ReferencerPage });
