function RichSegments({ segments }) {
  if (!segments) return null;
  return segments.map(function(s, i) {
    var node = s.text;
    if (s.code)          node = <code className="cs-inline-code">{node}</code>;
    if (s.bold)          node = <strong>{node}</strong>;
    if (s.italic)        node = <em>{node}</em>;
    if (s.strikethrough) node = <s>{node}</s>;
    if (s.href)          node = <a href={s.href} target="_blank" rel="noopener" className="cs-body-link">{node}</a>;
    return <React.Fragment key={i}>{node}</React.Fragment>;
  });
}

function groupBodyText(blocks) {
  var result = [];
  var currentList = null;
  (blocks || []).forEach(function(block) {
    if (block.type === "bulleted_list_item") {
      if (!currentList || currentList.listType !== "ul") {
        currentList = { listType: "ul", items: [] };
        result.push(currentList);
      }
      currentList.items.push(block);
    } else if (block.type === "numbered_list_item") {
      if (!currentList || currentList.listType !== "ol") {
        currentList = { listType: "ol", items: [] };
        result.push(currentList);
      }
      currentList.items.push(block);
    } else {
      currentList = null;
      result.push(block);
    }
  });
  return result;
}

// Case study modal — opens when a project is clicked
function CaseStudy({ project, onClose }) {
  const [activeAudio, setActiveAudio] = React.useState("main-reel");

  function toggleAudio(key) {
    setActiveAudio(function(prev) { return prev === key ? null : key; });
  }

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

  if (!project) return null;
  function toCSS(aspect) {
    var map = { "16:9": "16 / 9", "9:16": "9 / 16", "1:1": "1 / 1", "21:9": "21 / 9", "3:2": "3 / 2", "4:3": "4 / 3", "2:3": "2 / 3" };
    return map[aspect] || (aspect ? aspect.replace(":", " / ") : "16 / 9");
  }
  const mainReel = project.media ? project.media.find(function(m) { return m.kind === "video" || m.kind === "youtube"; }) : null;
  const galleryMedia = project.media ? project.media.filter(function(m, i) {
    return !(i === project.media.indexOf(mainReel));
  }) : [];

  return (
    <div className="cs-overlay" onClick={onClose}>
      <div className="cs-modal" onClick={(e) => e.stopPropagation()}>
        <header className="cs-header">
          <div className="cs-crumbs">
            <span>WORK</span>
            <span className="cs-arrow">/</span>
            <span>{project.type.join(" · ").toUpperCase()}</span>
            <span className="cs-arrow">/</span>
            <span className="cs-here">{project.title}</span>
          </div>
          <button className="cs-close" onClick={onClose} data-cursor="CLOSE">
            <span>Close</span>
          </button>
        </header>

        <div className="cs-hero" style={{ "--c": project.color, aspectRatio: toCSS(mainReel ? mainReel.aspect : project.aspect) }}>
          {mainReel && mainReel.kind === "video" && (
            <video
              className="cs-hero-video"
              src={mainReel.mp4Url}
              autoPlay
              loop
              playsInline
              muted={mainReel.forceMuted || activeAudio !== "main-reel"}
            />
          )}
          {mainReel && mainReel.kind === "youtube" && (
            <iframe
              className="cs-hero-video cs-embed-iframe"
              src={mainReel.embedUrl + "&autoplay=1&controls=1" + (mainReel.forceMuted ? "&mute=1" : "")}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
            />
          )}
          <div className="cs-hero-fx"></div>
          <div className="cs-hero-rgb"></div>
          <div className="cs-hero-corners">
            <span></span><span></span><span></span><span></span>
          </div>
          <div className="cs-hero-meta">
            <span>▶ MAIN REEL — {mainReel ? mainReel.aspect : project.aspect}</span>
            {mainReel && mainReel.kind === "video" && !mainReel.forceMuted && (
              <button className="cs-audio-btn" onClick={function(e) { e.stopPropagation(); toggleAudio("main-reel"); }}>
                {activeAudio === "main-reel" ? "◉ AUDIO" : "◎ MUTED"}
              </button>
            )}
          </div>
        </div>

        <section className="cs-titleblock">
          <div className="cs-tags">
            {project.tags.map(t => <span key={t} className="cs-tag">{t}</span>)}
          </div>
          <h1 className="cs-h1">{project.title}</h1>
          <div className="cs-summary">
            <p>{project.desc}</p>
          </div>
        </section>

        <section className="cs-info">
          {project.client        && <InfoCol label="Client"        value={project.client} />}
          {project.year          && <InfoCol label="Year"          value={project.year} />}
          {project.type?.length  > 0 && <InfoCol label="Type"     value={project.type.join(", ")} />}
          {project.location      && <InfoCol label="Location"      value={project.location} />}
          {project.collaborators?.length > 0 && <InfoCol label="Collaborators" value={project.collaborators.join(", ")} />}
          {project.tags?.length  > 0 && <InfoCol label="Technologies" value={project.tags.join(", ")} />}
          {project.projectUrl    && <InfoCol label="Project URL"   value={<a href={project.projectUrl} target="_blank" rel="noopener">{project.projectUrl}</a>} />}
        </section>

        {(project.desc || project.bodyText?.length > 0) && (
          <section className="cs-long">
            {project.desc && (
              <>
                <div className="cs-long-label">[ DESCRIPTION ]</div>
                <p className="cs-long-text">{project.desc}</p>
              </>
            )}
            {groupBodyText(project.bodyText).map(function(item, i) {
              if (item.listType === "ul") return (
                <ul key={i} className="cs-body-ul">
                  {item.items.map(function(li, j) {
                    return <li key={j} className="cs-body-li"><RichSegments segments={li.segments} /></li>;
                  })}
                </ul>
              );
              if (item.listType === "ol") return (
                <ol key={i} className="cs-body-ol">
                  {item.items.map(function(li, j) {
                    return <li key={j} className="cs-body-li"><RichSegments segments={li.segments} /></li>;
                  })}
                </ol>
              );
              var content = <RichSegments segments={item.segments} />;
              if (item.type === "heading_1") return <h2 key={i} className="cs-body-h1">{content}</h2>;
              if (item.type === "heading_2") return <h3 key={i} className="cs-body-h2">{content}</h3>;
              if (item.type === "heading_3") return <h4 key={i} className="cs-body-h3">{content}</h4>;
              if (item.type === "quote")     return <blockquote key={i} className="cs-body-quote">{content}</blockquote>;
              return <p key={i} className="cs-body-p">{content}</p>;
            })}
          </section>
        )}

        {galleryMedia.length > 0 && (
          <section className="cs-media">
            <div className="cs-media-label">Media</div>
            <div className="cs-media-grid">
              {galleryMedia.map(function(m, i) {
                var audioKey = "media-" + i;
                return (
                  <div key={i} className={`cs-media-item cs-aspect-${m.aspect.replace(":", "-")}`}>
                    {m.kind === "youtube" && (
                      <div className="cs-embed-wrap" style={{ aspectRatio: toCSS(m.aspect) }}>
                        <iframe
                          src={m.embedUrl + "&controls=1" + (m.forceMuted ? "&mute=1" : "")}
                          title={m.label}
                          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                          allowFullScreen className="cs-embed-iframe" />
                      </div>
                    )}
                    {m.kind === "video" && (
                      <div className="cs-embed-wrap" style={{ aspectRatio: toCSS(m.aspect) }}>
                        <video
                          src={m.mp4Url}
                          loop
                          autoPlay
                          playsInline
                          muted={m.forceMuted || activeAudio !== audioKey}
                          className="cs-media-video"
                        />
                        {!m.forceMuted && (
                          <button className="cs-audio-btn cs-audio-btn-gallery" onClick={function(e) { e.stopPropagation(); toggleAudio(audioKey); }}>
                            {activeAudio === audioKey ? "◉ AUDIO" : "◎ MUTED"}
                          </button>
                        )}
                      </div>
                    )}
                    {m.kind === "image" && (
                      <img src={m.url} alt={m.label} className="cs-media-img" loading="lazy" />
                    )}
                    {m.caption && <div className="cs-media-caption">{m.caption}</div>}
                  </div>
                );
              })}
            </div>
          </section>
        )}

        {(function() {
          var relWs = (window.WORKSHOPS || []).filter(function(w) {
            return w.relatedProjects && w.relatedProjects.indexOf(project.id) !== -1;
          });
          if (!relWs.length) return null;
          return (
            <section className="cs-related-ws">
              <div className="cs-related-ws-label">[ WORKSHOPS &amp; TALKS ]</div>
              {relWs.map(function(w, i) {
                var d = new Date(w.date);
                var mon = d.toLocaleString("en", { month: "short" });
                var year = d.getFullYear();
                return (
                  <a key={i} className={"cs-ws-row cs-ws-row--" + w.type.toLowerCase()} href={w.link} target="_blank" rel="noopener">
                    <span className="cs-ws-type">{w.type}</span>
                    <span className="cs-ws-title">{w.title}</span>
                    <span className="cs-ws-meta">{w.event} · {mon} {year}</span>
                    <span className="cs-ws-arrow">↗</span>
                  </a>
                );
              })}
            </section>
          );
        })()}

        <section className="cs-credits">
          <div className="cs-credits-label"></div>
          <div className="cs-credits-nav">
            <button className="cs-credits-btn" onClick={onClose}>
              <span>←</span>
              <span>Back to index</span>
            </button>
          </div>
        </section>
      </div>
    </div>
  );
}

function InfoCol({ label, value }) {
  return (
    <div className="cs-info-col">
      <div className="cs-info-label">{label}</div>
      <div className="cs-info-value">{value}</div>
    </div>
  );
}

Object.assign(window, { CaseStudy });
