import { useEffect, useMemo, useRef, useState } from 'react'
import './App.css'
import { Icon, ProgressRing } from './components'
import { createId, dashboardStats, formatDate, goalForTask, goalProgress, sortedUpcoming } from './domain'
import { createSampleData } from './sampleData'
import { storageAdapter } from './storage'
import type { AppStateV1, AppView, LearningGoal, LearningTask, Priority, TaskStatus } from './types'

type ModalState =
  | { type: 'goal'; item?: LearningGoal }
  | { type: 'task'; item?: LearningTask }
  | { type: 'delete-goal'; item: LearningGoal }
  | { type: 'delete-task'; item: LearningTask }
  | { type: 'data' }
  | null

const navItems: { id: AppView; label: string; icon: string }[] = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'goals', label: 'Learning goals', icon: 'goal' },
  { id: 'tasks', label: 'All tasks', icon: 'task' },
]

const emptyGoal = (): LearningGoal => ({
  id: createId(), title: '', description: '', category: '', targetDate: '', color: '#6257d9', createdAt: new Date().toISOString(),
})
const emptyTask = (goalId = ''): LearningTask => ({
  id: createId(), goalId, title: '', notes: '', dueDate: '', priority: 'medium', status: 'todo', estimatedMinutes: 30, createdAt: new Date().toISOString(),
})

