// Portfolio — section → category (expandable) → client → sub-folder → video

const Folder = ({ category, isOpen, onToggle }) => {
  return (
    <div
      className={"mr-folder" + (isOpen ? " is-open" : "")}
      onClick={onToggle}
      role="button"
      tabIndex={0}
      aria-expanded={isOpen}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onToggle(); } }}
    >
      {category.coverImage ? (
        <div className="mr-folder-cover" style={{ backgroundImage: `url(${category.coverImage})` }} />
      ) : (
        <div className={`mr-folder-fill ${category.accent || "ink"}`} />
      )}
      <div className="mr-folder-grain" />
      <div className="mr-folder-cta" aria-hidden="true">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          {isOpen ? (
            <polyline points="6 15 12 9 18 15" />
          ) : (
            <polyline points="6 9 12 15 18 9" />
          )}
        </svg>
      </div>
      <div className="mr-folder-content">
        <div className="mr-folder-meta">
          <span>{category.idx}</span>
          <span className="yt-tag">
            <span>{category.clients.length} {category.clients.length === 1 ? "client" : "clients"}</span>
          </span>
        </div>
        <div className="mr-folder-name-center">
          <div className="mr-folder-name">{category.name}</div>
        </div>
        <div className="mr-folder-desc">{category.description}</div>
      </div>
    </div>
  );
};

// Sub-item row inside a project's subfolder
const SubRow = ({ item, sectionName, categoryName, onOpen }) => (
  <div
    className="mr-client-row"
    onClick={() => onOpen({ ...item, sectionName, categoryName })}
    role="button"
    tabIndex={0}
    onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen({ ...item, sectionName, categoryName }); } }}
  >
    <div className="mr-client-thumb">
      <div className="mr-client-play" aria-hidden="true">
        <span className="play-tri" />
      </div>
    </div>
    <div className="mr-client-text">
      <div className="mr-client-name">{item.name}</div>
      {item.description && <div className="mr-client-desc">{item.description}</div>}
    </div>
    <div className="mr-client-arrow" aria-hidden="true">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <line x1="7" y1="17" x2="17" y2="7" />
        <polyline points="8 7 17 7 17 16" />
      </svg>
    </div>
  </div>
);

// Subfolder panel shown when a project with sub-items is selected
const SubPanel = ({ client, sectionName, categoryName, onOpen, onBack, onClose }) => (
  <div className="mr-client-panel mr-sub-panel" data-accent="warm">
    <div className="mr-client-panel-head">
      <div className="mr-sub-panel-nav">
        <button className="mr-sub-back-btn" onClick={onBack} aria-label="Back to projects">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="19" y1="12" x2="5" y2="12" />
            <polyline points="12 19 5 12 12 5" />
          </svg>
        </button>
        <div>
          <span className="mr-eyebrow">{categoryName} · {client.name}</span>
        </div>
      </div>
      <button className="mr-client-panel-close" onClick={onClose} aria-label="Close">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <line x1="6" y1="6" x2="18" y2="18" />
          <line x1="18" y1="6" x2="6" y2="18" />
        </svg>
      </button>
    </div>
    <div className="mr-client-list">
      {client.sub.map((s) => (
        <SubRow
          key={s.name}
          item={s}
          sectionName={sectionName}
          categoryName={`${categoryName} · ${client.name}`}
          onOpen={onOpen}
        />
      ))}
    </div>
  </div>
);

// Client row — shows folder icon if it has sub-items, play button otherwise, or photo icon
const ClientRow = ({ client, sectionName, categoryName, onOpen, onSubOpen, onPhotoOpen, thumbIcon }) => {
  const hasSub = client.sub && client.sub.length > 0;
  const hasPhotos = client.photos && client.photos.length > 0;
  const handleClick = () => {
    if (hasPhotos) return onPhotoOpen(client);
    if (hasSub) return onSubOpen(client);
    onOpen({ ...client, sectionName, categoryName });
  };

  return (
    <div
      className={"mr-client-row" + (hasSub ? " has-sub" : "")}
      onClick={handleClick}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); handleClick(); } }}
    >
      <div className="mr-client-thumb">
        {thumbIcon ? (
          <div className="mr-client-custom-icon" aria-hidden="true">
            <img src={thumbIcon} alt="" width="28" height="28" />
          </div>
        ) : hasPhotos ? (
          <div className="mr-client-photo-icon" aria-hidden="true">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
              <circle cx="8.5" cy="8.5" r="1.5"/>
              <polyline points="21 15 16 10 5 21"/>
            </svg>
          </div>
        ) : hasSub ? (
          <div className="mr-client-subfolder-icon" aria-hidden="true">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
            </svg>
          </div>
        ) : (
          <div className="mr-client-play" aria-hidden="true">
            <span className="play-tri" />
          </div>
        )}
      </div>
      <div className="mr-client-text">
        <div className="mr-client-name">{client.name}</div>
        {client.description && <div className="mr-client-desc">{client.description}</div>}
      </div>
        <div className="mr-client-arrow" aria-hidden="true">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <line x1="7" y1="17" x2="17" y2="7" />
          <polyline points="8 7 17 7 17 16" />
        </svg>
      </div>
    </div>
  );
};

