// Workspace — main layout: TopBar, Sidebar, IdentitySwitcher

function TopBar({ breadcrumb, identity, onLogout, onToggleSidebar, codeActive = true }) {
  const [open, setOpen] = React.useState(false);
  const [loggingOut, setLoggingOut] = React.useState(false);
  const [showDeleteModal, setShowDeleteModal] = React.useState(false);
  const a = ACTORS[identity];
  // Only User-linked actors (signup-based humans) can self-delete via this
  // flow. Legacy seeded actors (founder/tlead/code/claude) are fixtures.
  // The /api/me response sets `email` only for bridged Users — legacy
  // actors get email=null — so it's a stable client-side signal.
  const isUserLinked = !!(window.ME && window.ME.email);

  return (
    <div style={{
      height: 48, flexShrink: 0,
      display: 'flex', alignItems: 'center',
      padding: '0 12px 0 14px',
      background: 'var(--bg-0)',
      borderBottom: '1px solid var(--border)',
      gap: 12,
      position: 'relative', zIndex: 30,
    }}>
      <button className="btn-reset" onClick={onToggleSidebar} title="Toggle sidebar"
        style={{ width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 6, color: 'var(--text-2)' }}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
        <Icon name="panel-left" size={15} />
      </button>

      {/* Logo */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginRight: 6 }}>
        <div style={{ width: 18, height: 18, background: 'var(--text-0)', borderRadius: 4, position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 4, background: 'var(--bg-0)', borderRadius: 1 }} />
        </div>
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: -0.2 }}>Workspace</span>
      </div>

      {/* breadcrumb */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--text-2)', minWidth: 0, overflow: 'hidden' }}>
        <span style={{ color: 'var(--text-3)' }}>/</span>
        {breadcrumb.map((b, i) => (
          <React.Fragment key={i}>
            <span style={{ color: i === breadcrumb.length - 1 ? 'var(--text-0)' : 'var(--text-2)', whiteSpace: 'nowrap' }} className={b.mono ? 'mono' : ''}>{b.label}</span>
            {i < breadcrumb.length - 1 && <span style={{ color: 'var(--text-3)' }}>/</span>}
          </React.Fragment>
        ))}
      </div>

      {/* project switcher (Phase 1: scopes Claude Code sessions only) */}
      <div style={{ marginLeft: 8 }}>
        <ProjectSwitcher identity={identity} />
      </div>

      <div style={{ flex: 1 }} />

      {/* code agent active */}
      {codeActive && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', height: 24,
          background: 'rgba(168,85,247,.08)',
          border: '1px solid rgba(168,85,247,.25)',
          borderRadius: 999,
          fontSize: 11.5, color: '#C8A4F2',
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--code)', animation: 'pulse-soft 1.6s ease-in-out infinite' }} />
          Claude Code activo
        </div>
      )}

      {/* prompts — copy-to-clipboard library for claude.ai */}
      <PromptsButton />

      {/* admin — visible only to the founder. Same-origin /admin route
          serves the admin SPA so no subdomain cookie hop is needed. */}
      {window.ME && window.ME.email === 'sebastianc.rock2@gmail.com' && (
        <a href="/admin" target="_blank" rel="noreferrer" style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', height: 26, lineHeight: 1,
          fontSize: 12, fontWeight: 500,
          color: 'white',
          textDecoration: 'none',
          background: 'linear-gradient(135deg, #F59E0B 0%, #D97706 100%)',
          border: '1px solid rgba(217,119,6,.5)',
          borderRadius: 999,
          boxShadow: '0 6px 14px -8px rgba(245,158,11,.6)',
        }}>
          <Icon name="shield" size={12} color="white" /> Admin
        </a>
      )}

      {/* support — WhatsApp direct + group */}
      <SupportButton variant="topbar" />

      {/* identity menu — read-only avatar + logout */}
      <div style={{ position: 'relative' }}>
        <button className="btn-reset" onClick={() => setOpen(o => !o)}
          style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '4px 8px 4px 4px', height: 32,
            border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
            background: open ? 'var(--bg-2)' : 'transparent',
            transition: 'background var(--t-fast)',
          }}>
          <Avatar actor={identity} size={24} />
          <span style={{ fontSize: 12.5, fontWeight: 500 }}>{a.name}</span>
          <Icon name="chevron-down" size={13} color="var(--text-2)" />
        </button>
        {open && (
          <>
            <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
            <div style={{
              position: 'absolute', top: '100%', right: 0, marginTop: 6,
              width: 240, padding: 4,
              background: 'var(--bg-1)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-md)',
              boxShadow: '0 12px 32px rgba(0,0,0,.5)',
              zIndex: 50,
            }}>
              <div style={{ padding: '10px 10px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Avatar actor={identity} size={32} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-0)' }}>{a.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-2)' }}>{a.role}</div>
                </div>
              </div>
              <div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }} />
              <button
                className="btn-reset"
                disabled={loggingOut}
                onClick={async () => {
                  if (loggingOut) return;
                  setLoggingOut(true);
                  try { await onLogout(); } finally { setLoggingOut(false); setOpen(false); }
                }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '8px 10px',
                  borderRadius: 6, textAlign: 'left',
                  color: 'var(--text-1)',
                  background: 'transparent',
                  cursor: loggingOut ? 'default' : 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <Icon name="log-out" size={14} />
                <span style={{ fontSize: 12.5 }}>{loggingOut ? 'Cerrando sesión…' : 'Cerrar sesión'}</span>
              </button>
              {isUserLinked && (
                <>
                  <div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }} />
                  <button
                    className="btn-reset"
                    onClick={() => { setOpen(false); setShowDeleteModal(true); }}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '8px 10px',
                      borderRadius: 6, textAlign: 'left',
                      color: 'var(--danger)',
                      background: 'transparent',
                      cursor: 'pointer',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(239,68,68,.10)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <Icon name="trash-2" size={14} />
                    <span style={{ fontSize: 12.5 }}>Borrar mi cuenta</span>
                  </button>
                </>
              )}
            </div>
          </>
        )}
      </div>
      {showDeleteModal && <DeleteAccountModal onClose={() => setShowDeleteModal(false)} />}
    </div>
  );
}

