import React, { useState, useMemo, useEffect, lazy, Suspense } from 'react';
import { 
  Library, 
  Box, 
  Layers, 
  Code2, 
  ChevronRight,
  Monitor,
  Smartphone,
  Tablet,
  RotateCcw,
  ExternalLink,
  Info,
  Plus,
  FlaskConical,
  Rocket,
  Search,
  Loader2,
  Type,
  Route,
  FileText,
  Download,
  Edit2,
  ChevronLeft,
  Palette,
  Database
} from 'lucide-react';
import { cn } from '@/lib/utils';

// UI Components
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';

// Lazy loading components to showcase
const ExcelTable = lazy(() => import('@/features/prafrot/components/ExcelTable'));
const ItemDetailPanel = lazy(() => import('@/components/shared/ItemDetailPanel').then(m => ({ default: m.ItemDetailPanel })));
const ItemDetailPanelDebug = lazy(() => import('@/components/shared/ItemDetailPanel/ItemDetailPanel.debug').then(m => ({ default: m.ItemDetailPanelDebug })));
const StatusBadge = lazy(() => import('../components/sample/StatusBadge').then(m => ({ default: m.StatusBadge })));
const StatusBadgeDebug = lazy(() => import('../components/sample/StatusBadge/StatusBadge.debug').then(m => ({ default: m.default })));
const FinesCard = lazy(() => import('@/features/prafrot/components/FinesCard').then(m => ({ default: m.FinesCard })));
const FinesCardDebug = lazy(() => import('@/features/prafrot/components/FinesCard/FinesCard.debug').then(m => ({ default: m.default })));
const ThemeTuner = lazy(() => import('../components/ThemeTuner'));
const SmartTable = lazy(() => import('../components/SmartTable'));
const StatsGrid = lazy(() => import('@/components/shared/StatsGrid').then(m => ({ default: m.StatsGrid })));
const DataTable = lazy(() => import('@/components/shared/DataTable').then(m => ({ default: m.DataTable })));
const AutoFillInput = lazy(() => import('@/components/shared/AutoFillInput').then(m => ({ default: m.AutoFillInput })));
const DashboardKPICard = lazy(() => import('@/components/shared/DashboardKPICard').then(m => ({ default: m.DashboardKPICard })));
const DashboardKPICardDebug = lazy(() => import('@/components/shared/DashboardKPICard/DashboardKPICard.debug').then(m => ({ default: m.DashboardKPICardDebug })));
const KanbanBoard = lazy(() => import('@/components/shared/KanbanBoard').then(m => ({ default: m.KanbanBoard })));
const KanbanBoardDebug = lazy(() => import('@/components/shared/KanbanBoard/KanbanBoard.debug').then(m => ({ default: m.KanbanBoardDebug })));
const Sidebar = lazy(() => import('@/features/layout/components/Sidebar').then(m => ({ default: m.Sidebar })));
const SidebarDebug = lazy(() => import('@/features/layout/components/Sidebar/Sidebar.debug').then(m => ({ default: m.SidebarDebug })));
const LoadingOverlay = lazy(() => import('@/components/shared/LoadingOverlay').then(m => ({ default: m.LoadingOverlay })));
const Modal = lazy(() => import('@/components/shared/Modal').then(m => ({ default: m.Modal })));

// Contratos de rotas por ambiente (bundle; edite e baixe JSON para persistir em docs/contratos ou src/.../data/contratos)
import prafrotRoutes from '../data/contratos/prafrot-routes.json';
import workspaceRoutes from '../data/contratos/workspace-routes.json';
import financeiroRoutes from '../data/contratos/financeiro-v2-routes.json';
import rhRoutes from '../data/contratos/rh-routes.json';
import grRoutes from '../data/contratos/gr-routes.json';

/**
 * Loading Placeholder for Lazy Components
 */
const ComponentLoader = () => (
    <div className="flex flex-col items-center justify-center p-12 gap-4 h-full w-full bg-slate-500/5 animate-pulse rounded-xl border border-dashed border-slate-500/20">
        <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Iniciando Laboratório...</span>
    </div>
);

/** Temas por ambiente para preview de tipografia */
const TEMA_AMBIENTE = {
  prafrot: 'theme-frota',
  workspace: 'workspace-theme',
  'financeiro-v2': 'theme-financeiro',
  rh: 'font-sans',
  gr: 'font-sans',
  default: '',
};

/** Views por ambiente para preview de fontes (nome da view + tipo de mock: table | dashboard | list) */
const VIEWS_POR_AMBIENTE = {
  prafrot: [
    { name: 'MaintenanceView', mockType: 'table', title: 'Manutenção' },
    { name: 'DispatcherView', mockType: 'table', title: 'Dispatcher' },
    { name: 'StatisticsView', mockType: 'dashboard', title: 'Estatísticas' },
    { name: 'MonitoringView', mockType: 'table', title: 'Monitoramento' },
  ],
  workspace: [
    { name: 'ExpensesView', mockType: 'list', title: 'Despesas' },
    { name: 'IncomesView', mockType: 'list', title: 'Receitas' },
    { name: 'ReconciliationView', mockType: 'table', title: 'Conciliação' },
    { name: 'FluxoDeCaixaView', mockType: 'dashboard', title: 'Fluxo de Caixa' },
  ],
  'financeiro-v2': [
    { name: 'DashboardView', mockType: 'dashboard', title: 'Dashboard' },
    { name: 'FluxoCaixaView', mockType: 'dashboard', title: 'Fluxo de Caixa' },
    { name: 'ConciliacaoView', mockType: 'table', title: 'Conciliação' },
    { name: 'BoletosView', mockType: 'table', title: 'Boletos' },
  ],
  rh: [
    { name: 'RhDashboardView', mockType: 'dashboard', title: 'Dashboard RH' },
    { name: 'EmployeesView', mockType: 'table', title: 'Colaboradores' },
    { name: 'TrabalhadoresView', mockType: 'table', title: 'Trabalhadores' },
  ],
  gr: [
    { name: 'ContractsView', mockType: 'table', title: 'Contratos' },
    { name: 'RegistrationsView', mockType: 'table', title: 'Cadastros' },
  ],
};

/** Telinha de preview de uma view (mock de tabela, dashboard ou lista com tema aplicado) */
const TelinhaView = React.memo(({ viewName, mockType, title, themeClass, dark }) => {
  const base = cn('rounded-lg border overflow-hidden h-full flex flex-col', dark ? 'bg-white/5 border-white/10' : 'bg-slate-50/80 border-slate-200', themeClass);
  return (
    <div className={cn('w-full max-w-[280px] h-[200px] flex flex-col', base)}>
      <div className={cn('px-3 py-2 border-b', dark ? 'border-white/10' : 'border-slate-200')}>
        <p className="text-caption font-label text-muted-foreground truncate" title={viewName}>{title}</p>
      </div>
      <div className="flex-1 p-2 overflow-hidden">
        {mockType === 'table' && (
          <div className="text-table font-body">
            <table className="w-full text-left">
              <thead>
                <tr className={cn('text-label font-label', dark ? 'text-slate-400' : 'text-slate-500')}>
                  <th className="py-1 pr-2">Col. A</th>
                  <th className="py-1">Col. B</th>
                </tr>
              </thead>
              <tbody className="text-foreground">
                <tr><td className="py-0.5 pr-2">Valor 1</td><td className="py-0.5">Valor 2</td></tr>
                <tr><td className="py-0.5 pr-2">Valor 3</td><td className="py-0.5">Valor 4</td></tr>
              </tbody>
            </table>
          </div>
        )}
        {mockType === 'dashboard' && (
          <div className="grid grid-cols-2 gap-1.5">
            <div className={cn('p-2 rounded border', dark ? 'bg-white/5 border-white/10' : 'bg-white border-slate-200')}>
              <p className="text-caption text-muted-foreground">KPI 1</p>
              <p className="text-title-lg font-title text-foreground">142</p>
            </div>
            <div className={cn('p-2 rounded border', dark ? 'bg-white/5 border-white/10' : 'bg-white border-slate-200')}>
              <p className="text-caption text-muted-foreground">KPI 2</p>
              <p className="text-title-lg font-title text-foreground">R$ 1,2M</p>
            </div>
          </div>
        )}
        {mockType === 'list' && (
          <ul className="space-y-1 text-body font-body text-foreground">
            <li className="truncate">Item lista 1</li>
            <li className="truncate">Item lista 2</li>
            <li className="truncate">Item lista 3</li>
          </ul>
        )}
      </div>
    </div>
  );
});

