// ============================================================
// WASIED · App shell (authed) - sidebar + topbar
// ============================================================

function AppShell({ children, title, breadcrumbs, actions, sectionPadding = true, isAdmin = false }) {
  const [collapsed, setCollapsed] = React.useState(false);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [profileOpen, setProfileOpen] = React.useState(false);
  const { path } = useRouter();
  const currentService = !isAdmin ? serviceFromPath(path) : null;

  // Admin nav (unchanged structure)
  const navMain = isAdmin ? [
    { icon: 'dashboard',  label: 'Vue d\'ensemble', path: '/admin' },
    { icon: 'briefcase',  label: 'Commandes',       path: '/admin/orders' },
    { icon: 'users',      label: 'Utilisateurs',    path: '/admin/users' },
    { icon: 'edit',       label: 'Contenu (CMS)',   path: '/admin/content' },
    { icon: 'euro',       label: 'Facturation',     path: '/admin/billing' },
    { icon: 'logs',       label: 'Logs · webhooks', path: '/admin/logs' },
  ] : null;
  const navBottom = isAdmin ? [
    { icon: 'arrowLeft', label: 'Vue client', path: '/app' },
    { icon: 'settings', label: 'Paramètres', path: '/admin/settings' },
  ] : null;

  // Client nav (registry-driven)
  const services = !isAdmin ? listServices() : [];

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--surface-0)' }}>
      {/* SIDEBAR */}
      <aside style={{
        width: collapsed ? 64 : 248,
        background: 'var(--surface-1)',
        borderRight: '1px solid var(--border-1)',
        display: 'flex', flexDirection: 'column',
        position: 'sticky', top: 0, height: '100vh',
        transition: 'width 200ms var(--ease-out)',
        flexShrink: 0,
      }} className="app-sidebar">
        {/* Brand */}
        <div style={{ height: 56, display: 'flex', alignItems: 'center', padding: '0 16px', borderBottom: '1px solid var(--border-1)' }}>
          <Link to="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
            <WLogo size={22}/>
            {!collapsed && <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15, letterSpacing: '-0.01em', color: 'var(--fg-1)' }}>Wasied{isAdmin && <span style={{ color: 'var(--hp)', fontSize: 11, marginLeft: 6 }}>admin</span>}</span>}
          </Link>
        </div>

        {/* Current workspace pill (only client view) */}
        {!isAdmin && !collapsed && (
          <div style={{ padding: '14px 12px 0' }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
              background: currentService ? `color-mix(in srgb, ${currentService.color} 8%, var(--surface-2))` : 'var(--surface-2)',
              border: `1px solid ${currentService ? `color-mix(in srgb, ${currentService.color} 20%, var(--border-1))` : 'var(--border-1)'}`,
              borderRadius: 8,
            }}>
              <span style={{ width: 24, height: 24, borderRadius: 6, background: currentService ? `color-mix(in srgb, ${currentService.color} 18%, var(--surface-3))` : 'var(--surface-3)', color: currentService ? currentService.color : 'var(--fg-2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={currentService ? currentService.icon : 'user'} size={13}/>
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500 }}>Workspace</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {currentService ? currentService.brandName : 'Compte personnel'}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Nav */}
        <nav style={{ flex: 1, overflowY: 'auto', padding: '12px 8px' }}>
          {/* Admin: keep simple nav */}
          {isAdmin && (
            <>
              {!collapsed && <SidebarLabel>ADMINISTRATION</SidebarLabel>}
              {navMain.map(n => <SidebarLink key={n.path} item={n} active={path === n.path || (n.path !== '/admin' && path.startsWith(n.path))} collapsed={collapsed}/>)}
              <div style={{ height: 14 }}/>
              {navBottom.map(n => <SidebarLink key={n.path} item={n} active={path === n.path} collapsed={collapsed}/>)}
            </>
          )}

          {/* Client: workspaces + account */}
          {!isAdmin && (
            <>
              {!collapsed && <SidebarLabel>NAVIGATION</SidebarLabel>}
              <SidebarLink item={{ icon: 'dashboard', label: "Vue d'ensemble", path: '/app' }} active={path === '/app'} collapsed={collapsed}/>

              {!collapsed && <SidebarLabel style={{ marginTop: 14 }}>SERVICES</SidebarLabel>}
              {services.map(s => (
                <SidebarLink
                  key={s.id}
                  item={{ icon: s.icon, label: s.name, path: s.app.rootPath, color: s.color }}
                  active={currentService && currentService.id === s.id}
                  collapsed={collapsed}
                  rightAdorn={s.status === 'soon' ? <Badge tone="subtle" size="sm">Bientôt</Badge> : s.status === 'beta' ? <Badge tone="xp" size="sm">Bêta</Badge> : null}
                />
              ))}

              {!collapsed && <SidebarLabel style={{ marginTop: 14 }}>COMPTE</SidebarLabel>}
              {ACCOUNT_NAV.map(n => <SidebarLink key={n.path} item={n} active={path === n.path} collapsed={collapsed}/>)}
            </>
          )}
        </nav>

        {/* User card */}
        <div style={{ padding: 8, borderTop: '1px solid var(--border-1)' }}>
          <div style={{ position: 'relative' }}>
            <button onClick={() => setProfileOpen(!profileOpen)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 8, width: '100%', background: 'transparent', border: 'none', cursor: 'pointer', borderRadius: 7, color: 'var(--fg-1)' }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-2)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <Avatar name={isAdmin ? 'Wasied' : DATA.client.name} size={28} tone={isAdmin ? 'amber' : DATA.client.avatarTone}/>
              {!collapsed && (
                <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-1)' }}>{isAdmin ? 'Maxime' : DATA.client.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--fg-3)' }}>{isAdmin ? 'Admin · founder' : DATA.client.discord}</div>
                </div>
              )}
              {!collapsed && <Icon name="chevronUp" size={12} color="var(--fg-3)"/>}
            </button>
            {profileOpen && !collapsed && (
              <div style={{ position: 'absolute', bottom: '100%', left: 0, right: 0, marginBottom: 6, background: 'var(--surface-2)', border: '1px solid var(--border-2)', borderRadius: 8, boxShadow: 'var(--shadow-lg)', padding: 4, zIndex: 10 }}>
                <Link to={`/u/${isAdmin ? 'wasied' : DATA.client.handle}`} onClick={() => setProfileOpen(false)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 8, fontSize: 12, color: 'var(--fg-2)', borderRadius: 6 }}><Icon name="user" size={12}/>Profil public</Link>
                {!isAdmin && <Link to="/admin" onClick={() => setProfileOpen(false)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 8, fontSize: 12, color: 'var(--hp)', borderRadius: 6 }}><Icon name="shield" size={12}/>Vue admin</Link>}
                <Link to="/" onClick={() => setProfileOpen(false)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 8, fontSize: 12, color: 'var(--fg-2)', borderRadius: 6 }}><Icon name="logout" size={12}/>Déconnexion</Link>
              </div>
            )}
          </div>
        </div>
      </aside>

      {/* MAIN */}
      <div style={{ flex: 1, minWidth: 0 }}>
        {/* Topbar */}
        <header style={{ height: 56, borderBottom: '1px solid var(--border-1)', display: 'flex', alignItems: 'center', padding: '0 24px', gap: 16, background: 'var(--surface-0)', position: 'sticky', top: 0, zIndex: 20 }}>
          <button onClick={() => setCollapsed(!collapsed)} style={{ background: 'transparent', border: 'none', color: 'var(--fg-3)', cursor: 'pointer', padding: 6 }}><Icon name="menu" size={16}/></button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--fg-3)' }}>
            {(breadcrumbs || [{ label: title }]).map((b, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Icon name="chevron" size={12} color="var(--fg-4)"/>}
                {b.path ? <Link to={b.path}>{b.label}</Link> : <span style={{ color: 'var(--fg-1)', fontWeight: 500 }}>{b.label}</span>}
              </React.Fragment>
            ))}
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 9px', fontSize: 11, color: 'var(--fg-2)', background: 'var(--surface-2)', borderRadius: 999, border: '1px solid var(--border-1)' }}>
              <span className="live-dot" style={{ width: 5, height: 5, background: 'var(--cash)', color: 'var(--cash)', borderRadius: '50%' }}/>En direct
            </span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>·</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>{new Date().toLocaleTimeString('fr-FR', { hour12: false })}</span>
            <span style={{ width: 1, height: 16, background: 'var(--border-1)', margin: '0 6px' }}/>
            <button onClick={() => setNotifOpen(!notifOpen)} style={{ position: 'relative', background: 'transparent', border: 'none', cursor: 'pointer', padding: 8, color: 'var(--fg-2)' }}>
              <Icon name="bell" size={16}/>
              <span style={{ position: 'absolute', top: 6, right: 7, width: 6, height: 6, background: 'var(--hp)', borderRadius: '50%' }}/>
            </button>
            {actions}
          </div>
          {notifOpen && (
            <div style={{ position: 'absolute', right: 24, top: 56, width: 360, background: 'var(--surface-1)', border: '1px solid var(--border-2)', borderRadius: 12, boxShadow: 'var(--shadow-lg)', zIndex: 30, overflow: 'hidden' }}>
              <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border-1)', fontSize: 12, fontWeight: 500, color: 'var(--fg-1)' }}>Notifications · 3 non lues</div>
              {DATA.client.timeline.slice(0, 4).map((a, i) => (
                <div key={i} style={{ padding: '10px 16px', borderTop: i > 0 ? '1px solid var(--border-1)' : 'none', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <Icon name={a.icon} size={14} color="var(--fg-3)" style={{ marginTop: 2 }}/>
                  <div style={{ flex: 1, fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.5 }}>{a.text}<div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{a.t}</div></div>
                </div>
              ))}
              <div style={{ padding: '8px 16px', textAlign: 'center' }}><Link to="/app" style={{ fontSize: 12, color: 'var(--accent)' }}>Tout voir →</Link></div>
            </div>
          )}
        </header>

        {/* Page content */}
        <div style={{ padding: sectionPadding ? '32px 24px 80px' : 0 }} className="anim-fade">{children}</div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .app-sidebar { width: 56px !important; }
          .app-sidebar nav, .app-sidebar div[role="user"] { /* keep compact */ }
        }
      `}</style>
    </div>
  );
}

function SidebarLabel({ children, style }) {
  return <div style={{ fontSize: 10, fontWeight: 500, color: 'var(--fg-3)', padding: '8px 10px 4px', letterSpacing: '0.05em', ...style }}>{children}</div>;
}

function SidebarLink({ item, active, collapsed, rightAdorn }) {
  const [hover, setHover] = React.useState(false);
  return (
    <Link to={item.path} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: collapsed ? '10px' : '8px 10px',
        justifyContent: collapsed ? 'center' : 'flex-start',
        borderRadius: 7,
        fontSize: 13, fontWeight: 500,
        color: active ? 'var(--fg-1)' : (hover ? 'var(--fg-1)' : 'var(--fg-2)'),
        background: active ? 'var(--accent-soft)' : (hover ? 'var(--surface-2)' : 'transparent'),
        position: 'relative',
        transition: 'all 140ms var(--ease-out)',
        marginBottom: 2,
      }}>
      {active && <span style={{ position: 'absolute', left: -10, top: 6, bottom: 6, width: 2, background: item.color || 'var(--accent)', borderRadius: 2 }}/>}
      <Icon name={item.icon} size={16} color={active ? (item.color || 'var(--accent)') : 'currentColor'}/>
      {!collapsed && <span style={{ flex: 1 }}>{item.label}</span>}
      {!collapsed && rightAdorn}
    </Link>
  );
}

Object.assign(window, { AppShell, SidebarLink });