function App() {
  const initial = useMemo(() => storageAdapter.load(), [])
  const [state, setState] = useState<AppStateV1>(initial.state)
  const [view, setView] = useState<AppView>('dashboard')
  const [modal, setModal] = useState<ModalState>(null)
  const [query, setQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<TaskStatus | 'all'>('all')
  const [sort, setSort] = useState<'due' | 'priority' | 'title'>('due')
  const [notice, setNotice] = useState(initial.warning ?? '')
  const [saveError, setSaveError] = useState('')

  useEffect(() => {
    try {
      storageAdapter.save(state)
      setSaveError('')
    } catch {
      setSaveError('Changes are visible, but this browser could not save them. Export a backup before closing.')
    }
  }, [state])

  const stats = dashboardStats(state)
  const upcoming = sortedUpcoming(state.tasks).slice(0, 5)
  const filteredGoals = state.goals.filter((goal) => `${goal.title} ${goal.description} ${goal.category}`.toLowerCase().includes(query.toLowerCase()))
  const priorityOrder: Record<Priority, number> = { high: 0, medium: 1, low: 2 }
  const filteredTasks = [...state.tasks]
    .filter((task) => statusFilter === 'all' || task.status === statusFilter)
    .filter((task) => `${task.title} ${task.notes} ${goalForTask(task, state.goals)?.title ?? ''}`.toLowerCase().includes(query.toLowerCase()))
    .sort((a, b) => sort === 'priority' ? priorityOrder[a.priority] - priorityOrder[b.priority] : sort === 'title' ? a.title.localeCompare(b.title) : (a.dueDate || '9999').localeCompare(b.dueDate || '9999'))

  function saveGoal(goal: LearningGoal) {
    setState((current) => ({ ...current, goals: current.goals.some((item) => item.id === goal.id) ? current.goals.map((item) => item.id === goal.id ? goal : item) : [...current.goals, goal] }))
    setModal(null)
    setNotice(`Goal “${goal.title}” saved.`)
  }

  function saveTask(task: LearningTask) {
    setState((current) => ({ ...current, tasks: current.tasks.some((item) => item.id === task.id) ? current.tasks.map((item) => item.id === task.id ? task : item) : [...current.tasks, task] }))
    setModal(null)
    setNotice(`Task “${task.title}” saved.`)
  }

  function updateTaskStatus(id: string, status: TaskStatus) {
    setState((current) => ({ ...current, tasks: current.tasks.map((task) => task.id === id ? { ...task, status } : task) }))
  }

  function deleteItem() {
    if (modal?.type === 'delete-goal') {
      const id = modal.item.id
      setState((current) => ({ ...current, goals: current.goals.filter((goal) => goal.id !== id), tasks: current.tasks.filter((task) => task.goalId !== id) }))
      setNotice(`Goal “${modal.item.title}” and its tasks were deleted.`)
    }
    if (modal?.type === 'delete-task') {
      setState((current) => ({ ...current, tasks: current.tasks.filter((task) => task.id !== modal.item.id) }))
      setNotice(`Task “${modal.item.title}” was deleted.`)
    }
    setModal(null)
  }

  function selectView(next: AppView) {
    setView(next)
    setQuery('')
  }

  return (
    <div className="app-shell">
      <aside className="sidebar" aria-label="Primary navigation">
        <div className="brand">
          <span className="brand-mark"><Icon name="spark" size={22} /></span>
          <span><strong>Learning</strong><small>Planner</small></span>
        </div>
        <nav>
          <p className="nav-label">Workspace</p>
          {navItems.map((item) => (
            <button className={view === item.id ? 'nav-item active' : 'nav-item'} key={item.id} onClick={() => selectView(item.id)} aria-current={view === item.id ? 'page' : undefined}>
              <Icon name={item.icon} /> <span>{item.label}</span>
              {item.id === 'tasks' && <span className="nav-count">{state.tasks.filter((task) => task.status !== 'done').length}</span>}
            </button>
          ))}
        </nav>
        <div className="sidebar-card">
          <span className="mini-icon"><Icon name="spark" size={18} /></span>
          <strong>Keep the momentum</strong>
          <p>{stats.completed} tasks completed. Small, consistent steps add up.</p>
        </div>
        <button className="data-button" onClick={() => setModal({ type: 'data' })}><Icon name="download" /> Data &amp; backup</button>
        <p className="version">Local-first · Version 1.0</p>
      </aside>

      <main className="main-content">
        <header className="topbar">
          <div>
            <p className="eyebrow">My learning workspace</p>
            <h1>{view === 'dashboard' ? 'Good progress starts with a clear plan.' : view === 'goals' ? 'Learning goals' : 'Task library'}</h1>
            <p className="subtitle">{view === 'dashboard' ? 'See what matters today and keep every goal moving.' : view === 'goals' ? 'Define meaningful outcomes and watch the work add up.' : 'Search, prioritise and complete the next useful step.'}</p>
          </div>
          <button className="primary-button top-action" onClick={() => setModal(view === 'goals' ? { type: 'goal' } : { type: 'task' })} disabled={view !== 'goals' && !state.goals.length}>
            <Icon name="plus" /> {view === 'goals' ? 'New goal' : 'Add task'}
          </button>
        </header>

        {(notice || saveError) && <div className={saveError ? 'notice error' : 'notice'} role="status"><span>{saveError || notice}</span><button aria-label="Dismiss message" onClick={() => { setNotice(''); setSaveError('') }}><Icon name="close" size={17} /></button></div>}

        {view === 'dashboard' && <Dashboard state={state} stats={stats} upcoming={upcoming} onView={selectView} onEditTask={(task) => setModal({ type: 'task', item: task })} onStatus={updateTaskStatus} />}

        {view === 'goals' && (
          <section aria-labelledby="goals-heading">
            <div className="toolbar">
              <div className="search-field"><Icon name="search" /><input aria-label="Search goals" placeholder="Search goals or categories…" value={query} onChange={(event) => setQuery(event.target.value)} /></div>
              <span className="result-count">{filteredGoals.length} {filteredGoals.length === 1 ? 'goal' : 'goals'}</span>
            </div>
            <h2 id="goals-heading" className="sr-only">Your learning goals</h2>
            {filteredGoals.length ? <div className="goal-grid">{filteredGoals.map((goal) => <GoalCard key={goal.id} goal={goal} tasks={state.tasks} onOpen={() => { setView('tasks'); setQuery(goal.title) }} onEdit={() => setModal({ type: 'goal', item: goal })} onDelete={() => setModal({ type: 'delete-goal', item: goal })} />)}</div> : <EmptyState icon="goal" title="No goals found" text={query ? 'Try a different search phrase.' : 'Create a learning goal, then break it into focused tasks.'} action={!query ? () => setModal({ type: 'goal' }) : undefined} />}
          </section>
        )}

        {view === 'tasks' && (
          <section aria-labelledby="tasks-heading">
            <div className="toolbar task-toolbar">
              <div className="search-field"><Icon name="search" /><input aria-label="Search tasks" placeholder="Search tasks or goals…" value={query} onChange={(event) => setQuery(event.target.value)} /></div>
              <label>Show <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as TaskStatus | 'all')}><option value="all">All statuses</option><option value="todo">To do</option><option value="in-progress">In progress</option><option value="done">Done</option></select></label>
              <label>Sort <select value={sort} onChange={(event) => setSort(event.target.value as typeof sort)}><option value="due">Due date</option><option value="priority">Priority</option><option value="title">Title</option></select></label>
            </div>
            <div className="section-heading"><div><h2 id="tasks-heading">All tasks</h2><p>{filteredTasks.length} matching tasks across {state.goals.length} goals</p></div></div>
            {filteredTasks.length ? <div className="task-list">{filteredTasks.map((task) => <TaskRow key={task.id} task={task} goal={goalForTask(task, state.goals)} onStatus={updateTaskStatus} onEdit={() => setModal({ type: 'task', item: task })} onDelete={() => setModal({ type: 'delete-task', item: task })} />)}</div> : <EmptyState icon="task" title="No matching tasks" text="Change the filters or add a new task to one of your goals." action={state.goals.length ? () => setModal({ type: 'task' }) : undefined} />}
          </section>
        )}
      </main>

      {modal?.type === 'goal' && <GoalModal initial={modal.item ?? emptyGoal()} onClose={() => setModal(null)} onSave={saveGoal} />}
      {modal?.type === 'task' && <TaskModal initial={modal.item ?? emptyTask(state.goals[0]?.id)} goals={state.goals} onClose={() => setModal(null)} onSave={saveTask} />}
      {(modal?.type === 'delete-goal' || modal?.type === 'delete-task') && <ConfirmModal title={`Delete ${modal.type === 'delete-goal' ? 'goal' : 'task'}?`} text={modal.type === 'delete-goal' ? `“${modal.item.title}” and all of its tasks will be permanently removed from this browser.` : `“${modal.item.title}” will be permanently removed from this browser.`} onClose={() => setModal(null)} onConfirm={deleteItem} />}
      {modal?.type === 'data' && <DataModal state={state} onClose={() => setModal(null)} onRestore={(next, message) => { setState(next); setNotice(message); setModal(null) }} />}
    </div>
  )
}

