import type { Meta, StoryObj } from '@storybook/react';
import { Sidebar, useSidebar } from './sidebar';
import { useLayout } from '../../../contexts/LayoutContext';
import { BrowserRouter } from 'react-router-dom';
import {
  Home,
  Users,
  Settings,
  BarChart,
  Plus,
  Clock,
  FileEdit,
  ArrowRightLeft,
  PanelLeft,
  Menu,
  Trash2,
  Map,
  Archive,
  ShoppingCart,
  Package,
  Tag,
  Truck,
  CreditCard,
  Bell,
  Shield,
  Key,
  Database,
  Server,
  Activity,
  TrendingUp,
  PieChart,
  BarChart2,
  FileText,
  Folder,
  MessageSquare,
  Mail,
  Phone,
  Globe,
  Layers,
  Zap,
} from 'lucide-react';
import React, { useState } from 'react';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Progress } from '../../ui/progress';

const meta: Meta<typeof Sidebar> = {
  title: 'Layout/Sidebar',
  component: Sidebar,
  decorators: [
    Story => (
      <BrowserRouter>
        <div className="flex h-screen w-full overflow-hidden bg-background">
          <Story />
        </div>
      </BrowserRouter>
    ),
  ],
  parameters: {
    layout: 'fullscreen',
  },
};

export default meta;
type Story = StoryObj<typeof Sidebar>;

export const Default: Story = {
  args: {
    variant: 'default',
    expanded: false,
    user: { email: 'admin@example.com' },
    onLogout: () => console.log('Logged out'),
    location: { pathname: '/home' },
    routes: [
      { path: '/home', label: 'Home', icon: Home },
      { path: '/dashboard', label: 'Dashboard', icon: Users },
      { path: '/settings', label: 'Settings', icon: Settings },
    ],
    footer: {
      showUser: true,
      showSettings: true,
      showLogout: true,
    },
  },
  render: args => {
    const { sidebarWidth: contextWidth } = useLayout();
    const [isExpanded, setIsExpanded] = useState(args.expanded);

    // In Storybook, we match the sidebar widths (280 expanded, 80 collapsed)
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center">
            <p className="text-muted-foreground">Traditional System Navigation</p>
            <p className="text-xs text-muted-foreground mt-2">Click on the menu icon to expand</p>
          </div>
        </div>
      </div>
    );
  },
};

export const DefaultWithGroups: Story = {
  args: {
    variant: 'default',
    expanded: false,
    user: { name: 'Admin', email: 'admin@example.com' },
    onLogout: () => console.log('Logged out'),
    location: { pathname: '/home' },
    navigationGroups: [
      {
        id: 'main',
        label: 'Principal',
        items: [
          { path: '/home', label: 'Início', icon: Home },
          {
            path: '/dashboard',
            label: 'Dashboard',
            icon: BarChart,
            children: [
              { path: '/dashboard/overview', label: 'Visão Geral', icon: BarChart },
              { path: '/dashboard/reports', label: 'Relatórios', icon: FileEdit },
              { path: '/dashboard/analytics', label: 'Analytics', icon: Map },
            ],
          },
        ],
      },
      {
        id: 'admin',
        label: 'Administração',
        items: [
          {
            path: '/users',
            label: 'Usuários',
            icon: Users,
            children: [
              { path: '/users/list', label: 'Lista de Usuários', icon: Users },
              { path: '/users/roles', label: 'Perfis de Acesso', icon: Settings },
            ],
          },
          { path: '/settings', label: 'Configurações', icon: Settings },
        ],
      },
    ],
    footer: {
      showUser: true,
      showSettings: false,
      showLogout: true,
    },
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(args.expanded);
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center">
            <p className="text-muted-foreground">Navigation with Groups and Children</p>
            <p className="text-xs text-muted-foreground mt-2">
              Expand and click the arrow button on items to see sub-menus
            </p>
          </div>
        </div>
      </div>
    );
  },
};

