/**
 * React Router Generator (App Shell)
 *
 * Generates App.tsx with app-demo-quality navigation and routing.
 * Matches app-demo's visual patterns: sidebar, active states, model grouping,
 * specialist view links.
 */

import type { TemplateContext } from '@specverse/types';

export default function generateRouter(context: TemplateContext): string {
  const { spec, models = [], views = [] } = context;

  const specViews = views.length > 0 ? views : (spec?.views || []);
  const viewsArray = Array.isArray(specViews) ? specViews : Object.values(specViews);

  // Collect view info grouped by model
  const modelViews = new Map<string, Array<{ name: string; type: string; path: string }>>();
  const viewImports: string[] = [];
  const routeEntries: string[] = [];

  viewsArray.forEach((viewDef: any) => {
    const viewName = viewDef.name;
    if (!viewName) return;
    const model = Array.isArray(viewDef.model) ? viewDef.model[0] : viewDef.model;
    if (!model) return;

    const viewType = viewDef.type || 'list';
    const modelLower = model.toLowerCase();
    const path = `/${modelLower}${viewType}`;

    viewImports.push(`import ${viewName} from './components/${viewName}';`);
    routeEntries.push(`          <Route path="${path}" element={<${viewName} />} />`);

    if (!modelViews.has(model)) modelViews.set(model, []);
    modelViews.get(model)!.push({ name: viewName, type: viewType, path });
  });

  // Get app name from spec
  const appName = spec?.componentName || spec?.metadata?.component || spec?.name || 'App';

  // Build sidebar sections per model
  const sidebarSections = Array.from(modelViews.entries()).map(([model, views]) => {
    const lower = model.toLowerCase();
    const listView = views.find(v => v.type === 'list');
    const formView = views.find(v => v.type === 'form');
    const specialistViews = views.filter(v => !['list', 'detail', 'form'].includes(v.type));

    const specialistLinks = specialistViews.map(v => {
      const label = v.type.charAt(0).toUpperCase() + v.type.slice(1);
      const icon = v.type === 'board' ? '▦' : v.type === 'timeline' ? '⏱' : v.type === 'calendar' ? '📅' : v.type === 'dashboard' ? '📊' : v.type === 'analytics' ? '📈' : '◆';
      return `              <Link to="${v.path}" className={\`flex items-center gap-2 px-2 py-1.5 rounded text-sm transition-all \${location.pathname === '${v.path}' ? 'bg-blue-50 text-blue-700 font-medium border border-blue-200' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900 border border-transparent'}\`}>
                <span className="text-xs">${icon}</span> ${label}
              </Link>`;
    }).join('\n');

    return `          {/* ${model} */}
          <div>
            <h3 className="px-2 text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">${model}s</h3>
            <div className="space-y-0.5">
${listView ? `              <Link to="${listView.path}" className={\`flex items-center gap-2 px-2 py-1.5 rounded text-sm transition-all \${location.pathname === '${listView.path}' ? 'bg-blue-50 text-blue-700 font-medium border border-blue-200' : 'text-gray-700 hover:bg-gray-50 border border-transparent'}\`}>
                <span className="text-xs">☰</span> Browse
              </Link>` : ''}
${formView ? `              <Link to="${formView.path}" className={\`flex items-center gap-2 px-2 py-1.5 rounded text-sm transition-all \${location.pathname === '${formView.path}' ? 'bg-blue-50 text-blue-700 font-medium border border-blue-200' : 'text-gray-700 hover:bg-gray-50 border border-transparent'}\`}>
                <span className="text-xs">＋</span> New
              </Link>` : ''}
${specialistLinks}
            </div>
          </div>`;
  }).join('\n\n');

  // Default route
  const firstModel = Array.from(modelViews.keys())[0]?.toLowerCase() || 'unknown';
  const hasDashboard = viewsArray.some((v: any) => v.type === 'dashboard');
  const defaultElement = hasDashboard
    ? viewsArray.find((v: any) => v.type === 'dashboard')?.name || `${Array.from(modelViews.keys())[0]}ListView`
    : `${Array.from(modelViews.keys())[0] || 'Unknown'}ListView`;

  return `import { BrowserRouter as Router, Routes, Route, Link, useLocation } from 'react-router-dom';
${viewImports.join('\n')}

function Sidebar() {
  const location = useLocation();
  return (
    <aside className="w-60 bg-white border-r border-gray-200 flex flex-col">
      {/* App Header */}
      <div className="px-4 py-5 border-b border-gray-100">
        <h1 className="text-lg font-bold text-gray-900">${appName}</h1>
        <p className="text-xs text-gray-400 mt-0.5">Generated from specification</p>
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-5">
${sidebarSections}
      </nav>

      {/* Footer */}
      <div className="px-4 py-3 border-t border-gray-100 text-xs text-gray-400">
        Powered by SpecVerse
      </div>
    </aside>
  );
}

function App() {
  return (
    <Router>
      <div className="flex h-screen bg-gray-50 overflow-hidden">
        <Sidebar />
        <main className="flex-1 overflow-y-auto">
          <Routes>
            <Route path="/" element={<${defaultElement} />} />
${routeEntries.join('\n')}
            <Route path="*" element={
              <div className="flex items-center justify-center h-full">
                <div className="text-center">
                  <h1 className="text-4xl font-bold text-gray-300 mb-2">404</h1>
                  <p className="text-gray-500">Page not found</p>
                  <Link to="/" className="mt-4 inline-block text-blue-600 hover:text-blue-700 text-sm">← Back to home</Link>
                </div>
              </div>
            } />
          </Routes>
        </main>
      </div>
    </Router>
  );
}

export default App;
`;
}