function Dashboard({ state, stats, upcoming, onView, onEditTask, onStatus }: { state: AppStateV1; stats: ReturnType<typeof dashboardStats>; upcoming: LearningTask[]; onView: (view: AppView) => void; onEditTask: (task: LearningTask) => void; onStatus: (id: string, status: TaskStatus) => void }) {
  const cards = [
    { label: 'Active goals', value: stats.goals, detail: 'Across your learning plan', icon: 'goal', tone: 'purple' },
    { label: 'In progress', value: stats.active, detail: 'Tasks moving forward', icon: 'clock', tone: 'orange' },
    { label: 'Completed', value: stats.completed, detail: 'Tasks finished so far', icon: 'check', tone: 'green' },
    { label: 'Due this week', value: stats.dueSoon, detail: 'Time-sensitive tasks', icon: 'calendar', tone: 'blue' },
  ]
  return (
    <>
      <section className="stat-grid" aria-label="Learning summary">{cards.map((card) => <article className={`stat-card ${card.tone}`} key={card.label}><span className="stat-icon"><Icon name={card.icon} /></span><div><p>{card.label}</p><strong>{card.value}</strong><small>{card.detail}</small></div></article>)}</section>
      <div className="dashboard-grid">
        <section className="panel" aria-labelledby="goals-overview">
          <div className="panel-heading"><div><p className="eyebrow">At a glance</p><h2 id="goals-overview">Goal progress</h2></div><button className="text-button" onClick={() => onView('goals')}>View all <Icon name="chevron" size={16} /></button></div>
          <div className="goal-overview">{state.goals.slice(0, 4).map((goal) => { const progress = goalProgress(goal.id, state.tasks); const goalTasks = state.tasks.filter((task) => task.goalId === goal.id); return <button className="overview-row" key={goal.id} onClick={() => onView('goals')}><span className="goal-color" style={{ background: goal.color }}></span><span className="overview-copy"><strong>{goal.title}</strong><small>{goal.category} · {goalTasks.filter((task) => task.status === 'done').length}/{goalTasks.length} tasks</small><span className="bar"><span style={{ width: `${progress}%`, background: goal.color }}></span></span></span><span className="percent">{progress}%</span></button> })}</div>
        </section>
        <section className="panel upcoming-panel" aria-labelledby="upcoming-heading">
          <div className="panel-heading"><div><p className="eyebrow">Next up</p><h2 id="upcoming-heading">Upcoming tasks</h2></div><button className="text-button" onClick={() => onView('tasks')}>All tasks <Icon name="chevron" size={16} /></button></div>
          <div className="upcoming-list">{upcoming.map((task) => <div className="upcoming-item" key={task.id}><button className={`check-button ${task.status === 'done' ? 'checked' : ''}`} aria-label={`Mark ${task.title} complete`} onClick={() => onStatus(task.id, task.status === 'done' ? 'todo' : 'done')}><Icon name="check" size={14} /></button><button className="upcoming-copy" onClick={() => onEditTask(task)}><strong>{task.title}</strong><span><i className={`priority-dot ${task.priority}`}></i>{goalForTask(task, state.goals)?.title}</span></button><time dateTime={task.dueDate}>{formatDate(task.dueDate).replace(/ 20\d\d$/, '')}</time></div>)}</div>
        </section>
      </div>
      <section className="focus-banner"><div className="focus-icon"><Icon name="spark" size={24} /></div><div><p className="eyebrow">Weekly focus</p><h2>Protect time for the tasks already in progress.</h2><p>You have planned {Math.round(stats.totalMinutes / 60)} hours of focused learning. Complete one high-priority task before adding more.</p></div><button className="secondary-button" onClick={() => onView('tasks')}>Review priorities</button></section>
    </>
  )
}

