/* ResourceCenter.jsx — Main resource center component shared by
 * recursos-legales and recursos-tecnicos pages. Search, filters,
 * compact list view with pagination, and ranked lists.
 */
function ResourceCenter({ variant, eyebrow, heading, lede }) {
  const [allResources, setAllResources] = React.useState([]);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [debouncedQuery, setDebouncedQuery] = React.useState("");
  const [activeCategory, setActiveCategory] = React.useState("all");
  const [categories, setCategories] = React.useState([]);
  const [mostDownloaded, setMostDownloaded] = React.useState([]);
  const [mostViewed, setMostViewed] = React.useState([]);
  const [toast, setToast] = React.useState(null);
  const [page, setPage] = React.useState(1);
  const PER_PAGE = 12;

  const type = variant === "tecnico" ? "tecnico" : "legal";
  const accentVar = variant === "tecnico" ? "var(--hl-green-500)" : "var(--hl-blue-500)";

  function reload() {
    setAllResources(ResourceStore.getAll(type));
    setCategories(ResourceStore.getCategories(type));
    setMostDownloaded(ResourceStore.getMostDownloaded(type, 5));
    setMostViewed(ResourceStore.getMostViewed(type, 5));
  }

  React.useEffect(() => { reload(); }, []);

  React.useEffect(() => {
    const t = setTimeout(() => { setDebouncedQuery(searchQuery); setPage(1); }, 250);
    return () => clearTimeout(t);
  }, [searchQuery]);

  React.useEffect(() => { setPage(1); }, [activeCategory]);

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });

  React.useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2500);
    return () => clearTimeout(t);
  }, [toast]);

  const filtered = React.useMemo(() => {
    let items = allResources;
    if (debouncedQuery) {
      const q = debouncedQuery.toLowerCase();
      items = items.filter(d => d.name.toLowerCase().includes(q));
    }
    if (activeCategory !== "all") {
      items = items.filter(d => d.category === activeCategory);
    }
    return items;
  }, [allResources, debouncedQuery, activeCategory]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PER_PAGE));
  const currentPage = Math.min(page, totalPages);
  const paged = filtered.slice((currentPage - 1) * PER_PAGE, currentPage * PER_PAGE);
  const startIdx = (currentPage - 1) * PER_PAGE + 1;
  const endIdx = Math.min(currentPage * PER_PAGE, filtered.length);

  function pageNumbers() {
    const pages = [];
    const maxVisible = 5;
    let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
    let end = start + maxVisible - 1;
    if (end > totalPages) { end = totalPages; start = Math.max(1, end - maxVisible + 1); }
    if (start > 1) { pages.push(1); if (start > 2) pages.push("..."); }
    for (let i = start; i <= end; i++) pages.push(i);
    if (end < totalPages) { if (end < totalPages - 1) pages.push("..."); pages.push(totalPages); }
    return pages;
  }

  const goPage = (p) => {
    setPage(p);
    document.querySelector(".rc-list-section")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const handleDownload = (e, doc) => {
    e.stopPropagation();
    ResourceStore.incrementDownloads(doc.id);
    if (doc.fileUrl) {
      window.open(doc.fileUrl, "_blank", "noopener");
    } else {
      setToast("Este documento estara disponible proximamente");
    }
    reload();
  };

  const handleView = (doc) => {
    ResourceStore.incrementViews(doc.id);
    if (doc.fileUrl) {
      window.open(doc.fileUrl, "_blank", "noopener");
    }
    reload();
  };

  const breadcrumbLabel = variant === "tecnico" ? "Recursos Tecnicos" : "Recursos Legales";
  const iconName = variant === "tecnico" ? "file-bar-chart" : "file-text";

  return (
    <>
      <div className="int-container">
        <nav className="int-breadcrumb" aria-label="Breadcrumb" style={{ paddingTop: 28 }}>
          <a href="index.html">Inicio</a>
          <span className="sep">/</span>
          <span className="current">{breadcrumbLabel}</span>
        </nav>
      </div>

      <section className="int-section rc-list-section">
        <div className="int-container">
          <div className="int-section-head center">
            {eyebrow && (
              <p className="eyebrow">
                <span className="dot" style={{ background: accentVar }} />
                {eyebrow}
              </p>
            )}
            <h2>{heading}</h2>
            {lede && <p>{lede}</p>}
          </div>

          {/* Search bar */}
          <div className="rc-search-wrap">
            <span className="rc-search-icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
            </span>
            <input
              className="rc-search-input"
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Buscar recurso por nombre..."
              aria-label="Buscar recursos"
            />
            {searchQuery && (
              <button className="rc-search-clear" onClick={() => setSearchQuery("")} aria-label="Limpiar busqueda">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
              </button>
            )}
          </div>

          {/* Category chips */}
          {categories.length > 0 && (
            <div className="rc-filters" role="tablist" aria-label="Filtrar por categoria">
              <button
                className={"rc-chip" + (activeCategory === "all" ? " active" : "")}
                onClick={() => setActiveCategory("all")}
                role="tab"
                aria-selected={activeCategory === "all"}
              >
                Todos
              </button>
              {categories.map(cat => (
                <button
                  key={cat}
                  className={"rc-chip" + (activeCategory === cat ? " active" : "")}
                  onClick={() => setActiveCategory(cat)}
                  role="tab"
                  aria-selected={activeCategory === cat}
                >
                  {cat}
                </button>
              ))}
            </div>
          )}

          {/* Count */}
          <div className="rc-list-bar">
            <p className="rc-count">
              {filtered.length > 0
                ? <>Mostrando {startIdx}–{endIdx} de {filtered.length} recursos</>
                : <>0 recursos</>
              }
            </p>
          </div>

          {/* Resource list — compact rows */}
          {paged.length > 0 ? (
            <div className="rc-list">
              {/* Table header */}
              <div className="rc-list-head" aria-hidden="true">
                <span className="rc-lh-name">Documento</span>
                <span className="rc-lh-cat">Categoria</span>
                <span className="rc-lh-stat">Vistas</span>
                <span className="rc-lh-stat">Descargas</span>
                <span className="rc-lh-action"></span>
              </div>

              {paged.map(doc => (
                <div key={doc.id} className="rc-row" onClick={() => handleView(doc)}>
                  <div className="rc-row-icon">
                    <i data-lucide={iconName}></i>
                  </div>
                  <div className="rc-row-name">
                    <span className="rc-row-title">{doc.name}</span>
                    {doc.tags && doc.tags.length > 0 && (
                      <span className="rc-row-tags">
                        {doc.tags.slice(0, 3).map(t => <span key={t}>{t}</span>)}
                      </span>
                    )}
                  </div>
                  <span className="rc-row-cat">{doc.category}</span>
                  <span className="rc-row-stat">
                    <i data-lucide="eye"></i>
                    {doc.views.toLocaleString()}
                  </span>
                  <span className="rc-row-stat">
                    <i data-lucide="download"></i>
                    {doc.downloads.toLocaleString()}
                  </span>
                  <button className="rc-row-dl" onClick={e => handleDownload(e, doc)}>
                    <i data-lucide="download"></i>
                    <span>{doc.fileUrl ? "Descargar" : "Ver"}</span>
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div className="rc-empty">
              <div className="rc-empty-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/><path d="M8 8l6 6M14 8l-6 6"/></svg>
              </div>
              <p>No se encontraron recursos con estos criterios.</p>
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <nav className="rc-pagination" aria-label="Paginacion">
              <button
                className="rc-page-btn rc-page-arrow"
                onClick={() => goPage(currentPage - 1)}
                disabled={currentPage === 1}
                aria-label="Pagina anterior"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
              </button>
              {pageNumbers().map((p, i) =>
                p === "..." ? (
                  <span key={"e" + i} className="rc-page-ellipsis">...</span>
                ) : (
                  <button
                    key={p}
                    className={"rc-page-btn" + (p === currentPage ? " active" : "")}
                    onClick={() => goPage(p)}
                    aria-current={p === currentPage ? "page" : undefined}
                  >
                    {p}
                  </button>
                )
              )}
              <button
                className="rc-page-btn rc-page-arrow"
                onClick={() => goPage(currentPage + 1)}
                disabled={currentPage === totalPages}
                aria-label="Pagina siguiente"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
              </button>
            </nav>
          )}
        </div>
      </section>

      {/* Most Downloaded */}
      {mostDownloaded.length > 0 && (
        <section className="int-section rc-ranked-section">
          <div className="int-container">
            <div className="int-section-head center">
              <p className="eyebrow">
                <span className="dot" style={{ background: accentVar }} />
                LOS MAS DESCARGADOS
              </p>
              <h2>Recursos <em className="sn-italic-accent">Populares</em></h2>
            </div>
            <div className="rc-ranked-list">
              {mostDownloaded.map((doc, i) => (
                <div key={doc.id} className="rc-ranked-item" onClick={() => handleView(doc)}>
                  <span className="rc-rank-num">{String(i + 1).padStart(2, "0")}</span>
                  <div className="rc-rank-body">
                    <p className="rc-rank-name">{doc.name}</p>
                    <span className="rc-rank-cat">{doc.category}</span>
                  </div>
                  <div className="rc-rank-count">
                    <div className="rc-rank-count-val">{doc.downloads}</div>
                    <div className="rc-rank-count-label">descargas</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Most Viewed */}
      {mostViewed.length > 0 && (
        <section className="int-section tint rc-ranked-section">
          <div className="int-container">
            <div className="int-section-head center">
              <p className="eyebrow">
                <span className="dot" style={{ background: accentVar }} />
                LOS MAS CONSULTADOS
              </p>
              <h2>Recursos mas <em className="sn-italic-accent">Vistos</em></h2>
            </div>
            <div className="rc-ranked-list">
              {mostViewed.map((doc, i) => (
                <div key={doc.id} className="rc-ranked-item" onClick={() => handleView(doc)}>
                  <span className="rc-rank-num">{String(i + 1).padStart(2, "0")}</span>
                  <div className="rc-rank-body">
                    <p className="rc-rank-name">{doc.name}</p>
                    <span className="rc-rank-cat">{doc.category}</span>
                  </div>
                  <div className="rc-rank-count">
                    <div className="rc-rank-count-val">{doc.views}</div>
                    <div className="rc-rank-count-label">vistas</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Toast */}
      {toast && <div className="rc-toast">{toast}</div>}
    </>
  );
}

Object.assign(window, { ResourceCenter });
