import React, { useEffect, useState, type FormEvent } from 'react';
import { createRoot } from 'react-dom/client';
import { onAuthStateChanged, signInWithEmailAndPassword, createUserWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, sendPasswordResetEmail, signOut, type User } from 'firebase/auth';
import { auth } from './firebase';
import { asset, countries, loadQuestions, shuffle, topicNames, type Question } from './data';
import { readPreferences, savePreferences } from './preferences';
import './styles.css';
// Set to true to restore Firebase login.
const REQUIRE_LOGIN: boolean = false;

const message = (e: unknown) => e instanceof Error ? e.message : String(e);
function Login(){
 const [email,setEmail]=useState(''),[password,setPassword]=useState(''),[mode,setMode]=useState<'login'|'register'>('login'),[busy,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState('');
 async function run(task:()=>Promise<unknown>){setBusy(true);setError('');setNotice('');try{await task();}catch(e){setError(message(e));}finally{setBusy(false);}}
 function submit(e:FormEvent){e.preventDefault();if(!auth)return;const a=auth;void run(()=>mode==='login'?signInWithEmailAndPassword(a,email,password):createUserWithEmailAndPassword(a,email,password));}
 return <section className="panel narrow"><p className="eyebrow">DRIVE SKILL</p><h1>{mode==='login'?'Welcome back':'Create your account'}</h1><p className="muted">Sign in to start practising for your driving theory test.</p><form onSubmit={submit}><label>Email address<input autoComplete="email" type="email" required value={email} onChange={e=>setEmail(e.target.value)}/></label><label>Password<input type="password" autoComplete={mode==='login'?'current-password':'new-password'} minLength={mode==='register'?6:undefined} required value={password} onChange={e=>setPassword(e.target.value)}/></label><button className="primary full" disabled={busy}>{mode==='login'?'Sign in':'Create account'}</button></form><button className="secondary full" disabled={busy} onClick={()=>auth&&run(()=>signInWithPopup(auth!,new GoogleAuthProvider()))}>Continue with Google</button><div className="auth-links"><button className="link" disabled={busy} onClick={()=>{setMode(mode==='login'?'register':'login');setError('');}}>{mode==='login'?'Create account':'Already have an account? Sign in'}</button><button className="link" disabled={busy} onClick={()=>{if(!email){setError('Enter your email address first.');return;}if(auth)void run(async()=>{await sendPasswordResetEmail(auth!,email);setNotice('If an account exists, a reset email will be sent.');});}}>Reset password</button></div>{error&&<p role="alert" className="error">{error}</p>}{notice&&<p role="status">{notice}</p>}</section>;
}
const text = {
 en:{menu:'Choose how to practise',all:'All topics',allDesc:'Random questions from the entire question bank.',topics:'Practise by topic',change:'Change country or language',back:'Back to topics',next:'Next question',correct:'Correct!',incorrect:'Incorrect',answer:'Correct answer',score:'Correct',attempted:'Answered',question:'Question',partial:'',empty:'No questions available for this topic.',source:'Source',restart:'Start over'},
 is:{menu:'Veldu æfingu',all:'Allir flokkar',allDesc:'Tilviljanakenndar spurningar úr öllum flokkum.',topics:'Æfðu eftir flokkum',change:'Breyta landi eða tungumáli',back:'Til baka í flokka',next:'Næsta spurning',correct:'Rétt!',incorrect:'Rangt',answer:'Rétt svar',score:'Rétt',attempted:'Svarað',question:'Spurning',partial:'Athugið: Íslenski spurningabankinn er enn í vinnslu.',empty:'Engar spurningar í þessum flokki.',source:'Heimild',restart:'Byrja aftur'}
};
function Quiz({questions,language,topic,onBack}:{questions:Question[],language:string,topic:string|null,onBack:()=>void}){
 const t=language==='is'?text.is:text.en;
 const [queue,setQueue]=useState(()=>shuffle(questions)),[index,setIndex]=useState(0),[selected,setSelected]=useState<number|null>(null),[answered,setAnswered]=useState(0),[correct,setCorrect]=useState(0);
 const q=queue[index];
 if(!q)return <section className="panel"><p>{t.empty}</p><button onClick={onBack}>{t.back}</button></section>;
 function pick(i:number){if(selected!==null)return;setSelected(i);setAnswered(n=>n+1);if(i===q.correctIndex)setCorrect(n=>n+1);}
 function next(){if(selected===null)return;if(index+1>=queue.length){const fresh=shuffle(questions);if(fresh.length>1&&fresh[0].id===q.id)[fresh[0],fresh[1]]=[fresh[1],fresh[0]];setQueue(fresh);setIndex(0);}else setIndex(i=>i+1);setSelected(null);}
 return <><div className="toolbar"><button className="link" onClick={onBack}>← {t.back}</button><div className="stats">{t.score}: <strong>{correct}</strong> / {answered}</div></div><section className="panel quiz"><div className="quiz-meta"><span className="tag">{language==='is'?(topicNames[q.topic]??q.topic):q.topic}</span><span>{t.question} {answered+(selected===null?1:0)}</span></div>{q.image&&<div className="sign"><img key={q.image} src={asset(q.image)} alt={language==='is'?'Umferðarmerki fyrir spurninguna':'Road sign for the question'}/></div>}<h1>{q.question}</h1><div className="answers">{q.choices.map((choice,i)=><button key={i} disabled={selected!==null} className={'option '+(selected!==null?(i===q.correctIndex?'right':i===selected?'wrong':''):'')} onClick={()=>pick(i)}><span className="letter">{'ABCD'[i]}</span><span>{choice}</span>{selected!==null&&i===q.correctIndex&&<span className="mark">✓</span>}{selected===i&&i!==q.correctIndex&&<span className="mark">×</span>}</button>)}</div>{selected!==null&&<div className="feedback" role="status"><strong className={selected===q.correctIndex?'positive':'negative'}>{selected===q.correctIndex?t.correct:t.incorrect}</strong><p>{t.answer}: {q.choices[q.correctIndex]}</p>{q.explanation&&q.explanation!==q.choices[q.correctIndex]&&<p className="muted">{q.explanation}</p>}{q.source&&<details><summary>{t.source}</summary><small>{q.source}</small></details>}</div>}<button className="primary full" disabled={selected===null} onClick={next}>{t.next} →</button></section></>;
}
function Dashboard({user=null}:{user?:User|null}){
 const [preferences]=useState(readPreferences);
 const [country,setCountry]=useState(preferences.country),[language,setLanguage]=useState(preferences.language),[screen,setScreen]=useState<'restore'|'select'|'menu'|'quiz'>(preferences.country ? 'restore' : 'select'),[questions,setQuestions]=useState<Question[]>([]),[topic,setTopic]=useState<string|null>(null),[error,setError]=useState(''),[loading,setLoading]=useState(false);
 const countryInfo=countries.find(c=>c.id===country), t=language==='is'?text.is:text.en;
 useEffect(()=>{document.documentElement.lang=screen==='select'?'en':language;return()=>{document.documentElement.lang='en';};},[language,screen]);
 useEffect(()=>{
  if(!preferences.country)return;
  const controller=new AbortController();
  loadQuestions(preferences.country,preferences.language,controller.signal)
   .then(data=>{if(controller.signal.aborted)return;setQuestions(data);setScreen('menu');})
   .catch(e=>{if(controller.signal.aborted)return;setError(message(e));setScreen('select');});
  return ()=>controller.abort();
 },[preferences]);
 async function continueToMenu(e:FormEvent){e.preventDefault();if(!countryInfo||!countryInfo.languages.some(l=>l.id===language))return;setLoading(true);setError('');try{setQuestions(await loadQuestions(country,language));savePreferences({country,language});setTopic(null);setScreen('menu');}catch(e){setError(message(e));}finally{setLoading(false);}}
 const topics=[...new Set(questions.map(q=>q.topic))].sort((a,b)=>Number(b==='Exam-style practice')-Number(a==='Exam-style practice') || a.localeCompare(b));
 const start=(value:string|null)=>{setTopic(value);setScreen('quiz');};
 const openSelection=()=>{setError('');setTopic(null);setScreen('select');};
 return <><header><div className="header-inner"><a className="brand" href="#" onClick={e=>{e.preventDefault();if(screen!=='select'&&questions.length)setScreen('menu');}}>Drive <span>Skill</span></a><a className="link location-link" href="#selection" onClick={e=>{e.preventDefault();if(!loading&&screen!=='restore')openSelection();}} aria-current={screen==='select'?'page':undefined} title={t.change}>{countryInfo?`${countryInfo.name} / ${countryInfo.languages.find(l=>l.id===language)?.name??'English'}`:'Choose country / language'}</a>{REQUIRE_LOGIN&&user&&<div className="account"><span>{user.email??user.displayName??'Signed in'}</span><button className="link" onClick={()=>auth&&signOut(auth).catch(e=>setError(message(e)))}>Sign out</button></div>}</div></header><main>{error&&<p role="alert" className="error">{error}</p>}{screen==='restore'&&<p role="status">Loading…</p>}{screen==='select'&&<section id="selection" className="panel narrow"><p className="eyebrow">GET STARTED</p><h1>Choose your test</h1><p className="muted">Select the country and language you want to practise in.</p><form onSubmit={continueToMenu}><label>Country<select required disabled={loading} value={country} onChange={e=>{setCountry(e.target.value);setLanguage('en');}}><option value="" disabled>Select a country</option>{countries.map(c=><option value={c.id} key={c.id}>{c.name}</option>)}</select></label><label>Language<select value={language} disabled={!country||loading} onChange={e=>setLanguage(e.target.value)}>{(countryInfo?.languages??[{id:'en',name:'English'}]).map(l=><option key={l.id} value={l.id}>{l.name}</option>)}</select></label>{language==='is'&&<p className="notice">Icelandic is a partial question bank; more translations will be added.</p>}<button className="primary full" disabled={!country||loading}>{loading?'Loading…':'Continue →'}</button></form></section>}{screen==='menu'&&<><h1>{t.menu}</h1>{language==='is'&&<p className="notice">{t.partial}</p>}<button className="all-topics" onClick={()=>start(null)}><div><span className="eyebrow">{questions.length} {language==='is'?'spurningar':'questions'}</span><h2>{t.all}</h2><p>{t.allDesc}</p></div><span className="arrow">→</span></button><h2 className="section-title">{t.topics}</h2><div className="topics">{topics.map(name=><button className="topic" key={name} onClick={()=>start(name)}><div><strong>{language==='is'?(topicNames[name]??name):name}</strong><small>{questions.filter(q=>q.topic===name).length} {language==='is'?'spurningar':'questions'}</small></div><span>→</span></button>)}</div></>}{screen==='quiz'&&<Quiz key={`${country}-${language}-${topic??'all'}`} questions={topic?questions.filter(q=>q.topic===topic):questions} language={language} topic={topic} onBack={()=>setScreen('menu')}/>}</main><footer>Drive Skill · Independent practice resource</footer></>;
}
function AuthenticatedApp(){const [user,setUser]=useState<User|null>(null),[ready,setReady]=useState(false);useEffect(()=>{if(!auth){setReady(true);return;}return onAuthStateChanged(auth,u=>{setUser(u);setReady(true);});},[]);if(!auth)return <main><section className="panel narrow"><h1>Firebase setup required</h1><p>Copy .env.example to .env.local, fill in your Firebase web app configuration, and restart Vite.</p></section></main>;if(!ready)return <main><p role="status">Loading…</p></main>;return user?<Dashboard key={user.uid} user={user}/>:<main className="login-wrap"><Login/></main>;}
function App(){
 return REQUIRE_LOGIN ? <AuthenticatedApp/> : <Dashboard/>;
}
createRoot(document.getElementById('root')!).render(<React.StrictMode><App/></React.StrictMode>);