function GoalCard({ goal, tasks, onOpen, onEdit, onDelete }: { goal: LearningGoal; tasks: LearningTask[]; onOpen: () => void; onEdit: () => void; onDelete: () => void }) {
  const progress = goalProgress(goal.id, tasks)
  const matching = tasks.filter((task) => task.goalId === goal.id)
  return <article className="goal-card"><div className="goal-card-top"><span className="category" style={{ color: goal.color, background: `${goal.color}15` }}>{goal.category}</span><div className="card-actions"><button aria-label={`Edit ${goal.title}`} onClick={onEdit}><Icon name="edit" size={17} /></button><button aria-label={`Delete ${goal.title}`} onClick={onDelete}><Icon name="trash" size={17} /></button></div></div><h3>{goal.title}</h3><p>{goal.description}</p><div className="goal-card-progress"><ProgressRing value={progress} color={goal.color} /><div><strong>{matching.filter((task) => task.status === 'done').length} of {matching.length}</strong><span>tasks complete</span></div></div><div className="goal-card-footer"><span><Icon name="calendar" size={16} /> Target {formatDate(goal.targetDate)}</span><button onClick={onOpen}>View tasks <Icon name="chevron" size={15} /></button></div></article>
}

function TaskRow({ task, goal, onStatus, onEdit, onDelete }: { task: LearningTask; goal?: LearningGoal; onStatus: (id: string, status: TaskStatus) => void; onEdit: () => void; onDelete: () => void }) {
  return <article className={`task-row ${task.status === 'done' ? 'complete' : ''}`}><button className={`check-button ${task.status === 'done' ? 'checked' : ''}`} aria-label={`${task.status === 'done' ? 'Reopen' : 'Complete'} ${task.title}`} onClick={() => onStatus(task.id, task.status === 'done' ? 'todo' : 'done')}><Icon name="check" size={15} /></button><div className="task-main"><div><span className={`priority-pill ${task.priority}`}>{task.priority}</span><span className={`status-pill ${task.status}`}>{task.status.replace('-', ' ')}</span></div><h3>{task.title}</h3><p>{task.notes || 'No notes added.'}</p></div><div className="task-meta"><strong>{goal?.title ?? 'Unknown goal'}</strong><span><Icon name="calendar" size={15} /> {formatDate(task.dueDate)}</span><span><Icon name="clock" size={15} /> {task.estimatedMinutes} min</span></div><div className="card-actions"><button aria-label={`Edit ${task.title}`} onClick={onEdit}><Icon name="edit" size={17} /></button><button aria-label={`Delete ${task.title}`} onClick={onDelete}><Icon name="trash" size={17} /></button></div></article>
}