// Category panel — expands below the folder grid row. Handles sub-panel navigation.
const ClientPanel = ({ category, sectionName, onOpen, onClose, onPhotoOpen }) => {
  const [openSub, setOpenSub] = React.useState(null);

  if (openSub) {
    return (
      <SubPanel
        client={openSub}
        sectionName={sectionName}
        categoryName={category.name}
        onOpen={onOpen}
        onBack={() => setOpenSub(null)}
        onClose={onClose}
      />
    );
  }

  return (
    <div className="mr-client-panel" data-accent={category.accent || "ink"}>
      <div className="mr-client-panel-head">
        <div>
          <span className="mr-eyebrow">{sectionName} · {category.name}</span>
          <h3 className="mr-client-panel-title">{category.clients.length} {category.clients.length === 1 ? "project" : "projects"} in {category.name}</h3>
        </div>
        <button className="mr-client-panel-close" onClick={onClose} aria-label="Collapse">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <line x1="6" y1="6" x2="18" y2="18" />
            <line x1="18" y1="6" x2="6" y2="18" />
          </svg>
        </button>
      </div>
      <div className="mr-client-list">
        {category.clients.map((c) => (
          <ClientRow
            key={c.name}
            client={c}
            sectionName={sectionName}
            categoryName={category.name}
            onOpen={onOpen}
            onSubOpen={setOpenSub}
            onPhotoOpen={onPhotoOpen}
            thumbIcon={category.clientThumb}
          />
        ))}
      </div>
    </div>
  );
};