export const Assistant: Story = {
  args: {
    variant: 'assistant',
    expanded: false,
    user: { email: 'admin@example.com' },
    onLogout: () => console.log('Logged out'),
    location: { pathname: '/assistant/refatoracao' },
    search: {
      show: true,
      placeholder: 'Buscar tópicos...',
      filter: {
        show: true,
        content: (
          <div className="p-2 space-y-2">
            <div className="text-xs font-semibold uppercase text-muted-foreground px-2 text-left">
              Filter by Status
            </div>
            <div className="flex flex-wrap gap-2 p-1">
              <Badge className="bg-sidebar-foreground/20 text-sidebar-foreground border-none cursor-pointer hover:bg-sidebar-foreground/30">
                Active
              </Badge>
              <Badge
                variant="outline"
                className="text-sidebar-foreground/70 border-sidebar-foreground/20 cursor-pointer hover:bg-sidebar-foreground/10"
              >
                Archived
              </Badge>
              <Badge
                variant="outline"
                className="text-sidebar-foreground/70 border-sidebar-foreground/20 cursor-pointer hover:bg-sidebar-foreground/10"
              >
                Pending
              </Badge>
            </div>
          </div>
        ),
      },
    },
    fixedArea: {
      show: true,
      icon: Plus,
      onClick: () => console.log('New Conversation clicked'),
      content: (
        <Button className="w-full bg-sidebar-primary hover:bg-sidebar-primary/90 text-sidebar-primary-foreground shadow-lg font-bold border-none transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98]">
          <Plus className="w-4 h-4 mr-2" />
          New Conversation
        </Button>
      ),
    },
    navigationGroups: [
      {
        id: 'recent',
        label: 'Recent',
        icon: Clock,
        items: [
          {
            path: '/assistant/refatoracao',
            label: 'Edit Sidebar',
            description: 'Active now',
            actions: [
              { label: 'Rename', icon: FileEdit, onClick: () => console.log('Open rename...') },
              {
                label: 'Move',
                icon: ArrowRightLeft,
                children: [
                  {
                    label: 'Active Projects',
                    onClick: () => console.log('Moved to Active Projects'),
                  },
                  { label: 'Monitoring', onClick: () => console.log('Moved to Monitoring') },
                  { label: 'Archive', onClick: () => console.log('Moved to Archive') },
                ],
              },
              {
                label: 'Clear',
                icon: Trash2,
                onClick: () => console.log('History Cleared!'),
                variant: 'destructive',
              },
            ],
          },
        ],
      },
      {
        id: 'projects',
        label: 'Project Monitoring',
        icon: Map,
        actions: [
          {
            label: 'New Category',
            icon: Plus,
            onClick: () => console.log('Create new category...'),
          },
          {
            label: 'Archive Group',
            icon: Archive,
            onClick: () => console.log('Archiving group...'),
          },
        ],
        items: [
          {
            path: '/assistant/br163',
            label: 'Panel Status',
            icon: () => <div className="w-2 h-2 rounded-full bg-yellow-500" />,
            description: (
              <div className="space-y-1.5 min-w-[160px]">
                <Progress value={67} className="h-1.5 bg-sidebar-foreground/10" />
                <div className="flex justify-between items-center text-[10px] text-sidebar-foreground/60">
                  <span>Label</span>
                  <span>67%</span>
                </div>
              </div>
            ),
          },
        ],
      },
    ],
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(args.expanded);
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center">
            <p className="text-muted-foreground">Assistant Mode Content</p>
            <p className="text-xs text-muted-foreground mt-2">Click on the menu icon to expand</p>
          </div>
        </div>
      </div>
    );
  },
};

export const Collapsed: Story = {
  args: {
    ...Default.args,
    expanded: false,
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(args.expanded);
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center">
            <p className="text-muted-foreground">Compact Navigation</p>
            <p className="text-xs text-muted-foreground mt-2">Click on the menu icon to expand</p>
          </div>
        </div>
      </div>
    );
  },
};
export const NoFooter: Story = {
  args: {
    ...Default.args,
    showFooter: false,
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(args.expanded);
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center">
            <p className="text-muted-foreground">Sidebar without Footer</p>
            <p className="text-xs text-muted-foreground mt-2">Click on the menu icon to expand</p>
          </div>
        </div>
      </div>
    );
  },
};