function EmptyState({ icon, title, text, action }: { icon: string; title: string; text: string; action?: () => void }) {
  return <div className="empty-state"><span><Icon name={icon} size={28} /></span><h2>{title}</h2><p>{text}</p>{action && <button className="primary-button" onClick={action}><Icon name="plus" /> Create one</button>}</div>
}

function ModalFrame({ title, subtitle, onClose, children }: { title: string; subtitle: string; onClose: () => void; children: React.ReactNode }) {
  return <div className="modal-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}><section className="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title"><div className="modal-heading"><div><p className="eyebrow">Learning Planner</p><h2 id="modal-title">{title}</h2><p>{subtitle}</p></div><button className="close-button" aria-label="Close dialog" onClick={onClose}><Icon name="close" /></button></div>{children}</section></div>
}

function GoalModal({ initial, onClose, onSave }: { initial: LearningGoal; onClose: () => void; onSave: (goal: LearningGoal) => void }) {
  const [goal, setGoal] = useState(initial)
  const [errors, setErrors] = useState<Record<string, string>>({})
  function submit(event: React.FormEvent) { event.preventDefault(); const next: Record<string, string> = {}; if (!goal.title.trim()) next.title = 'Enter a goal title.'; if (!goal.category.trim()) next.category = 'Enter a category.'; if (!goal.targetDate) next.targetDate = 'Choose a target date.'; setErrors(next); if (!Object.keys(next).length) onSave({ ...goal, title: goal.title.trim(), description: goal.description.trim(), category: goal.category.trim() }) }
  return <ModalFrame title={initial.title ? 'Edit learning goal' : 'Create a learning goal'} subtitle="Describe the outcome, then connect focused tasks." onClose={onClose}><form onSubmit={submit} noValidate><label className="field full">Goal title<input autoFocus value={goal.title} onChange={(e) => setGoal({ ...goal, title: e.target.value })} aria-invalid={!!errors.title} aria-describedby={errors.title ? 'goal-title-error' : undefined} placeholder="e.g. Build confident TypeScript skills" />{errors.title && <span className="field-error" id="goal-title-error">{errors.title}</span>}</label><label className="field full">Description<textarea rows={3} value={goal.description} onChange={(e) => setGoal({ ...goal, description: e.target.value })} placeholder="What will success look like?" /></label><div className="form-grid"><label className="field">Category<input value={goal.category} onChange={(e) => setGoal({ ...goal, category: e.target.value })} aria-invalid={!!errors.category} />{errors.category && <span className="field-error">{errors.category}</span>}</label><label className="field">Target date<input type="date" value={goal.targetDate} onChange={(e) => setGoal({ ...goal, targetDate: e.target.value })} aria-invalid={!!errors.targetDate} />{errors.targetDate && <span className="field-error">{errors.targetDate}</span>}</label></div><fieldset className="color-field"><legend>Accent colour</legend>{['#6257d9', '#0b8f74', '#db6b35', '#3973c7', '#b23a75'].map((color) => <label key={color} style={{ background: color }}><input type="radio" name="color" value={color} checked={goal.color === color} onChange={() => setGoal({ ...goal, color })} /><span className="sr-only">{color}</span></label>)}</fieldset><div className="modal-actions"><button type="button" className="secondary-button" onClick={onClose}>Cancel</button><button className="primary-button" type="submit">Save goal</button></div></form></ModalFrame>
}

