import React, { useState, useEffect } from 'react'; import { motion, AnimatePresence } from 'motion/react'; import { FolderGit2, Trash2, Plus, ExternalLink, X, ShieldAlert, FileCode, Search, Sparkles, Github, RefreshCw, GitBranch, Terminal, ShieldCheck, Check, Code2, AlertCircle, Bookmark, Eye, EyeOff, LayoutGrid, Cpu, Layers, Clipboard, Info, Mail, Link, Settings, Copy, Code, CheckCircle2, ChevronRight } from 'lucide-react'; import { LocalizationSchema, Project } from '../types'; import { safeReadFromClipboard, safeCopyToClipboard } from '../utils/clipboard'; interface ProjectsViewProps { key?: string; t: LocalizationSchema['projects']; projects: Project[]; onAddProject: (project: Omit) => void; onDeleteProject: (id: string) => void; isAddModalOpen: boolean; setIsAddModalOpen: (open: boolean) => void; lang?: 'ar' | 'en'; } export default function ProjectsView({ t, projects, onAddProject, onDeleteProject, isAddModalOpen, setIsAddModalOpen, lang = 'ar', }: ProjectsViewProps) { // Form State const [name, setName] = useState(''); const [platform, setPlatform] = useState('Lovable'); const [customPlatform, setCustomPlatform] = useState(''); const [email, setEmail] = useState(''); const [url, setUrl] = useState(''); const [errorMess, setErrorMess] = useState(''); // GitHub Integration State const [gitHubToken, setGitHubToken] = useState(() => localStorage.getItem('git_hub_projects_pat') || ''); const [isGitHubConnected, setIsGitHubConnected] = useState(() => !!localStorage.getItem('git_hub_projects_pat')); const [isGitHubLoading, setIsGitHubLoading] = useState(false); const [gitHubUser, setGitHubUser] = useState(null); const [gitHubRepos, setGitHubRepos] = useState([]); const [usingSandbox, setUsingSandbox] = useState(false); const [gitHubError, setGitHubError] = useState(''); const [githubSearch, setGithubSearch] = useState(''); const [isGitHubPanelExpanded, setIsGitHubPanelExpanded] = useState(true); const [showToken, setShowToken] = useState(false); // Tracking syncing status of individual repos const [syncingRepos, setSyncingRepos] = useState>({}); // List of synced repo URLs in this session const [syncedRepoUrls, setSyncedRepoUrls] = useState([]); // Hugging Face Integration State const [hfToken, setHfToken] = useState(() => localStorage.getItem('hf_projects_token') || ''); const [isHfConnected, setIsHfConnected] = useState(() => !!localStorage.getItem('hf_projects_token')); const [isHfLoading, setIsHfLoading] = useState(false); const [hfUser, setHfUser] = useState(null); const [hfSpaces, setHfSpaces] = useState([]); const [usingHfSandbox, setUsingHfSandbox] = useState(false); const [hfError, setHfError] = useState(''); const [hfSearch, setHfSearch] = useState(''); const [showHfToken, setShowHfToken] = useState(false); const [syncingSpaces, setSyncingSpaces] = useState>({}); const [syncedSpaceUrls, setSyncedSpaceUrls] = useState([]); // Email Profile Linking & Custom Docker templates for Hugging Face Spaces const [linkedHfEmail, setLinkedHfEmail] = useState(() => localStorage.getItem('hf_projects_linked_email') || 'drmartin2050@gmail.com'); const [selectedDockerTemplate, setSelectedDockerTemplate] = useState<'gradio' | 'streamlit' | 'pytorch' | 'node' | 'fastapi'>('gradio'); const [containerDockerPort, setContainerDockerPort] = useState('7860'); const [dockerEnvVars, setDockerEnvVars] = useState('MODEL_ID=stabilityai/stable-diffusion-3\nUSE_GPU=true'); const [copiedDockerFile, setCopiedDockerFile] = useState(false); const [copiedDockerReadme, setCopiedDockerReadme] = useState(false); // Load registered emails list from localStorage (matching EmailsView.tsx) const getRegisteredEmailsAndAliases = () => { const saved = localStorage.getItem('dev_hub_emails_aliases'); const emailsList: { address: string; type: 'main' | 'alias'; platform?: string }[] = []; // Fallback seed accounts emailsList.push({ address: 'drmartin2050@gmail.com', type: 'main' }); emailsList.push({ address: 'drmartin.bolt@gmail.com', type: 'alias', platform: 'Bolt.new' }); emailsList.push({ address: 'drmartin.lovable@gmail.com', type: 'alias', platform: 'Lovable' }); emailsList.push({ address: 'drmartin.supabase@gmail.com', type: 'alias', platform: 'Supabase' }); emailsList.push({ address: 'eissa.developer@outlook.com', type: 'main' }); emailsList.push({ address: 'eissa.v0@outlook.com', type: 'alias', platform: 'v0.dev' }); emailsList.push({ address: 'eissa.replit@outlook.com', type: 'alias', platform: 'Replit' }); if (saved) { try { const accounts = JSON.parse(saved); if (Array.isArray(accounts)) { accounts.forEach((acc: any) => { if (acc?.address && !emailsList.some(e => e.address.toLowerCase() === acc.address.toLowerCase())) { emailsList.push({ address: acc.address, type: 'main' }); } if (Array.isArray(acc?.aliases)) { acc.aliases.forEach((alias: any) => { if (alias?.aliasAddress && !emailsList.some(e => e.address.toLowerCase() === alias.aliasAddress.toLowerCase())) { emailsList.push({ address: alias.aliasAddress, type: 'alias', platform: alias.platform }); } }); } }); } } catch (e) { console.warn("Error parsing EmailsView localStorage state inside ProjectsView", e); } } return emailsList; }; const getDockerTemplates = ( template: 'gradio' | 'streamlit' | 'pytorch' | 'node' | 'fastapi', port: string, envVars: string ): { dockerfile: string; readme: string } => { const activePort = port || '7860'; // Parse environment variables to ENV commands const envLines = envVars .split('\n') .map(line => line.trim()) .filter(line => line.length > 0 && !line.startsWith('#')) .map(line => { if (line.toUpperCase().startsWith('ENV ')) { return line; } return `ENV ${line}`; }) .join('\n'); const envStatement = envLines ? `\n# Custom Container Environment Secrets\n${envLines}\n` : ''; let dockerfile = ''; let readme = ''; switch (template) { case 'gradio': dockerfile = `# Use Python base runtime optimal for Gradio FROM python:3.10-slim WORKDIR /code COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY . . ${envStatement} # Run with active port mapping EXPOSE ${activePort} CMD ["python", "app.py", "--port", "${activePort}"]`; readme = `--- title: Custom Gradio Space emoji: 🚀 colorFrom: indigo colorTo: purple sdk: gradio sdk_version: 4.19.2 app_port: ${activePort} pinned: false license: mit --- # Gradio ML Model Space Synchronized via the AI Studio Development Hub. This Space hosts an interactive app powered by Python Gradio.`; break; case 'streamlit': dockerfile = `# Use official lightweight Python runtime FROM python:3.10-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . ${envStatement} # Streamlit required port EXPOSE EXPOSE ${activePort} CMD ["streamlit", "run", "app.py", "--server.port=${activePort}", "--server.address=0.0.0.0"]`; readme = `--- title: Custom Streamlit Space emoji: 📊 colorFrom: blue colorTo: green sdk: streamlit app_port: ${activePort} pinned: false license: apache-2.0 --- # Streamlit Data App Space Synchronized via the AI Studio Development Hub. Created to visualize datasets and model inferences seamlessly.`; break; case 'pytorch': dockerfile = `# Torch CUDA-enabled machine learning container FROM pytorch/pytorch:2.1.0-cuda11.8-cudnn8-runtime WORKDIR /workspace COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . ${envStatement} EXPOSE ${activePort} ENV PORT=${activePort} CMD ["python", "main.py"]`; readme = `--- title: PyTorch CUDA Container emoji: 🔥 colorFrom: red colorTo: orange sdk: docker app_port: ${activePort} pinned: false license: gpl-3.0 --- # Advanced CUDA PyTorch Space A high-performance machine learning Docker container for deep neural networks.`; break; case 'node': dockerfile = `# Lightweight Alpine production container for full-stack SPA and servers FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . ${envStatement} EXPOSE ${activePort} ENV PORT=${activePort} CMD ["node", "server.js"]`; readme = `--- title: Node.js Express Backend emoji: ⚡ colorFrom: green colorTo: gray sdk: docker app_port: ${activePort} pinned: false license: mit --- # Fullstack Javascript Container Space Running an Express.js backend or Static SPA optimized for server-side operations.`; break; case 'fastapi': dockerfile = `# Python slim FastAPI container FROM python:3.10-slim WORKDIR /code COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY . . ${envStatement} EXPOSE ${activePort} CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "${activePort}"]`; readme = `--- title: FastAPI ML Endpoint emoji: 🦄 colorFrom: teal colorTo: cyan sdk: docker app_port: ${activePort} pinned: false license: mit --- # High-Performance FastAPI Space Hosts highly performant REST APIs and model inference endpoints.`; break; default: dockerfile = `# Generic Docker template FROM alpine:latest RUN apk add --no-cache curl EXPOSE ${activePort} CMD ["echo", "Custom Hugging Face Space Active"]`; readme = `--- title: Custom Docker Space emoji: 🐳 sdk: docker app_port: ${activePort} ---`; } return { dockerfile, readme }; }; // Active integration tab ("github" | "huggingface") const [activeSyncTab, setActiveSyncTab] = useState<'github' | 'huggingface'>('github'); const [gitHubPasteStatus, setGitHubPasteStatus] = useState<'idle' | 'success' | 'blocked'>('idle'); const [hfPasteStatus, setHfPasteStatus] = useState<'idle' | 'success' | 'blocked'>('idle'); const handlePasteGitHubToken = async () => { setGitHubPasteStatus('idle'); const text = await safeReadFromClipboard(); if (text) { setGitHubToken(text); setGitHubPasteStatus('success'); setTimeout(() => setGitHubPasteStatus('idle'), 3000); } else { setGitHubPasteStatus('blocked'); setTimeout(() => setGitHubPasteStatus('idle'), 6000); } }; const handlePasteHfToken = async () => { setHfPasteStatus('idle'); const text = await safeReadFromClipboard(); if (text) { setHfToken(text); setHfPasteStatus('success'); setTimeout(() => setHfPasteStatus('idle'), 3000); } else { setHfPasteStatus('blocked'); setTimeout(() => setHfPasteStatus('idle'), 6000); } }; // Auto load GitHub and Hugging Face if tokens exist on mount useEffect(() => { if (gitHubToken && isGitHubConnected) { handleLoadGitHub(gitHubToken, false); } if (hfToken && isHfConnected) { handleLoadHuggingFace(hfToken, false); } }, []); const handleLoadHuggingFace = async (token: string, isManualSetup = false) => { if (!token.trim()) return; setIsHfLoading(true); setHfError(''); try { // Clean and sanitize the input token (removing accidentally pasted quotes, brackets, or "Bearer" prefix) let sanitizedToken = token.trim(); sanitizedToken = sanitizedToken.replace(/['"\[\]]/g, '').trim(); const hfMatch = sanitizedToken.match(/(hf_[a-zA-Z0-9_-]+)/); if (hfMatch) { sanitizedToken = hfMatch[1]; } // 1. Syntax Warning check (non-blocking to allow custom token designs/OAuth tokens) if (!sanitizedToken.startsWith('hf_')) { console.warn('Hugging Face access token warning: Token does not start with standard hf_ prefix. Attempting link anyway.'); } // 2. State resets setHfUser(null); setHfSpaces([]); // 3. API direct query let whoamiData: any = null; try { // Use our secure backend proxy to bypass CORS const userRes = await fetch('/api/hf/whoami', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: sanitizedToken }) }); if (userRes.status === 401 || userRes.status === 403) { throw new Error( lang === 'ar' ? 'تأكد من أن الرمز (Token) صالح ويحتوي على صلاحية (Read & Write) ضمن إعدادات Fine-grained Access Tokens. (خطأ 401/403)' : 'Ensure your Token is valid and has "Read & Write" permissions configured under Fine-grained Access Tokens. (Error 401/403)' ); } if (!userRes.ok) { throw new Error( lang === 'ar' ? `استجابة غير صالحة من خادم Hugging Face. رمز الاستجابة: ${userRes.status}` : `Invalid response from Hugging Face server. Status code: ${userRes.status}` ); } whoamiData = await userRes.json(); } catch (fErr: any) { // If it's a known HTTP error we threw, forward it. if (fErr.message && (fErr.message.includes('401') || fErr.message.includes('403') || fErr.message.includes('استجابة غير صالحة'))) { throw fErr; } console.error('Hugging Face API backend proxy error:', fErr); throw new Error( lang === 'ar' ? 'يتعذر الاتصال بالخادم الوسيط (Backend) لدينا. قد تكون هناك مشكلة في إعداد Express Server.' : 'Could not connect to the Backend Proxy. There might be an issue with the Express Server setup.' ); } // 4. Successful real API login if (whoamiData) { const parsedUser = { name: whoamiData.name || 'hf_user', fullname: whoamiData.fullname || whoamiData.name || (lang === 'ar' ? 'مطور هانجينج فيس' : 'Hugging Face Space Builder'), avatarUrl: whoamiData.avatarUrl || 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?q=80&w=150&auto=format&fit=crop', email: whoamiData.email || 'authenticated@huggingface.co', }; // Pull real user spaces via proxy let spacesList: any[] = []; try { const spacesRes = await fetch('/api/hf/spaces', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: sanitizedToken, author: parsedUser.name }) }); if (spacesRes.ok) { const rawSpaces = await spacesRes.json(); if (Array.isArray(rawSpaces)) { spacesList = rawSpaces.map((s: any) => ({ id: s.id, idFull: s.id, author: s.author || s.id.split('/')[0], name: s.id.split('/')[1] || s.id, sdk: s.sdk || 'gradio', likes: s.likes || 0, private: !!s.private, updatedAt: s.lastModified || new Date().toISOString() })); } } } catch (e) { console.warn('Failed compiling user spaces list via backend proxy', e); } setHfUser(parsedUser); setHfSpaces(spacesList); setIsHfConnected(true); setUsingHfSandbox(false); localStorage.setItem('hf_projects_token', sanitizedToken); } } catch (err: any) { setHfError(err.message || String(err)); setIsHfConnected(false); localStorage.removeItem('hf_projects_token'); } finally { setIsHfLoading(false); } }; const handleSyncHfSpace = (space: any) => { const spaceId = space.id; setSyncingSpaces(prev => ({ ...prev, [spaceId]: true })); setTimeout(() => { onAddProject({ projectName: space.name, platformUsed: `Hugging Face Space (${space.sdk || 'Gradio'})`, associatedEmail: linkedHfEmail, projectUrl: `https://huggingface.co/spaces/${space.id}`, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }); setSyncingSpaces(prev => ({ ...prev, [spaceId]: false })); setSyncedSpaceUrls(prev => [...prev, `https://huggingface.co/spaces/${space.id}`]); }, 1000); }; const handleDisconnectHf = () => { localStorage.removeItem('hf_projects_token'); setHfToken(''); setIsHfConnected(false); setHfUser(null); setHfSpaces([]); setUsingHfSandbox(false); setHfError(''); }; const handleLoadGitHub = async (token: string, isManualSetup = false) => { if (!token.trim()) return; setIsGitHubLoading(true); setGitHubError(''); try { // 1. Fetch user data const userRes = await fetch('https://api.github.com/user', { headers: { Authorization: `token ${token.trim()}`, Accept: 'application/vnd.github.v3+json', } }); if (!userRes.ok) throw new Error(lang === 'ar' ? 'الرمز التعريفي غير صالح أو منتهي الصلاحية.' : 'Invalid or expired GitHub access token.'); const userData = await userRes.json(); setGitHubUser(userData); // 2. Fetch user repositories const reposRes = await fetch('https://api.github.com/user/repos?sort=updated&per_page=50', { headers: { Authorization: `token ${token.trim()}`, Accept: 'application/vnd.github.v3+json', } }); if (!reposRes.ok) throw new Error(lang === 'ar' ? 'فشل جلب قائمة مستودعات الأكواد.' : 'Failed to retrieve repositories list.'); const reposData = await reposRes.json(); setGitHubRepos(Array.isArray(reposData) ? reposData : []); setIsGitHubConnected(true); setUsingSandbox(false); localStorage.setItem('git_hub_projects_pat', token.trim()); } catch (err: any) { setGitHubError(err.message || String(err)); if (isManualSetup) { setIsGitHubConnected(false); localStorage.removeItem('git_hub_projects_pat'); } } finally { setIsGitHubLoading(false); } }; const handleSyncRepository = (repo: any) => { const repoId = String(repo.id); setSyncingRepos(prev => ({ ...prev, [repoId]: true })); setTimeout(() => { onAddProject({ projectName: repo.name, platformUsed: repo.language || 'GitHub Repo', associatedEmail: 'drmartin2050@gmail.com', projectUrl: repo.html_url, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }); setSyncingRepos(prev => ({ ...prev, [repoId]: false })); setSyncedRepoUrls(prev => [...prev, repo.html_url]); }, 1000); }; const handleDisconnectGitHub = () => { localStorage.removeItem('git_hub_projects_pat'); setGitHubToken(''); setIsGitHubConnected(false); setGitHubUser(null); setGitHubRepos([]); setUsingSandbox(false); setGitHubError(''); }; // Search filter const [searchQuery, setSearchQuery] = useState(''); const filteredProjects = projects.filter(p => p.projectName.toLowerCase().includes(searchQuery.toLowerCase()) || p.platformUsed.toLowerCase().includes(searchQuery.toLowerCase()) || p.associatedEmail.toLowerCase().includes(searchQuery.toLowerCase()) ); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const finalPlatform = platform === 'Other' ? customPlatform.trim() : platform; // Direct simple inputs verification if (!name.trim() || !finalPlatform.trim() || !email.trim()) { setErrorMess(t.validationError); return; } // URL optional check if (url.trim() && !url.match(/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/)) { setErrorMess(t.validationError); return; } // Add protocol if missing from URL let formattedUrl = url.trim(); if (formattedUrl && !formattedUrl.startsWith('http://') && !formattedUrl.startsWith('https://')) { formattedUrl = 'https://' + formattedUrl; } onAddProject({ projectName: name.trim(), platformUsed: finalPlatform, associatedEmail: email.trim(), projectUrl: formattedUrl, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }); // Reset Form Fields setName(''); setPlatform('Lovable'); setCustomPlatform(''); setEmail(''); setUrl(''); setErrorMess(''); setIsAddModalOpen(false); }; const platformsList = ['Lovable', 'Bolt.new', 'Base44', 'Kimi', 'Google', 'Vercel', 'Netlify', 'Other']; // Beautiful brand gradient badge assignments const getPlatformGradient = (pForm: string) => { const norm = pForm.toLowerCase(); if (norm.includes('lovable')) { return 'linear-gradient(135deg, #f43f5e 0%, #ec4899 100%)'; // Rose/Pink } if (norm.includes('bolt')) { return 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)'; // Electric blue } if (norm.includes('base44')) { return 'linear-gradient(135deg, #06b6d4 0%, #0891b2 100%)'; // Cyan depth } if (norm.includes('kimi')) { return 'linear-gradient(135deg, #10b981 0%, #059669 100%)'; // Emerald } if (norm.includes('google')) { return 'linear-gradient(135deg, #ea4335 0%, #f9ab00 100%)'; // Red-yellow arc } if (norm.includes('vercel')) { return 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)'; // Dark premium slate } return 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)'; // Violet gradient }; return ( {/* Header and Add Project Controls */}

{t.title}

{t.subtitle}

{/* GitHub/Hugging Face double account link and repositories sync center */}
{/* Decorative subtle background design */}
{activeSyncTab === 'github' ? ( ) : ( 🤗 )}

{activeSyncTab === 'github' ? (lang === 'ar' ? 'مركز مزامنة مستودعات GitHub الذكي' : 'GitHub Repository Sync Center') : (lang === 'ar' ? 'مركز مزامنة مساحات Hugging Face' : 'Hugging Face AI Spaces Sync')} {lang === 'ar' ? 'التزامن الحي' : 'LIVE API SYNC'}

{lang === 'ar' ? 'اربط حساباتك السحابية بمفاتيح الوصول لاستيراد وتثبيت ومزامنة خدماتك بضغطة واحدة.' : 'Link your cloud accounts with Personal Access Tokens to retrieve and register projects.'}

{/* Integration Tab Switches */} {isGitHubPanelExpanded && (
)} {isGitHubPanelExpanded && ( {/* Active Tab is GitHub */} {activeSyncTab === 'github' && ( <> {!isGitHubConnected ? ( // Setup / Link flow
setGitHubToken(e.target.value)} placeholder={ lang === 'ar' ? 'أدخل مفتاح ghp_... أو قم بتجربة المحاكي مباشرة' : 'Paste ghp_... token or launch the offline simulator' } className="w-full bg-white/5 border border-white/10 rounded-xl p-3 pl-11 pr-24 text-sm outline-none placeholder:text-slate-500 text-white font-mono font-semibold focus:border-indigo-400 hover:border-white/20 transition-all" />
{gitHubPasteStatus === 'success' && (

{lang === 'ar' ? 'تم لصق المفتاح تلقائياً من الحافظة بنجاح!' : 'Successfully pasted key from clipboard!'}

)} {gitHubPasteStatus === 'blocked' && (

{lang === 'ar' ? 'تم حظر القراءة التلقائية للمتصفح!' : 'Direct browser reading is restricted!'}

{lang === 'ar' ? 'بسبب قيود أمان متصفحك داخل إطارات العرض (iFrame)، لا يمكن قراءة حافظتك بنقرة زر واحدة. يرجى المتابعة يدوياً: انقر داخل مربع النص واضغط على (Ctrl+V) أو (Cmd+V) في لوحة مفاتيحك للصق الرمز مباشرة.' : 'Due to secure sandboxing restrictions of your browser inside previews, clipboard read failed. Please paste manually: click on the text input and press (Ctrl+V) or (Cmd+V) on your keyboard.'}

)}
{gitHubError && (
{gitHubError}
)}

{lang === 'ar' ? 'كيفية إصدار الرمز التعريفي؟' : 'How does this integration work?'}

{lang === 'ar' ? 'يمكنك توليد PAT بالذهاب لـ Settings > Developer settings > Personal access tokens مع تفعيل صلاحيات repo.' : 'You can generate a classic Personal Access Token with "repo" read scopes via Settings > Developer Settings on your GitHub account.'}

{lang === 'ar' ? 'اصنع المفتاح الآن على GitHub ↗' : 'Generate PAT Token on GitHub ↗'}
) : ( // Linked Account Dashboard view
GitHub Avatar

{gitHubUser?.name || gitHubUser?.login}

{usingSandbox ? (lang === 'ar' ? 'وضع المحاكاة' : 'SANDBOX SIM') : (lang === 'ar' ? 'حساب متصل' : 'AUTH ONLINE')}

@{gitHubUser?.login} • {gitHubUser?.public_repos || gitHubRepos.length} {lang === 'ar' ? 'مستودع كود' : 'Repositories available'}

setGithubSearch(e.target.value)} placeholder={lang === 'ar' ? 'ابحث في مستودعاتك...' : 'Search repositories...'} className="bg-transparent text-xs text-white outline-none w-28 sm:w-40 placeholder:text-slate-500 font-bold" />
{/* List of active repositories ready to sync */}
{gitHubRepos .filter(r => r.name.toLowerCase().includes(githubSearch.toLowerCase())) .map((repo) => { const isSyncing = !!syncingRepos[repo.id]; // Synced means already added. Let's check matching projectURL or synced state const isSynced = syncedRepoUrls.includes(repo.html_url) || projects.some(p => p.projectUrl && p.projectUrl.replace(/^https?:\/\//, '') === repo.html_url.replace(/^https?:\/\//, '')); return (
{repo.name}
{repo.language && ( {repo.language} )}

{repo.description || (lang === 'ar' ? 'مستودع كود بدون وصف إيضاحي متاح.' : 'No descriptive overview recorded yet.')}

★ {repo.stargazers_count ?? 0} ⑂ {repo.forks_count ?? 0}
{lang === 'ar' ? 'معاينة' : 'View'} {isSynced ? ( {lang === 'ar' ? 'تمت المزامنة' : 'Synced'} ) : ( )}
); })}
)} )} {/* Active Tab is Hugging Face */} {activeSyncTab === 'huggingface' && (
{!isHfConnected ? ( // Hugging Face Link setup flow
setHfToken(e.target.value)} placeholder={ lang === 'ar' ? 'أدخل مفتاح hf_... أو قم بتجربة محاكي المنصة مباشرة' : 'Paste hf_... token or launch the offline simulator' } className="w-full bg-white/5 border border-white/10 rounded-xl p-3 pl-11 pr-24 text-sm outline-none placeholder:text-slate-500 text-white font-mono font-semibold focus:border-amber-400 hover:border-white/20 transition-all" />
{hfPasteStatus === 'success' && (

{lang === 'ar' ? 'تم لصق رمز Hugging Face تلقائياً بنجاح!' : 'Successfully pasted HF token from clipboard!'}

)} {hfPasteStatus === 'blocked' && (

{lang === 'ar' ? 'تم حظر القراءة التلقائية للمتصفح!' : 'Direct browser reading is restricted!'}

{lang === 'ar' ? 'بسبب قيود أمان متصفحك داخل إطارات العرض (iFrame)، لا يمكن قراءة حافظتك بنقرة زر واحدة. يرجى المتابعة يدوياً: انقر داخل مربع النص واضغط على (Ctrl+V) أو (Cmd+V) في لوحة مفاتيحك للصق الرمز مباشرة.' : 'Due to secure sandboxing restrictions of your browser inside previews, clipboard read failed. Please paste manually: click on the text input and press (Ctrl+V) or (Cmd+V) on your keyboard.'}

)}
{/* 🌟 Hugging Face Token Diagnostic & Security Audit Panel */}

{lang === 'ar' ? 'مساعد تشخيص وفحص صلاحية رمز هانجينغ فيس' : 'Hugging Face Token Audit Assistant'}

{/* Prefix Indicator */}
{lang === 'ar' ? 'تبدأ بـ hf_ :' : 'Starts with hf_:'} {hfToken.trim().startsWith('hf_') ? ( {lang === 'ar' ? 'موافق' : 'YES'} ) : ( {lang === 'ar' ? 'غير مطابق' : 'NO'} )}
{/* Length Indicator */}
{lang === 'ar' ? 'حالة الطول :' : 'Length check:'} {hfToken.trim().length >= 20 ? ( {lang === 'ar' ? 'سليم' : 'OK'} ) : ( {lang === 'ar' ? 'قصير جداً' : 'TOO SHORT'} )}
{/* Connection Status Indicator */}
{lang === 'ar' ? 'حالة الربط الفعلي :' : 'Live connection:'} {isHfConnected ? ( {usingHfSandbox ? (lang === 'ar' ? 'متصل بالمحاكي الآمن' : 'Connected via Secure Sandbox') : (lang === 'ar' ? 'متصل ومؤكد عبر السيرفر' : 'Connected & Verified via Hub')} ) : hfError ? ( {lang === 'ar' ? 'فشل التحقق الأخير' : 'Last check failed'} ) : hfToken.trim() ? ( {lang === 'ar' ? 'جاهز للربط الفعلي...' : 'Ready to authenticate...'} ) : ( {lang === 'ar' ? 'بانتظار لصق الرمز' : 'Awaiting token input'} )}
{/* Recommendation Banner */}
{lang === 'ar' ? 'التشخيص والتوافق الفني:' : 'DIAGNOSIS & TECHNICAL ALIGNMENT:'} {isHfConnected ? ( lang === 'ar' ? 'الرمز صالح وموثق تماماً! تم تشغيل المزامنة وجلب المساحات بشكل سليم، ولا يتطلب الرمز أي تغيير حالياً.' : 'Your token is fully verified and connected. No action or renewal needed!' ) : hfError ? ( lang === 'ar' ? `المفتاح الحالي منتهي الصلاحية أو تم إيقافه: (${hfError}). يجب توليد رمز وصول ذو صلاحية Read جديد كلياً وتغييره فوراً لتمكين التزامن.` : `Warning: Current token returned error: (${hfError}). You MUST generate a new Read access token and replace the current one.` ) : hfToken.trim() && !hfToken.trim().startsWith('hf_') ? ( lang === 'ar' ? 'تنسيق المفتاح يبدو خاطئاً! المفاتيح من Hugging Face يجب أن تبدأ دائماً بـ "hf_". يرجى نسخ الرمز بالكامل بدقة ولصقه مجدداً.' : 'Format mismatch! The token you pasted does not follow Hugging Face conventions (must start with "hf_").' ) : ( lang === 'ar' ? 'بعد إدخال المفتاح بمدخل النصوص، اضغط على زر "ربط الحساب ومزامنة المساحات" لفحصه وتوثيقه مباسرة تزامناً مع المنصة.' : 'Paste your token first, then click "Authenticate & Link Spaces" to verify and fetch spaces.' )}
{hfError && (
{hfError}
)}

{lang === 'ar' ? 'مزامنة مساحات الذكاء الاصطناعي' : 'Sync AI Spaces & Models'}

{lang === 'ar' ? 'يدعم Hugging Face مزامنة جميع مساحات الذكاء الاصطناعي (Spaces) المبنية باستخدام Gradio أو Streamlit أو Docker وتثبيتها فورياً.' : 'Retrieve and synchronize machine learning and AI spaces directly from your Hugging Face developer profile into this dashboard.'}

{lang === 'ar' ? 'احصل على رمز الوصول من هانجينج فيس ↗' : 'Generate Token on Hugging Face ↗'}
) : ( // Linked HF Profile Dashboard view
HuggingFace Avatar

{hfUser?.fullname || hfUser?.name}

{usingHfSandbox ? (lang === 'ar' ? 'وضع المحاكاة' : 'SANDBOX SIM') : (lang === 'ar' ? 'حساب متصل' : 'AUTH ONLINE')}

@{hfUser?.name} • {hfSpaces.length} {lang === 'ar' ? 'مساحة عمل مخصصة للذكاء' : 'AI Spaces available'}

setHfSearch(e.target.value)} placeholder={lang === 'ar' ? 'ابحث في مساحاتك...' : 'Search spaces...'} className="bg-transparent text-xs text-white outline-none w-28 sm:w-40 placeholder:text-slate-500 font-bold" />
{/* List of active Spaces ready to sync */}
{hfSpaces .filter(s => s.name.toLowerCase().includes(hfSearch.toLowerCase())) .map((space) => { const isSyncing = !!syncingSpaces[space.id]; const spaceUrl = `https://huggingface.co/spaces/${space.id}`; const isSynced = syncedSpaceUrls.includes(spaceUrl) || projects.some(p => p.projectUrl && p.projectUrl.replace(/^https?:\/\//, '') === spaceUrl.replace(/^https?:\/\//, '')); return (
{space.name}
{space.sdk && ( {space.sdk} )}

{lang === 'ar' ? 'مساحة عمل مخصصة ومطورة لاستضافة وعرض نماذج وتطبيقات الذكاء الاصطناعي.' : 'Hugging Face specialized hosting environment and model demonstrator space.'}

♥ {space.likes ?? 0} {space.private ? '🔒 Private' : '🌐 Public'}
{lang === 'ar' ? 'معاينة' : 'View'} {isSynced ? ( {lang === 'ar' ? 'تمت المزامنة' : 'Synced'} ) : ( )}
); })}
)} {/* 📧 Section 1: Complete Linking with Any Registered Primary or Alias Sub-Emails */}

{lang === 'ar' ? 'ربط هوية ومساحات Hugging Face بالبريد الإلكتروني المبرمج' : 'Link Hugging Face with Registered Email/Alias'} {lang === 'ar' ? 'نشط آمن' : 'Live Sync'}

{lang === 'ar' ? 'حدد أي بريد رئيسي تم تسجيله في "إدارة الهوية والبروكسي" أو حتى بريد فرعي (Alias) لربط وإسناد مشاريع هانجينغ فيس المستوردة له تلقائياً.' : 'Associate all synchronized space deployments with any primary or secondary alias email defined in your proxy account repository.' }

{lang === 'ar' ? 'حالة الربط:' : 'BINDING STATE:'} {linkedHfEmail}
{/* 🐳 Section 2: Complete Docker Configurator and Space Settings wizard */}

{lang === 'ar' ? 'مدير ملفات Docker وبقية أشكال إعدادات هانجينغ فيس' : 'Hugging Face Spaces Docker Setup Assistant'} {lang === 'ar' ? 'قوالب جاهزة' : 'Docker SDK'}

{lang === 'ar' ? 'هل تستخدم حاويات مخصصة؟ قم بتوليد ملف الـ Dockerfile وواجهة الأكواد لجميع تطبيقات ومساحات ومنافذ التشغيل بنقرة واحدة.' : 'Using custom containers? Generate deployment-ready Dockerfile templates and application port mappings optimized specifically for Hugging Face Spaces.' }

{/* Controller Form Column */}
{/* Template Type Selector */}
{/* Container Port Config */}
{lang === 'ar' ? 'مستحسن 7860' : '7860 is HF standard'}
setContainerDockerPort(e.target.value)} placeholder="7860" className="w-full text-xs text-white bg-slate-900 border border-white/10 rounded-xl p-3 outline-none focus:border-blue-400 font-mono font-extrabold" />
{/* Custom Environment Settings */}