const PortfolioSection = ({ section, openCat, setOpenCat, onOpen, onPhotoOpen }) => {
  const cats = section.categories.map((c, i) => ({
    ...c,
    idx: String(i + 1).padStart(2, "0"),
  }));
  const openIndex = openCat && openCat.sectionId === section.id ? openCat.catIndex : -1;
  const openCategory = openIndex >= 0 ? cats[openIndex] : null;

  // Insertion index: snap to the end of the row containing the open folder.
  // We measure columns at runtime so it works at any breakpoint.
  const gridRef = React.useRef(null);
  const [insertAfter, setInsertAfter] = React.useState(-1);

  React.useLayoutEffect(() => {
    if (openIndex < 0 || !gridRef.current) { setInsertAfter(-1); return; }
    const compute = () => {
      const grid = gridRef.current;
      if (!grid) return;
      const w = grid.clientWidth;
      const styles = getComputedStyle(grid);
      const cols = styles.gridTemplateColumns.split(" ").length || 1;
      const rowEnd = Math.min(cats.length - 1, Math.floor(openIndex / cols) * cols + cols - 1);
      setInsertAfter(rowEnd);
    };
    compute();
    window.addEventListener("resize", compute);
    return () => window.removeEventListener("resize", compute);
  }, [openIndex, cats.length]);

  return (
    <div className="mr-portfolio-section" id={section.id}>
      <div className="mr-portfolio-section-head">
        <h2 className="mr-portfolio-section-title">
          <span className="idx">({section.index})</span>
          {section.name}
        </h2>
        <p className="mr-portfolio-section-desc">{section.description}</p>
      </div>
      <div className="mr-folders" ref={gridRef}>
        {cats.map((c, i) => (
          <React.Fragment key={c.name}>
            <Folder
              category={c}
              isOpen={i === openIndex}
              onToggle={() => {
                if (i === openIndex) setOpenCat(null);
                else setOpenCat({ sectionId: section.id, catIndex: i });
              }}
            />
            {i === insertAfter && openCategory && (
              <ClientPanel
                category={openCategory}
                sectionName={section.name}
                onOpen={onOpen}
                onClose={() => setOpenCat(null)}
                onPhotoOpen={onPhotoOpen}
              />
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

const PortfolioBlock = ({ portfolio, onOpen }) => {
  const [openCat, setOpenCat] = React.useState(null);
  const [photoClient, setPhotoClient] = React.useState(null);
  const totalCats = portfolio.sections.reduce((n, s) => n + s.categories.length, 0);
  const totalClients = portfolio.sections.reduce(
    (n, s) => n + s.categories.reduce((m, c) => m + c.clients.length, 0), 0
  );
  return (
    <section id="work" className="mr-portfolio" data-screen-label="work" data-comment-anchor="work">
      <div className="mr-section">
        <div className="mr-section-eyebrow-row">
          <span className="meta">Work · Index</span>
          <span className="meta">{totalCats} folders · {totalClients} projects</span>
        </div>
        <h2 className="mr-section-headline">{portfolio.intro.title}</h2>
        <p className="mr-section-lead">{portfolio.intro.description}</p>
      </div>
      {portfolio.sections.map((s) => (
        <PortfolioSection
          key={s.id}
          section={s}
          openCat={openCat}
          setOpenCat={setOpenCat}
          onOpen={onOpen}
          onPhotoOpen={setPhotoClient}
        />
      ))}
      <PhotoGallery
        open={!!photoClient}
        client={photoClient}
        onClose={() => setPhotoClient(null)}
      />
    </section>
  );
};

const VideoModal = ({ open, client, onClose }) => {
  React.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 || !client) return null;

  const creditsEntries = client.credits ? Object.entries(client.credits) : [];
  const enParas = client.descriptionEn ? client.descriptionEn.split("\n\n") : [];
  const esParas = client.descriptionEs ? client.descriptionEs.split("\n\n") : [];
  // Fallback for items without bilingual fields
  const legacyParas = client.description ? client.description.split("\n\n") : [];
  const hasBilingual = enParas.length > 0 || esParas.length > 0;

  return (
    <div className="mr-modal-scrim" onClick={onClose}>
      <div className="mr-modal" onClick={(e) => e.stopPropagation()}>

        {/* Video embed — first, portrait 9:16 */}
        <div className="mr-modal-video">
          <div className="mr-modal-video-inner">
            <iframe
              src={`https://www.youtube.com/embed/${client.ytId}?autoplay=1&rel=0&modestbranding=1`}
              title={client.name}
              allow="autoplay; encrypted-media; fullscreen"
              allowFullScreen
            />
          </div>
        </div>

        {/* Text: header + about */}
        <div className="mr-modal-scroll">
          <div className="mr-modal-header">
            <div>
              <div className="mr-modal-meta">{client.sectionName} · {client.categoryName} · {client.year}</div>
              <div className="mr-modal-title">{client.name}</div>
            </div>
            <button className="mr-modal-close" onClick={onClose} aria-label="Close">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                <line x1="6" y1="6" x2="18" y2="18" />
                <line x1="18" y1="6" x2="6" y2="18" />
              </svg>
            </button>
          </div>

          {(hasBilingual || legacyParas.length > 0) && (
            <div className="mr-modal-body">
              {hasBilingual ? (
                <div className="mr-modal-about-bilingual">
                  {enParas.length > 0 && (
                    <div className="mr-modal-about">
                      <span className="mr-modal-section-label">About — EN</span>
                      <div className="mr-modal-desc">
                        {enParas.map((p, i) => <p key={i}>{p}</p>)}
                      </div>
                    </div>
                  )}
                  {esParas.length > 0 && (
                    <div className="mr-modal-about">
                      <span className="mr-modal-section-label">About — ES</span>
                      <div className="mr-modal-desc">
                        {esParas.map((p, i) => <p key={i}>{p}</p>)}
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="mr-modal-about">
                  <span className="mr-modal-section-label">About</span>
                  <div className="mr-modal-desc">
                    {legacyParas.map((p, i) => <p key={i}>{p}</p>)}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Campaign design frame — below text */}
        {client.heroFrame && (
          <div className="mr-modal-hero-frame">
            <iframe
              src={client.heroFrame}
              title={`${client.name} — campaign`}
              scrolling="no"
            />
          </div>
        )}

        {/* Credits — always last */}
        {creditsEntries.length > 0 && (
          <div className="mr-modal-credits">
            <span className="mr-modal-section-label">Credits</span>
            <div className="mr-modal-credits-list">
              {creditsEntries.map(([label, value]) => (
                <div key={label} className="mr-modal-credit-row">
                  <span className="mr-modal-credit-label">{label}</span>
                  <span className="mr-modal-credit-value">{value}</span>
                </div>
              ))}
            </div>
          </div>
        )}

      </div>
    </div>
  );
};

Object.assign(window, { PortfolioBlock, VideoModal });