export const Autonomous: Story = {
  args: {
    ...Default.args,
    expanded: undefined,
    onToggle: undefined,
  },
  render: args => {
    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar {...args} />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `80px` }}
        >
          <div className="text-center max-w-md">
            <p className="text-muted-foreground font-bold">Autonomous Sidebar</p>
            <p className="text-sm text-muted-foreground/80 mt-2">
              This instance is managing its own state internally. No `expanded` or `onToggle` props
              are passed.
            </p>
            <p className="text-xs text-muted-foreground mt-4">
              Note: Layout coordination (content padding) must be handled manually when using
              autonomous mode without LayoutProvider.
            </p>
          </div>
        </div>
      </div>
    );
  },
};

/**
 * Desktop view with sub-items expanded.
 * Items with `children` show a ChevronRight button; clicking it opens a
 * dropdown listing the child routes positioned to the right of the sidebar.
 */
export const WithSubitemsDesktop: Story = {
  name: 'With Sub-items (Desktop)',
  args: {
    variant: 'default',
    expanded: true,
    user: { name: 'Admin', email: 'admin@example.com' },
    onLogout: () => console.log('Logged out'),
    location: { pathname: '/dashboard' },
    navigationGroups: [
      {
        id: 'main',
        label: 'Principal',
        items: [
          { path: '/home', label: 'Início', icon: Home },
          {
            path: '/dashboard',
            label: 'Dashboard',
            icon: BarChart,
            children: [
              { path: '/dashboard/overview', label: 'Visão Geral', icon: BarChart },
              { path: '/dashboard/reports', label: 'Relatórios', icon: FileEdit },
              { path: '/dashboard/analytics', label: 'Analytics', icon: Map },
              { path: '/dashboard/trends', label: 'Tendências', icon: TrendingUp },
              { path: '/dashboard/kpis', label: 'KPIs', icon: Activity },
              { path: '/dashboard/charts', label: 'Gráficos', icon: PieChart },
              { path: '/dashboard/comparison', label: 'Comparativos', icon: BarChart2 },
            ],
          },
          {
            path: '/reports',
            label: 'Relatórios',
            icon: FileText,
            children: [
              { path: '/reports/sales', label: 'Vendas', icon: ShoppingCart },
              { path: '/reports/financial', label: 'Financeiro', icon: CreditCard },
              { path: '/reports/operational', label: 'Operacional', icon: Layers },
              { path: '/reports/exports', label: 'Exportações', icon: FileEdit },
            ],
          },
          {
            path: '/catalog',
            label: 'Catálogo',
            icon: Package,
            children: [
              { path: '/catalog/products', label: 'Produtos', icon: Package },
              { path: '/catalog/categories', label: 'Categorias', icon: Tag },
              { path: '/catalog/inventory', label: 'Estoque', icon: Database },
            ],
          },
        ],
      },
      {
        id: 'commerce',
        label: 'Comercial',
        items: [
          {
            path: '/orders',
            label: 'Pedidos',
            icon: ShoppingCart,
            children: [
              { path: '/orders/pending', label: 'Pendentes', icon: Clock },
              { path: '/orders/processing', label: 'Em Andamento', icon: Zap },
              { path: '/orders/shipped', label: 'Enviados', icon: Truck },
              { path: '/orders/delivered', label: 'Entregues', icon: Package },
              { path: '/orders/cancelled', label: 'Cancelados', icon: Trash2 },
            ],
          },
          {
            path: '/logistics',
            label: 'Logística',
            icon: Truck,
            children: [
              { path: '/logistics/carriers', label: 'Transportadoras', icon: Truck },
              { path: '/logistics/tracking', label: 'Rastreamento', icon: Map },
              { path: '/logistics/warehouses', label: 'Armazéns', icon: Archive },
            ],
          },
          {
            path: '/billing',
            label: 'Faturamento',
            icon: CreditCard,
            children: [
              { path: '/billing/invoices', label: 'Faturas', icon: FileText },
              { path: '/billing/payments', label: 'Pagamentos', icon: CreditCard },
              { path: '/billing/refunds', label: 'Estornos', icon: ArrowRightLeft },
            ],
          },
        ],
      },
      {
        id: 'communication',
        label: 'Comunicação',
        items: [
          {
            path: '/notifications',
            label: 'Notificações',
            icon: Bell,
            children: [
              { path: '/notifications/email', label: 'E-mail', icon: Mail },
              { path: '/notifications/sms', label: 'SMS', icon: Phone },
              { path: '/notifications/push', label: 'Push', icon: Bell },
            ],
          },
          {
            path: '/messages',
            label: 'Mensagens',
            icon: MessageSquare,
            children: [
              { path: '/messages/inbox', label: 'Caixa de Entrada', icon: Mail },
              { path: '/messages/sent', label: 'Enviadas', icon: MessageSquare },
              { path: '/messages/templates', label: 'Templates', icon: FileText },
            ],
          },
          { path: '/integrations', label: 'Integrações', icon: Globe },
        ],
      },
      {
        id: 'admin',
        label: 'Administração',
        items: [
          {
            path: '/users',
            label: 'Usuários',
            icon: Users,
            children: [
              { path: '/users/list', label: 'Lista de Usuários', icon: Users },
              { path: '/users/roles', label: 'Perfis de Acesso', icon: Shield },
              { path: '/users/permissions', label: 'Permissões', icon: Key },
              { path: '/users/audit', label: 'Auditoria', icon: Activity },
            ],
          },
          {
            path: '/infrastructure',
            label: 'Infraestrutura',
            icon: Server,
            children: [
              { path: '/infrastructure/servers', label: 'Servidores', icon: Server },
              { path: '/infrastructure/databases', label: 'Bancos de Dados', icon: Database },
              { path: '/infrastructure/backups', label: 'Backups', icon: Archive },
            ],
          },
          {
            path: '/files',
            label: 'Arquivos',
            icon: Folder,
            children: [
              { path: '/files/documents', label: 'Documentos', icon: FileText },
              { path: '/files/media', label: 'Mídia', icon: Layers },
              { path: '/files/exports', label: 'Exportações', icon: FileEdit },
            ],
          },
          { path: '/settings', label: 'Configurações', icon: Settings },
        ],
      },
    ],
    footer: {
      showUser: true,
      showSettings: false,
      showLogout: true,
    },
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(true);
    const currentWidth = isExpanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(!isExpanded)}
          width={currentWidth}
          navigate={() => {}}
        />
        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center max-w-sm space-y-2">
            <p className="text-muted-foreground font-medium">Desktop — Subitens</p>
            <p className="text-xs text-muted-foreground">
              Itens com subitens exibem um botão{' '}
              <code className="bg-muted px-1 rounded text-xs">ChevronRight</code> ao final da
              linha. Clique nele para abrir o dropdown de rotas filhas.
            </p>
            <p className="text-xs text-muted-foreground mt-2">
              Use o botão de toggle para alternar entre expandido e recolhido.
            </p>
          </div>
        </div>
      </div>
    );
  },
};