// Confirmation modal for the destructive "Borrar mi cuenta" action. Forces
// the user to type their password (re-auth) and the literal word BORRAR
// (typo guard) before sending DELETE /api/me. On success we hard-reload
// to '/' — the data layer's deleteMyAccount() handles that.
function DeleteAccountModal({ onClose }) {
  const [password, setPassword] = React.useState('');
  const [confirmText, setConfirmText] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = password.length >= 1 && confirmText.trim().toUpperCase() === 'BORRAR';

  const submit = async () => {
    if (!valid || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      await window.deleteMyAccount(password);
      // deleteMyAccount triggers a hard reload; if we're still here, fall
      // back to closing the modal so the user isn't trapped.
      onClose();
    } catch (e) {
      if (e?.status === 401) setError('Contraseña incorrecta.');
      else setError(e?.message || 'No se pudo borrar la cuenta. Intentá de nuevo.');
      setSubmitting(false);
    }
  };

  return (
    <Modal title="Borrar mi cuenta" onClose={onClose} width={520}
      footer={<>
        <Button variant="ghost" onClick={onClose} disabled={submitting}>Cancelar</Button>
        <Button variant="danger" onClick={submit} disabled={!valid || submitting}>
          {submitting ? 'Borrando…' : 'Borrar todo permanentemente'}
        </Button>
      </>}>
      <div style={{
        marginBottom: 14, padding: '10px 12px',
        background: 'rgba(239,68,68,.08)', border: '1px solid rgba(239,68,68,.30)',
        borderRadius: 6, color: 'var(--danger)', fontSize: 12, lineHeight: 1.5,
      }}>
        <strong>Esta acción es irreversible.</strong> Vamos a borrar:
        <ul style={{ margin: '6px 0 0', paddingLeft: 18 }}>
          <li>Todos tus workspaces y proyectos (docs, tareas, fases, uploads, comentarios, log, pagos).</li>
          <li>Todas tus sesiones de Claude Code activas (las matamos antes de borrar).</li>
          <li>Tus VPS conectados (los desregistramos — el agente deja de poder autenticarse).</li>
          <li>Tu conexión claude.ai y los tokens MCP de cualquier vendor que hayas conectado.</li>
          <li>Tu acceso como invitado a los workspaces de otros (ellos conservan su contenido).</li>
        </ul>
        <div style={{ marginTop: 8 }}>
          <strong>Lo que NO tocamos:</strong> las carpetas de proyecto en disco en tu VPS. Quedan intactas.
        </div>
      </div>
      {error && (
        <div style={{
          marginBottom: 12, padding: '8px 12px',
          background: 'rgba(239,68,68,.08)', border: '1px solid rgba(239,68,68,.30)',
          borderRadius: 6, color: 'var(--danger)', fontSize: 12,
        }}>{error}</div>
      )}
      <label style={{ display: 'block', marginBottom: 14 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-2)', textTransform: 'uppercase', marginBottom: 6 }}>Contraseña actual</div>
        <input
          type="password"
          autoFocus
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Tu contraseña"
          autoComplete="current-password"
          style={{
            width: '100%', padding: '10px 12px',
            background: 'var(--bg-1)', border: '1px solid var(--border)',
            borderRadius: 6, color: 'var(--text-0)', fontSize: 14, outline: 'none',
          }}
        />
      </label>
      <label style={{ display: 'block' }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-2)', textTransform: 'uppercase', marginBottom: 6 }}>Para confirmar, escribe <span className="mono" style={{ color: 'var(--danger)' }}>BORRAR</span></div>
        <input
          type="text"
          value={confirmText}
          onChange={(e) => setConfirmText(e.target.value)}
          placeholder="BORRAR"
          autoComplete="off"
          style={{
            width: '100%', padding: '10px 12px',
            background: 'var(--bg-1)', border: '1px solid var(--border)',
            borderRadius: 6, color: 'var(--text-0)', fontSize: 14, outline: 'none',
            fontFamily: 'var(--font-mono)',
          }}
        />
      </label>
    </Modal>
  );
}

// ── Sidebar ─────────────────────────────────────────────────────────
function Sidebar({ collapsed, onNavigate, current, identity }) {
  const [openFolder, setOpenFolder] = React.useState({ specs: true, sesiones: false });
  const [showNewFolder, setShowNewFolder] = React.useState(false);
  const [editingFolder, setEditingFolder] = React.useState(null);
  const [confirmDeleteFolder, setConfirmDeleteFolder] = React.useState(null);

  const totals = {
    docs: VAULT_TREE.reduce((n, f) => n + (f.count || 0), 0),
    open: TASKS.filter(t => !['closed'].includes(t.status)).length,
  };

  if (collapsed) {
    return (
      <div style={{
        width: 48, flexShrink: 0,
        background: 'var(--bg-0)',
        borderRight: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        padding: '12px 0', gap: 4,
      }}>
        <div style={{ width: 22, height: 22, background: 'var(--text-0)', borderRadius: 5, position: 'relative', marginBottom: 8 }}>
          <div style={{ position: 'absolute', inset: 5, background: 'var(--bg-0)', borderRadius: 1 }} />
        </div>
        {[
          { icon: 'library', view: 'vault.home', tip: 'Vault' },
          { icon: 'kanban', view: 'tracker.kanban', tip: 'Tracker' },
          { icon: 'layers', view: 'tracker.phases', tip: 'Fases' },
          { icon: 'gantt-chart', view: 'tracker.timeline', tip: 'Timeline' },
          { icon: 'user-circle', view: 'tracker.mine', tip: 'Mis tareas' },
          { icon: 'book-open', view: 'log.bitacora', tip: 'Bitácora' },
          { icon: 'terminal', view: 'code.session', tip: 'Claude Code' },
        ].map(item => {
          const active = current.startsWith(item.view.split('.')[0]) && (current === item.view || (item.view === 'vault.home' && current.startsWith('vault')));
          return (
            <button key={item.view} className="btn-reset" title={item.tip}
              onClick={() => onNavigate(item.view)}
              style={{
                width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center',
                borderRadius: 6,
                background: active ? 'var(--accent-dim)' : 'transparent',
                color: active ? 'var(--accent)' : 'var(--text-1)',
              }}>
              <Icon name={item.icon} size={16} />
            </button>
          );
        })}
      </div>
    );
  }

  return (
    <div style={{
      width: 256, flexShrink: 0,
      background: 'var(--bg-0)',
      borderRight: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>

        {/* VAULT section */}
        <SidebarSectionLabel label="VAULT" />
        <SidebarRow icon="library" label="Inicio del Vault" active={current === 'vault.home'} onClick={() => onNavigate('vault.home')} />
        {VAULT_TREE.map(folder => {
          const slug = folder.slug || folder.id;
          const name = folder.name || slug;
          const isOpen = openFolder[slug];
          const isActive = current === `vault.folder.${slug}`;
          return (
            <div key={folder.id}>
              <FolderSidebarRow
                folder={folder}
                slug={slug}
                name={name}
                isOpen={isOpen}
                isActive={isActive}
                onExpand={() => setOpenFolder(o => ({ ...o, [slug]: !o[slug] }))}
                onClick={() => onNavigate(`vault.folder.${slug}`)}
                onEdit={() => setEditingFolder(folder)}
                onDelete={() => setConfirmDeleteFolder(folder)}
              />
              {isOpen && folder.children && folder.children.map(f => {
                const active = current === `vault.doc.${slug}/${f.id}`;
                return (
                  <SidebarRow key={f.id} indent={2}
                    icon="file-text"
                    label={f.id}
                    mono
                    active={active}
                    onClick={() => onNavigate(`vault.doc.${slug}/${f.id}`)} />
                );
              })}
            </div>
          );
        })}
        <button className="btn-reset"
          onClick={() => setShowNewFolder(true)}
          style={{
            display: 'flex', alignItems: 'center', gap: 8,
            margin: '4px 6px 0', padding: '5px 8px 5px 22px',
            borderRadius: 6, color: 'var(--text-2)',
            fontSize: 12.5, textAlign: 'left',
            cursor: 'pointer',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-1)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          <Icon name="plus" size={13} />
          <span>Nueva carpeta</span>
        </button>

        {showNewFolder && <NewFolderModal onClose={() => setShowNewFolder(false)} />}
        {editingFolder && <EditFolderModal folder={editingFolder} onClose={() => setEditingFolder(null)} />}
        {confirmDeleteFolder && (
          <DeleteFolderModal folder={confirmDeleteFolder} onClose={() => setConfirmDeleteFolder(null)} />
        )}

        <div style={{ height: 14 }} />
        <div style={{ borderTop: '1px solid var(--border)', margin: '0 12px' }} />
        <div style={{ height: 6 }} />

        {/* TRACKER */}
        <SidebarSectionLabel label="TRACKER" />
        <SidebarRow icon="kanban"      label="Tablero"      active={current === 'tracker.kanban'}        onClick={() => onNavigate('tracker.kanban')} />
        <SidebarRow icon="layers"      label="Fases"        active={current === 'tracker.phases'}        onClick={() => onNavigate('tracker.phases')} />
        <SidebarRow icon="trello"      label="Fases tablero" active={current === 'tracker.phases-board'} onClick={() => onNavigate('tracker.phases-board')} />
        <SidebarRow icon="gantt-chart" label="Timeline"     active={current === 'tracker.timeline'}      onClick={() => onNavigate('tracker.timeline')} />
        <SidebarRow icon="user-circle" label="Mis tareas"  active={current === 'tracker.mine'}     onClick={() => onNavigate('tracker.mine')}
          badge={TASKS.filter(t => t.assignee === identity && t.status === 'progress').length} />

        <div style={{ height: 14 }} />
        <div style={{ borderTop: '1px solid var(--border)', margin: '0 12px' }} />
        <div style={{ height: 6 }} />

        {/* NEGOCIO */}
        <SidebarSectionLabel label="NEGOCIO" />
        <SidebarRow icon="banknote" label="Pagos" active={current === 'business.payments'} onClick={() => onNavigate('business.payments')} />

        <div style={{ height: 14 }} />
        <div style={{ borderTop: '1px solid var(--border)', margin: '0 12px' }} />
        <div style={{ height: 6 }} />

        {/* BITÁCORA */}
        <SidebarSectionLabel label="BITÁCORA" />
        <SidebarRow icon="book-open" label="Diario / Retros" active={current === 'log.bitacora'} onClick={() => onNavigate('log.bitacora')} />

        <div style={{ height: 14 }} />
        <div style={{ borderTop: '1px solid var(--border)', margin: '0 12px' }} />
        <div style={{ height: 6 }} />

        {/* CLAUDE CODE */}
        <SidebarSectionLabel label="AGENTE" />
        <SidebarRow icon="terminal" label="Claude Code" active={current === 'code.session'} onClick={() => onNavigate('code.session')} />

        <div style={{ height: 14 }} />
        <div style={{ borderTop: '1px solid var(--border)', margin: '0 12px' }} />
        <div style={{ height: 6 }} />

        {/* WORKSPACE — settings + collaborators */}
        <SidebarSectionLabel label="WORKSPACE" />
        <SidebarRow icon="users" label="Colaboradores" active={current === 'workspace.members'} onClick={() => onNavigate('workspace.members')} />
      </div>

      {/* Footer */}
      <div style={{
        padding: '10px 14px',
        borderTop: '1px solid var(--border)',
        display: 'flex', justifyContent: 'space-between',
        fontSize: 11, color: 'var(--text-2)',
      }}>
        <span><span className="mono" style={{ color: 'var(--text-1)' }}>{totals.docs}</span> docs</span>
        <span><span className="mono" style={{ color: 'var(--text-1)' }}>{totals.open}</span> tareas abiertas</span>
      </div>
    </div>
  );
}

function SidebarSectionLabel({ label }) {
  return (
    <div style={{
      padding: '10px 16px 4px',
      fontSize: 10.5, fontWeight: 600, letterSpacing: 0.7,
      color: 'var(--text-3)', textTransform: 'uppercase',
    }}>{label}</div>
  );
}

// SidebarRow variant for Vault folders: shows the display name, the slug as
// hover hint, and a kebab on hover that opens edit / delete.
function FolderSidebarRow({ folder, slug, name, isOpen, isActive, onExpand, onClick, onEdit, onDelete }) {
  const [hover, setHover] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  React.useEffect(() => {
    if (!menuOpen) return;
    const handler = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [menuOpen]);
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: 'relative', padding: '0 6px' }}>
      <button className="btn-reset" onClick={onClick}
        title={name !== slug ? `/${slug}` : undefined}
        style={{
          display: 'flex', alignItems: 'center',
          gap: 8, width: '100%', padding: '5px 8px 5px 22px',
          borderRadius: 6,
          background: isActive ? 'var(--accent-dim)' : (hover ? 'var(--bg-1)' : 'transparent'),
          color: isActive ? 'var(--accent)' : 'var(--text-1)',
          fontSize: 12.5, fontWeight: isActive ? 500 : 400,
          textAlign: 'left',
          transition: 'background var(--t-fast), color var(--t-fast)',
        }}>
        <span onClick={(e) => { e.stopPropagation(); onExpand(); }} style={{ display: 'flex', color: 'var(--text-2)' }}>
          <Icon name={isOpen ? 'chevron-down' : 'chevron-right'} size={12} />
        </span>
        <Icon name={folder.icon || 'folder'} size={14} />
        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
        {(hover || menuOpen) ? (
          <span ref={menuRef} style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <span
              onClick={(e) => { e.stopPropagation(); setMenuOpen((v) => !v); }}
              style={{
                width: 18, height: 18, display: 'flex', alignItems: 'center', justifyContent: 'center',
                borderRadius: 4, color: 'var(--text-2)',
                background: menuOpen ? 'var(--bg-2)' : 'transparent',
              }}>
              <Icon name="more-horizontal" size={12} />
            </span>
            {menuOpen && (
              <div style={{
                position: 'absolute', top: 26, right: 8, zIndex: 30,
                background: 'var(--bg-1)', border: '1px solid var(--border-strong)',
                borderRadius: 6, padding: 4, minWidth: 140,
                boxShadow: '0 8px 22px rgba(0,0,0,.45)',
              }}>
                <button className="btn-reset"
                  onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onEdit(); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '6px 8px', borderRadius: 4, fontSize: 12.5, color: 'var(--text-1)', textAlign: 'left' }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <Icon name="pencil" size={12} /> Renombrar
                </button>
                <button className="btn-reset"
                  onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onDelete(); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '6px 8px', borderRadius: 4, fontSize: 12.5, color: 'var(--danger)', textAlign: 'left' }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <Icon name="trash-2" size={12} /> Borrar
                </button>
              </div>
            )}
          </span>
        ) : (folder.count != null && (
          <span className="mono" style={{
            fontSize: 10.5, color: 'var(--text-3)',
            background: 'var(--bg-2)', padding: '0 5px', height: 16, lineHeight: '16px',
            borderRadius: 4,
          }}>{folder.count}</span>
        ))}
      </button>
    </div>
  );
}