function TaskModal({ initial, goals, onClose, onSave }: { initial: LearningTask; goals: LearningGoal[]; onClose: () => void; onSave: (task: LearningTask) => void }) {
  const [task, setTask] = useState(initial)
  const [errors, setErrors] = useState<Record<string, string>>({})
  function submit(event: React.FormEvent) { event.preventDefault(); const next: Record<string, string> = {}; if (!task.title.trim()) next.title = 'Enter a task title.'; if (!task.goalId) next.goalId = 'Choose a goal.'; if (!task.dueDate) next.dueDate = 'Choose a due date.'; if (task.estimatedMinutes < 5) next.estimatedMinutes = 'Use at least 5 minutes.'; setErrors(next); if (!Object.keys(next).length) onSave({ ...task, title: task.title.trim(), notes: task.notes.trim() }) }
  return <ModalFrame title={initial.title ? 'Edit task' : 'Add a focused task'} subtitle="Make the next step specific, realistic and easy to start." onClose={onClose}><form onSubmit={submit} noValidate><label className="field full">Task title<input autoFocus value={task.title} onChange={(e) => setTask({ ...task, title: e.target.value })} aria-invalid={!!errors.title} placeholder="e.g. Complete keyboard walkthrough" />{errors.title && <span className="field-error">{errors.title}</span>}</label><label className="field full">Goal<select value={task.goalId} onChange={(e) => setTask({ ...task, goalId: e.target.value })} aria-invalid={!!errors.goalId}><option value="">Choose a goal</option>{goals.map((goal) => <option key={goal.id} value={goal.id}>{goal.title}</option>)}</select>{errors.goalId && <span className="field-error">{errors.goalId}</span>}</label><label className="field full">Notes<textarea rows={3} value={task.notes} onChange={(e) => setTask({ ...task, notes: e.target.value })} placeholder="Useful context, acceptance criteria or resource…" /></label><div className="form-grid three"><label className="field">Due date<input type="date" value={task.dueDate} onChange={(e) => setTask({ ...task, dueDate: e.target.value })} aria-invalid={!!errors.dueDate} />{errors.dueDate && <span className="field-error">{errors.dueDate}</span>}</label><label className="field">Priority<select value={task.priority} onChange={(e) => setTask({ ...task, priority: e.target.value as Priority })}><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select></label><label className="field">Status<select value={task.status} onChange={(e) => setTask({ ...task, status: e.target.value as TaskStatus })}><option value="todo">To do</option><option value="in-progress">In progress</option><option value="done">Done</option></select></label></div><label className="field full">Estimated minutes<input type="number" min="5" step="5" value={task.estimatedMinutes} onChange={(e) => setTask({ ...task, estimatedMinutes: Number(e.target.value) })} aria-invalid={!!errors.estimatedMinutes} />{errors.estimatedMinutes && <span className="field-error">{errors.estimatedMinutes}</span>}</label><div className="modal-actions"><button type="button" className="secondary-button" onClick={onClose}>Cancel</button><button className="primary-button" type="submit">Save task</button></div></form></ModalFrame>
}

function ConfirmModal({ title, text, onClose, onConfirm }: { title: string; text: string; onClose: () => void; onConfirm: () => void }) {
  return <ModalFrame title={title} subtitle="This action cannot be undone." onClose={onClose}><p className="confirm-copy">{text}</p><div className="modal-actions"><button className="secondary-button" onClick={onClose}>Keep it</button><button className="danger-button" onClick={onConfirm}>Delete permanently</button></div></ModalFrame>
}

function DataModal({ state, onClose, onRestore }: { state: AppStateV1; onClose: () => void; onRestore: (state: AppStateV1, message: string) => void }) {
  const [error, setError] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)
  function download() { const blob = new Blob([storageAdapter.export(state)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `learning-planner-backup-${new Date().toISOString().slice(0, 10)}.json`; link.click(); URL.revokeObjectURL(url) }
  async function upload(file?: File) { if (!file) return; try { onRestore(storageAdapter.import(await file.text()), 'Backup imported successfully.') } catch (reason) { setError(reason instanceof Error ? reason.message : 'The selected backup is invalid.') } }
  return <ModalFrame title="Data & backup" subtitle="Your plan stays in this browser unless you export it." onClose={onClose}><div className="data-options"><button onClick={download}><span className="option-icon"><Icon name="download" /></span><span><strong>Export JSON backup</strong><small>Download a portable, readable copy of every goal and task.</small></span><Icon name="chevron" /></button><button onClick={() => inputRef.current?.click()}><span className="option-icon"><Icon name="upload" /></span><span><strong>Import JSON backup</strong><small>Validate and replace this browser’s current plan.</small></span><Icon name="chevron" /></button><input ref={inputRef} className="sr-only" type="file" accept="application/json,.json" onChange={(e) => upload(e.target.files?.[0])} /><button onClick={() => onRestore(createSampleData(), 'Sample learning plan restored.')}><span className="option-icon"><Icon name="reset" /></span><span><strong>Restore sample data</strong><small>Reset to a realistic, non-sensitive evidence dataset.</small></span><Icon name="chevron" /></button></div>{error && <p className="import-error" role="alert">{error}</p>}<div className="modal-actions"><button className="secondary-button" onClick={onClose}>Close</button></div></ModalFrame>
}

export default App
