'use client';

import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  GitBranch, FolderOpen, File, ChevronRight, ChevronDown,
  Search, Globe, Lock, Zap, Check, Loader2, ArrowRight, FileCode2, BarChart3,
  Star, GitFork, Eye, Clock, Users, BookOpen, Shield, Code, Database,
  Activity, ExternalLink, AlertTriangle, Upload, HardDrive, X
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { api } from '../lib/api';

interface TreeNode {
  name: string;
  type: 'file' | 'folder';
  size?: string;
  lang?: string;
  children?: TreeNode[];
}

function FileTreeItem({ node, depth = 0 }: { node: TreeNode; depth?: number }) {
  const [open, setOpen] = useState(depth < 2);
  const isFolder = node.type === 'folder';

  const langColor: Record<string, string> = {
    COBOL: 'text-orange-400 bg-orange-500/15',
    COPYBOOK: 'text-purple-400 bg-purple-500/15',
    'SQL/DB2': 'text-amber-400 bg-amber-500/15',
    JCL: 'text-pink-400 bg-pink-500/15',
  };

  return (
    <div>
      <button
        onClick={() => isFolder && setOpen(!open)}
        className={`w-full flex items-center gap-2 py-1.5 px-2 rounded-md text-sm hover:bg-surface-light transition-colors cursor-pointer`}
        style={{ paddingLeft: `${depth * 16 + 8}px` }}
      >
        {isFolder ? (
          open ? <ChevronDown className="w-3.5 h-3.5 text-muted" /> : <ChevronRight className="w-3.5 h-3.5 text-muted" />
        ) : (
          <span className="w-3.5" />
        )}
        {isFolder ? (
          <FolderOpen className="w-4 h-4 text-accent-light" />
        ) : (
          <File className="w-4 h-4 text-muted" />
        )}
        <span className={`flex-1 text-left ${isFolder ? 'text-foreground font-medium' : 'text-muted'}`}>
          {node.name}
        </span>
        {node.lang && (
          <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${langColor[node.lang] || 'text-muted bg-surface-light'}`}>
            {node.lang}
          </span>
        )}
        {node.size && <span className="text-[10px] text-muted font-mono">{node.size}</span>}
      </button>
      <AnimatePresence>
        {isFolder && open && node.children && (
          <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.2 }}>
            {node.children.map((child) => (
              <FileTreeItem key={child.name} node={child} depth={depth + 1} />
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// GitHub data shape from /api/github/repo-info
interface GHData {
  repo: {
    name: string; fullName: string; description: string; defaultBranch: string;
    stars: number; forks: number; watchers: number; openIssues: number;
    size: number; createdAt: string; updatedAt: string; pushedAt: string;
    license: string | null; topics: string[]; visibility: string;
  } | null;
  fileTree: TreeNode[];
  totalFiles: number;
  extensions: { ext: string; count: number; percentage: number }[];
  languages: { name: string; bytes: number; percentage: number }[];
  commits: { sha: string; message: string; author: string; avatar: string; date: string }[];
  contributors: { login: string; avatar: string; contributions: number }[];
  readme: string;
}

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return `${Math.floor(days / 30)}mo ago`;
}

function formatKB(kb: number): string {
  if (kb < 1024) return `${kb} KB`;
  return `${(kb / 1024).toFixed(1)} MB`;
}

const langColors: Record<string, string> = {
  COBOL: '#005ca5', Java: '#b07219', Python: '#3572A5', JavaScript: '#f1e05a',
  TypeScript: '#3178c6', 'C#': '#178600', Go: '#00ADD8', Rust: '#dea584',
  Ruby: '#701516', PHP: '#4F5D95', Shell: '#89e051', JCL: '#8a8a8a',
  'C++': '#f34b7d', C: '#555555', SQL: '#e38c00', PLI: '#3d6117',
  REXX: '#d90e09', RPG: '#2BDE21', Copybook: '#005ca5',
};

export default function Repository({ onNavigate, projectId, project: _project }: { onNavigate: (s: string, pid?: string) => void; projectId?: string; project?: Project | null }) {
  const projConfig = (_project?.config ?? {}) as Record<string, unknown>;
  const repoUrl = _project?.repoUrl || (projConfig.repoUrl as string) || '';
  const branch = (projConfig.branch as string) || 'main';
  const includePatterns = (projConfig.includePatterns as string) || '';
  const selectedProvider = (projConfig.selectedProvider as string) || 'GitHub';
  const targetLang = _project?.targetLanguage || '';
  const sourceLang = _project?.sourceLanguage || '';
  const sourceVersion = (projConfig.sourceVersion as string) || '';
  const targetVersion = (projConfig.targetVersion as string) || '';
  const architecturePattern = (projConfig.architecturePattern as string) || '';
  const intent = (projConfig.intent as string) || '';
  const selectedDatabase = (projConfig.selectedDatabase as string) || '';
  const testingFramework = (projConfig.testingFramework as string) || '';
  const repoDisplay = repoUrl.replace(/^https?:\/\//, '');
  const targetLabel = targetLang.charAt(0).toUpperCase() + targetLang.slice(1);
  const targetInitial = targetLang.charAt(0).toUpperCase() || '?';

  // Persisted upload state from project config
  const storedUploadId = (projConfig.uploadId as string) || '';
  const storedFolderName = (projConfig.folderName as string) || '';
  const storedUploadMeta = projConfig.uploadMeta as { fileCount?: number; totalBytes?: number } | undefined;

  const providerList = [
    { name: 'GitHub', icon: '🐙' },
    { name: 'GitLab', icon: '🦊' },
    { name: 'Azure DevOps', icon: '🔷' },
    { name: 'Bitbucket', icon: '🪣' },
  ];

  function detectProvider(url: string): 'github' | 'gitlab' | 'azure' | 'bitbucket' | 'unknown' {
    if (url.includes('github.com')) return 'github';
    if (url.includes('gitlab.com')) return 'gitlab';
    if (url.includes('dev.azure.com') || url.includes('visualstudio.com')) return 'azure';
    if (url.includes('bitbucket.org')) return 'bitbucket';
    return 'unknown';
  }

  const detectedProvider = detectProvider(repoUrl);

  const isLocalFolderStored = !repoUrl && !!storedUploadId;
  const [activeProvider, setActiveProvider] = useState(
    isLocalFolderStored ? 'Local Folder' : (selectedProvider || 'GitHub')
  );
  const [connected, setConnected] = useState(!!repoUrl || isLocalFolderStored);
  const [connecting, setConnecting] = useState(false);
  const [connectError, setConnectError] = useState<string | null>(null);
  const [ghData, setGhData] = useState<GHData | null>(null);
  const [ghLoading, setGhLoading] = useState(false);
  const [ghError, setGhError] = useState<string | null>(null);
  const [treeSearch, setTreeSearch] = useState('');
  const [activeTab, setActiveTab] = useState<'tree' | 'commits' | 'readme'>('tree');
  const [inputRepoUrl, setInputRepoUrl] = useState(repoDisplay || '');

  // Local folder upload state
  const [localFiles, setLocalFiles] = useState<File[] | null>(null);
  const [localFolderName, setLocalFolderName] = useState(storedFolderName);
  const [uploadStatus, setUploadStatus] = useState<'idle' | 'uploading' | 'done' | 'error'>(
    storedUploadId ? 'done' : 'idle'
  );
  const [uploadMeta, setUploadMeta] = useState<{ uploadId: string; fileCount: number; totalBytes: number } | null>(
    storedUploadId && storedUploadMeta
      ? { uploadId: storedUploadId, fileCount: storedUploadMeta.fileCount ?? 0, totalBytes: storedUploadMeta.totalBytes ?? 0 }
      : null
  );
  const [uploadError, setUploadError] = useState<string | null>(null);
  const folderInputRef = useRef<HTMLInputElement | null>(null);

  const isLocalFolderConnected = connected && activeProvider === 'Local Folder';

  // Fetch GitHub data when connected (only for GitHub repos)
  useEffect(() => {
    if (!connected || !repoUrl || ghData || detectedProvider !== 'github') return;
    let cancelled = false;
    setGhLoading(true);
    setGhError(null);
    fetch(`/api/github/repo-info?repoUrl=${encodeURIComponent(repoUrl)}&branch=${encodeURIComponent(branch)}`)
      .then(async res => {
        const data = await res.json();
        if (cancelled) return;
        if (!res.ok || data.error) setGhError(data.error ?? 'Failed to fetch repository data');
        else setGhData(data);
      })
      .catch(() => { if (!cancelled) setGhError('Failed to fetch repository data'); })
      .finally(() => { if (!cancelled) setGhLoading(false); });
    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [connected, repoUrl, branch, detectedProvider]);

  const handleConnect = async () => {
    const url = inputRepoUrl.startsWith('http') ? inputRepoUrl : `https://${inputRepoUrl}`;
    const provider = detectProvider(url);
    setConnecting(true);
    setConnectError(null);
    try {
      if (provider === 'github') {
        const res = await fetch(`/api/github/repo-info?repoUrl=${encodeURIComponent(url)}&branch=${encodeURIComponent(branch)}`);
        const data = await res.json().catch(() => ({}));
        if (!res.ok || data.error) {
          setConnectError(data.error ?? 'Repository not found or not accessible. Check the URL and try again.');
          setConnecting(false);
          return;
        }
        setGhData(data);
      } else if (provider === 'gitlab') {
        if (!url.match(/^https?:\/\/gitlab\.com\/[^/]+\/[^/]+/)) {
          setConnectError('Invalid GitLab URL. Expected format: gitlab.com/owner/repository');
          setConnecting(false);
          return;
        }
      } else if (provider === 'azure') {
        if (!url.match(/^https?:\/\/dev\.azure\.com\/[^/]+\/[^/]+\/_git\/.+/)) {
          setConnectError('Invalid Azure DevOps URL. Expected format: dev.azure.com/org/project/_git/repository');
          setConnecting(false);
          return;
        }
      } else if (provider === 'bitbucket') {
        if (!url.match(/^https?:\/\/bitbucket\.org\/[^/]+\/[^/]+/)) {
          setConnectError('Invalid Bitbucket URL. Expected format: bitbucket.org/workspace/repository');
          setConnecting(false);
          return;
        }
      } else {
        setConnectError('Enter a valid repository URL (github.com, gitlab.com, dev.azure.com, or bitbucket.org).');
        setConnecting(false);
        return;
      }
      setConnected(true);
    } catch {
      setConnectError('Failed to connect to the repository. Check the URL and try again.');
    }
    setConnecting(false);
  };

  const handleFolderSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    if (files.length === 0) return;
    const firstPath = files[0].webkitRelativePath || files[0].name;
    const folderName = firstPath.split('/')[0] || 'folder';
    setLocalFiles(files);
    setLocalFolderName(folderName);
    setUploadStatus('idle');
    setUploadError(null);
  };

  const handleUploadFolder = async () => {
    if (!localFiles || localFiles.length === 0) return;
    setUploadStatus('uploading');
    setUploadError(null);
    try {
      const result = await api.engine.uploadBundle(localFiles);
      setUploadMeta(result);
      setUploadStatus('done');
      if (projectId) {
        await api.updateProject(projectId, {
          config: {
            uploadId: result.uploadId,
            folderName: localFolderName,
            uploadMeta: {
              fileCount: result.fileCount,
              totalBytes: result.totalBytes,
              preparedAt: new Date().toISOString(),
              source: 'browser',
            },
          },
        }).catch(() => {});
      }
      setConnected(true);
    } catch (err) {
      setUploadStatus('error');
      setUploadError(err instanceof Error ? err.message : 'Upload failed');
    }
  };

  // Filter file tree by search
  const filterTree = (nodes: TreeNode[], q: string): TreeNode[] => {
    if (!q) return nodes;
    const lower = q.toLowerCase();
    return nodes.reduce<TreeNode[]>((acc, node) => {
      if (node.name.toLowerCase().includes(lower)) {
        acc.push(node);
      } else if (node.children) {
        const filtered = filterTree(node.children, q);
        if (filtered.length > 0) acc.push({ ...node, children: filtered });
      }
      return acc;
    }, []);
  };

  const filteredTree = ghData ? filterTree(ghData.fileTree, treeSearch) : [];

  return (
    <div className="space-y-5">
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
        <h2 className="text-2xl font-bold text-foreground">Repository Ingestion</h2>
        <p className="text-sm text-muted mt-1">Connect a Git repository or upload a local project folder</p>
      </motion.div>

      {!connected ? (
        /* ─── Connect Form ─── */
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          <div className="glass rounded-xl p-6">
            <h3 className="text-sm font-semibold text-foreground mb-4">Connect Repository</h3>
            <div className="grid grid-cols-2 gap-4 mb-4">
              {providerList.map((provider) => {
                const isSelected = provider.name === activeProvider;
                return (
                  <div key={provider.name} onClick={() => setActiveProvider(provider.name)} className={`p-4 rounded-lg border cursor-pointer transition-all ${isSelected ? 'border-accent/50 bg-accent/10 glow-accent' : 'border-border bg-surface hover:border-accent/30'}`}>
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">{provider.icon}</span>
                      <div>
                        <p className="text-sm font-medium text-foreground">{provider.name}</p>
                        <p className="text-[10px] text-muted">{isSelected ? 'Selected' : 'Click to select'}</p>
                      </div>
                      {isSelected && <Check className="w-4 h-4 text-accent-light ml-auto" />}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Local Folder option */}
            <div
              onClick={() => setActiveProvider('Local Folder')}
              className={`mb-5 p-4 rounded-lg border cursor-pointer transition-all flex items-center gap-3 ${activeProvider === 'Local Folder' ? 'border-accent/50 bg-accent/10 glow-accent' : 'border-border bg-surface hover:border-accent/30'}`}
            >
              <span className="text-2xl">📁</span>
              <div className="flex-1">
                <p className="text-sm font-medium text-foreground">Local Folder</p>
                <p className="text-[10px] text-muted">Upload a project folder from your computer</p>
              </div>
              {activeProvider === 'Local Folder' && <Check className="w-4 h-4 text-accent-light" />}
            </div>

            {activeProvider === 'Local Folder' ? (
              /* ── Local folder picker ── */
              <div className="space-y-3">
                <input
                  ref={folderInputRef}
                  type="file"
                  // @ts-expect-error webkitdirectory is not in the TS types
                  webkitdirectory=""
                  multiple
                  className="hidden"
                  onChange={handleFolderSelect}
                />
                {localFiles && localFolderName ? (
                  <div className="glass-light rounded-lg px-4 py-3 flex items-center gap-3">
                    <FolderOpen className="w-4 h-4 text-accent-light shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">{localFolderName}/</p>
                      <p className="text-[10px] text-muted">{localFiles.length.toLocaleString()} files · {(localFiles.reduce((s, f) => s + f.size, 0) / (1024 * 1024)).toFixed(1)} MB</p>
                    </div>
                    <button onClick={() => { setLocalFiles(null); setLocalFolderName(''); setUploadStatus('idle'); }} className="text-muted hover:text-foreground transition-colors cursor-pointer">
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={() => folderInputRef.current?.click()}
                    className="w-full py-8 rounded-lg border-2 border-dashed border-border hover:border-accent/40 transition-colors flex flex-col items-center gap-2 text-muted hover:text-foreground cursor-pointer"
                  >
                    <Upload className="w-6 h-6" />
                    <span className="text-sm font-medium">Choose project folder</span>
                    <span className="text-[10px]">Click to browse your computer</span>
                  </button>
                )}
                {uploadError && (
                  <div className="flex items-start gap-2 text-xs text-danger bg-danger/10 border border-danger/20 rounded-lg px-3 py-2">
                    <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />{uploadError}
                  </div>
                )}
                <button
                  onClick={handleUploadFolder}
                  disabled={!localFiles || uploadStatus === 'uploading'}
                  className="w-full py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer disabled:opacity-60"
                >
                  {uploadStatus === 'uploading'
                    ? <><Loader2 className="w-4 h-4 animate-spin" /> Uploading…</>
                    : <><Upload className="w-4 h-4" /> Upload &amp; Connect</>}
                </button>
              </div>
            ) : (
              /* ── Git URL / branch inputs ── */
              <>
                <div className="space-y-3">
                  <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                    <Globe className="w-4 h-4 text-muted" />
                    <input
                      type="text"
                      value={inputRepoUrl}
                      onChange={e => { setInputRepoUrl(e.target.value); setConnectError(null); }}
                      className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted"
                      placeholder="https://github.com/owner/repo"
                    />
                    {repoUrl && <Lock className="w-4 h-4 text-amber-400" />}
                  </div>
                  <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                    <GitBranch className="w-4 h-4 text-muted" />
                    <input type="text" defaultValue={branch} className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" placeholder="Branch" />
                  </div>
                  {includePatterns && (
                    <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                      <Search className="w-4 h-4 text-muted" />
                      <input type="text" defaultValue={includePatterns} className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" placeholder="File patterns" />
                    </div>
                  )}
                </div>
                {connectError && (
                  <div className="mt-3 flex items-start gap-2 text-xs text-danger bg-danger/10 border border-danger/20 rounded-lg px-3 py-2">
                    <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />{connectError}
                  </div>
                )}
                <button onClick={handleConnect} disabled={connecting || !inputRepoUrl} className="mt-4 w-full py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer disabled:opacity-60">
                  {connecting ? <><Loader2 className="w-4 h-4 animate-spin" /> Validating…</> : <><Zap className="w-4 h-4" /> Connect Repository</>}
                </button>
              </>
            )}
          </div>
        </motion.div>
      ) : ghLoading ? (
        /* ─── Loading ─── */
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="glass rounded-xl p-12 text-center">
          <Loader2 className="w-8 h-8 animate-spin text-accent-light mx-auto mb-4" />
          <h3 className="text-sm font-semibold text-foreground mb-1">Fetching Repository Data</h3>
          <p className="text-xs text-muted">Scanning {repoDisplay}...</p>
        </motion.div>
      ) : ghError ? (
        /* ─── Error ─── */
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="glass rounded-xl p-8 text-center border border-danger/30">
          <AlertTriangle className="w-8 h-8 text-danger mx-auto mb-3" />
          <h3 className="text-sm font-semibold text-foreground mb-1">Unable to fetch repository</h3>
          <p className="text-xs text-muted mb-4">{ghError}</p>
          <button onClick={() => { setGhError(null); setGhData(null); }} className="px-4 py-2 rounded-lg glass-light text-xs font-medium text-foreground hover:border-accent/30 cursor-pointer">
            Retry
          </button>
        </motion.div>
      ) : ghData ? (
        /* ─── Connected: Rich View ─── */
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">

          {/* ── Header bar ── */}
          <div className="glass rounded-xl p-4">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-2.5 h-2.5 rounded-full bg-success animate-pulse" />
              <span className="text-sm font-medium text-success">Connected to {selectedProvider}</span>
              <a href={repoUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-accent-light flex items-center gap-1 ml-auto hover:underline">
                {repoDisplay} <ExternalLink className="w-3 h-3" />
              </a>
            </div>
            {/* Stats row */}
            <div className="grid grid-cols-6 gap-2">
              {[
                { icon: FileCode2, label: 'Files', value: ghData.totalFiles.toLocaleString(), color: 'text-accent-light' },
                { icon: GitBranch, label: 'Branch', value: branch, color: 'text-purple-400' },
                { icon: Star, label: 'Stars', value: (ghData.repo?.stars ?? 0).toLocaleString(), color: 'text-amber-400' },
                { icon: GitFork, label: 'Forks', value: (ghData.repo?.forks ?? 0).toLocaleString(), color: 'text-cyan-400' },
                { icon: Shield, label: 'Visibility', value: ghData.repo?.visibility ?? '—', color: 'text-green-400' },
                { icon: Database, label: 'Size', value: formatKB(ghData.repo?.size ?? 0), color: 'text-pink-400' },
              ].map((s) => {
                const Icon = s.icon;
                return (
                  <div key={s.label} className="glass-light rounded-lg p-2.5 text-center">
                    <Icon className={`w-3.5 h-3.5 ${s.color} mx-auto mb-1`} />
                    <p className="text-sm font-bold text-foreground leading-tight">{s.value}</p>
                    <p className="text-[9px] text-muted uppercase tracking-wider">{s.label}</p>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Main content grid ── */}
          <div className="grid grid-cols-5 gap-4">

            {/* Left: file tree + tabs */}
            <div className="col-span-3 space-y-4">
              {/* Tab bar */}
              <div className="glass rounded-xl p-1 flex gap-1">
                {[
                  { id: 'tree' as const, label: 'File Tree', icon: FolderOpen },
                  { id: 'commits' as const, label: `Commits (${ghData.commits.length})`, icon: Clock },
                  { id: 'readme' as const, label: 'README', icon: BookOpen },
                ].map(t => {
                  const Icon = t.icon;
                  return (
                    <button key={t.id} onClick={() => setActiveTab(t.id)} className={`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-xs font-medium transition-all cursor-pointer ${activeTab === t.id ? 'bg-surface-light text-foreground border border-border' : 'text-muted hover:text-foreground'}`}>
                      <Icon className="w-3.5 h-3.5" /> {t.label}
                    </button>
                  );
                })}
              </div>

              {activeTab === 'tree' && (
                <div className="glass rounded-xl p-4">
                  <div className="flex items-center gap-2 mb-3">
                    <Search className="w-3.5 h-3.5 text-muted" />
                    <input type="text" value={treeSearch} onChange={e => setTreeSearch(e.target.value)} className="flex-1 bg-transparent text-xs text-foreground outline-none placeholder-muted" placeholder="Search files..." />
                    <span className="text-[10px] text-muted">{ghData.totalFiles} files</span>
                  </div>
                  <div className="max-h-[450px] overflow-y-auto pr-1">
                    {filteredTree.length > 0 ? filteredTree.map(node => (
                      <FileTreeItem key={node.name} node={node} />
                    )) : (
                      <p className="text-xs text-muted py-4 text-center">No files match your search</p>
                    )}
                  </div>
                </div>
              )}

              {activeTab === 'commits' && (
                <div className="glass rounded-xl p-4 space-y-2">
                  <h3 className="text-sm font-semibold text-foreground mb-2">Recent Commits</h3>
                  {ghData.commits.map(c => (
                    <div key={c.sha} className="glass-light rounded-lg p-3 flex items-start gap-3">
                      {c.avatar && <img src={c.avatar} alt="" className="w-7 h-7 rounded-full mt-0.5" />}
                      <div className="flex-1 min-w-0">
                        <p className="text-xs text-foreground truncate font-medium">{c.message}</p>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-[10px] text-muted">{c.author}</span>
                          <span className="text-[10px] text-accent-light font-mono">{c.sha}</span>
                          {c.date && <span className="text-[10px] text-muted ml-auto">{timeAgo(c.date)}</span>}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {activeTab === 'readme' && (
                <div className="glass rounded-xl p-4">
                  <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                    <BookOpen className="w-4 h-4 text-accent-light" /> README.md
                  </h3>
                  {ghData.readme ? (
                    <pre className="text-xs text-muted leading-relaxed whitespace-pre-wrap max-h-[450px] overflow-y-auto font-mono bg-surface/50 rounded-lg p-4">
                      {ghData.readme}
                    </pre>
                  ) : (
                    <p className="text-xs text-muted py-4 text-center">No README found</p>
                  )}
                </div>
              )}
            </div>

            {/* Right sidebar */}
            <div className="col-span-2 space-y-4">

              {/* Languages */}
              <div className="glass rounded-xl p-4">
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Code className="w-4 h-4 text-accent-light" /> Languages
                </h3>
                {/* Color bar */}
                {ghData.languages.length > 0 && (
                  <div className="flex h-2 rounded-full overflow-hidden mb-3">
                    {ghData.languages.map(l => (
                      <div key={l.name} style={{ width: `${l.percentage}%`, backgroundColor: langColors[l.name] || '#6e7681' }} title={`${l.name}: ${l.percentage}%`} />
                    ))}
                  </div>
                )}
                <div className="space-y-2">
                  {ghData.languages.map(l => (
                    <div key={l.name} className="flex items-center gap-2 text-xs">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: langColors[l.name] || '#6e7681' }} />
                      <span className="text-foreground flex-1">{l.name}</span>
                      <span className="text-muted font-mono">{l.percentage}%</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* File extensions */}
              <div className="glass rounded-xl p-4">
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <FileCode2 className="w-4 h-4 text-purple-400" /> File Types
                </h3>
                <div className="space-y-1.5">
                  {ghData.extensions.slice(0, 10).map(e => (
                    <div key={e.ext} className="flex items-center justify-between text-xs">
                      <span className="text-foreground font-mono">{e.ext}</span>
                      <span className="text-muted">{e.count} files ({e.percentage}%)</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Contributors */}
              {ghData.contributors.length > 0 && (
                <div className="glass rounded-xl p-4">
                  <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                    <Users className="w-4 h-4 text-cyan-400" /> Contributors ({ghData.contributors.length})
                  </h3>
                  <div className="space-y-2">
                    {ghData.contributors.map(c => (
                      <div key={c.login} className="flex items-center gap-2">
                        <img src={c.avatar} alt="" className="w-6 h-6 rounded-full" />
                        <span className="text-xs text-foreground flex-1">{c.login}</span>
                        <span className="text-[10px] text-muted">{c.contributions} commits</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Conversion target */}
              <div className="glass rounded-xl p-4">
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Zap className="w-4 h-4 text-amber-400" /> Conversion Target
                </h3>
                <div className="glass-light rounded-lg p-3 flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-accent/15 flex items-center justify-center text-accent-light text-lg font-bold">{targetInitial}</div>
                  <div>
                    <p className="text-sm font-medium text-foreground">{targetVersion || targetLabel || 'Not configured'}</p>
                    <p className="text-[10px] text-muted">{sourceLang ? `from ${sourceVersion || sourceLang.toUpperCase()}` : ''}</p>
                  </div>
                </div>
                {(architecturePattern || selectedDatabase || testingFramework || intent) && (
                  <div className="mt-3 space-y-1.5">
                    {architecturePattern && <div className="flex items-center justify-between text-xs"><span className="text-muted">Architecture</span><span className="text-foreground font-medium">{architecturePattern}</span></div>}
                    {intent && <div className="flex items-center justify-between text-xs"><span className="text-muted">Intent</span><span className="text-foreground font-medium">{intent}</span></div>}
                    {selectedDatabase && <div className="flex items-center justify-between text-xs"><span className="text-muted">Database</span><span className="text-foreground font-medium">{selectedDatabase}</span></div>}
                    {testingFramework && <div className="flex items-center justify-between text-xs"><span className="text-muted">Testing</span><span className="text-foreground font-medium">{testingFramework}</span></div>}
                  </div>
                )}
              </div>

              {/* Repo info */}
              {ghData.repo && (
                <div className="glass rounded-xl p-4">
                  <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                    <Activity className="w-4 h-4 text-green-400" /> Repository Info
                  </h3>
                  <div className="space-y-1.5 text-xs">
                    {ghData.repo.description && <p className="text-muted mb-2">{ghData.repo.description}</p>}
                    <div className="flex justify-between"><span className="text-muted">Created</span><span className="text-foreground">{new Date(ghData.repo.createdAt).toLocaleDateString()}</span></div>
                    <div className="flex justify-between"><span className="text-muted">Last push</span><span className="text-foreground">{timeAgo(ghData.repo.pushedAt)}</span></div>
                    <div className="flex justify-between"><span className="text-muted">Open issues</span><span className="text-foreground">{ghData.repo.openIssues}</span></div>
                    {ghData.repo.license && <div className="flex justify-between"><span className="text-muted">License</span><span className="text-foreground">{ghData.repo.license}</span></div>}
                    {ghData.repo.topics.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {ghData.repo.topics.map(t => (
                          <span key={t} className="px-1.5 py-0.5 rounded-full bg-accent/10 text-accent-light text-[10px]">{t}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Action button */}
              <button
                onClick={() => onNavigate('migration-strategy', projectId)}
                className="w-full py-3.5 rounded-xl gradient-accent text-white text-sm font-bold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer glow-accent"
              >
                <ArrowRight className="w-4 h-4" /> Proceed to Migration Strategy
              </button>
            </div>
          </div>
        </motion.div>
      ) : isLocalFolderConnected ? (
        /* ─── Connected: Local folder upload ─── */
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          <div className="glass rounded-xl p-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-2.5 h-2.5 rounded-full bg-success animate-pulse" />
              <span className="text-sm font-medium text-success">Local folder connected</span>
              <button
                onClick={() => { setConnected(false); setUploadStatus('idle'); setLocalFiles(null); }}
                className="text-xs text-muted hover:text-foreground ml-auto cursor-pointer transition-colors"
              >
                Change
              </button>
            </div>
            <div className="flex items-center gap-3 glass-light rounded-lg px-4 py-3 mb-4">
              <FolderOpen className="w-5 h-5 text-accent-light shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-foreground truncate">{localFolderName || storedFolderName || 'Uploaded folder'}/</p>
                <p className="text-[10px] text-muted">
                  {(uploadMeta?.uploadId || storedUploadId) && `Upload ID: ${(uploadMeta?.uploadId || storedUploadId).slice(0, 16)}…`}
                </p>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="glass-light rounded-lg p-3 text-center">
                <FileCode2 className="w-4 h-4 text-accent-light mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">
                  {(uploadMeta?.fileCount ?? storedUploadMeta?.fileCount ?? 0).toLocaleString()}
                </p>
                <p className="text-[10px] text-muted uppercase tracking-wider">Files</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <HardDrive className="w-4 h-4 text-purple-400 mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">
                  {(((uploadMeta?.totalBytes ?? storedUploadMeta?.totalBytes ?? 0)) / (1024 * 1024)).toFixed(1)} MB
                </p>
                <p className="text-[10px] text-muted uppercase tracking-wider">Size</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <Shield className="w-4 h-4 text-green-400 mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">Uploaded</p>
                <p className="text-[10px] text-muted uppercase tracking-wider">Status</p>
              </div>
            </div>
          </div>

          <div className="glass rounded-xl p-5">
            <div className="flex items-start gap-3 mb-3">
              <div className="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center shrink-0">
                <Code className="w-4 h-4 text-accent-light" />
              </div>
              <div>
                <p className="text-sm font-semibold text-foreground">Folder uploaded to engine</p>
                <p className="text-xs text-muted mt-0.5">Full source analysis runs in the Pre-Analysis step.</p>
              </div>
            </div>
            {(sourceLang || targetLang) && (
              <div className="border-t border-white/5 pt-3 grid grid-cols-2 gap-2">
                {sourceLang && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Source</span><span className="text-foreground font-medium">{sourceVersion || sourceLang.toUpperCase()}</span></div>}
                {targetLang && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Target</span><span className="text-foreground font-medium">{targetVersion || targetLang.toUpperCase()}</span></div>}
              </div>
            )}
          </div>

          <button
            onClick={() => onNavigate('migration-strategy', projectId)}
            className="w-full py-3.5 rounded-xl gradient-accent text-white text-sm font-bold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer glow-accent"
          >
            <ArrowRight className="w-4 h-4" /> Proceed to Migration Strategy
          </button>
        </motion.div>
      ) : connected && detectedProvider !== 'github' ? (
        /* ─── Connected: Non-GitHub provider (GitLab / Azure DevOps / Bitbucket) ─── */
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          <div className="glass rounded-xl p-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-2.5 h-2.5 rounded-full bg-success animate-pulse" />
              <span className="text-sm font-medium text-success">Connected to {selectedProvider}</span>
              <a href={repoUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-accent-light flex items-center gap-1 ml-auto hover:underline">
                {repoDisplay} <ExternalLink className="w-3 h-3" />
              </a>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="glass-light rounded-lg p-3 text-center">
                <GitBranch className="w-4 h-4 text-purple-400 mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">{branch}</p>
                <p className="text-[10px] text-muted uppercase tracking-wider">Branch</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <Globe className="w-4 h-4 text-accent-light mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">{selectedProvider}</p>
                <p className="text-[10px] text-muted uppercase tracking-wider">Provider</p>
              </div>
              <div className="glass-light rounded-lg p-3 text-center">
                <Shield className="w-4 h-4 text-green-400 mx-auto mb-1" />
                <p className="text-sm font-bold text-foreground">Verified</p>
                <p className="text-[10px] text-muted uppercase tracking-wider">URL format</p>
              </div>
            </div>
          </div>

          <div className="glass rounded-xl p-5">
            <div className="flex items-start gap-3 mb-4">
              <div className="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center shrink-0">
                <Code className="w-4 h-4 text-accent-light" />
              </div>
              <div>
                <p className="text-sm font-semibold text-foreground">Repository connected</p>
                <p className="text-xs text-muted mt-0.5">
                  {detectedProvider === 'gitlab' && 'GitLab repository connected. Full file-tree analysis runs in the Pre-Analysis step.'}
                  {detectedProvider === 'azure' && 'Azure DevOps repository connected. Full file-tree analysis runs in the Pre-Analysis step.'}
                  {detectedProvider === 'bitbucket' && 'Bitbucket repository connected. Full file-tree analysis runs in the Pre-Analysis step.'}
                  {detectedProvider === 'unknown' && 'Repository connected. Proceed to Migration Strategy to begin scanning.'}
                </p>
              </div>
            </div>
            {(architecturePattern || selectedDatabase || testingFramework || intent || sourceLang || targetLang) && (
              <div className="border-t border-white/5 pt-4 grid grid-cols-2 gap-2">
                {sourceLang && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Source</span><span className="text-foreground font-medium">{sourceVersion || sourceLang.toUpperCase()}</span></div>}
                {targetLang && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Target</span><span className="text-foreground font-medium">{targetVersion || targetLang.toUpperCase()}</span></div>}
                {architecturePattern && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Architecture</span><span className="text-foreground font-medium">{architecturePattern}</span></div>}
                {intent && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Intent</span><span className="text-foreground font-medium">{intent}</span></div>}
                {selectedDatabase && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Database</span><span className="text-foreground font-medium">{selectedDatabase}</span></div>}
                {testingFramework && <div className="flex items-center justify-between text-xs glass-light rounded-lg px-3 py-2"><span className="text-muted">Testing</span><span className="text-foreground font-medium">{testingFramework}</span></div>}
              </div>
            )}
          </div>

          <button
            onClick={() => onNavigate('migration-strategy', projectId)}
            className="w-full py-3.5 rounded-xl gradient-accent text-white text-sm font-bold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer glow-accent"
          >
            <ArrowRight className="w-4 h-4" /> Proceed to Migration Strategy
          </button>
        </motion.div>
      ) : null}
    </div>
  );
}
