// Dashboard — sidebar + topbar + content (grid/list) + detail panel.
const { useState: useStateD, useMemo, useEffect, useRef } = React;

/* ------------------------------------------------------------------ */
/*  Thumb renderer                                                     */
/* ------------------------------------------------------------------ */
function Thumb({ item, large = false }) {
  const [imgError, setImgError] = useStateD(false);

  // Si hay thumbnail real en el servidor, usarlo
  if (item.thumbnail_url && !imgError) {
    return (
      <img
        src={item.thumbnail_url}
        alt={item.name}
        style={{ width: "100%", height: "100%", objectFit: "cover" }}
        onError={() => setImgError(true)}
      />
    );
  }

  // Fallback generativo basado en tipo
  const colors = {
    image: { a: "#1B1A1A", b: "#00B147" },
    pdf:   { a: "#DC2626", b: "#FEF2F2" },
    docx:  { a: "#1D4ED8", b: "#EFF6FF" },
    xlsx:  { a: "#065F46", b: "#ECFDF5" },
    pptx:  { a: "#EA580C", b: "#FFF7ED" },
    zip:   { a: "#7C3AED", b: "#F5F3FF" },
    video: { a: "#0E7490", b: "#ECFEFF" },
  };
  const c = colors[item.type] || { a: "#6B7280", b: "#F9FAFB" };

  return (
    <div className="thumb-doc" style={{ width: "100%", height: "100%", "--a": c.a, "--b": c.b }}>
      <div className="sheet">
        <div className="more"/>
        <div className="stamp">{item.type}</div>
      </div>
    </div>
  );
}

const typeIcon = (t) => ({
  pdf: "pdf", xlsx: "xlsx", docx: "docx", zip: "zip", image: "image",
}[t] || "document");

const fmtDate = (s) => {
  const d = new Date(s);
  if (isNaN(d)) return s;
  return d.toLocaleDateString("es-MX", { day: "2-digit", month: "short", year: "numeric" });
};

const fmtSize = (bytes) => {
  if (!bytes) return "—";
  if (bytes < 1024)       return bytes + " B";
  if (bytes < 1048576)    return (bytes / 1024).toFixed(1) + " KB";
  if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + " MB";
  return (bytes / 1073741824).toFixed(2) + " GB";
};

/* ------------------------------------------------------------------ */
/*  Sidebar                                                            */
/* ------------------------------------------------------------------ */
function Sidebar({ sections, folders, currentUser, sectionId, setSection, folderId, setFolder, favorites, onLogout, onOpenAdmin }) {
  return (
    <aside className="sidebar" data-screen-label="Sidebar">
      <div className="sidebar-brand">
        <div className="brand-mark">B</div>
        <div>
          <div className="brand-name">Biblioteca</div>
          <div className="brand-sub">Acervo digital</div>
        </div>
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Acervo</div>
        {sections.map(s => (
          <React.Fragment key={s.id}>
            <div
              className={"nav-item" + (sectionId === s.id ? " active" : "")}
              onClick={() => { setSection(s.id); setFolder(null); }}
            >
              <Icon name={s.icon} size={17}/>
              <span>{s.label}</span>
              <span className="count">{(s.items_count || 0).toLocaleString("es-MX")}</span>
            </div>
            {sectionId === s.id && (
              <div className="subnav">
                <div className={"sub" + (folderId === null ? " active" : "")} onClick={() => setFolder(null)}>
                  <span className="dot"/>
                  <span>Todo</span>
                  <span className="count">{(s.items_count || 0).toLocaleString("es-MX")}</span>
                </div>
                {(folders[s.id] || []).map(f => (
                  <div
                    key={f.id}
                    className={"sub" + (folderId === f.id ? " active" : "")}
                    onClick={() => setFolder(f.id)}
                  >
                    <span className="dot" style={{ background: f.color, opacity: 1 }}/>
                    <span>{f.name}</span>
                    <span className="count">{(f.items_count || 0).toLocaleString("es-MX")}</span>
                  </div>
                ))}
                <div className="sub" style={{ color: "#6E6D68", marginTop: 4 }}>
                  <Icon name="plus" size={12}/>
                  <span>Nueva carpeta</span>
                </div>
              </div>
            )}
          </React.Fragment>
        ))}
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Atajos</div>
        <div className="nav-item"><Icon name="star" size={17}/><span>Favoritos</span><span className="count">{favorites.length}</span></div>
        <div className="nav-item"><Icon name="share" size={17}/><span>Compartidos conmigo</span></div>
        <div className="nav-item"><Icon name="tag" size={17}/><span>Etiquetas</span></div>
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Sistema</div>
        <div className="nav-item" onClick={onOpenAdmin}>
          <Icon name="lock" size={17}/><span>Administración</span>
          <span className="count" style={{color:"var(--green)"}}>●</span>
        </div>
      </div>

      <div className="sidebar-foot">
        <div className="avatar" style={{background: currentUser?.avatar_color || "#374151"}}>
          {currentUser?.initials || "U"}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div className="user-name">{currentUser?.name || "Usuario"}</div>
          <div className="user-role">{currentUser?.role?.name || ""}</div>
        </div>
        <button className="icon-btn" style={{color:"#8A8A86"}} title="Cerrar sesión" onClick={onLogout}>
          <Icon name="logout" size={16}/>
        </button>
      </div>
    </aside>
  );
}

