import React, { useState, useMemo, useRef, useEffect } from 'react'; import type { MapNode, MapTheme } from '../../types/mapTypes'; import { Search, CheckCircle2, Circle, Star, ExternalLink, SlidersHorizontal, ArrowUpDown, X, ChevronDown, ChevronUp, MapPin, Route, RefreshCw, Target, FileText, } from 'lucide-react'; import { soundManager } from '../../utils/audio'; import { getCatalogProblemByNumber, getAllPatterns } from '../../services/catalogService'; import { supabase } from '../../firebaseClient'; import { activateCatalogProblem } from '../../services/reviewService'; const API_BASE = import.meta.env.VITE_API_BASE_URL || ''; interface JourneyListViewProps { nodes: MapNode[]; activeNodeIndex: number; setActiveNodeIndex: (index: number) => void; completions: Set; theme: MapTheme; onToggleCompletion: (problemNum: number) => void; onSelectProblemForReview: (problemId: string) => void; onSwitchToMap: (targetIndex?: number) => void; tracks?: { id: string; name: string }[]; activeTrack?: string; onTrackChange?: (trackId: string) => void; onToggleTheme?: () => void; } type StatusFilter = 'all' | 'solved' | 'unsolved'; type SortOption = 'sequence' | 'number_asc' | 'number_desc' | 'name'; export const JourneyListView: React.FC = ({ nodes, activeNodeIndex, setActiveNodeIndex, completions, theme, onToggleCompletion, onSelectProblemForReview, onSwitchToMap, tracks, activeTrack, onTrackChange, }) => { const isDark = theme.id !== 'parchment'; // Search & Filter State const [searchQuery, setSearchQuery] = useState(''); const [statusFilter, setStatusFilter] = useState('all'); const [selectedPattern, setSelectedPattern] = useState('all'); const [selectedDifficulty, setSelectedDifficulty] = useState('all'); const [sortOption, setSortOption] = useState('sequence'); const [expandedNodeId, setExpandedNodeId] = useState(null); const [activatingProblemId, setActivatingProblemId] = useState(null); const scrollContainerRef = useRef(null); // Extract unique DSA patterns for filter dropdown const uniquePatterns = useMemo(() => { const patternSet = new Set(); nodes.forEach((n) => { const p = getCatalogProblemByNumber(n.id); if (p?.pattern) patternSet.add(p.pattern); }); if (patternSet.size === 0) { getAllPatterns().forEach((pat) => patternSet.add(pat)); } return Array.from(patternSet); }, [nodes]); // Overall Statistics const totalCount = nodes.length; const solvedCount = useMemo(() => { return nodes.filter((n) => completions.has(n.id)).length; }, [nodes, completions]); const progressPercent = totalCount > 0 ? Math.round((solvedCount / totalCount) * 100) : 0; // Filtered & Sorted Nodes (Clean, problem-focused logic) const filteredNodes = useMemo(() => { const q = searchQuery.trim().toLowerCase(); const cleanNumQuery = q.replace(/^#/, ''); return nodes .filter((node) => { // Status filter const isSolved = completions.has(node.id); if (statusFilter === 'solved' && !isSolved) return false; if (statusFilter === 'unsolved' && isSolved) return false; const catalogProb = getCatalogProblemByNumber(node.id); // Pattern filter if (selectedPattern !== 'all' && catalogProb?.pattern !== selectedPattern) return false; // Difficulty filter if (selectedDifficulty !== 'all' && catalogProb?.difficulty !== selectedDifficulty) return false; // Search Query filter (matches problem number, sequence step, title, pattern, or difficulty) if (q) { const matchId = String(node.id).includes(cleanNumQuery); const matchStep = String(node.sequenceIndex + 1) === cleanNumQuery; const matchName = node.name.toLowerCase().includes(q); const matchPattern = catalogProb?.pattern?.toLowerCase().includes(q) ?? false; const matchDifficulty = catalogProb?.difficulty?.toLowerCase().includes(q) ?? false; if (!matchId && !matchStep && !matchName && !matchPattern && !matchDifficulty) { return false; } } return true; }) .sort((a, b) => { switch (sortOption) { case 'number_asc': return a.id - b.id; case 'number_desc': return b.id - a.id; case 'name': return a.name.localeCompare(b.name); case 'sequence': default: return a.sequenceIndex - b.sequenceIndex; } }); }, [nodes, completions, statusFilter, selectedPattern, selectedDifficulty, searchQuery, sortOption]); // Launch or Activate Problem for SRS Review const handleReviewNode = async (node: MapNode) => { if (activatingProblemId !== null) return; setActivatingProblemId(node.id); try { const { data: { session } } = await supabase.auth.getSession(); const token = session ? session.access_token : 'sandbox'; const headers = { 'Authorization': `Bearer ${token}` }; // 1. Check if problem already exists in DB const res = await fetch(`${API_BASE}/api/reviews/problems/${node.id}`, { headers }); if (res.ok) { const probs = await res.json().catch(() => []); if (Array.isArray(probs) && probs.length > 0 && probs[0]?.id) { onSelectProblemForReview(probs[0].id); return; } } // 2. If not yet in DB, check catalog and activate const catalogProb = getCatalogProblemByNumber(node.id); if (catalogProb) { const actRes = await activateCatalogProblem(catalogProb); if (actRes?.problem_id) { onSelectProblemForReview(actRes.problem_id); return; } } // Fallback: pass node ID as string onSelectProblemForReview(String(node.id)); } catch (err) { console.error('Failed to prepare problem for review:', err); onSelectProblemForReview(String(node.id)); } finally { setActivatingProblemId(null); } }; // Jump to Current Active Problem const handleJumpToCurrent = () => { const activeEl = document.getElementById(`problem-item-${activeNodeIndex}`); if (activeEl) { activeEl.scrollIntoView({ behavior: 'smooth', block: 'center' }); soundManager.playPencilScratch(); } }; // Scroll active node into view on initial mount if list is not filtered useEffect(() => { if ( activeNodeIndex >= 0 && !searchQuery && statusFilter === 'all' && selectedPattern === 'all' && selectedDifficulty === 'all' ) { const timer = setTimeout(() => { const activeEl = document.getElementById(`problem-item-${activeNodeIndex}`); if (activeEl) { activeEl.scrollIntoView({ behavior: 'auto', block: 'center' }); } }, 80); return () => clearTimeout(timer); } }, [activeNodeIndex, searchQuery, statusFilter, selectedPattern, selectedDifficulty]); return (
{/* Decorative Border Vignette */}
{/* 1. Header Toolbar: Search, Track Selector, Filters */}
{/* Row 1: Search Bar, Track Selector & Jump to Current Problem */}
{/* Search Input */}
setSearchQuery(e.target.value)} placeholder="Search problem title, #number, or pattern (e.g. 1, Two Sum, Two Pointers)..." className={`w-full pl-9 pr-8 py-2 rounded-xl text-xs md:text-sm font-garamond font-semibold border-2 shadow-inner focus:outline-none transition-all ${ isDark ? 'bg-[#231e18] border-[#5a4836] text-[#f4ebd9] placeholder-stone-500 focus:border-amber-500/70' : 'bg-[#fcf7ee] border-[#cfbc9c] text-[#2c2014] placeholder-stone-500 focus:border-amber-700/60' }`} /> {searchQuery && ( )}
{/* Right Controls: Track switcher & Current Problem jump */}
{tracks && tracks.length > 0 && onTrackChange && (
Track:
)} {/* Jump to Current Problem Button */}
{/* Row 2: Status Tabs, Pattern Filter, Difficulty Filter, Sort & Progress Count */}
{/* Status Filter Tabs */}
{(['all', 'solved', 'unsolved'] as StatusFilter[]).map((tab) => { const isActive = statusFilter === tab; const count = tab === 'all' ? totalCount : tab === 'solved' ? solvedCount : totalCount - solvedCount; return ( ); })}
{/* Middle: Pattern, Difficulty & Sort Dropdowns */}
{/* Pattern Filter */}
Pattern:
{/* Difficulty Filter */}
Diff:
{/* Sort Option */}
Sort:
{/* Results Count & Progress Stat */}
Showing {filteredNodes.length} of {totalCount}
{progressPercent}%
{/* 2. Scrollable Problem List */}
{filteredNodes.length === 0 ? ( /* Empty State */

No Problems Found

No problems matched "{searchQuery || 'the current filter settings'}". Try adjusting your search keywords or filter criteria.

{(searchQuery || statusFilter !== 'all' || selectedPattern !== 'all' || selectedDifficulty !== 'all') && ( )}
) : ( filteredNodes.map((node) => { const isSolved = completions.has(node.id); const isActive = node.sequenceIndex === activeNodeIndex; const isExpanded = expandedNodeId === node.id; const catalogProb = getCatalogProblemByNumber(node.id); const difficulty = catalogProb?.difficulty; const pattern = catalogProb?.pattern; return (
{/* Active Problem Ribbon */} {isActive && (
Current Problem
)}
{/* Left: Completion Checkbox + Sequence Number + Problem Info */}
{/* Checkbox Button */} {/* Sequence Number Pill */}
Seq #{node.sequenceIndex + 1}
{/* Problem Title & Meta tags */}
{/* LeetCode ID tag */} {node.id > 0 ? `LC #${node.id}` : 'Custom'} {/* Difficulty Pill */} {difficulty && ( {difficulty} )} {/* Pattern Badge */} {pattern && ( {pattern} )} {/* Problem Title */}

{ setActiveNodeIndex(node.sequenceIndex); soundManager.playNodeLightUp(node.sequenceIndex, totalCount); }} className={`font-garamond font-bold text-sm sm:text-base leading-tight truncate cursor-pointer hover:underline ${ isActive ? 'text-amber-700 dark:text-amber-300 font-bold' : isDark ? 'text-stone-200 hover:text-amber-300' : 'text-stone-900 hover:text-amber-800' }`} > {node.name}

{/* Solved check pill */} {isSolved && ( ✓ Solved )}
{/* Problem Complexities (Clean, replacing map region and elevation) */} {(catalogProb?.time_complexity || catalogProb?.space_complexity) && (
{catalogProb.time_complexity && ( Time:{' '} {catalogProb.time_complexity} )} {catalogProb.space_complexity && ( Space:{' '} {catalogProb.space_complexity} )}
)}
{/* Right Action Buttons */}
{/* View on Map Button */} {/* Spaced-Repetition Review Button */} {/* External LeetCode Link */} 0 ? `https://leetcode.com/problemset/?search=${node.id}` : `https://www.google.com/search?q=${encodeURIComponent(node.name)}`) } target="_blank" rel="noreferrer" title="Open Problem on LeetCode" className={`p-1.5 rounded-lg border transition-all cursor-pointer ${ isDark ? 'border-stone-700 text-stone-400 hover:text-stone-200 hover:bg-white/5' : 'border-stone-300 text-stone-600 hover:text-stone-900 hover:bg-black/5' }`} > {/* Expand Details Accordion */}
{/* Expanded Accordion: Problem Description, Examples, Constraints & Complexity */} {isExpanded && (
{/* Canonical Problem Description */} {catalogProb?.description ? (
Canonical Problem Description
{catalogProb.description}
) : (

Review this problem in CodeStudio to access the full starter code, test suites, and review queue.

)} {/* Examples */} {catalogProb?.examples && catalogProb.examples.length > 0 && (
Examples
{catalogProb.examples.map((ex, exIdx) => (
Input: {ex.input}
Output: {ex.output}
{ex.explanation && (
{ex.explanation}
)}
))}
)} {/* Problem Specifications Summary Bar */}
{pattern && ( Pattern: {pattern} )} {difficulty && ( Difficulty: {difficulty} )} {catalogProb?.time_complexity && ( Time: {catalogProb.time_complexity} )} {catalogProb?.space_complexity && ( Space: {catalogProb.space_complexity} )} {catalogProb?.constraints && catalogProb.constraints.length > 0 && ( Constraints: {catalogProb.constraints.join(' • ')} )}
)}
); }) )}
); };