/**
 * Mobile view with sub-items.
 * Simulates a narrow viewport (375 px) so the sidebar renders in its
 * full-screen overlay mode. When expanded the sidebar covers the entire
 * container; clicking a nav item (or the back-arrow toggle) closes it.
 *
 * Sub-item dropdowns behave identically to desktop — the ChevronRight
 * button opens a `DropdownMenuContent` positioned to the right.
 * This story exists so the mobile layout can be inspected and adjusted.
 */
export const WithSubitemsMobile: Story = {
  name: 'With Sub-items (Mobile)',
  parameters: {
    viewport: { defaultViewport: 'mobile1' },
  },
  args: {
    variant: 'default',
    expanded: false,
    user: { name: 'Admin', email: 'admin@example.com' },
    onLogout: () => console.log('Logged out'),
    location: { pathname: '/dashboard' },
    navigationGroups: [
      {
        id: 'main',
        label: 'Principal',
        items: [
          { path: '/home', label: 'Início', icon: Home },
          {
            path: '/dashboard',
            label: 'Dashboard',
            icon: BarChart,
            children: [
              { path: '/dashboard/overview', label: 'Visão Geral', icon: BarChart },
              { path: '/dashboard/reports', label: 'Relatórios', icon: FileEdit },
              { path: '/dashboard/analytics', label: 'Analytics', icon: Map },
              { path: '/dashboard/trends', label: 'Tendências', icon: TrendingUp },
              { path: '/dashboard/kpis', label: 'KPIs', icon: Activity },
              { path: '/dashboard/charts', label: 'Gráficos', icon: PieChart },
              { path: '/dashboard/comparison', label: 'Comparativos', icon: BarChart2 },
            ],
          },
          {
            path: '/reports',
            label: 'Relatórios',
            icon: FileText,
            children: [
              { path: '/reports/sales', label: 'Vendas', icon: ShoppingCart },
              { path: '/reports/financial', label: 'Financeiro', icon: CreditCard },
              { path: '/reports/operational', label: 'Operacional', icon: Layers },
              { path: '/reports/exports', label: 'Exportações', icon: FileEdit },
            ],
          },
          {
            path: '/catalog',
            label: 'Catálogo',
            icon: Package,
            children: [
              { path: '/catalog/products', label: 'Produtos', icon: Package },
              { path: '/catalog/categories', label: 'Categorias', icon: Tag },
              { path: '/catalog/inventory', label: 'Estoque', icon: Database },
            ],
          },
        ],
      },
      {
        id: 'commerce',
        label: 'Comercial',
        items: [
          {
            path: '/orders',
            label: 'Pedidos',
            icon: ShoppingCart,
            children: [
              { path: '/orders/pending', label: 'Pendentes', icon: Clock },
              { path: '/orders/processing', label: 'Em Andamento', icon: Zap },
              { path: '/orders/shipped', label: 'Enviados', icon: Truck },
              { path: '/orders/delivered', label: 'Entregues', icon: Package },
              { path: '/orders/cancelled', label: 'Cancelados', icon: Trash2 },
            ],
          },
          {
            path: '/logistics',
            label: 'Logística',
            icon: Truck,
            children: [
              { path: '/logistics/carriers', label: 'Transportadoras', icon: Truck },
              { path: '/logistics/tracking', label: 'Rastreamento', icon: Map },
              { path: '/logistics/warehouses', label: 'Armazéns', icon: Archive },
            ],
          },
          {
            path: '/billing',
            label: 'Faturamento',
            icon: CreditCard,
            children: [
              { path: '/billing/invoices', label: 'Faturas', icon: FileText },
              { path: '/billing/payments', label: 'Pagamentos', icon: CreditCard },
              { path: '/billing/refunds', label: 'Estornos', icon: ArrowRightLeft },
            ],
          },
        ],
      },
      {
        id: 'communication',
        label: 'Comunicação',
        items: [
          {
            path: '/notifications',
            label: 'Notificações',
            icon: Bell,
            children: [
              { path: '/notifications/email', label: 'E-mail', icon: Mail },
              { path: '/notifications/sms', label: 'SMS', icon: Phone },
              { path: '/notifications/push', label: 'Push', icon: Bell },
            ],
          },
          {
            path: '/messages',
            label: 'Mensagens',
            icon: MessageSquare,
            children: [
              { path: '/messages/inbox', label: 'Caixa de Entrada', icon: Mail },
              { path: '/messages/sent', label: 'Enviadas', icon: MessageSquare },
              { path: '/messages/templates', label: 'Templates', icon: FileText },
            ],
          },
          { path: '/integrations', label: 'Integrações', icon: Globe },
        ],
      },
      {
        id: 'admin',
        label: 'Administração',
        items: [
          {
            path: '/users',
            label: 'Usuários',
            icon: Users,
            children: [
              { path: '/users/list', label: 'Lista de Usuários', icon: Users },
              { path: '/users/roles', label: 'Perfis de Acesso', icon: Shield },
              { path: '/users/permissions', label: 'Permissões', icon: Key },
              { path: '/users/audit', label: 'Auditoria', icon: Activity },
            ],
          },
          {
            path: '/infrastructure',
            label: 'Infraestrutura',
            icon: Server,
            children: [
              { path: '/infrastructure/servers', label: 'Servidores', icon: Server },
              { path: '/infrastructure/databases', label: 'Bancos de Dados', icon: Database },
              { path: '/infrastructure/backups', label: 'Backups', icon: Archive },
            ],
          },
          {
            path: '/files',
            label: 'Arquivos',
            icon: Folder,
            children: [
              { path: '/files/documents', label: 'Documentos', icon: FileText },
              { path: '/files/media', label: 'Mídia', icon: Layers },
              { path: '/files/exports', label: 'Exportações', icon: FileEdit },
            ],
          },
          { path: '/settings', label: 'Configurações', icon: Settings },
        ],
      },
    ],
    footer: {
      showUser: true,
      showSettings: false,
      showLogout: true,
    },
  },
  render: args => {
    const [isExpanded, setIsExpanded] = useState(false);

    return (
      /* Constrain to ~375 px to reproduce a mobile viewport inside Storybook */
      <div
        className="relative bg-muted/20 overflow-hidden border rounded-[var(--radius-lg)]"
        style={{ width: '375px', height: '100vh', margin: '0 auto' }}
      >
        {/* Page content visible when sidebar is closed */}
        {!isExpanded && (
          <div className="h-full flex flex-col">
            <div className="flex items-center gap-3 px-4 py-3 border-b border-border bg-background">
              <button
                onClick={() => setIsExpanded(true)}
                className="p-2 rounded-md hover:bg-accent transition-colors"
                aria-label="Abrir menu"
              >
                <Menu className="w-5 h-5" />
              </button>
              <span className="font-semibold text-sm">Minha Aplicação</span>
            </div>
            <div className="flex-1 flex items-center justify-center p-8">
              <div className="text-center space-y-2">
                <p className="text-muted-foreground font-medium">Mobile — Subitens</p>
                <p className="text-xs text-muted-foreground">
                  Clique no ícone de menu (☰) no topo para abrir a sidebar em modo
                  tela-cheia. Itens com subitens mostram um{' '}
                  <code className="bg-muted px-1 rounded text-xs">ChevronRight</code> ao final
                  da linha.
                </p>
              </div>
            </div>
          </div>
        )}

        <Sidebar
          {...args}
          expanded={isExpanded}
          onToggle={() => setIsExpanded(prev => !prev)}
          width={375}
          navigate={() => setIsExpanded(false)}
        />
      </div>
    );
  },
};