/* ------------------------------------------------------------------ */
/*  Topbar                                                             */
/* ------------------------------------------------------------------ */
function Topbar({ query, setQuery, onUpload }) {
  return (
    <div className="topbar">
      <div className="search">
        <Icon name="search" size={16} style={{color:"var(--muted)"}}/>
        <input
          value={query}
          onChange={(e)=>setQuery(e.target.value)}
          placeholder="Buscar en todo el acervo — archivos, etiquetas, autores…"
        />
        <span className="kbd">⌘ K</span>
      </div>
      <div className="topbar-actions">
        <button className="icon-btn" title="Ayuda"><Icon name="help" size={17}/></button>
        <button className="icon-btn" title="Notificaciones"><Icon name="bell" size={17}/><span className="dot-notif"/></button>
        <button className="icon-btn" title="Ajustes"><Icon name="settings" size={17}/></button>
        <div className="divider-vert"/>
        <button className="btn ghost"><Icon name="plus" size={14}/> Nueva carpeta</button>
        <button className="btn green" onClick={onUpload}><Icon name="upload" size={14}/> Subir archivo</button>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Card                                                               */
/* ------------------------------------------------------------------ */
function Card({ item, onOpen, onDownload }) {
  return (
    <div className="card" onClick={() => onOpen(item)}>
      <div className="thumb">
        <Thumb item={item}/>
        <div className="badge">{item.type}</div>
        <div className="actions">
          <button onClick={(e)=>{e.stopPropagation(); onDownload(item);}} title="Descargar"><Icon name="download" size={14}/></button>
          <button onClick={(e)=>{e.stopPropagation();}} title="Más"><Icon name="more" size={14}/></button>
        </div>
      </div>
      <div className="meta">
        <h4>{item.name}</h4>
        <div className="line">
          <span className="v">{fmtSize(item.size_bytes)}</span>
          <span className="dot-sep"/>
          <span>{fmtDate(item.updated_at)}</span>
          <span className="dot-sep"/>
          <span className="v">v{item.version}</span>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Row (list view)                                                    */
/* ------------------------------------------------------------------ */
function Row({ item, folderName, onOpen, onDownload }) {
  return (
    <div className="row" onClick={() => onOpen(item)}>
      <div className="ico"><Icon name={typeIcon(item.type)} size={18}/></div>
      <div>
        <div className="nm">{item.name}</div>
        <div className="sub">{item.description}</div>
      </div>
      <div className="tabular">{folderName}</div>
      <div><span className="pill">{item.type}</span></div>
      <div className="tabular">{fmtDate(item.updated_at)}</div>
      <div className="tabular">{fmtSize(item.size_bytes)}</div>
      <div>
        <button className="dl" onClick={(e)=>{e.stopPropagation(); onDownload(item);}} title="Descargar">
          <Icon name="download" size={14}/>
        </button>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Upload modal simplificado                                          */
/* ------------------------------------------------------------------ */
function UploadModal({ sectionId, folderId, onClose, onSuccess }) {
  const [file, setFile]         = useStateD(null);
  const [name, setName]         = useStateD("");
  const [desc, setDesc]         = useStateD("");
  const [tags, setTags]         = useStateD("");
  const [uploading, setUploading] = useStateD(false);
  const [error, setError]       = useStateD(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!file) { setError("Selecciona un archivo"); return; }
    setUploading(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("section_id", sectionId);
      if (folderId) fd.append("folder_id", folderId);
      fd.append("name", name || file.name);
      fd.append("description", desc);
      fd.append("tags", tags);
      await API.Items.upload(fd);
      onSuccess();
      onClose();
    } catch(err) {
      setError(err.message || "Error al subir el archivo");
    } finally {
      setUploading(false);
    }
  };

  return (
    <div style={{
      position:"fixed", inset:0, background:"rgba(0,0,0,0.5)", zIndex:200,
      display:"flex", alignItems:"center", justifyContent:"center",
    }} onClick={onClose}>
      <form
        style={{background:"var(--paper)", borderRadius:10, padding:28, width:460, display:"flex", flexDirection:"column", gap:14}}
        onClick={e=>e.stopPropagation()}
        onSubmit={handleSubmit}
      >
        <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:4}}>
          <strong style={{fontSize:15}}>Subir archivo</strong>
          <button type="button" className="icon-btn" onClick={onClose}><Icon name="close" size={14}/></button>
        </div>

        {error && <div style={{color:"#B91C1C", fontSize:13, background:"#FEF2F2", padding:"8px 12px", borderRadius:6}}>{error}</div>}

        <div className="field">
          <label>Archivo</label>
          <input type="file" onChange={e=>{ setFile(e.target.files[0]); if(!name) setName(e.target.files[0]?.name||""); }} required style={{fontSize:13}}/>
        </div>
        <div className="field">
          <label>Nombre (opcional)</label>
          <div className="input"><input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="Nombre del archivo"/></div>
        </div>
        <div className="field">
          <label>Descripción</label>
          <div className="input"><input type="text" value={desc} onChange={e=>setDesc(e.target.value)} placeholder="Descripción breve"/></div>
        </div>
        <div className="field">
          <label>Etiquetas (separadas por coma)</label>
          <div className="input"><input type="text" value={tags} onChange={e=>setTags(e.target.value)} placeholder="contrato, 2024, rh"/></div>
        </div>

        <button type="submit" className="btn-primary" disabled={uploading}>
          {uploading ? "Subiendo…" : "Subir archivo"}
          <Icon name="upload" size={14} className="arr"/>
        </button>
      </form>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Detail panel                                                       */
/* ------------------------------------------------------------------ */
function DetailPanel({ item, folderName, onClose, onDownload, favorites, onToggleFav }) {
  if (!item) return null;
  const isFav = favorites.includes(item.id);
  return (
    <>
      <div className={"detail-backdrop" + (item ? " open" : "")} onClick={onClose}/>
      <aside className={"detail" + (item ? " open" : "")}>
        <div className="d-head">
          <div className="eyebrow">Detalle del archivo</div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={16}/></button>
        </div>
        <div className="d-body">
          <div className="d-preview"><Thumb item={item} large/></div>
          <div className="eyebrow" style={{marginBottom: 6}}>{folderName || "Sin carpeta"} · v{item.version}</div>
          <h2>{item.name}</h2>
          <p className="subtitle d-sub">{item.author}</p>
          <p className="desc">{item.description}</p>

          <div className="table">
            <div className="k">ID</div>           <div className="v mono">{item.id}</div>
            <div className="k">Tipo</div>         <div className="v">{item.type.toUpperCase()} · {item.mime}</div>
            <div className="k">Tamaño</div>       <div className="v">{fmtSize(item.size_bytes)}</div>
            <div className="k">Creado</div>       <div className="v">{fmtDate(item.created_at)}</div>
            <div className="k">Actualizado</div>  <div className="v">{fmtDate(item.updated_at)}</div>
            <div className="k">Autor</div>        <div className="v">{item.author || "—"}</div>
            <div className="k">Versión</div>      <div className="v">{item.version}</div>
          </div>

          <div className="eyebrow" style={{marginBottom: 8}}>Etiquetas</div>
          <div className="tags">
            {(item.tags || []).map(tag => <span className="t" key={tag}>#{tag}</span>)}
          </div>
        </div>
        <div className="d-foot">
          <button className="btn ghost" style={{flex:0}} title="Compartir"><Icon name="share" size={14}/></button>
          <button
            className="btn ghost"
            style={{flex:0, color: isFav ? "var(--green)" : undefined}}
            title={isFav ? "Quitar de favoritos" : "Agregar a favoritos"}
            onClick={() => onToggleFav(item)}
          >
            <Icon name="star" size={14}/>
          </button>
          <button className="btn green" onClick={() => onDownload(item)}>
            <Icon name="download" size={14}/> Descargar archivo
          </button>
        </div>
      </aside>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Main Dashboard                                                     */
/* ------------------------------------------------------------------ */
function Dashboard({ sections, allFolders, currentUser, onLogout, onOpenAdmin }) {
  const [sectionId, setSection] = useStateD(sections[0]?.id || null);
  const [folderId, setFolder]   = useStateD(null);
  const [query, setQuery]       = useStateD("");
  const [view, setView]         = useStateD("grid");
  const [typeFilter, setType]   = useStateD("all");
  const [sort, setSort]         = useStateD("recent");
  const [openItem, setOpenItem] = useStateD(null);
  const [toast, setToast]       = useStateD(null);
  const [showUpload, setShowUpload] = useStateD(false);

  // Items cargados del servidor
  const [items, setItems]           = useStateD([]);
  const [loadingItems, setLoading]  = useStateD(false);
  const [totalItems, setTotal]      = useStateD(0);

  // Favoritos
  const [favorites, setFavorites] = useStateD([]);

  const debounceRef = useRef(null);

  // Inicializar sectionId cuando sections lleguen
  useEffect(() => {
    if (!sectionId && sections.length > 0) {
      setSection(sections[0].id);
    }
  }, [sections]);

  // Cargar items al cambiar sección/carpeta (sin búsqueda activa)
  useEffect(() => {
    if (!sectionId) return;
    if (query.trim().length > 1) return; // búsqueda activa maneja sus propios items

    setLoading(true);
    const params = { section_id: sectionId, per_page: 100, sort };
    if (folderId) params.folder_id = folderId;

    API.Items.list(params)
      .then(function(res) {
        setItems(res.data || []);
        setTotal(res.total || 0);
        // Extraer favoritos
        const favIds = (res.data || []).filter(i => i.is_favorite).map(i => i.id);
        setFavorites(function(prev) {
          const merged = new Set([...prev, ...favIds]);
          return Array.from(merged);
        });
      })
      .catch(function() { setItems([]); })
      .finally(function() { setLoading(false); });
  }, [sectionId, folderId, sort]);

  // Búsqueda con debounce
  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);

    if (!query.trim() || query.trim().length < 2) {
      // Sin query: recargar items normales
      if (!query.trim() && sectionId) {
        setLoading(true);
        const params = { section_id: sectionId, per_page: 100, sort };
        if (folderId) params.folder_id = folderId;
        API.Items.list(params)
          .then(function(res) { setItems(res.data || []); setTotal(res.total || 0); })
          .catch(function() {})
          .finally(function() { setLoading(false); });
      }
      return;
    }

    debounceRef.current = setTimeout(function() {
      setLoading(true);
      const params = { q: query.trim(), per_page: 50 };
      if (sectionId) params.section_id = sectionId;
      API.Search.query(params)
        .then(function(res) { setItems(res.data || []); setTotal(res.total || 0); })
        .catch(function() {})
        .finally(function() { setLoading(false); });
    }, 350);
  }, [query]);

  // ESC para cerrar detail panel
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") setOpenItem(null); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  // Filtros cliente (sobre items ya cargados)
  const filtered = useMemo(() => {
    let out = items;
    if (typeFilter !== "all") out = out.filter(i => i.type === typeFilter);
    if (sort === "name")   out = [...out].sort((a,b) => a.name.localeCompare(b.name));
    if (sort === "size")   out = [...out].sort((a,b) => b.size_bytes - a.size_bytes);
    return out;
  }, [items, typeFilter, sort]);

  // Tipos disponibles
  const types = useMemo(() => {
    const set = new Set(items.map(i => i.type));
    return Array.from(set);
  }, [items]);

  const section = sections.find(s => s.id === sectionId);
  const folders = allFolders[sectionId] || [];
  const folder  = folders.find(f => f.id === folderId);

  const handleDownload = function(item) {
    window.open(API.Items.downloadUrl(item.id), "_blank");
  };

  const handleToggleFav = async function(item) {
    const isFav = favorites.includes(item.id);
    try {
      if (isFav) {
        await API.Items.unfavorite(item.id);
        setFavorites(function(prev) { return prev.filter(id => id !== item.id); });
      } else {
        await API.Items.favorite(item.id);
        setFavorites(function(prev) { return [...prev, item.id]; });
      }
    } catch(e) {
      setToast("Error al actualizar favorito");
      setTimeout(() => setToast(null), 2000);
    }
  };

  const handleUploadSuccess = function() {
    // Recargar items
    if (!sectionId) return;
    const params = { section_id: sectionId, per_page: 100 };
    if (folderId) params.folder_id = folderId;
    API.Items.list(params).then(function(res) { setItems(res.data || []); }).catch(function() {});
    setToast("Archivo subido correctamente");
    setTimeout(() => setToast(null), 2000);
  };

  if (!section && sections.length > 0) {
    return <div style={{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh",color:"var(--muted)"}}>Cargando sección…</div>;
  }

  return (
    <div className="app-shell" data-screen-label={"02 " + (section?.label || "Dashboard")}>
      <Sidebar
        sections={sections}
        folders={allFolders}
        currentUser={currentUser}
        sectionId={sectionId} setSection={setSection}
        folderId={folderId}   setFolder={setFolder}
        favorites={favorites}
        onLogout={onLogout}
        onOpenAdmin={onOpenAdmin}
      />

      <div className="main">
        <Topbar query={query} setQuery={setQuery} onUpload={() => setShowUpload(true)}/>

        <div className="content">
          {/* Crumbs */}
          <div className="crumbs">
            <span>Biblioteca</span>
            <Icon name="chevron" size={12} className="sep"/>
            <span>{section?.label}</span>
            {folder && <>
              <Icon name="chevron" size={12} className="sep"/>
              <span className="now">{folder.name}</span>
            </>}
            {!folder && <span className="now" style={{marginLeft: 4}}>Todo</span>}
          </div>

          {/* Page head */}
          <div className="page-head">
            <div>
              <div className="eyebrow" style={{marginBottom: 10}}>Sección</div>
              <h1 className="h-title">{folder ? folder.name : section?.label}</h1>
              <p className="subtitle h-sub">{section?.description}</p>
            </div>
            <div className="h-meta">
              <div>
                <div>Total</div>
                <b>{totalItems.toLocaleString("es-MX")}</b>
              </div>
            </div>
          </div>

          {/* Folder strip */}
          {!folderId && folders.length > 0 && (
            <>
              <div className="section-label">
                <span className="lbl">Carpetas</span>
                <span className="ln"/>
                <span className="meta">{folders.length} carpetas</span>
              </div>
              <div className="folder-strip">
                {folders.map(f => (
                  <div key={f.id} className="folder-card" onClick={() => setFolder(f.id)}>
                    <div className="f-bar" style={{background: f.color}}/>
                    <div>
                      <div className="f-name">{f.name}</div>
                      <div className="f-count">{(f.items_count || 0).toLocaleString("es-MX")} elementos</div>
                    </div>
                  </div>
                ))}
                <div className="folder-card" style={{borderStyle:"dashed", color: "var(--muted)"}}>
                  <div className="f-bar" style={{background: "var(--muted-2)"}}/>
                  <div>
                    <div className="f-name" style={{color:"var(--muted)"}}>+ Nueva carpeta</div>
                    <div className="f-count">Expandir esta sección</div>
                  </div>
                </div>
              </div>
            </>
          )}

          {/* Section label */}
          <div className="section-label">
            <span className="lbl">{folder ? "Contenido" : "Archivos"}</span>
            <span className="ln"/>
            <span className="meta">{filtered.length} resultado{filtered.length===1?"":"s"}</span>
          </div>

          {/* Toolbar */}
          <div className="toolbar">
            <button className={"chip" + (typeFilter==="all" ? " active" : "")} onClick={()=>setType("all")}>Todos</button>
            {types.map(tp => (
              <button key={tp} className={"chip" + (typeFilter===tp ? " active" : "")} onClick={()=>setType(tp)}>
                {tp.toUpperCase()}
              </button>
            ))}
            <span className="spacer"/>
            <button className="chip"><Icon name="filter" size={12}/> Filtros</button>
            <button className="sort-select" onClick={() => {
              const opts = ["recent","name","size"];
              const idx = (opts.indexOf(sort) + 1) % opts.length;
              setSort(opts[idx]);
            }}>
              <Icon name="sort" size={12}/>
              Orden: {sort === "recent" ? "Más reciente" : sort === "name" ? "Nombre" : "Tamaño"}
              <Icon name="chevronDown" size={12}/>
            </button>
            <div className="view-toggle">
              <button className={view==="grid"?"active":""} onClick={()=>setView("grid")} title="Cuadrícula"><Icon name="grid" size={14}/></button>
              <button className={view==="list"?"active":""} onClick={()=>setView("list")} title="Lista"><Icon name="list" size={14}/></button>
            </div>
          </div>

          {/* Loading */}
          {loadingItems && (
            <div style={{display:"flex", alignItems:"center", gap:8, color:"var(--muted)", fontSize:13, padding:"24px 0"}}>
              <span style={{width:14, height:14, border:"2px solid var(--green)", borderTopColor:"transparent", borderRadius:"50%", animation:"spin 0.7s linear infinite", display:"inline-block"}}/>
              Cargando archivos…
            </div>
          )}

          {/* Empty */}
          {!loadingItems && filtered.length === 0 && (
            <div className="empty">
              <div className="subtitle" style={{fontSize:20, marginBottom:6}}>Sin resultados</div>
              <div className="mono">Ajuste su búsqueda o limpie los filtros.</div>
            </div>
          )}

          {/* Grid */}
          {!loadingItems && filtered.length > 0 && view === "grid" && (
            <div className="cards">
              {filtered.map(i => (
                <Card key={i.id} item={i} onOpen={setOpenItem} onDownload={handleDownload}/>
              ))}
            </div>
          )}

          {/* List */}
          {!loadingItems && filtered.length > 0 && view === "list" && (
            <div className="list">
              <div className="row head">
                <div></div>
                <div>Archivo</div>
                <div>Carpeta</div>
                <div>Tipo</div>
                <div>Actualizado</div>
                <div>Tamaño</div>
                <div></div>
              </div>
              {filtered.map(i => (
                <Row key={i.id} item={i}
                  folderName={folders.find(f=>f.id===i.folder_id)?.name || "—"}
                  onOpen={setOpenItem}
                  onDownload={handleDownload}/>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Detail */}
      <DetailPanel
        item={openItem}
        folderName={openItem ? folders.find(f => f.id === openItem.folder_id)?.name : null}
        onClose={() => setOpenItem(null)}
        onDownload={handleDownload}
        favorites={favorites}
        onToggleFav={handleToggleFav}
      />

      {/* Upload modal */}
      {showUpload && (
        <UploadModal
          sectionId={sectionId}
          folderId={folderId}
          onClose={() => setShowUpload(false)}
          onSuccess={handleUploadSuccess}
        />
      )}

      {/* Toast */}
      {toast && (
        <div style={{
          position:"fixed", bottom:24, left:"50%", transform:"translateX(-50%)",
          background:"var(--ink)", color:"#fff", padding:"12px 18px",
          fontSize:13, borderRadius: 6,
          boxShadow:"var(--shadow-pop)", zIndex: 100,
          display:"flex", alignItems:"center", gap:10,
        }}>
          <Icon name="check" size={14} style={{color:"var(--green)"}}/>
          {toast}
        </div>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
