import React, { useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";

const BANK = [
  {q:"Which statement best defines government?", options:["A group that shares a language and culture","The institution through which society makes and enforces public policies","A market where goods are exchanged","A group of citizens who all share the same opinion"], answer:1, topic:"Defining government", explain:"Government makes and enforces public policies."},
  {q:"What is the central dilemma of government?", options:["Choosing between a president and a prime minister","Balancing order and security with individual freedom","Deciding whether all laws should be local","Balancing imports and exports"], answer:1, topic:"Defining government", explain:"Too little authority can create disorder; too much can threaten liberty."},
  {q:"Which branch has the power to make laws?", options:["Executive","Judicial","Legislative","Administrative"], answer:2, topic:"Branches of government", explain:"The legislative branch makes laws."},
  {q:"Which branch interprets laws and resolves legal disputes?", options:["Legislative","Judicial","Executive","Electoral"], answer:1, topic:"Branches of government", explain:"The judicial branch interprets laws and settles legal disputes."},
  {q:"A powerful group conquers a territory and establishes a state. Which theory explains this?", options:["Divine Right Theory","Social Contract Theory","Evolutionary Theory","Force Theory"], answer:3, topic:"Origin of the state", explain:"Force Theory says states originated through conquest or force."},
  {q:"A state develops gradually from families to clans and tribes. Which theory is this?", options:["Evolutionary Theory","Force Theory","Divine Right Theory","Social Contract Theory"], answer:0, topic:"Origin of the state", explain:"Evolutionary Theory describes gradual development from early social groups."},
  {q:"A ruler claims their authority comes directly from God. Which theory is this?", options:["Social Contract Theory","Force Theory","Divine Right Theory","Evolutionary Theory"], answer:2, topic:"Origin of the state", explain:"Divine Right Theory claims rulers receive authority from God."},
  {q:"Which theory says people agree to form a government in exchange for protection and order?", options:["Force Theory","Social Contract Theory","Evolutionary Theory","Divine Right Theory"], answer:1, topic:"Origin of the state", explain:"Social Contract Theory emphasizes people's consent in forming government."},
  {q:"Which philosopher emphasized natural rights such as life, liberty, and property?", options:["Thomas Hobbes","John Locke","James Madison","Alexander Hamilton"], answer:1, topic:"Social contract", explain:"John Locke argued that government should protect natural rights."},
  {q:"Which philosopher emphasized the need for strong government to maintain peace and security?", options:["John Locke","Thomas Hobbes","Jean-Jacques Rousseau","Montesquieu"], answer:1, topic:"Social contract", explain:"Hobbes emphasized order and security."},
  {q:"According to Locke, what may people do if a government repeatedly violates their rights?", options:["They must obey without question","They may change or replace the government","They must give up their natural rights","They must establish a monarchy"], answer:1, topic:"Social contract", explain:"Locke argued people may change or replace a government that fails its responsibilities."},
  {q:"What is a democracy?", options:["A government ruled by one person","A government controlled by a small elite","A system where political power ultimately belongs to the people","A government led by a hereditary monarch"], answer:2, topic:"Democracy", explain:"In a democracy, political power ultimately belongs to the people."},
  {q:"Which is most characteristic of a dictatorship?", options:["Power is effectively limited by frequent fair elections","One person or a small group holds power with few effective limits","All citizens directly vote on every law","Regional governments hold all authority"], answer:1, topic:"Dictatorship and other systems", explain:"Dictatorships concentrate power and often restrict rights or opposition."},
  {q:"A government controlled by one person with supreme political power is a(n)...", options:["Oligarchy","Republic","Autocracy","Confederation"], answer:2, topic:"Dictatorship and other systems", explain:"An autocracy is ruled by one person with supreme power."},
  {q:"A government controlled by a small group is a(n)...", options:["Oligarchy","Autocracy","Direct democracy","Monarchy"], answer:0, topic:"Dictatorship and other systems", explain:"An oligarchy is controlled by a small group."},
  {q:"In a direct democracy, citizens...", options:["Elect representatives to make all decisions","Vote directly on laws and policies","Have no role in government","Choose a hereditary ruler"], answer:1, topic:"Democracy", explain:"Direct democracy allows citizens to vote directly on policies."},
  {q:"What best describes representative democracy?", options:["Citizens elect officials to make decisions on their behalf","A king makes every decision","The military appoints all lawmakers","Courts write all public policy"], answer:0, topic:"Democracy", explain:"Citizens choose representatives who make decisions for them."},
  {q:"Why is the United States described as both a representative democracy and a republic?", options:["It has no constitution","Citizens elect representatives and it has no hereditary monarch","Every citizen votes on every federal law","The president is selected by parliament"], answer:1, topic:"Democracy", explain:"Citizens elect officials, and the government is not headed by a hereditary monarch."},
  {q:"Which democratic principle means government authority comes from the people?", options:["Minority rights","Popular sovereignty","Compromise","Judicial review"], answer:1, topic:"Concepts of democracy", explain:"Popular sovereignty means government derives its authority from the people."},
  {q:"A majority votes to ban a minority group's peaceful religious practice. Which principle explains why this should not automatically be allowed?", options:["Majority rule","Minority rights","Unitary government","Supply and demand"], answer:1, topic:"Concepts of democracy", explain:"Democracy requires protection of minority rights, not just majority rule."},
  {q:"What does the rule of law mean?", options:["Only citizens must obey laws","Government officials are above the law","Everyone, including government officials, must obey the law","Judges can ignore the constitution"], answer:2, topic:"Concepts of democracy", explain:"The rule of law applies to citizens and officials alike."},
  {q:"Which is an example of political participation?", options:["Contacting an elected official about a public issue","Ignoring every election","A business changing its product price","A court interpreting a law"], answer:0, topic:"Concepts of democracy", explain:"Political participation includes voting, contacting officials, and public debate."},
  {q:"What is a nation?", options:["Any government agency","A group of people with a shared national identity","A geographic area with no population","A court system"], answer:1, topic:"Nation, state, and nation-state", explain:"A nation is a group connected by a shared identity, often cultural or historical."},
  {q:"Which set lists the four characteristics of a state?", options:["Elections, courts, taxes, parties","Population, territory, government, sovereignty","Language, religion, culture, ancestry","President, parliament, monarch, judges"], answer:1, topic:"Nation, state, and nation-state", explain:"A state has population, territory, government, and sovereignty."},
  {q:"The defined geographic area controlled by a state is its...", options:["Population","Sovereignty","Territory","Constitution"], answer:2, topic:"Nation, state, and nation-state", explain:"Territory is the geographic area under a state's authority."},
  {q:"What is sovereignty?", options:["The supreme authority of a state to govern itself","The number of people in a country","The process of choosing representatives","A shared cultural identity"], answer:0, topic:"Nation, state, and nation-state", explain:"Sovereignty is a state's supreme authority to govern itself."},
  {q:"A constitution is best described as...", options:["A list of campaign promises","The fundamental law that structures and limits government","A temporary court ruling","A treaty between political parties"], answer:1, topic:"Nation, state, and nation-state", explain:"A constitution establishes government structure, powers, and limits."},
  {q:"In a unitary system, constitutional authority is mainly...", options:["Held by the central government","Held by independent member states","Split equally between all cities","Held by the courts alone"], answer:0, topic:"Government structures", explain:"Unitary systems concentrate the main authority in the central government."},
  {q:"What is a key feature of federal government?", options:["Regional governments have no powers","The national government controls every local decision","Constitutional powers are divided between national and regional governments","Independent states control a weak central authority only"], answer:2, topic:"Government structures", explain:"Federal systems divide constitutional powers between levels of government."},
  {q:"Which system has independent member states cooperating through a relatively weak central authority?", options:["Unitary","Federal","Confederate","Parliamentary"], answer:2, topic:"Government structures", explain:"In a confederation, member states retain most power."},
  {q:"Which example best represents a federal system?", options:["A national government grants all regional powers and may revoke them","The U.S. Constitution divides powers between federal and state governments","Independent states cooperate through a weak central authority","A prime minister depends on parliament's confidence"], answer:1, topic:"Government structures", explain:"The United States divides constitutional powers between federal and state governments."},
  {q:"In a presidential system, the executive is...", options:["Chosen from and dependent on parliament","Institutionally separate from the legislature","Always a hereditary monarch","Controlled by local governments"], answer:1, topic:"Presidential and parliamentary", explain:"Presidential systems separate the executive and legislative branches."},
  {q:"In a parliamentary system, the executive generally depends on...", options:["Support from the legislature","A hereditary succession","The judicial branch's daily approval","Independent state governments"], answer:0, topic:"Presidential and parliamentary", explain:"A parliamentary government depends on legislative confidence."},
  {q:"Which is generally true of a parliamentary system?", options:["The president always has a fixed term separate from the legislature","The prime minister usually leads the government and needs parliamentary support","The executive cannot come from the legislature","The legislature has no role in forming the government"], answer:1, topic:"Presidential and parliamentary", explain:"The prime minister usually leads the government, often backed by a majority party or coalition."},
  {q:"Which pairing is correct?", options:["United States — parliamentary; United Kingdom — presidential","United States — presidential; United Kingdom — parliamentary","Both countries — confederate","Both countries — unitary presidential"], answer:1, topic:"Presidential and parliamentary", explain:"The United States is presidential; the United Kingdom is parliamentary and generally unitary."},
  {q:"If demand rises while supply stays limited, prices generally...", options:["Fall to zero","Rise","Stay fixed by definition","Become unrelated to demand"], answer:1, topic:"Supply and demand", explain:"High demand with limited supply tends to push prices upward."},
  {q:"Equilibrium price is the price at which...", options:["Supply equals demand in quantity","Government sets every price","No one wants the product","Producers offer unlimited quantities"], answer:0, topic:"Supply and demand", explain:"Equilibrium occurs where quantity supplied equals quantity demanded."},
  {q:"The law of demand says that, other things equal, consumers generally buy...", options:["More when price rises","Less when price rises","The same amount at every price","Only government-owned products"], answer:1, topic:"Supply and demand", explain:"As price rises, quantity demanded generally falls, other things equal."},
  {q:"What is a mixed economy?", options:["An economy with only government ownership","An economy combining private markets with government involvement","An economy with no rules or public services","An economy where all prices are fixed by consumers"], answer:1, topic:"Economics and political decisions", explain:"A mixed economy combines private ownership and markets with government involvement."},
  {q:"Why is compromise important in a democracy?", options:["It eliminates all disagreement permanently","It lets people with different views make concessions to reach an acceptable agreement","It means the majority can ignore all minority rights","It prevents elected officials from negotiating"], answer:1, topic:"Economics and political decisions", explain:"Compromise helps people with different priorities reach workable solutions."},
  {q:"Which term means a government decision or course of action addressing a public issue?", options:["Public policy","Sovereignty","Territory","Oligarchy"], answer:0, topic:"Defining government", explain:"Public policy is a government decision or course of action designed to address a public issue."},
  {q:"Which statement best distinguishes a state from a nation?", options:["A state is a political organization with territory and sovereignty; a nation is a group with shared identity","A state must share one language; a nation must have a president","A nation always has four branches of government","There is no difference in political science"], answer:0, topic:"Nation, state, and nation-state", explain:"A state is a political organization; a nation is a group sharing a national identity."},
  {q:"Which democratic principle means citizens should have equal political rights?", options:["Political equality","Majority rule","Compromise","Federalism"], answer:0, topic:"Concepts of democracy", explain:"Political equality includes equal political rights, such as equal voting rights under the law."},
  {q:"A government lets citizens vote, but opposition candidates are threatened and ballots are manipulated. What democratic standard is missing?", options:["Free and fair elections","A mixed economy","Sovereignty","A unitary structure"], answer:0, topic:"Concepts of democracy", explain:"Elections must be free and fair, without coercion or fraud."},
  {q:"A lawmaker negotiates a budget by accepting some changes in exchange for support. This is an example of...", options:["Sovereignty","Compromise","Autocracy","Divine right"], answer:1, topic:"Economics and political decisions", explain:"Compromise involves concessions to reach an agreement."},
  {q:"Which power is exercised when the president carries out a law passed by Congress?", options:["Judicial","Legislative","Executive","Sovereign"], answer:2, topic:"Branches of government", explain:"The executive branch enforces and carries out laws."},
  {q:"A state has people, territory, and a government, but another country controls its major decisions. Which characteristic is most clearly missing?", options:["Population","Territory","Sovereignty","Government"], answer:2, topic:"Nation, state, and nation-state", explain:"Sovereignty means the state has supreme authority to govern itself."},
  {q:"Which principle means decisions generally follow the preference of more than half the voters, while rights remain protected?", options:["Majority rule","Divine right","Oligarchy","Judicial power"], answer:0, topic:"Concepts of democracy", explain:"Majority rule guides decisions, but it must coexist with minority rights."},
  {q:"Which government form is headed by a king, queen, or other hereditary ruler?", options:["Republic","Monarchy","Oligarchy","Direct democracy"], answer:1, topic:"Dictatorship and other systems", explain:"A monarchy is headed by a hereditary ruler and may be absolute or constitutional."},
  {q:"Which statement about the United States is correct?", options:["It is a pure direct democracy","It is a representative democracy and a republic","It is a confederation under the Articles of Confederation today","Its president is the head of parliament"], answer:1, topic:"Democracy", explain:"The United States is a representative democracy and a republic."}
];

function App() {
  const [count, setCount] = useState(30);
  const [quiz, setQuiz] = useState([]);
  const [answers, setAnswers] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [started, setStarted] = useState(false);
  const [mode, setMode] = useState("mixed");
  const [missedOnly, setMissedOnly] = useState(false);

  const begin = () => {
    const pool = mode === "mixed" ? BANK : BANK.filter(x => x.topic === mode);
    const shuffled = [...pool].sort(() => Math.random() - 0.5);
    const selected = shuffled.slice(0, Math.min(count, pool.length));
    setQuiz(selected); setAnswers({}); setSubmitted(false); setStarted(true); setMissedOnly(false);
  };
  const score = useMemo(() => quiz.reduce((n, q, i) => n + (answers[i] === q.answer ? 1 : 0), 0), [quiz, answers]);
  const topics = [...new Set(BANK.map(q => q.topic))];

  return <main className="app-shell">
    <header className="hero">
      <div className="eyebrow">CHAPTER REVIEW • INTERACTIVE QUIZ</div>
      <h1>American Government</h1>
      <p>Practice the concepts, terms, and scenarios from your chapter study guide.</p>
      <div className="hero-stats"><span><b>{BANK.length}</b> question bank</span><span><b>25–50</b> questions per test</span><span><b>Instant</b> feedback</span></div>
    </header>

    {!started ? <section className="setup card">
      <div className="section-heading"><div><div className="eyebrow dark">SET UP YOUR TEST</div><h2>Build a practice test</h2></div><div className="round-icon">✎</div></div>
      <label className="field-label" htmlFor="count">Number of questions <strong>{count}</strong></label>
      <input id="count" className="range" type="range" min="25" max="50" step="1" value={count} onChange={e => setCount(Number(e.target.value))}/>
      <div className="range-ends"><span>25 questions</span><span>50 questions</span></div>
      <div className="field-label topic-label">Topic coverage</div>
      <div className="topic-grid">
        <button className={mode==="mixed"?"topic active":"topic"} onClick={()=>setMode("mixed")}><span>✦</span><b>All topics</b><small>Mixed chapter review</small></button>
        {topics.map(t=><button key={t} className={mode===t?"topic active":"topic"} onClick={()=>setMode(t)}><span>◦</span><b>{t}</b><small>{BANK.filter(q=>q.topic===t).length} questions in bank</small></button>)}
      </div>
      <div className="setup-bottom"><div className="note"><span>ⓘ</span><p>Questions are shuffled each time. Select an answer for every question, then submit to see your score and explanations.</p></div><button className="primary" onClick={begin}>Start test <span>→</span></button></div>
    </section> : <section className="quiz-area">
      <div className="quiz-top"><button className="back" onClick={()=>{setStarted(false);setSubmitted(false)}}>← Test setup</button><div className="progress-label">{submitted ? "TEST COMPLETE" : `QUESTION ${Object.keys(answers).length} OF ${quiz.length} ANSWERED`}</div></div>
      {submitted && <section className="result card">
        <div className="result-icon">{score/quiz.length>=.8?"★":score/quiz.length>=.6?"✓":"↗"}</div>
        <div><div className="eyebrow dark">YOUR RESULT</div><h2>{Math.round(score/quiz.length*100)}% <span className="result-sub">{score} out of {quiz.length} correct</span></h2><p>{score/quiz.length>=.8?"Great work — you have a strong grasp of this material.":score/quiz.length>=.6?"Good start. Review the explanations for the concepts you missed.":"Keep practicing. Use the explanations below to strengthen your understanding."}</p></div>
        <button className="primary" onClick={begin}>Try another test ↻</button>
      </section>}
      <div className="quiz-toolbar"><span>{mode==="mixed"?"All topics":mode}</span><span>{quiz.length} questions</span></div>
      {quiz.map((q,i)=>{
        const chosen=answers[i];
        const correct=chosen===q.answer;
        if (submitted && missedOnly && correct) return null;
        return <article className={`question card ${submitted?(correct?"is-correct":"is-wrong"):""}`} key={i}>
          <div className="question-meta"><span>QUESTION {String(i+1).padStart(2,"0")}</span><span>{q.topic}</span></div>
          <h3>{q.q}</h3>
          <div className="options">{q.options.map((op,j)=>{
            let cls="option";
            if(chosen===j) cls+=" selected";
            if(submitted && j===q.answer) cls+=" right-answer";
            if(submitted && chosen===j && !correct) cls+=" wrong-answer";
            return <button key={j} className={cls} disabled={submitted} onClick={()=>setAnswers(a=>({...a,[i]:j}))}><span className="letter">{String.fromCharCode(65+j)}</span><span>{op}</span>{submitted&&j===q.answer&&<span className="check">✓</span>}</button>
          })}</div>
          {submitted && <div className="explanation"><b>{correct?"Correct":"Correct answer: "+String.fromCharCode(65+q.answer)}</b><p>{q.explain}</p></div>}
        </article>
      })}
      <div className="submit-row">
        {submitted ? <><button className="secondary" onClick={()=>setMissedOnly(v=>!v)}>{missedOnly?"Show all questions":"Review missed questions"}</button><button className="primary" onClick={begin}>New test ↻</button></> : <><span>{quiz.length-Object.keys(answers).length} unanswered</span><button className="primary" onClick={()=>setSubmitted(true)}>Submit test <span>→</span></button></>}
      </div>
    </section>}
    <footer>AMERICAN GOVERNMENT • STUDY SMARTER</footer>
  </main>;
}

createRoot(document.getElementById("root")).render(<App />);