function SidebarRow({ icon, label, active, onClick, indent = 0, badge, mono, expandable, expanded, onExpand }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div style={{ position: 'relative', padding: '0 6px' }}>
      <button className="btn-reset" onClick={onClick}
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          display: 'flex', alignItems: 'center',
          gap: 8, width: '100%', padding: `5px 8px 5px ${8 + indent * 14}px`,
          borderRadius: 6,
          background: active ? 'var(--accent-dim)' : (hover ? 'var(--bg-1)' : 'transparent'),
          color: active ? 'var(--accent)' : 'var(--text-1)',
          fontSize: 12.5, fontWeight: active ? 500 : 400,
          fontFamily: mono ? 'var(--font-mono)' : 'inherit',
          textAlign: 'left',
          transition: 'background var(--t-fast), color var(--t-fast)',
        }}>
        {expandable && (
          <span onClick={(e) => { e.stopPropagation(); onExpand(); }} style={{ display: 'flex', color: 'var(--text-2)' }}>
            <Icon name={expanded ? 'chevron-down' : 'chevron-right'} size={12} />
          </span>
        )}
        <Icon name={icon} size={14} />
        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        {badge != null && (
          <span className="mono" style={{
            fontSize: 10.5, color: 'var(--text-3)',
            background: 'var(--bg-2)', padding: '0 5px', height: 16, lineHeight: '16px',
            borderRadius: 4,
          }}>{badge}</span>
        )}
      </button>
    </div>
  );
}

Object.assign(window, { TopBar, Sidebar });
