'use client'; import Link from 'next/link'; import { useState, useEffect, useCallback } from 'react'; import { Repository, repoService } from '@/services/repoService'; import { githubService } from '@/services/githubService'; import { useAuthStore } from '@/store/authStore'; import { getErrorMessage } from '@/utils/error'; import { buildRepoTextPath } from '@/utils/repositoryRouting'; interface RepoInteractionPanelProps { repository: Repository; owner: string; name: string; onFollow: () => void; } function fmt(num?: number) { return Number(num || 0).toLocaleString(); } /** Simple activity graph -- 12-week bar chart (commit counts). */ function ActivityGraph({ owner, name }: { owner: string; name: string }) { const [weeklyData, setWeeklyData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetchActivity(); }, [owner, name]); const fetchActivity = async () => { try { const res = await fetch(`https://api.github.com/repos/${owner}/${name}/stats/participation`); if (res.ok) { const data = await res.json(); // participation.all is 52-week array of commit counts; take last 12 weeks const all: number[] = data?.all || []; setWeeklyData(all.slice(-12)); } } catch { // Silently handle if rate limited } finally { setLoading(false); } }; const maxVal = Math.max(...weeklyData, 1); if (loading) { return (
{Array.from({ length: 12 }).map((_, i) => (
))}
); } if (weeklyData.length === 0) { return (

Activity data unavailable.

); } return (
{weeklyData.map((val, i) => { const pct = Math.max((val / maxVal) * 100, 4); return (
); })}
12 weeks ago This week
); } /** Recent contributors row from GitHub API. */ function RecentContributors({ owner, name }: { owner: string; name: string }) { const [contributors, setContributors] = useState([]); useEffect(() => { fetchContributors(); }, [owner, name]); const fetchContributors = async () => { try { const res = await fetch(`https://api.github.com/repos/${owner}/${name}/contributors?per_page=8`); if (res.ok) { const data = await res.json(); setContributors(Array.isArray(data) ? data.slice(0, 8) : []); } } catch { // Silently handle } }; if (contributors.length === 0) return null; return (

Recent Contributors

{contributors.map((c) => ( {c.login} ))}
); } export default function RepoInteractionPanel({ repository, owner, name, onFollow }: RepoInteractionPanelProps) { const REACTIONS = ['\u{1F44D}', '\u{2764}\u{FE0F}', '\u{1F389}', '\u{1F680}', '\u{1F440}', '\u{1F525}']; const { user } = useAuthStore(); const isGitHubConnected = Boolean(user?.githubId); const [shareCopied, setShareCopied] = useState(false); const [exportLoading, setExportLoading] = useState<'copy' | 'download' | null>(null); const [exportMessage, setExportMessage] = useState(null); const [cachedRepoText, setCachedRepoText] = useState(null); // GitHub one-click star state const [starred, setStarred] = useState(null); const [starLoading, setStarLoading] = useState(false); const [starError, setStarError] = useState(null); // Resolve current star state once GitHub is connected. useEffect(() => { let active = true; if (!isGitHubConnected) { setStarred(null); return; } githubService .hasStarredRepo(repository.fullName) .then((value) => { if (active) setStarred(value); }) .catch(() => { // Non-fatal: leave as unknown so the button still offers to star. if (active) setStarred(false); }); return () => { active = false; }; }, [isGitHubConnected, repository.fullName]); const handleStarOnGitHub = useCallback(async () => { // Not connected → fall back to opening the repo on GitHub (previous behavior). if (!isGitHubConnected) { window.open(repository.htmlUrl, '_blank', 'noopener,noreferrer'); return; } if (starLoading) return; setStarError(null); const next = !starred; // Optimistic toggle. setStarred(next); setStarLoading(true); try { const result = next ? await githubService.starRepo(repository.fullName) : await githubService.unstarRepo(repository.fullName); if (!result.success) { throw new Error(result.message || 'GitHub action failed'); } setStarred(result.active); } catch (error) { // Revert on failure. setStarred(!next); setStarError(getErrorMessage(error)); } finally { setStarLoading(false); } }, [isGitHubConnected, starred, starLoading, repository.fullName, repository.htmlUrl]); const handleReaction = async (type: string) => { try { await repoService.addReaction(owner, name, type); } catch (error) { console.error('Failed to add reaction', error); } }; const handleShare = async () => { try { await repoService.shareRepo(owner, name); setShareCopied(true); setTimeout(() => setShareCopied(false), 2000); } catch (error) { console.error('Failed to share', error); } }; const fetchRepoText = async () => { if (cachedRepoText) { return cachedRepoText; } const text = await repoService.exportToText(owner, name); setCachedRepoText(text); return text; }; const handleCopyRepoText = async () => { setExportLoading('copy'); setExportMessage(null); try { const text = await fetchRepoText(); await navigator.clipboard.writeText(text); setExportMessage('Repo text copied.'); } catch (error) { console.error('Failed to copy repo text', error); setExportMessage('Repo text export failed.'); } finally { setExportLoading(null); } }; const handleDownloadRepoText = async () => { setExportLoading('download'); setExportMessage(null); try { const text = await fetchRepoText(); const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `${owner}-${name}-repo-to-text.txt`; link.click(); URL.revokeObjectURL(url); setExportMessage('Repo text downloaded.'); } catch (error) { console.error('Failed to download repo text', error); setExportMessage('Repo text export failed.'); } finally { setExportLoading(null); } }; return (
{/* Follow / Star / Share */}
{starError && (

{starError}

)}
Open Text View {exportMessage ? (

{exportMessage}

) : null}

{fmt(repository.stars)}

Stars

{fmt(repository.forks)}

Forks

{fmt(repository.social?.followers)}

Followers

{fmt(repository.social?.posts)}

Posts

{/* Quick reactions */}

React to this repo

{REACTIONS.map((emoji) => ( ))}
{/* Activity graph */}

Commit Activity

{/* Recent contributors */}
); }