/** Preview do tema de tipografia + sub-tela por ambiente + telinhas por view */
const TypographyPanel = React.memo(({ theme }) => {
  const [typographyTab, setTypographyTab] = useState('geral');
  const [ambientePreview, setAmbientePreview] = useState('prafrot');
  const ambientes = [
    { id: 'prafrot', label: 'Prafrot' },
    { id: 'workspace', label: 'Workspace' },
    { id: 'financeiro-v2', label: 'Financeiro v2' },
    { id: 'rh', label: 'RH' },
    { id: 'gr', label: 'GR' },
  ];
  const themeClass = TEMA_AMBIENTE[ambientePreview] || TEMA_AMBIENTE.default;
  const viewsDoAmbiente = VIEWS_POR_AMBIENTE[ambientePreview] || [];
  const dark = theme === 'dark';
  return (
    <div className={cn("mx-auto max-w-4xl p-8 rounded-2xl border", dark ? "bg-[#111] border-white/5" : "bg-white border-slate-200")}>
      <h2 className="text-title font-title text-foreground mb-6">Tipografia / Fontes</h2>
      <Tabs value={typographyTab} onValueChange={setTypographyTab} className="w-full">
        <TabsList className={cn("p-1 border mb-6", dark ? "bg-white/5 border-white/10" : "bg-slate-100 border-slate-200")}>
          <TabsTrigger value="geral" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Preview geral</TabsTrigger>
          <TabsTrigger value="por-ambiente" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Preview por ambiente</TabsTrigger>
        </TabsList>
        <TabsContent value="geral" className="space-y-8">
          <p className="text-body font-body text-muted-foreground mb-6">
            Preview dos estilos do tema global. Use <code className="px-1.5 py-0.5 rounded bg-muted text-xs font-mono">text-title</code>, <code className="px-1.5 py-0.5 rounded bg-muted text-xs font-mono">text-body</code>, <code className="px-1.5 py-0.5 rounded bg-muted text-xs font-mono">text-label</code> nas telas.
          </p>
          <div className="space-y-8">
            <div>
              <span className="text-label font-label text-muted-foreground uppercase tracking-wider block mb-2">Título principal</span>
              <p className="text-title font-title text-foreground">Dashboard Integra RH</p>
            </div>
            <div>
              <span className="text-label font-label text-muted-foreground uppercase tracking-wider block mb-2">Subtítulo</span>
              <p className="text-subtitle font-body text-foreground">Resumo do mês atual</p>
            </div>
            <div>
              <span className="text-label font-label text-muted-foreground uppercase tracking-wider block mb-2">Corpo</span>
              <p className="text-body font-body text-foreground">Corpo de texto padrão para leitura. Tamanho mínimo 14px–16px.</p>
            </div>
            <div>
              <span className="text-label font-label text-muted-foreground uppercase tracking-wider block mb-2">Número em card</span>
              <p className="text-title-lg font-title text-foreground">R$ 159,2M</p>
            </div>
          </div>
        </TabsContent>
        <TabsContent value="por-ambiente" className="space-y-6">
          <p className="text-body font-body text-muted-foreground">
            Teste como a fonte fica em cada ambiente e em cada view (aplica a classe de tema do módulo).
          </p>
          <div className="flex flex-wrap gap-2 mb-4">
            {ambientes.map((a) => (
              <Button
                key={a.id}
                variant={ambientePreview === a.id ? 'default' : 'outline'}
                size="sm"
                onClick={() => setAmbientePreview(a.id)}
                className={ambientePreview === a.id ? 'bg-emerald-500 hover:bg-emerald-600' : ''}
              >
                {a.label}
              </Button>
            ))}
          </div>
          <div className={cn("p-6 rounded-xl border min-h-[120px] mb-6", dark ? "bg-white/5 border-white/10" : "bg-slate-50 border-slate-200", themeClass)}>
            <p className="text-caption text-muted-foreground mb-2">Ambiente: {ambientes.find((a) => a.id === ambientePreview)?.label}</p>
            <p className="text-title font-title text-foreground mb-2">Título no {ambientes.find((a) => a.id === ambientePreview)?.label}</p>
            <p className="text-body font-body text-foreground">Corpo de texto e tabelas usam o mesmo tema.</p>
          </div>
          <div>
            <p className="text-label font-label text-foreground mb-3">Como ficam as fontes em cada view do ambiente</p>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
              {viewsDoAmbiente.map((v) => (
                <TelinhaView
                  key={v.name}
                  viewName={v.name}
                  mockType={v.mockType}
                  title={v.title}
                  themeClass={themeClass}
                  dark={dark}
                />
              ))}
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
});

/** Papéis padrão (roles) para organização da aba Componentes. Lista interna = referência para novos ambientes. */
const PAPEIS_PADRAO = [
  { id: 'apresentacao', label: 'Apresentação de dados', descricao: 'Listagem/tabela de registros (GET list)' },
  { id: 'detalhamento', label: 'Detalhamento', descricao: 'Painel ou modal de detalhe de um registro (GET :id)' },
  { id: 'formulario', label: 'Formulário', descricao: 'Criação/edição (POST, PUT) – modal ou página' },
  { id: 'filtros', label: 'Filtros', descricao: 'Filtros avançados ou busca' },
  { id: 'cards', label: 'Cards / KPIs', descricao: 'Resumos numéricos, dashboards' },
  { id: 'notificacao', label: 'Notificação / feedback', descricao: 'Toasts, avisos' },
];

/** Lista interna: componentes que o projeto adota como padrão por papel. Ao adicionar uma view, preencher o mapeamento em COMPONENTES_POR_AMBIENTE_PAPEL. */
const COMPONENTES_INTERNOS = {
  apresentacao: ['ExcelTable'],
  detalhamento: ['ItemDetailPanel', 'EmployeeDetailPanel'],
  formulario: ['Dialog'],
  filtros: ['AdvancedFiltersModal', 'AutoFillInput'],
  cards: ['DashboardKPICard', 'StatsGrid', 'FinesCard'],
  notificacao: ['FeedbackNotification'],
};

/** Por ambiente: qual componente cumpre cada papel. Usado na aba Componentes para exibir Papel | Componente | Na lista interna? */
const COMPONENTES_POR_AMBIENTE_PAPEL = [
  { ambiente: 'Prafrot', papeis: { apresentacao: 'ExcelTable', detalhamento: 'ItemDetailPanel', formulario: 'Dialog', filtros: 'AdvancedFiltersModal', cards: 'FinesCard', notificacao: 'FeedbackNotification' }, views: ['MaintenanceView', 'DispatcherView', 'StatisticsView'] },
  { ambiente: 'Workspace', papeis: { apresentacao: 'WorkspaceLayout', detalhamento: '—', formulario: 'Dialog', filtros: 'AutoFillInput', cards: 'FineCard', notificacao: '—' }, views: ['ExpensesView', 'IncomesView', 'ReconciliationView', 'FluxoDeCaixaView'] },
  { ambiente: 'Financeiro v2', papeis: { apresentacao: 'ExcelTable', detalhamento: '—', formulario: 'Dialog', filtros: 'AutoFillInput', cards: 'DashboardKPICard', notificacao: '—' }, views: ['DashboardView', 'FluxoCaixaView', 'ConciliacaoView'] },
  { ambiente: 'RH', papeis: { apresentacao: 'ExcelTable', detalhamento: 'EmployeeDetailPanel', formulario: 'Dialog', filtros: 'AutoFillInput', cards: 'StatsGrid', notificacao: '—' }, views: ['RhDashboardView', 'EmployeesView'] },
  { ambiente: 'GR', papeis: { apresentacao: 'ExcelTable', detalhamento: '—', formulario: 'Dialog', filtros: '—', cards: '—', notificacao: '—' }, views: ['ContractsView', 'RegistrationsView'] },
];

const CONTRACT_ENV_IDS = ['prafrot', 'workspace', 'financeiro-v2', 'rh', 'gr'];

/** Labels por envId para fallback na aba Ambientes quando contrato não carrega */
const ENV_LABELS = { 
  prafrot: 'Prafrot (Prafrota)', 
  workspace: 'Workspace',
  'financeiro-v2': 'Financeiro v2',
  rh: 'RH (Recursos Humanos)',
  gr: 'GR (Gerenciamento)'
};

const methodColor = (method) => {
  if (method === 'GET') return 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30';
  if (method === 'POST') return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
  if (method === 'PUT' || method === 'PATCH') return 'bg-amber-500/20 text-amber-400 border-amber-500/30';
  return 'bg-slate-500/20 text-slate-400 border-slate-500/30';
};

/** Gera exemplo de JSON a partir do responseShape */
const buildExampleFromShape = (responseShape) => {
  if (!responseShape || !responseShape.length) return {};
  const obj = {};
  responseShape.forEach(({ field, type }) => {
    if (type === 'number') obj[field] = 1;
    else if (type === 'boolean') obj[field] = true;
    else obj[field] = `${field}_exemplo`;
  });
  return obj;
};

const RotasPanel = React.memo(({ theme }) => {
  const [tab, setTab] = useState('mapa');
  const [contracts] = useState({ 
    prafrot: prafrotRoutes, 
    workspace: workspaceRoutes,
    'financeiro-v2': financeiroRoutes,
    rh: rhRoutes,
    gr: grRoutes
  });
  const loading = false; // reserved for future async contract loading
  const [selectedEnv, setSelectedEnv] = useState(null);
  const [selectedRoute, setSelectedRoute] = useState(null);
  const [selectedOp, setSelectedOp] = useState(null);
  const [editPayload, setEditPayload] = useState(null);
  const [editRaw, setEditRaw] = useState('');
  const [mapEnvTab, setMapEnvTab] = useState('prafrot'); // New state for sub-tabs in 'mapa'

  /** Fallback estático quando os JSON não carregam (ex.: base path, 404) */
  const FALLBACK_FLAT_OPS = useMemo(() => [
    { envId: 'prafrot', envLabel: 'Prafrot (Prafrota)', method: 'GET', path: '/cadastro_frota/apresentar', descricao: 'Lista veículos cadastrados na frota' },
    { envId: 'prafrot', envLabel: 'Prafrot (Prafrota)', method: 'GET', path: '/manutencao_frota/apresentar', descricao: 'Lista todas as manutenções' },
    { envId: 'workspace', envLabel: 'Workspace', method: 'GET', path: '/extrato/apresentar', descricao: 'Extrato bancário; C=receitas, D=despesas' },
    { envId: 'financeiro-v2', envLabel: 'Financeiro v2', method: 'GET', path: '/boletos/apresentar', descricao: 'Lista de boletos e títulos' },
    { envId: 'rh', envLabel: 'RH', method: 'GET', path: '/colaboradores/apresentar', descricao: 'Lista de colaboradores ativos' },
    { envId: 'gr', envLabel: 'GR', method: 'GET', path: '/gr/contratos', descricao: 'Lista de contratos GR' },
  ], []);

  const flatOps = useMemo(() => {
    const list = [];
    CONTRACT_ENV_IDS.forEach((envId) => {
      const c = contracts[envId];
      if (!c || !c.rotas) return;
      c.rotas.forEach((r) => {
        (r.operations || []).forEach((op) => {
          list.push({ envId, envLabel: c.label, recurso: r.recurso, ...op });
        });
      });
    });
    return list.length > 0 ? list : FALLBACK_FLAT_OPS;
  }, [contracts, FALLBACK_FLAT_OPS]);

  const handleDownloadContract = (envId) => {
    let c = contracts[envId];
    if (editRaw) {
      try {
        c = JSON.parse(editRaw);
      } catch (_) {
        c = editPayload || c;
      }
    } else if (editPayload) {
      c = editPayload;
    }
    if (!c) return;
    const blob = new Blob([JSON.stringify(c, null, 2)], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${envId}-routes.json`;
    a.click();
    URL.revokeObjectURL(a.href);
  };

  const currentContract = selectedEnv ? contracts[selectedEnv] : null;
  const currentRouteGroup = currentContract?.rotas?.find((r) => r.id === selectedRoute);
  const currentOp = currentRouteGroup?.operations?.find((o) => o.path === selectedOp?.path && o.method === selectedOp?.method);

  // Filter ops by the selected sub-tab environment
  const displayedOps = flatOps.filter(op => op.envId === mapEnvTab);

  return (
    <div className={cn("mx-auto max-w-6xl p-8 rounded-2xl border", theme === 'dark' ? "bg-[#111] border-white/5" : "bg-white border-slate-200")}>
      <div className="flex items-center gap-3 mb-6">
        <Route className="text-emerald-500" size={24} />
        <h2 className="text-title font-title text-foreground">Rotas e Ambientes</h2>
      </div>
      <p className="text-body font-body text-muted-foreground mb-6">
        Contratos em <code className="px-1.5 py-0.5 rounded bg-muted text-xs font-mono">public/contratos/</code>. Detalhe o que cada rota devolve; edite e baixe o JSON para atualizar o doc do ambiente.
      </p>

      {loading ? (
        <div className="flex items-center justify-center py-12 gap-2 text-muted-foreground">
          <Loader2 className="w-5 h-5 animate-spin" />
          <span>Carregando contratos...</span>
        </div>
      ) : (
        <Tabs value={tab} onValueChange={setTab} className="w-full">
          <TabsList className={cn("p-1 border mb-6", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-100 border-slate-200")}>
            <TabsTrigger value="mapa" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Mapa visual</TabsTrigger>
            <TabsTrigger value="ambientes" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Ambientes</TabsTrigger>
            <TabsTrigger value="componentes" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Componentes</TabsTrigger>
          </TabsList>

          <TabsContent value="mapa" className="space-y-6">
            <div className="mb-4">
                 <Tabs value={mapEnvTab} onValueChange={setMapEnvTab} className="w-full">
                      <TabsList className="bg-transparent border-b rounded-none p-0 h-auto justify-start mb-4">
                          {CONTRACT_ENV_IDS.map(envId => (
                              <TabsTrigger 
                                key={envId} 
                                value={envId}
                                className={cn(
                                    "rounded-none border-b-2 border-transparent px-4 py-2 font-medium text-muted-foreground data-[state=active]:text-emerald-500 data-[state=active]:border-emerald-500 bg-transparent shadow-none"
                                )}
                              >
                                {contracts[envId]?.label || envId.toUpperCase()}
                              </TabsTrigger>
                          ))}
                      </TabsList>
                 </Tabs>
            </div>

            {flatOps.length > 0 && !contracts.prafrot && !contracts.workspace && (
              <p className="text-caption text-amber-500 dark:text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-4 py-2">
                Contratos não carregados; exibindo lista resumida. Coloque os arquivos em <code className="px-1 rounded bg-muted">public/contratos/prafrot-routes.json</code> e <code className="px-1 rounded bg-muted">workspace-routes.json</code> para ver detalhes e editar.
              </p>
            )}
            {(selectedEnv && selectedRoute && currentOp) ? (
              <div>
                <Button variant="ghost" size="sm" className="mb-4 gap-1" onClick={() => { setSelectedOp(null); setSelectedRoute(null); setSelectedEnv(null); setEditPayload(null); }}>
                  <ChevronLeft size={16} /> Voltar ao mapa
                </Button>
                <Card className={cn("p-6 border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-50 border-slate-200")}>
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2 flex-wrap">
                      <Badge className={cn("font-mono", methodColor(currentOp.method))}>{currentOp.method}</Badge>
                      <span className="font-mono text-sm text-foreground">{currentOp.path}</span>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => {
                        const copy = contracts[selectedEnv] ? JSON.parse(JSON.stringify(contracts[selectedEnv])) : null;
                        setEditPayload(copy);
                        setEditRaw(copy ? JSON.stringify(copy, null, 2) : '');
                      }}>
                        <Edit2 size={14} className="mr-1" /> Editar contrato
                      </Button>
                      {(editPayload || editRaw) && (
                        <Button size="sm" variant="ghost" onClick={() => { setEditPayload(null); setEditRaw(''); }} className="text-muted-foreground">
                          Cancelar edição
                        </Button>
                      )}
                      <Button size="sm" variant="outline" onClick={() => handleDownloadContract(selectedEnv)}>
                        <Download size={14} className="mr-1" /> Baixar JSON
                      </Button>
                    </div>
                  </div>
                  {(editPayload || editRaw) && (
                    <div className="mb-4">
                      <span className="text-caption text-muted-foreground block mb-2">Edite o JSON do ambiente e use &quot;Baixar JSON&quot; para substituir <code className="px-1 rounded bg-muted">public/contratos/{selectedEnv}-routes.json</code> ou <code className="px-1 rounded bg-muted">docs/contratos/{selectedEnv}-routes.json</code>.</span>
                      <textarea
                        className={cn("w-full min-h-[200px] p-4 rounded-lg font-mono text-xs border", theme === 'dark' ? "bg-black/40 border-white/10 text-slate-200" : "bg-slate-100 border-slate-200 text-slate-900")}
                        value={editRaw}
                        onChange={(e) => setEditRaw(e.target.value)}
                        spellCheck={false}
                      />
                      <p className="text-caption text-muted-foreground mt-1">Altere o texto acima (JSON válido) e clique em Baixar JSON para gravar no seu ambiente.</p>
                    </div>
                  )}
                  <p className="text-body text-muted-foreground mb-4">{currentOp.descricao}</p>
                  <Tabs defaultValue="resposta" className="w-full">
                    <TabsList className={cn("p-1 border mb-4", theme === 'dark' ? "bg-black/40 border-white/10" : "bg-slate-100 border-slate-200")}>
                      <TabsTrigger value="resposta" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">O que devolve</TabsTrigger>
                      <TabsTrigger value="requisicao" className="data-[state=active]:bg-emerald-500 data-[state=active]:text-white">Requisição</TabsTrigger>
                    </TabsList>
                    <TabsContent value="resposta" className="space-y-4">
                      {currentOp.responseShape?.length > 0 ? (
                        <>
                          <div className={cn("border rounded-lg overflow-hidden", theme === 'dark' ? "border-white/10" : "border-slate-200")}>
                            <table className="w-full text-sm">
                              <thead className={theme === 'dark' ? "bg-white/5" : "bg-slate-50"}>
                                <tr>
                                  <th className="text-left p-3 font-label">Campo</th>
                                  <th className="text-left p-3 font-label">Tipo</th>
                                  <th className="text-left p-3 font-label">Descrição</th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-border">
                                {currentOp.responseShape.map((s) => (
                                  <tr key={s.field}>
                                    <td className="p-3 font-mono text-emerald-500">{s.field}</td>
                                    <td className="p-3 text-muted-foreground">{s.type}</td>
                                    <td className="p-3 text-muted-foreground">{s.description || '-'}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                          <div>
                            <span className="text-caption text-muted-foreground block mb-2">Exemplo de resposta (1 item)</span>
                            <pre className={cn("p-4 rounded-lg text-xs font-mono overflow-x-auto", theme === 'dark' ? "bg-black/40 border border-white/10" : "bg-slate-100 border border-slate-200")}>
                              {JSON.stringify(buildExampleFromShape(currentOp.responseShape), null, 2)}
                            </pre>
                          </div>
                        </>
                      ) : (
                        <p className="text-muted-foreground text-sm">Sem responseShape definido.</p>
                      )}
                    </TabsContent>
                    <TabsContent value="requisicao" className="space-y-4">
                      {currentOp.requestBody?.length > 0 ? (
                        <div className={cn("border rounded-lg overflow-hidden", theme === 'dark' ? "border-white/10" : "border-slate-200")}>
                          <table className="w-full text-sm">
                            <thead className={theme === 'dark' ? "bg-white/5" : "bg-slate-50"}>
                              <tr>
                                <th className="text-left p-3 font-label">Campo</th>
                                <th className="text-left p-3 font-label">Tipo</th>
                                <th className="text-left p-3 font-label">Obrigatório</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                              {currentOp.requestBody.map((b) => (
                                <tr key={b.field}>
                                  <td className="p-3 font-mono text-blue-500">{b.field}</td>
                                  <td className="p-3 text-muted-foreground">{b.type}</td>
                                  <td className="p-3">{b.required ? 'Sim' : 'Não'}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      ) : (
                        <p className="text-muted-foreground text-sm">Rota sem body (GET) ou requestBody não definido.</p>
                      )}
                    </TabsContent>
                  </Tabs>
                </Card>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {displayedOps.map((op) => (
                  <Card
                    key={`${op.envId}-${op.path}-${op.method}`}
                    className={cn(
                      "p-4 border cursor-pointer transition-all hover:ring-2 hover:ring-emerald-500/50",
                      theme === 'dark' ? "bg-white/5 border-white/10 hover:bg-white/10" : "bg-slate-50/50 border-slate-200 hover:bg-slate-100"
                    )}
                    onClick={() => {
                      setSelectedEnv(op.envId);
                      setSelectedRoute(contracts[op.envId]?.rotas?.find((r) => r.operations?.some((o) => o.path === op.path && o.method === op.method))?.id);
                      setSelectedOp({ path: op.path, method: op.method });
                    }}
                  >
                    <div className="flex items-center gap-2 flex-wrap mb-2">
                      <Badge className={cn("font-mono text-xs", methodColor(op.method))}>{op.method}</Badge>
                      <span className="text-caption text-muted-foreground">{op.envLabel}</span>
                    </div>
                    <p className="font-mono text-sm text-foreground break-all">{op.path}</p>
                    {op.descricao && <p className="text-caption text-muted-foreground mt-1 line-clamp-2">{op.descricao}</p>}
                  </Card>
                ))}
                {displayedOps.length === 0 && (
                     <p className="text-muted-foreground col-span-full py-8 text-center bg-muted/20 rounded border border-dashed">
                       Ainda não há rotas documentadas para este ambiente.
                     </p>
                )}
              </div>
            )}
          </TabsContent>

          <TabsContent value="ambientes" className="space-y-4">
            {CONTRACT_ENV_IDS.map((envId) => {
              const c = contracts[envId];
              const label = c?.label ?? ENV_LABELS[envId] ?? envId;
              const opCount = c?.rotas?.reduce((acc, r) => acc + (r.operations?.length || 0), 0) ?? 0;
              const fallbackOpCount = FALLBACK_FLAT_OPS.filter((o) => o.envId === envId).length;
              return (
                <Card key={envId} className={cn("p-4 border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-50/50 border-slate-200")}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <FileText size={16} className={c ? "text-emerald-500" : "text-muted-foreground"} />
                      <span className="font-label text-foreground">{label}</span>
                    </div>
                    {c ? (
                      <div className="flex gap-2">
                        <span className="text-caption text-muted-foreground">{opCount} operações</span>
                        <Button size="sm" variant="outline" onClick={() => handleDownloadContract(envId)}>
                          <Download size={12} className="mr-1" /> JSON
                        </Button>
                      </div>
                    ) : (
                      <span className="text-caption text-muted-foreground">{fallbackOpCount} rotas (resumo)</span>
                    )}
                  </div>
                  {c ? (
                    <ul className="mt-2 text-body text-muted-foreground space-y-1 font-mono text-sm">
                      {c.rotas?.slice(0, 5).map((r) => (
                        <li key={r.id}>{r.recurso}: {r.operations?.length || 0} ops</li>
                      ))}
                    </ul>
                  ) : (
                    <div className="mt-2 text-body text-muted-foreground space-y-1">
                      <p>Contratos não carregados para este ambiente.</p>
                      <p className="text-caption">
                        Coloque os JSON em <code className="px-1 rounded bg-muted">public/contratos/{envId}-routes.json</code> ou use os dados do bundle em <code className="px-1 rounded bg-muted">src/features/dev-tools/data/contratos/</code>.
                      </p>
                    </div>
                  )}
                </Card>
              );
            })}
          </TabsContent>

          <TabsContent value="componentes" className="space-y-4">
            {COMPONENTES_POR_AMBIENTE_PAPEL.map((row) => {
              const isNaListaInterna = (papelId, componente) =>
                componente && componente !== '—' && (COMPONENTES_INTERNOS[papelId] ?? []).includes(componente);
              return (
                <Card key={row.ambiente} className={cn("p-4 border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-50/50 border-slate-200")}>
                  <div className="font-label text-foreground mb-3">{row.ambiente}</div>
                  <Table>
                    <TableHeader>
                      <TableRow className={theme === 'dark' ? "border-white/10" : ""}>
                        <TableHead className="font-label text-muted-foreground">Papel</TableHead>
                        <TableHead className="font-label text-muted-foreground">Componente usado</TableHead>
                        <TableHead className="font-label text-muted-foreground">Na lista interna?</TableHead>
                        <TableHead className="font-label text-muted-foreground">Views</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {PAPEIS_PADRAO.map((papel) => {
                        const componente = row.papeis[papel.id] ?? '—';
                        const naLista = isNaListaInterna(papel.id, componente);
                        return (
                          <TableRow key={papel.id} className={theme === 'dark' ? "border-white/5" : ""}>
                            <TableCell className="text-body text-foreground">{papel.label}</TableCell>
                            <TableCell className="font-mono text-sm text-foreground">{componente}</TableCell>
                            <TableCell>
                              {componente === '—' ? (
                                <span className="text-caption text-muted-foreground">—</span>
                              ) : naLista ? (
                                <Badge variant="secondary" className="bg-emerald-500/20 text-emerald-600 dark:text-emerald-400">Sim</Badge>
                              ) : (
                                <Badge variant="outline" className="text-amber-600 dark:text-amber-400 border-amber-500/30">Não</Badge>
                              )}
                            </TableCell>
                            <TableCell className="text-caption text-muted-foreground font-mono">{row.views?.slice(0, 3).join(', ')}{row.views?.length > 3 ? '…' : ''}</TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </Card>
              );
            })}
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
});

// Sidebar Navigation Component
const SidebarNav = React.memo(({ 
    activeCategory, 
    setActiveCategory, 
    setSelectedComponent, 
    theme, 
    setTheme,
    categories,
    searchQuery,
    setSearchQuery,
    filteredComponents,
    selectedComponent
}) => (
  <aside className={cn(
    "w-80 flex flex-col border-r h-full",
    theme === 'dark' ? "bg-[#111] border-white/5" : "bg-white border-slate-200"
  )}>
    <div className="p-6">
      <div className="flex items-center gap-3 mb-8">
        <div className="w-10 h-10 bg-emerald-500 rounded-xl flex items-center justify-center shadow-lg shadow-emerald-500/20">
          <Box className="text-white" size={20} />
        </div>
        <div>
          <h1 className="font-black tracking-tight text-lg leading-tight uppercase italic">Component</h1>
          <span className="text-[10px] font-bold text-emerald-500 tracking-[0.3em] uppercase opacity-80">Laboratory</span>
        </div>
      </div>

      <div className="space-y-1">
        {categories.map((cat) => (
          <button
            key={cat.id}
            onClick={() => {
              setActiveCategory(cat.id);
              setSelectedComponent(null);
            }}
            className={cn(
              "w-full flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200",
              activeCategory === cat.id 
                ? (theme === 'dark' ? "bg-emerald-500/10 text-emerald-400" : "bg-emerald-50 text-emerald-600")
                : (theme === 'dark' ? "text-slate-500 hover:text-slate-300 hover:bg-white/5" : "text-slate-600 hover:bg-slate-100")
            )}
          >
            <cat.icon size={18} />
            {cat.label}
            {activeCategory === cat.id && (
              <div className="ml-auto w-1.5 h-1.5 rounded-full bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]" />
            )}
          </button>
        ))}
      </div>
    </div>

    <Separator className={theme === 'dark' ? "bg-white/5" : "bg-slate-100"} />

    <ScrollArea className="flex-1">
      <div className="p-4 space-y-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={14} />
          <input 
            type="text" 
            placeholder="Filtrar componentes..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className={cn(
              "w-full pl-9 pr-4 py-2 rounded-md text-xs border focus:outline-none transition-all",
              theme === 'dark' ? "bg-white/5 border-white/10 focus:border-emerald-500/50 text-white" : "bg-slate-100 border-slate-200 focus:border-emerald-500/50"
            )}
          />
        </div>

        <div className="space-y-1">
          <span className="px-2 text-[10px] font-bold text-slate-500 uppercase tracking-widest">Lista de Items</span>
          {filteredComponents.map((comp) => (
            <button
              key={comp.name}
              onClick={() => setSelectedComponent(comp)}
              className={cn(
                "w-full flex items-center justify-between px-3 py-2.5 rounded-md text-sm transition-all group",
                selectedComponent?.name === comp.name
                  ? (theme === 'dark' ? "bg-white/5 text-white" : "bg-white shadow-sm ring-1 ring-slate-200 text-slate-900")
                  : (theme === 'dark' ? "text-slate-400 hover:text-slate-200 hover:bg-white/5" : "text-slate-600 hover:bg-slate-100")
              )}
            >
              <span className="truncate">{comp.name}</span>
              <div className="flex items-center gap-2">
                {comp.debugRender && (
                    <FlaskConical size={12} className="text-purple-400" title="Possui versão Debug" />
                )}
                <ChevronRight size={14} className={cn(
                    "transition-transform shrink-0",
                    selectedComponent?.name === comp.name ? "rotate-90 text-emerald-500" : "opacity-0 group-hover:opacity-100"
                )} />
              </div>
            </button>
          ))}
          {filteredComponents.length === 0 && (
              <div className="p-4 text-center text-xs text-slate-500 italic">Nenhum componente encontrado.</div>
          )}
        </div>
      </div>
    </ScrollArea>

    {/* Theme Toggler - Restored to Sidebar */}
    <div className="p-4 border-t border-white/5">
      <div className="flex gap-2 p-1 bg-black/20 rounded-lg">
        <button 
          onClick={() => setTheme('dark')}
          className={cn(
            "flex-1 py-1.5 rounded text-[10px] font-bold uppercase tracking-wider transition-all",
            theme === 'dark' ? "bg-emerald-500 text-white shadow-lg shadow-emerald-500/20" : "text-slate-500 hover:text-slate-300"
          )}
        >
          Dark Mode
        </button>
        <button 
          onClick={() => setTheme('light')}
          className={cn(
            "flex-1 py-1.5 rounded text-[10px] font-bold uppercase tracking-wider transition-all",
            theme === 'light' ? "bg-white text-emerald-600 shadow-sm" : "text-slate-500 hover:text-slate-300"
          )}
        >
          Light Mode
        </button>
      </div>
    </div>
  </aside>
));

// Header/Toolbar Component
const PlaygroundHeader = React.memo(({ 
    selectedComponent, 
    activeCategory, 
    theme, 
    versionMode, 
    setVersionMode, 
    viewMode, 
    setViewMode 
}) => (
  <header className={cn(
    "h-16 flex items-center justify-between px-8 border-b transition-colors",
    theme === 'dark' ? "bg-[#0d0d0d] border-white/5" : "bg-white border-slate-200"
  )}>
    <div className="flex items-center gap-4">
      {selectedComponent ? (
        <>
          <Badge variant="outline" className="text-emerald-500 border-emerald-500/20 px-2 py-0 text-[10px] uppercase font-bold tracking-tighter">{activeCategory}</Badge>
          <div className="h-4 w-[1px] bg-white/10" />
          <h2 className="text-lg font-bold tracking-tight">{selectedComponent.name}</h2>
        </>
      ) : (
        <h2 className="text-lg font-bold tracking-tight text-slate-500 italic">Pronto para criar sua próxima obra-prima?</h2>
      )}
    </div>

    <div className="flex items-center gap-6">
      <div className={cn(
          "flex p-1 rounded-lg border",
          theme === 'dark' ? "bg-black/20 border-white/5" : "bg-slate-100 border-slate-200"
      )}>
          <button 
            onClick={() => setVersionMode('production')}
            className={cn(
                "flex items-center gap-2 px-3 py-1.5 rounded transition-all text-[10px] font-bold uppercase tracking-wider",
                versionMode === 'production' 
                  ? (theme === 'dark' ? "bg-emerald-500 text-white shadow-lg shadow-emerald-500/20" : "bg-emerald-500 text-white")
                  : "text-slate-500 hover:text-slate-300"
            )}
          >
            <Rocket size={12} />
            Production
          </button>
          <button 
            onClick={() => setVersionMode('debug')}
            className={cn(
              "flex items-center gap-2 px-3 py-1.5 rounded transition-all text-[10px] font-bold uppercase tracking-wider",
              versionMode === 'debug'
                ? (theme === 'dark' ? "bg-purple-500 text-white shadow-lg shadow-purple-500/20" : "bg-purple-500 text-white")
                : "text-slate-500 hover:text-slate-300"
            )}
          >
            <FlaskConical size={12} />
            Debug
          </button>
      </div>

      <Separator orientation="vertical" className="h-6 bg-white/10 mx-1" />

      <div className={cn(
          "flex p-1 rounded-lg border",
          theme === 'dark' ? "bg-black/20 border-white/5" : "bg-slate-100 border-slate-200"
      )}>
        <button 
          onClick={() => setViewMode('mobile')}
          className={cn("p-1.5 rounded transition-all", viewMode === 'mobile' ? "bg-emerald-500 text-white" : "text-slate-400")}
          title="Mobile View"
        >
          <Smartphone size={16} />
        </button>
        <button 
          onClick={() => setViewMode('tablet')}
          className={cn("p-1.5 rounded transition-all", viewMode === 'tablet' ? "bg-emerald-500 text-white" : "text-slate-400")}
          title="Tablet View"
        >
          <Tablet size={16} />
        </button>
        <button 
          onClick={() => setViewMode('desktop')}
          className={cn("p-1.5 rounded transition-all", viewMode === 'desktop' ? "bg-emerald-500 text-white" : "text-slate-400")}
          title="Desktop View"
        >
          <Monitor size={16} />
        </button>
      </div>
    </div>
  </header>
));

/**
 * Component Laboratory - Main View
 * A premium environment to test and document components.
 */
const PlaygroundView = () => {
  const [activeCategory, setActiveCategory] = useState('shared');
  const [selectedComponent, setSelectedComponent] = useState(null);
  const [viewMode, setViewMode] = useState('desktop'); 
  const [versionMode, setVersionMode] = useState('production'); 
  const [theme, setTheme] = useState('dark');
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  // Debounce search query
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  const categories = useMemo(() => [
    { id: 'shared', label: 'Componentes Shared', icon: Layers },
    { id: 'connector', label: 'Conector Universal', icon: Database },
    { id: 'ui', label: 'Base UI (Shadcn)', icon: Box },
    { id: 'icons', label: 'Ícones & Assets', icon: Library },
    { id: 'layout', label: 'Componentes de Layout', icon: Layers },
    { id: 'sample', label: 'Exemplos Versionados', icon: FlaskConical },
    { id: 'typography', label: 'Editor de Tema', icon: Palette },
    { id: 'rotas', label: 'Rotas e Ambientes', icon: Route },
  ], []);

  const componentsList = useMemo(() => ({
    shared: [
      { 
        name: 'ExcelTable (Pixel Perfect)', 
        description: 'Tabela de alta performance estilo Excel com filtros avançados e colunas fixas.',
        props: {
          data: [
            { id: 1, modelo: 'TEO0G02', placa: 'TEO0G02', status: 'Em uso', motorista: 'Larissa Souza', combustivel: 'Flex', tipo: 'Passeio', marca: 'Fiat', ano: '2020', cidade: 'São Paulo' },
            { id: 2, modelo: 'HFB3A70', placa: 'HFB3A70', status: 'Manutenção', motorista: 'Carlos Silva', combustivel: 'Diesel', tipo: 'Utilitário', marca: 'VW', ano: '2021', cidade: 'Rio' },
            { id: 3, modelo: 'LUN1968', placa: 'LUN1968', status: 'Em uso', motorista: 'Roberto Alves', combustivel: 'Gasolina', tipo: 'Passeio', marca: 'Ford', ano: '2022', cidade: 'Curitiba' },
          ],
          columns: [
            { header: 'MODELO', field: 'modelo', width: '120px' },
            { header: 'PLACA', field: 'placa', width: '120px', className: 'text-amber-500 font-bold' },
            { header: 'STATUS', field: 'status', width: '150px' },
            { header: 'MOTORISTA', field: 'motorista', width: '200px' },
            { header: 'COMBUSTÍVEL', field: 'combustivel', width: '120px' },
          ],
          filterDefs: [
            { field: 'status', label: 'Status', type: 'select' },
            { field: 'combustivel', label: 'Combustível', type: 'select' }
          ]
        },
        render: (props) => <Suspense fallback={<ComponentLoader />}><div className="h-[500px] w-full"><ExcelTable {...props} /></div></Suspense>
      },
      { 
        name: 'ItemDetailPanel', 
        description: 'Painel deslizante modular para detalhes de registros (Clientes, Veículos, etc).',
        props: {
          title: 'Título do Panel', 
          subtitle: 'Subtítulo',
          status: 'Status'
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
           <div className="relative w-full h-[600px] bg-muted/10 border rounded-xl overflow-hidden flex items-center justify-center">
              <ItemDetailPanel 
                  title="Item Exemplo"
                  subtitle="#123456"
                  status="Ativo"
                  actions={[
                    { label: 'Editar', onClick: () => {} },
                    { label: 'Deletar', isDestructive: true, onClick: () => {} }
                  ]}
                  tabs={[
                    { id: '1', label: 'Geral', content: <div className="p-4">Conteúdo Geral</div> }
                  ]}
                  {...props}
              />
           </div>
          </Suspense>
        ),
        debugRender: () => <Suspense fallback={<ComponentLoader />}><ItemDetailPanelDebug /></Suspense>
      },
      { 
        name: 'StatsGrid', 
        description: 'Grade de KPIs com tendências e ícones.',
        props: {
          stats: [
            { label: 'Frota Total', value: '142', change: '+5', trend: 'up' },
            { label: 'Em Manutenção', value: '8', change: '-2', trend: 'down' },
            { label: 'Sinistros Mês', value: '3', change: '+1', trend: 'up' },
            { label: 'Disponibilidade', value: '94%', change: '+2%', trend: 'up' },
          ]
        },
        render: (props) => <Suspense fallback={<ComponentLoader />}><StatsGrid {...props} /></Suspense>
      },
      { 
        name: 'DashboardKPICard (Premium)', 
        description: 'Card de KPI de alta fidelidade visual com suporte a tendências, ícones customizados e temas.',
        props: {
          label: 'Veículos em uso',
          value: 'R$ 159,2M',
          subtitle: '1033 de 1364 veículos - Total R$ 221,2M',
          trend: '72.0%',
          trendDirection: 'down',
          color: 'blue'
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="flex items-center justify-center h-full">
               <DashboardKPICard {...props} icon={() => <Box size={24} />} className="w-80" />
            </div>
          </Suspense>
        ),
        debugRender: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <DashboardKPICardDebug {...props} />
          </Suspense>
        )
      },
      {
        name: 'DataTable',
        description: 'Tabela otimizada com busca e paginação.',
        props: {
          data: [
            { id: 1, name: 'João Silva', role: 'Dev', status: 'Ativo' },
            { id: 2, name: 'Maria Santos', role: 'Designer', status: 'Inativo' },
          ],
          columns: ['ID', 'Nome', 'Cargo', 'Status'],
          searchKey: 'name',
          renderRow: (item) => (
            <TableRow key={item.id}>
              <TableCell className="font-medium">{item.id}</TableCell>
              <TableCell>{item.name}</TableCell>
              <TableCell>{item.role}</TableCell>
              <TableCell>
                <Badge variant={item.status === 'Ativo' ? 'default' : 'secondary'}>
                  {item.status}
                </Badge>
              </TableCell>
            </TableRow>
          )
        },
        render: (props) => <Suspense fallback={<ComponentLoader />}><DataTable {...props} /></Suspense>
      },
      {
        name: 'AutoFillInput (Smart Search)',
        description: 'Input inteligente com consulta em tempo real, debounce e autopreenchimento de formulários.',
        props: {
          label: 'Pesquisar Colaborador',
          placeholder: 'Digite nome, cargo ou CPF...',
          filterField: 'name',
          displayField: 'name',
          data: [
            { id: '101', name: 'Larissa Ribeiro de Souza', role: 'Motorista Categoria D', phone: '(11) 98888-7777', document: '123.456.789-00', registration: 'PR-2024-001' },
            { id: '102', name: 'Carlos Silva Pereira', role: 'Operador de Empilhadeira', phone: '(11) 97777-6666', document: '987.654.321-11', registration: 'PR-2024-002' },
            { id: '103', name: 'Roberto Alves da Costa', role: 'Supervisor de Logística', phone: '(11) 96666-5555', document: '456.123.789-22', registration: 'PR-2024-003' },
            { id: '104', name: 'Ana Beatriz Mendes', role: 'Auxiliar Administrativo', phone: '(11) 95555-4444', document: '321.654.987-33', registration: 'PR-2024-004' },
            { id: '105', name: 'Marcos Vinícius Jota', role: 'Motorista Carreteiro', phone: '(11) 94444-3333', document: '159.357.258-44', registration: 'PR-2024-005' },
          ]
        },
        render: (props) => {
          const TestForm = () => {
            const [formData, setFormData] = React.useState({
              name: '',
              role: '',
              phone: '',
              document: '',
              registration: ''
            });

            const handleSelect = (item) => {
              setFormData({
                name: item.name,
                role: item.role,
                phone: item.phone,
                document: item.document,
                registration: item.registration
              });
            };

            const handleAddNew = (term) => {
              const confirmCreate = window.confirm(`Deseja iniciar o cadastro para "${term}"?`);
              if (confirmCreate) {
                  setFormData({
                    name: term,
                    role: 'NOVO CADASTRADO',
                    phone: '',
                    document: '',
                    registration: 'AGUARDANDO...'
                  });
              }
            };

            const resetForm = () => {
              setFormData({ name: '', role: '', phone: '', document: '', registration: '' });
            };

            return (
              <div className="max-w-2xl mx-auto space-y-8 py-4">
                <div className="bg-emerald-500/5 border border-emerald-500/10 p-6 rounded-2xl">
                   <Suspense fallback={<ComponentLoader />}>
                     <AutoFillInput 
                        {...props} 
                        onSelect={handleSelect} 
                        onAddNew={handleAddNew}
                      />
                   </Suspense>
                    <div className="mt-3 flex items-center justify-between">
                      <p className="text-[10px] text-slate-500 font-bold uppercase tracking-widest leading-relaxed">
                        Teste: Digite "Larissa" ou "Analista"
                      </p>
                      <Button variant="ghost" size="sm" onClick={resetForm} className="h-6 text-[10px] uppercase font-black italic text-rose-500 hover:bg-rose-500/10">
                         Limpar Formulário
                      </Button>
                    </div>
                </div>

                <div className="grid grid-cols-2 gap-4 animate-in fade-in slide-in-from-top-4 duration-500">
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-widest ml-1">Cargo / Função</label>
                    <input readOnly value={formData.role} className="w-full bg-slate-500/5 border border-white/5 rounded-lg px-4 py-2.5 text-sm text-slate-400 outline-none" placeholder="Preenchido automaticamente..." />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-widest ml-1">Telefone</label>
                    <input readOnly value={formData.phone} className="w-full bg-slate-500/5 border border-white/5 rounded-lg px-4 py-2.5 text-sm text-slate-400 outline-none" placeholder="(00) 00000-0000" />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-widest ml-1">CPF / Documento</label>
                    <input readOnly value={formData.document} className="w-full bg-slate-500/5 border border-white/5 rounded-lg px-4 py-2.5 text-sm text-slate-400 outline-none" placeholder="000.000.000-00" />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-widest ml-1">Matrícula</label>
                    <input readOnly value={formData.registration} className="w-full bg-slate-500/5 border border-white/5 rounded-lg px-4 py-2.5 text-sm text-slate-400 outline-none" placeholder="REG-000000" />
                  </div>
                </div>
              </div>
            );
          };
          return <TestForm />;
        }
      },
      {
        name: 'KanbanBoard (Premium)',
        description: 'Quadro Kanban de alta fidelidade para gestão de processos e status.',
        props: {
          columns: [
            { id: '1', title: 'A FAZER', color: 'blue', cards: [{ id: 1, title: 'TESTE', date: '12/01/2026' }] }
          ]
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="h-[600px] w-full">
              <KanbanBoard {...props} />
            </div>
          </Suspense>
        ),
        debugRender: () => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="h-[700px] w-full">
              <KanbanBoardDebug />
            </div>
          </Suspense>
        )
      },
      {
        name: 'LoadingOverlay',
        description: 'Overlay de carregamento com backdrop-blur e animação premium.',
        props: {
          show: true,
          message: 'Processando dados...'
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="h-[400px] w-full relative border rounded-xl overflow-hidden">
               <div className="p-8">Conteúdo abaixo do overlay...</div>
               <LoadingOverlay {...props} />
            </div>
          </Suspense>
        )
      },
      {
        name: 'Modal (Base)',
        description: 'Componente base para modais com suporte a formulários e ações.',
        props: {
          isOpen: true,
          title: 'Modal do Sistema',
          description: 'Esta é a base para todos os modais.'
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="h-[400px] w-full bg-muted/10 border rounded-xl flex items-center justify-center">
               <Modal {...props} onClose={() => {}}>
                  <div className="p-4 text-sm">Conteúdo interno do modal.</div>
               </Modal>
            </div>
          </Suspense>
        )
      }
    ],
    layout: [
      {
        name: 'Sidebar (Reproduced)',
        description: 'Menu lateral completo reproduzido do Angular. Possui estados colapsáveis, busca e submenus.',
        props: {
          isCollapsed: false
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="h-[700px] w-full relative bg-slate-900 rounded-xl overflow-hidden p-8">
              <div className="relative h-full w-[260px] translate-x-2 translate-y-2">
                <Sidebar {...props} />
              </div>
            </div>
          </Suspense>
        ),
        debugRender: () => (
          <Suspense fallback={<ComponentLoader />}>
            <SidebarDebug />
          </Suspense>
        )
      }
    ],
    ui: [
      { 
        name: 'Button', 
        description: 'Botão padrão do sistema.',
        render: () => (
          <div className="flex flex-wrap gap-4 items-center justify-center h-full">
            <Button variant="default">Primary Button</Button>
            <Button variant="outline">Outline Button</Button>
            <Button variant="destructive">Destructive</Button>
            <Button variant="secondary">Secondary</Button>
            <Button variant="ghost">Ghost Button</Button>
            <Button variant="link">Link Button</Button>
          </div>
        )
      },
      {
        name: 'Badge',
        description: 'Indicadores de status e tags.',
        render: () => (
          <div className="flex gap-4 items-center justify-center h-full">
            <Badge>Default</Badge>
            <Badge variant="secondary">Secondary</Badge>
            <Badge variant="outline">Outline</Badge>
            <Badge variant="destructive">Destructive</Badge>
            <Badge className="bg-emerald-500 hover:bg-emerald-600">Emerald</Badge>
          </div>
        )
      },
      {
        name: 'Card',
        description: 'Container base para conteúdo.',
        render: () => (
          <div className="p-8 flex items-center justify-center h-full">
            <Card className="p-6 w-80 shadow-xl border-white/5 bg-white/5 backdrop-blur-md">
              <h3 className="font-bold mb-2">Premium Card</h3>
              <p className="text-sm text-slate-400">Este é um exemplo de card com efeito de glassmorphism aplicado.</p>
              <Button className="w-full mt-4 bg-emerald-500 hover:bg-emerald-600">Ação</Button>
            </Card>
          </div>
        )
      }
    ],
    icons: [
      {
        name: 'Lucide Icons Set',
        description: 'Conjunto de ícones vetoriais padrão.',
        render: () => (
          <div className="grid grid-cols-6 gap-8 p-8 place-items-center h-full">
            <div className="flex flex-col items-center gap-2"><Plus className="text-emerald-500" /><span className="text-[10px] text-slate-500">Plus</span></div>
            <div className="flex flex-col items-center gap-2"><Search className="text-emerald-500" /><span className="text-[10px] text-slate-500">Search</span></div>
            <div className="flex flex-col items-center gap-2"><Monitor className="text-emerald-500" /><span className="text-[10px] text-slate-500">Monitor</span></div>
            <div className="flex flex-col items-center gap-2"><Smartphone className="text-emerald-500" /><span className="text-[10px] text-slate-500">Mobile</span></div>
            <div className="flex flex-col items-center gap-2"><RotateCcw className="text-emerald-500" /><span className="text-[10px] text-slate-500">Reload</span></div>
            <div className="flex flex-col items-center gap-2"><ExternalLink className="text-emerald-500" /><span className="text-[10px] text-slate-500">Link</span></div>
          </div>
        )
      }
    ],
    typography: [],
    rotas: [],
    sample: [
      {
        name: 'StatusBadge',
        description: 'Badge de status versionado. Possui uma versão de produção simplificada e uma de debug com controles extras.',
        props: {
          status: 'active',
          label: 'Ativo'
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="flex items-center justify-center h-full">
              <StatusBadge {...props} />
            </div>
          </Suspense>
        ),
        debugRender: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="flex items-center justify-center h-full w-full">
              <StatusBadgeDebug {...props} />
            </div>
          </Suspense>
        )
      },
      {
        name: 'FinesCard',
        description: 'Card de KPIs de Multas com comparação mensal e suporte a gráfico de composição.',
        props: {
          currentValue: 850,
          currentCount: 3,
          previousValue: 1100,
          previousCount: 6,
          isLoading: false,
          monthlyData: [
            { name: 'Jul', value: 1200 },
            { name: 'Ago', value: 950 },
            { name: 'Set', value: 1100 },
            { name: 'Out', value: 800 },
            { name: 'Nov', value: 1350 },
            { name: 'Dez', value: 850 },
          ],
          data: [
            { name: 'Excesso de Velocidade', value: 450.00, color: '#ef4444' },
            { name: 'Estacionamento Irregular', value: 250.00, color: '#f59e0b' },
            { name: 'Documentação', value: 150.00, color: '#3b82f6' }
          ]
        },
        render: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="flex items-center justify-center h-full">
              <div className="w-[350px] h-[450px]">
                <FinesCard {...props} />
              </div>
            </div>
          </Suspense>
        ),
        debugRender: (props) => (
          <Suspense fallback={<ComponentLoader />}>
            <div className="flex items-center justify-center h-full w-full">
              <FinesCardDebug {...props} />
            </div>
          </Suspense>
        )
      }
    ]
  }), []);

  const filteredComponents = useMemo(() => 
    (componentsList[activeCategory] || []).filter(comp => 
      comp.name.toLowerCase().includes(debouncedSearch.toLowerCase())
    ),
    [activeCategory, componentsList, debouncedSearch]
  );

  return (
    <div className={cn(
      "flex h-screen w-full overflow-hidden font-sans transition-colors duration-300",
      theme, 
      theme === 'dark' ? "bg-[#0a0a0a] text-slate-200" : "bg-slate-50 text-slate-900"
    )}>
      <SidebarNav 
        activeCategory={activeCategory}
        setActiveCategory={setActiveCategory}
        setSelectedComponent={setSelectedComponent}
        theme={theme}
        setTheme={setTheme}
        categories={categories}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        filteredComponents={filteredComponents}
        selectedComponent={selectedComponent}
      />

      <main className="flex-1 flex flex-col min-w-0">
        <PlaygroundHeader 
          selectedComponent={selectedComponent}
          activeCategory={activeCategory}
          theme={theme}
          versionMode={versionMode}
          setVersionMode={setVersionMode}
          viewMode={viewMode}
          setViewMode={setViewMode}
        />

        <div className={cn(
            "flex-1 overflow-auto p-12 custom-scrollbar transition-all duration-500",
            theme === 'dark' 
                ? "bg-[radial-gradient(#1a1a1a_1px,transparent_1px)] [background-size:20px_20px]" 
                : "bg-[radial-gradient(#e2e8f0_1px,transparent_1px)] [background-size:20px_20px]",
            versionMode === 'debug' && (theme === 'dark' ? "bg-[radial-gradient(#2e1065_1px,transparent_1px)]" : "bg-[radial-gradient(#e9d5ff_1px,transparent_1px)]")
        )}>
          {activeCategory === 'typography' ? (
            <Suspense fallback={<ComponentLoader />}>
                <ThemeTuner theme={theme} />
            </Suspense>
          ) : activeCategory === 'rotas' ? (
            <RotasPanel theme={theme} />
          ) : activeCategory === 'connector' ? (
            <div className="max-w-6xl mx-auto space-y-6 min-h-[600px] flex flex-col">
                <Card className={cn("p-6 border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-white border-slate-200")}>
                    <div className="flex items-center gap-3 mb-4">
                        <Database className="text-emerald-500" size={24} />
                        <div>
                            <h2 className="text-title font-title">Conector Universal Modular</h2>
                            <p className="text-caption text-muted-foreground">Cole seu JSON abaixo para visualizar automaticamente em tabela, sem configurar colunas.</p>
                        </div>
                    </div>
                </Card>
                <div className="flex-1 grid grid-cols-1 lg:grid-cols-3 gap-6">
                     <Card className={cn("p-0 overflow-hidden border flex flex-col", theme === 'dark' ? "bg-[#111] border-white/10" : "bg-white border-slate-200")}>
                        <div className="p-3 border-b border-border bg-muted/20 flex justify-between items-center">
                            <span className="font-bold text-xs uppercase tracking-wider text-muted-foreground">Entrada de Dados (JSON)</span>
                            <Badge variant="outline" className="font-mono text-[10px]">ARRAY DE OBJETOS</Badge>
                        </div>
                        <textarea 
                            className="flex-1 w-full bg-transparent p-4 font-mono text-xs resize-none focus:outline-none" 
                            placeholder='[{"id": 1, "nome": "Exemplo", "valor": 100}]'
                            onChange={(e) => {
                                try {
                                    const parsed = JSON.parse(e.target.value);
                                    if(Array.isArray(parsed)) setSelectedComponent({ ...selectedComponent, temp_data: parsed });
                                } catch(err) {} 
                            }}
                            defaultValue='[
  { "id": 1, "nome": "Produto A", "categoria": "Eletronicos", "valor": 1250.00, "estoque": 15, "ativo": true },
  { "id": 2, "nome": "Produto B", "categoria": "Moveis", "valor": 450.50, "estoque": 8, "ativo": true },
  { "id": 3, "nome": "Produto C", "categoria": "Eletronicos", "valor": 899.90, "estoque": 0, "ativo": false },
  { "id": 4, "nome": "Serviço X", "categoria": "Serviços", "valor": 150.00, "estoque": null, "ativo": true }
]'
                        />
                     </Card>
                     <Card className={cn("lg:col-span-2 p-0 overflow-hidden border flex flex-col h-[600px]", theme === 'dark' ? "bg-[#111] border-white/10" : "bg-white border-slate-200")}>
                        <div className="p-3 border-b border-border bg-muted/20">
                            <span className="font-bold text-xs uppercase tracking-wider text-muted-foreground">Visualização Automática (Modular)</span>
                        </div>
                        <div className="flex-1 relative">
                            <Suspense fallback={<ComponentLoader />}>
                                <SmartTable 
                                    data={selectedComponent?.temp_data || [
                                      { "id": 1, "nome": "Produto A", "categoria": "Eletronicos", "valor": 1250.00, "estoque": 15, "ativo": true },
                                      { "id": 2, "nome": "Produto B", "categoria": "Moveis", "valor": 450.50, "estoque": 8, "ativo": true },
                                      { "id": 3, "nome": "Produto C", "categoria": "Eletronicos", "valor": 899.90, "estoque": 0, "ativo": false },
                                      { "id": 4, "nome": "Serviço X", "categoria": "Serviços", "valor": 150.00, "estoque": null, "ativo": true }
                                    ]}
                                    loading={false}
                                />
                            </Suspense>
                        </div>
                     </Card>
                </div>
            </div>
          ) : selectedComponent ? (
            <div className="mx-auto h-full flex flex-col gap-10">
              <div className={cn(
                "mx-auto rounded-2xl shadow-2xl transition-all duration-500 overflow-hidden relative border",
                viewMode === 'desktop' && "w-full max-w-6xl h-auto min-h-[500px]",
                viewMode === 'tablet' && "w-[768px] h-[1024px] scale-[0.6] origin-top",
                viewMode === 'mobile' && "w-[375px] h-[667px] scale-[0.8] origin-top",
                theme === 'dark' ? "bg-[#111] border-white/5 shadow-black/50" : "bg-white border-slate-200 shadow-slate-200",
                versionMode === 'debug' && "border-purple-500/20 shadow-purple-500/10"
              )}>
                <div className={cn(
                    "h-8 border-b flex items-center px-4 gap-1.5",
                    theme === 'dark' ? "bg-white/5 border-white/5" : "bg-slate-50 border-slate-200"
                )}>
                  <div className="w-2.5 h-2.5 rounded-full bg-red-500/40" />
                  <div className="w-2.5 h-2.5 rounded-full bg-yellow-500/40" />
                  <div className="w-2.5 h-2.5 rounded-full bg-green-500/40" />
                  <div className="ml-4 flex items-center gap-2 text-[10px] text-slate-400 font-mono tracking-tighter truncate opacity-60">
                    <span>preview://components/{selectedComponent.name.toLowerCase().replace(/ /g, '-')}</span>
                    {versionMode === 'debug' && <span className="text-purple-400 font-bold px-1 bg-purple-500/10 rounded">@DEBUG-BUILD</span>}
                  </div>
                </div>

                <div className="p-8 h-full overflow-auto relative">
                   {versionMode === 'debug' && (
                       <div className="absolute inset-0 pointer-events-none opacity-20" 
                            style={{ backgroundImage: `linear-gradient(#a855f7 1px, transparent 1px), linear-gradient(90deg, #a855f7 1px, transparent 1px)`, backgroundSize: '20px 20px' }} 
                       />
                   )}
                   
                   {versionMode === 'debug' && selectedComponent.debugRender ? (
                        selectedComponent.debugRender(selectedComponent.props || {})
                   ) : (
                        versionMode === 'debug' ? (
                            <div className="h-full flex flex-col items-center justify-center">
                                <div className="absolute top-4 right-4 bg-orange-500/10 text-orange-500 px-3 py-1 rounded text-[10px] font-bold uppercase border border-orange-500/20">
                                    Fallback: Production Version
                                </div>
                                {selectedComponent.render(selectedComponent.props || {})}
                            </div>
                        ) : (
                            selectedComponent.render(selectedComponent.props || {})
                        )
                   )}
                </div>
              </div>

              <div className="w-full max-w-6xl mx-auto space-y-6 pb-20">
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                  <Card className={cn(
                    "p-8 lg:col-span-2 border-white/5 shadow-xl",
                    theme === 'dark' ? "bg-[#111]" : "bg-white"
                  )}>
                    <div className="flex items-center gap-3 mb-6">
                      <div className="p-2 bg-emerald-500/10 rounded-lg">
                        <Info size={18} className="text-emerald-500" />
                      </div>
                      <h3 className="text-sm font-black uppercase tracking-[0.2em]">{versionMode === 'debug' ? 'Debug Spec & Logs' : 'Blueprint & Contrato'}</h3>
                    </div>
                    
                    <p className="text-slate-400 text-sm leading-relaxed mb-8 font-medium">
                      {selectedComponent.description}
                    </p>

                    <Tabs defaultValue="props" className="w-full">
                      <TabsList className={cn(
                          "p-1 border h-auto",
                          theme === 'dark' ? "bg-black/40 border-white/5" : "bg-slate-100 border-slate-200"
                      )}>
                        <TabsTrigger value="props" className="px-6 py-2 text-xs font-bold uppercase tracking-wider data-[state=active]:bg-emerald-500 data-[state=active]:text-white">API Props</TabsTrigger>
                        <TabsTrigger value="code" className="px-6 py-2 text-xs font-bold uppercase tracking-wider data-[state=active]:bg-emerald-500 data-[state=active]:text-white">
                          <Code2 size={14} className="mr-2" /> Source Code
                        </TabsTrigger>
                      </TabsList>
                      
                      <TabsContent value="props" className="mt-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        <div className={cn(
                            "border rounded-xl overflow-hidden",
                            theme === 'dark' ? "border-white/5" : "border-slate-200"
                        )}>
                          <table className="w-full text-xs text-left border-collapse">
                            <thead>
                              <tr className={cn(
                                  "border-b transition-colors",
                                  theme === 'dark' ? "bg-white/5 text-slate-500 border-white/5" : "bg-slate-50 text-slate-500 border-slate-200"
                              )}>
                                <th className="px-6 py-4 font-black uppercase tracking-widest text-[10px]">Propriedade</th>
                                <th className="px-6 py-4 font-black uppercase tracking-widest text-[10px]">Tipo esperado</th>
                                <th className="px-6 py-4 font-black uppercase tracking-widest text-[10px]">Status</th>
                              </tr>
                            </thead>
                            <tbody className={cn(
                                "divide-y",
                                "divide-white/5"
                            )}>
                              {Object.keys(selectedComponent.props || {}).map(key => (
                                <tr key={key} className="hover:bg-white/5 transition-colors group">
                                  <td className="px-6 py-4 font-mono text-emerald-500 font-bold">{key}</td>
                                  <td className="px-6 py-4 text-slate-400 italic">{typeof selectedComponent.props[key]}</td>
                                  <td className="px-6 py-4">
                                      <Badge variant="outline" className="text-[9px] border-emerald-500/30 text-emerald-500">DEFINIDO</Badge>
                                  </td>
                                </tr>
                              ))}
                              {(!selectedComponent.props || Object.keys(selectedComponent.props).length === 0) && (
                                <tr>
                                  <td colSpan={3} className="px-6 py-10 text-slate-500 italic text-center">Componente puro ou sem propriedades de teste configuradas.</td>
                                </tr>
                              )}
                            </tbody>
                          </table>
                        </div>
                      </TabsContent>
                      
                      <TabsContent value="code" className="mt-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        <div className="bg-[#050505] p-8 rounded-xl border border-white/5 font-mono text-[13px] leading-relaxed overflow-x-auto shadow-2xl">
                            <div className="text-emerald-500/40 mb-4 select-none">/* Auto-generated snippet */</div>
                            <span className="text-blue-400">const</span> <span className="text-emerald-400">MyComponent</span> <span className="text-white">=</span> <span className="text-white">()</span> <span className="text-blue-400">=&gt;</span> <span className="text-white">{`{`}</span>
                            <pre className="text-emerald-500/90 mt-2">{`  return (
    <${selectedComponent.name.split(' (')[0]} 
      ${Object.keys(selectedComponent.props || {}).map(k => {
          const val = selectedComponent.props[k];
          let valStr = '';
          try {
             valStr = typeof val === 'function' ? '() => { ... }' : JSON.stringify(val);
             if (!valStr) valStr = 'undefined'; 
          } catch (e) {
             valStr = '"Could not serialize"';
          }
          return `${k}={${valStr.slice(0, 20)}${valStr.length > 20 ? '...' : ''}}`;
      }).join('\n      ')}
    />
  )`}</pre>
                            <span className="text-white">{`}`}</span>
                        </div>
                      </TabsContent>
                    </Tabs>
                  </Card>

                  <div className="space-y-6">
                    <Card className={cn(
                        "p-6 border-white/5 shadow-xl",
                        theme === 'dark' ? "bg-[#111]" : "bg-white"
                    )}>
                        <h4 className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-500 mb-4">Dicas Pro</h4>
                        <ul className="space-y-3">
                            <li className="flex gap-2 text-[11px] text-slate-400">
                                <span className="text-emerald-500 font-bold">01.</span> Use o Toggler de Tema para testar contraste.
                            </li>
                            <li className="flex gap-2 text-[11px] text-slate-400">
                                <span className="text-emerald-500 font-bold">02.</span> Verifique o Mobile View para responsividade.
                            </li>
                            {versionMode === 'debug' && (
                                <li className="flex gap-2 text-[11px] text-purple-400">
                                    <span className="text-purple-500 font-bold">04.</span> Modo Debug ativo: Visualizando versões experimentais.
                                </li>
                            )}
                        </ul>
                    </Card>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="h-full flex flex-col items-center justify-center text-center gap-8 animate-in fade-in zoom-in-95 duration-700">
              <div className="relative">
                <div className="w-32 h-32 bg-emerald-500/5 rounded-[2.5rem] flex items-center justify-center border border-emerald-500/10 shadow-2xl relative z-10">
                    <Layers className="text-emerald-500/40" size={64} />
                </div>
                <div className="absolute -inset-4 bg-emerald-500/5 rounded-[3rem] blur-2xl animate-pulse" />
              </div>
              <div className="space-y-2">
                <h2 className="text-2xl font-black uppercase italic tracking-tighter">Laboratório de Componentes</h2>
                <p className="text-slate-500 max-w-sm text-sm font-medium">Selecione um componente na barra lateral para começar a testar comportamentos e designs.</p>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
};

export default PlaygroundView;
