import {localeTag} from '../i18n/locale';
import {lazy,Suspense,useState,useRef} from 'react';
import { History as HistoryIcon, ArrowUpRight, Trash2, ArrowLeft } from 'lucide-react';
import { useApp } from '../app/store';
import { MODES } from '../training/modes/modes';
import {trainingTitle,scenarioTitleIsLiteral} from './trainingPresentation';
import { clearHistory } from '../storage/history';
import { ResultDetails, Trend } from './Results';
import type { SessionData, Mode } from '../engine/types';
function exportLocalHistory(history:SessionData[]){const rows=history.map(({replay,...session})=>({...session,replayAvailable:!!replay})),url=URL.createObjectURL(new Blob([JSON.stringify({schema:1,exportedAt:new Date().toISOString(),sessions:rows},null,2)],{type:'application/json'})),link=document.createElement('a');link.href=url;link.download='valoprac-training-history.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
const ReplayLibrary=lazy(()=>import('./ReplayViewer').then(m=>({default:m.ReplayLibrary})));
export function History(){const history=useApp(s=>s.history),refresh=useApp(s=>s.refreshHistory);const [replays,setReplays]=useState(false),[selected,setSelected]=useState<SessionData|null>(null),[deleting,setDeleting]=useState(false),[deleteError,setDeleteError]=useState(''),[mode,setMode]=useState<Mode>('precision'),[runtime,setRuntime]=useState<'all'|'browser'|'unreal'>('all');const deleteDialog=useRef<HTMLDialogElement>(null);const filtered=history.filter(s=>runtime==='all'||(s.runtime??'browser')===runtime);
  const totals=filtered.reduce((a,s)=>({seconds:a.seconds+s.duration,shots:a.shots+s.summary.shots,heads:a.heads+s.summary.heads,eliminations:a.eliminations+s.summary.eliminations}),{seconds:0,shots:0,heads:0,eliminations:0});
  if(selected)return <div className="history-view"><button className="back-button" onClick={()=>setSelected(null)}><ArrowLeft size={16}/> 기록 목록</button><div className="view-title"><h1><span data-locale={scenarioTitleIsLiteral(selected.sessionOptions)?'literal':undefined}>{trainingTitle(selected.mode,selected.settings,selected.sessionOptions)}</span></h1><p>{new Date(selected.createdAt).toLocaleString(localeTag())}</p></div><ResultDetails session={selected}/>{!selected.shots.length&&selected.summary.shots>0&&<p className="field-note">오래된 훈련은 요약만 보관합니다. 상세 탄착 기록은 최근 10회에 제공됩니다.</p>}</div>;
  return <div className="history-view"><div className="view-title"><p className="eyebrow">내 훈련의 측정 기록</p><h1>훈련 기록</h1><p>최근 40회의 결과와 최근 10회의 상세 사격 데이터를 이 브라우저에 보관합니다.</p></div><section className="history-tools" aria-label="기록과 리플레이 관리"><div><h2>기록 관리</h2><p>기록을 내보내거나 저장한 훈련을 다시 확인합니다.</p></div><div className="history-tool-actions"><button className="secondary-button" onClick={()=>exportLocalHistory(history)}>훈련 기록 JSON 내보내기</button><button className="secondary-button" aria-expanded={replays} onClick={()=>setReplays(!replays)}>{replays?'보관함 접기':'리플레이 보관함 열기'}</button></div></section>{replays&&<section className="data-card"><Suspense fallback={<p role="status">리플레이 보관함을 준비합니다…</p>}><ReplayLibrary sessions={history}/></Suspense></section>}<dl className="history-overview" aria-label="보관 중인 훈련 요약"><div><dt>보관된 세션</dt><dd>{filtered.length}<small>회</small></dd></div><div><dt>총 훈련 시간</dt><dd>{Math.floor(totals.seconds/60)}<small>분</small></dd></div><div><dt>발사 / 제거</dt><dd>{totals.shots.toLocaleString()}<small>/ {totals.eliminations.toLocaleString()}</small></dd></div><div><dt>전체 헤드샷 명중률</dt><dd>{totals.shots?(totals.heads/totals.shots*100).toFixed(1):'—'}<small>{totals.shots?'%':'측정 대기'}</small></dd></div></dl><section className="data-card history-trend"><div className="history-chart-heading"><h3>헤드샷 명중률 추이</h3><div><label>훈련<select aria-label="기록 모드" value={mode} onChange={e=>setMode(e.target.value as Mode)}>{Object.entries(MODES).map(([key,v])=><option key={key} value={key}>{v.title}</option>)}</select></label><label>실행 환경<select aria-label="기록 실행 환경" value={runtime} onChange={e=>setRuntime(e.target.value as typeof runtime)}><option value="all">전체</option><option value="browser">브라우저</option><option value="unreal">언리얼 스트림</option></select></label></div></div><Trend sessions={filtered.filter(s=>s.mode===mode)}/></section>{filtered.length?<section className="history-list" aria-label="세션 목록"><div className="history-list-heading"><span>훈련 / 일시</span><span>헤드샷</span><span>제거</span><span/></div>{filtered.map(s=><button key={s.id} className="history-row" onClick={()=>setSelected(s)}><span className="history-row-icon"><HistoryIcon size={16}/></span><div><strong><span data-locale={scenarioTitleIsLiteral(s.sessionOptions)?'literal':undefined}>{trainingTitle(s.mode,s.settings,s.sessionOptions)}</span><span className="session-runtime">{s.runtime==='unreal'?'언리얼 스트림':'브라우저'}</span></strong><small>{new Date(s.createdAt).toLocaleString(localeTag(),{month:'numeric',day:'numeric',hour:'2-digit',minute:'2-digit'})} · {Math.round(s.duration)}초</small></div><span><strong>{s.summary.headshotAccuracy.toFixed(1)}%</strong><small>헤드샷 명중률</small></span><span><strong>{s.summary.eliminations}개</strong><small>제거</small></span><ArrowUpRight size={16}/></button>)}</section>:<div className="history-empty"><HistoryIcon size={28}/><h3>{history.length?'선택한 실행 환경의 기록이 없습니다.':'첫 번째 기록을 기다립니다.'}</h3><p>훈련을 완료하면 결과가 자동으로 저장됩니다.</p></div>}
  {history.length>0&&<div className="settings-reset"><button onClick={()=>{setDeleteError('');deleteDialog.current?.showModal();}}><Trash2 size={14}/> 기록 지우기</button></div>}
  <dialog ref={deleteDialog} className="utility-confirm-dialog" aria-labelledby="delete-history-title" aria-describedby="delete-history-description">
   <p className="eyebrow">로컬 기록 관리</p><h2 id="delete-history-title">훈련 기록을 모두 지울까요?</h2><p id="delete-history-description">이 브라우저의 훈련 결과와 연결된 리플레이를 삭제합니다. 감도와 조작 설정은 유지됩니다. 필요한 기록은 먼저 내보내세요.</p>
   {deleteError&&<p className="utility-delete-error" role="alert">{deleteError}</p>}
   <form method="dialog" className="utility-dialog-actions"><button className="secondary-button" value="cancel" autoFocus>취소</button><button type="button" className="utility-danger-button" disabled={deleting} onClick={async()=>{if(deleting)return;setDeleting(true);setDeleteError('');try{await clearHistory();await refresh();deleteDialog.current?.close();}catch{setDeleteError('기록을 삭제하지 못했습니다. 다시 시도하세요.');}finally{setDeleting(false);}}}>{deleting?'삭제 중…':'모두 삭제'}</button></form>
  </dialog></div>;
}