/**
 * Compound Component API — demonstrates using Sidebar.Root + sub-components
 * for full layout control. This is the recommended pattern for advanced
 * customization without forking the component.
 */
export const CompoundComponentAPI: Story = {
  name: 'Compound Component API',
  render: () => {
    const [isExpanded, setIsExpanded] = React.useState(true);
    const currentWidth = isExpanded ? 280 : 80;
    const groups = [
      {
        id: 'main',
        label: 'Principal',
        items: [
          { path: '/home', label: 'Início', icon: Home },
          { path: '/dashboard', label: 'Dashboard', icon: BarChart },
        ],
      },
      {
        id: 'admin',
        label: 'Administração',
        items: [
          { path: '/users', label: 'Usuários', icon: Users },
          { path: '/settings', label: 'Configurações', icon: Settings },
        ],
      },
    ];

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        {/* Compound Component usage */}
        <Sidebar.Root
          expanded={isExpanded}
          onToggle={() => setIsExpanded(prev => !prev)}
          width={currentWidth}
          location={{ pathname: '/home' }}
          navigate={() => {}}
        >
          <Sidebar.Header />
          <Sidebar.Nav navigationGroups={groups} />
          <Sidebar.Footer
            user={{ name: 'Admin', email: 'admin@example.com' }}
            onLogout={() => console.log('logout')}
            showUser
            showSettings
            showLogout
          />
        </Sidebar.Root>

        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${currentWidth}px` }}
        >
          <div className="text-center max-w-md space-y-3">
            <p className="text-muted-foreground font-bold">Compound Component API</p>
            <p className="text-sm text-muted-foreground/80">
              Built with <code className="bg-muted px-1 rounded text-xs">&lt;Sidebar.Root&gt;</code>
              , <code className="bg-muted px-1 rounded text-xs">&lt;Sidebar.Header&gt;</code>,{' '}
              <code className="bg-muted px-1 rounded text-xs">&lt;Sidebar.Nav&gt;</code>, and{' '}
              <code className="bg-muted px-1 rounded text-xs">&lt;Sidebar.Footer&gt;</code>.
            </p>
            <p className="text-xs text-muted-foreground">
              Each sub-component reads shared state from{' '}
              <code className="bg-muted px-1 rounded text-xs">SidebarContext</code> via{' '}
              <code className="bg-muted px-1 rounded text-xs">Sidebar.Root</code>.
            </p>
          </div>
        </div>
      </div>
    );
  },
};

/**
 * Headless Hook — demonstrates using `useSidebar` directly for fully custom rendering.
 * The hook manages all state; the UI is entirely up to the consumer.
 */
export const HeadlessHook: Story = {
  name: 'Headless Hook (useSidebar)',
  render: () => {
    const groups = [
      {
        id: 'main',
        label: 'Principal',
        items: [
          { path: '/home', label: 'Início', icon: Home },
          { path: '/dashboard', label: 'Dashboard', icon: BarChart },
          { path: '/users', label: 'Usuários', icon: Users },
        ],
      },
    ];

    const {
      expanded,
      toggleExpanded,
      navigationGroups: resolvedGroups,
    } = useSidebar({ defaultExpanded: true, navigationGroups: groups });

    const width = expanded ? 280 : 80;

    return (
      <div
        className="relative h-screen w-full border rounded-[var(--radius-lg)] bg-muted/20 overflow-hidden"
        style={{ transform: 'translateZ(0)' }}
      >
        {/* Fully custom sidebar built with useSidebar hook */}
        <div
          className="absolute inset-y-0 left-0 bg-sidebar text-sidebar-foreground flex flex-col transition-all duration-300 z-50"
          style={{ width: `${width}px` }}
        >
          <div className="p-4">
            <button
              onClick={toggleExpanded}
              className="w-full h-10 flex items-center justify-center rounded-md bg-sidebar-foreground/10 hover:bg-sidebar-foreground/20 text-sidebar-foreground transition-colors"
              aria-label={expanded ? 'Collapse' : 'Expand'}
            >
              {expanded ? <PanelLeft className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </button>
          </div>
          <nav className="flex-1 px-3 space-y-1">
            {resolvedGroups
              .flatMap(g => g.items)
              .map(item => {
                const Icon = item.icon;
                return (
                  <button
                    key={item.path}
                    className="w-full h-10 flex items-center gap-3 px-3 rounded-md text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground transition-colors"
                  >
                    {Icon && <Icon className="w-5 h-5 flex-shrink-0" />}
                    {expanded && <span className="truncate text-sm">{item.label}</span>}
                  </button>
                );
              })}
          </nav>
        </div>

        <div
          className="absolute inset-y-0 right-0 p-8 flex items-center justify-center transition-all duration-300"
          style={{ left: `${width}px` }}
        >
          <div className="text-center max-w-md space-y-3">
            <p className="text-muted-foreground font-bold">Headless Hook</p>
            <p className="text-sm text-muted-foreground/80">
              State managed by <code className="bg-muted px-1 rounded text-xs">useSidebar()</code>.
              The entire UI is custom — no Sidebar component used.
            </p>
            <p className="text-xs text-muted-foreground">
              Sidebar is currently: <strong>{expanded ? 'Expanded' : 'Collapsed'}</strong>
            </p>
          </div>
        </div>
      </div>
    );
  },
};
