const G_SECTIONS=window.GRAMMAR_SECTIONS,G_INDEX=window.GRAMMAR_INDEX;
const G_LABELS={howto:'How to Use This Book',exammap:'Where Grammar Earns Marks',m1:'01 · Subject–Verb Agreement',m2:'02 · Nouns and Number',m3:'03 · Pronouns',m4:'04 · Articles & Determiners',m5:'05 · Tense & Sequence',m6:'06 · Verb Forms & Voice',m7:'07 · Adjectives & Comparison',m8:'08 · Prepositions',m9:'09 · Conjunctions & Parallelism',m10:'10 · Modifiers',m11:'11 · Conditionals & Subjunctive',m12:'12 · Structure & Punctuation',m13:'13 · Redundancy & Precision',t1:'T1 · Subject–Verb',t2:'T2 · Nouns & Number',t3:'T3 · Pronouns',t4:'T4 · Articles',t5:'T5 · Tense',t6:'T6 · Verb Forms',t7:'T7 · Comparison',t8:'T8 · Prepositions',t9:'T9 · Parallelism',t10:'T10 · Modifiers',t11:'T11 · Conditionals',t12:'T12 · Punctuation',t13:'T13 · Redundancy',appA:'A · 70 Confusable Pairs',appB:'B · 136 Prepositional Combos',appC:'C · Night-Before Sheet',p1:'Set 1 · Error Spotting',p2:'Set 2 · Sentence Correction',p3:'Set 3 · Fill in the Blanks',keys:'Test Analysis'};
const G_GROUPS=[['Start here',['howto','exammap']],['Modules',['m1','m2','m3','m4','m5','m6','m7','m8','m9','m10','m11','m12','m13']],['Module tests',['t1','t2','t3','t4','t5','t6','t7','t8','t9','t10','t11','t12','t13']],['Appendices',['appA','appB','appC']],['Practice',['p1','p2','p3','keys']]];
const G_STATS=[['125','Numbered rules','13 modules, each closed by a mini-test'],['206','Memory items','70 confusable pairs + 136 fixed prepositions'],['445','Practice questions','13 module tests of 30 Qs + 3 mixed sets of 55 Qs']];
function GrammarPage(){
const {Badge,Tag,Button}=window.ScorebuddyDesignSystem_ee75f2;
const [group,setGroup]=React.useState(0);
const [sec,setSec]=React.useState('howto');
const ref=React.useRef(null);
React.useEffect(()=>{
const el=ref.current;if(!el)return;
el.classList.remove('attempt','revealed');
el.querySelectorAll('.gq-bar,.g-toolbar,.g-score,.g-exp').forEach(n=>n.remove());
if(!/^t\d+$/.test(sec)&&!['p1','p2','p3'].includes(sec))return;
el.classList.add('attempt');
const key={},exp={};
if(/^p\d$/.test(sec)){
const kt=document.createElement('div');kt.innerHTML=window.GRAMMAR_KEYS;
kt.querySelectorAll('.ans').forEach(a=>{const an=a.querySelector('.an');if(!an)return;const mm=an.textContent.match(/(\d+)\.\s*\(([A-Ea-e])\)/);if(mm){key[mm[1]+'.']=mm[2].toLowerCase();exp[mm[1]+'.']=a.innerHTML;}});
}else{
el.querySelectorAll('.ansblock .an2').forEach(a=>{const t=a.textContent;let m=t.match(/([\d.]+)\s*\(([A-Ea-e])\)/);if(m){key[m[1]]=m[2].toLowerCase();return;}m=t.match(/^\s*([\d.]+)\s+(C|X)\b/);if(m)key[m[1]]=m[2];});
}
const picks={};
const qs=[...el.querySelectorAll('.q')].filter(q=>q.querySelector('.qn')&&key[q.querySelector('.qn').textContent.trim()]);
const count=document.createElement('span');
count.style.cssText='font-family:var(--font-body);font-size:14px;color:var(--gray-500)';
count.textContent='0 / '+qs.length+' answered';
qs.forEach(q=>{
const qn=q.querySelector('.qn').textContent.trim();
const corr=key[qn];
const letters=(corr==='C'||corr==='X')?['C','X']:[...new Set([...q.textContent.matchAll(/\(([A-Ea-e])\)/g)].map(m=>m[1].toLowerCase()))].sort();
const bar=document.createElement('div');bar.className='gq-bar';
letters.forEach(l=>{const b=document.createElement('button');b.className='gq-btn';b.textContent=l==='C'?'\u2713 Correct':l==='X'?'\u2717 Wrong':l.toUpperCase();b.dataset.l=l;
b.onclick=()=>{if(window.SBAuth&&!window.SBAuth.guard())return;if(el.classList.contains('revealed'))return;picks[qn]=l;bar.querySelectorAll('.gq-btn').forEach(x=>x.classList.remove('sel'));b.classList.add('sel');count.textContent=Object.keys(picks).length+' / '+qs.length+' answered';};
bar.appendChild(b);});
q.appendChild(bar);q.dataset.qn=qn;});
const bar=document.createElement('div');bar.className='g-toolbar';
const btn=document.createElement('button');btn.className='g-submit';btn.textContent='Submit test & show answers';
btn.onclick=()=>{
if(window.SBAuth&&!window.SBAuth.guard())return;
let right=0,attempted=0;
qs.forEach(q=>{const qn=q.dataset.qn,pick=picks[qn],corr=key[qn];
q.querySelectorAll('.gq-btn').forEach(b=>{if(b.dataset.l===corr)b.classList.add('hit');else if(b.classList.contains('sel'))b.classList.add('miss');});
if(pick){attempted++;if(pick===corr){right++;q.classList.add('g-hit');}else q.classList.add('g-miss');}
if(exp[qn]){const e=document.createElement('div');e.className='g-exp';e.innerHTML=exp[qn];q.appendChild(e);}});
el.classList.add('revealed');
const sc=document.createElement('div');sc.className='g-score';
sc.textContent='Score: '+right+' / '+qs.length+' correct ('+attempted+' attempted). Full answers and explanations below — every answer names the rule it comes from.';
bar.after(sc);btn.disabled=true;btn.textContent='Submitted';
if(window.SBAuth){
const modName=n=>(G_LABELS['m'+n]||'').replace(/^\d+\s*·\s*/,'');
const setName=(G_LABELS[sec]||'').replace(/^Set \d+\s*·\s*/,'');
// Mixed sets cite global rule numbers ("Rule 13"); each module header states its range ("Rules 1–18").
const ranges=[];for(let i=1;i<=13;i++){const mm=String(G_SECTIONS['m'+i]||'').match(/Rules\s+(\d+)\s*(?:&ndash;|–|-)\s*(\d+)/);if(mm)ranges.push([+mm[1],+mm[2],i]);}
const moduleOfRule=r=>{const f=ranges.find(x=>r>=x[0]&&r<=x[1]);return f?modName(f[2]):null;};
const topicOf=qn=>{if(/^t\d+$/.test(sec))return modName(sec.slice(1));const m=exp[qn]&&exp[qn].replace(/<[^>]+>/g,' ').match(/Rule\s+(\d+)/);return (m&&moduleOfRule(+m[1]))||setName||'Grammar';};
const questions=qs.map(q=>{const qn=q.dataset.qn,pick=picks[qn]||null;return {q:qn,n:qn.replace(/\.$/,''),t:topicOf(qn),a:pick?pick.toUpperCase():null,k:String(key[qn]).toUpperCase(),c:pick?(pick===key[qn]?1:0):null};});
window.SBAuth.recordAttempt('grammar:'+sec,right,qs.length,{attempted,questions}).then(res=>{if(!res||!res.id)return;const l=document.createElement('a');l.href='analysis.html?id='+encodeURIComponent(res.id);l.className='g-analysis';l.textContent='Detailed analysis →';l.style.cssText='display:inline-block;margin:10px 0 0;padding:9px 18px;border-radius:999px;background:var(--brand-accent);color:#fff;font-family:var(--font-body);font-weight:700;font-size:14px;text-decoration:none';sc.appendChild(document.createElement('br'));sc.appendChild(l);}).catch(()=>{});}};
bar.appendChild(btn);bar.appendChild(count);
const ansb=el.querySelector('.ansblock');
if(ansb)ansb.before(bar);else el.appendChild(bar);
},[sec,group]);
const go=(id,anchor)=>{
G_GROUPS.forEach(([,ids],gi)=>{if(ids.includes(id))setGroup(gi);});
setSec(id);
setTimeout(()=>{const el=anchor&&document.getElementById(anchor);if(el){const y=el.getBoundingClientRect().top+window.scrollY-140;window.scrollTo(0,y);}else window.scrollTo(0,0);},50);};
const onClick=e=>{
const a=e.target.closest('a[href^="#"]');if(!a)return;e.preventDefault();
const target=a.getAttribute('href').slice(1);
const owner=Object.keys(G_INDEX).find(k=>k===target||G_INDEX[k].includes(target));
if(owner)go(owner,target===owner?null:target);};
const ids=G_GROUPS[group][1];
const cur=ids.includes(sec)?sec:ids[0];
return React.createElement('div',null,
React.createElement('section',{style:{padding:'72px 48px 64px',background:'var(--navy-900)'}},
React.createElement('div',{style:{maxWidth:1180,margin:'0 auto',display:'grid',gridTemplateColumns:'1.2fr 1fr',gap:48,alignItems:'center'},className:'grid3'},
React.createElement('div',null,
React.createElement(Badge,{tone:'accent'},'FREE · GRAMMAR RULE BOOK'),
React.createElement('h1',{style:{fontFamily:'var(--font-display)',fontWeight:800,fontSize:40,lineHeight:1.15,color:'var(--on-dark)',margin:'18px 0 16px',letterSpacing:'.01em'}},'The CAT & IPMAT ',React.createElement('span',{style:{color:'var(--magenta-500)'}},'Grammar Rule Book')),
React.createElement('p',{style:{fontFamily:'var(--font-body)',fontSize:16.5,color:'var(--text-on-inverse)',lineHeight:1.65,margin:0}},'Every rule the exams actually test — 125 rules in 13 modules, with exam-style traps, mini-tests, three appendices and 55 mixed practice questions. Read a module a day; the whole book closes in two weeks.')),
React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:12}},
G_STATS.map(([n,t,s])=>React.createElement('div',{key:t,style:{display:'flex',alignItems:'center',gap:18,background:'rgba(255,255,255,.06)',border:'1px solid rgba(255,255,255,.14)',borderRadius:'var(--radius-md)',padding:'14px 20px'}},
React.createElement('div',{style:{fontFamily:'var(--font-display)',fontWeight:800,fontSize:32,color:'var(--magenta-500)',minWidth:64,textAlign:'right'}},n),
React.createElement('div',null,
React.createElement('div',{style:{fontFamily:'var(--font-display)',fontWeight:700,fontSize:15,color:'var(--on-dark)'}},t),
React.createElement('div',{style:{fontFamily:'var(--font-body)',fontSize:12.5,color:'var(--text-on-inverse)',marginTop:2}},s)))))))
,
React.createElement('section',{style:{padding:'20px 48px 60px',maxWidth:1180,margin:'0 auto'}},
React.createElement('div',{className:'gb-sticky',style:{position:'sticky',top:73,background:'var(--color-bg-page)',zIndex:5,paddingTop:6,borderBottom:'1px solid var(--border-default)',paddingBottom:12}},
React.createElement('div',{className:'gb-row',style:{display:'flex',gap:8,flexWrap:'wrap',marginBottom:10}},
G_GROUPS.map(([label,gids],gi)=>React.createElement(Tag,{key:label,active:group===gi,onClick:()=>{setGroup(gi);setSec(gids[0]);scrollTo(0,0);}},label))),
React.createElement('div',{className:'gb-row',style:{display:'flex',gap:6,flexWrap:'wrap'}},
ids.map(id=>React.createElement('button',{key:id,onClick:()=>{setSec(id);scrollTo(0,0);},style:{fontFamily:'var(--font-body)',fontWeight:600,fontSize:12.5,padding:'6px 12px',borderRadius:'var(--radius-pill)',border:'1px solid '+(cur===id?'var(--brand-accent)':'var(--border-default)'),background:cur===id?'var(--magenta-100)':'var(--white)',color:cur===id?'var(--accent-strong)':'var(--text-body)',cursor:'pointer'}},G_LABELS[id])))),
React.createElement('div',{ref,className:'gbook',onClick,style:{maxWidth:860,margin:'26px auto 0'},dangerouslySetInnerHTML:{__html:G_SECTIONS[cur]}}),
React.createElement('div',{style:{maxWidth:860,margin:'30px auto 0',display:'flex',justifyContent:'space-between',gap:10}},
(()=>{const flat=G_GROUPS.flatMap(g=>g[1]);const i=flat.indexOf(cur);
return [i>0?React.createElement(Button,{key:'p',variant:'secondary',size:'sm',onClick:()=>go(flat[i-1])},'← '+G_LABELS[flat[i-1]]):React.createElement('span',{key:'p'}),
i<flat.length-1?React.createElement(Button,{key:'n',variant:'primary',size:'sm',onClick:()=>go(flat[i+1])},G_LABELS[flat[i+1]]+' →'):React.createElement('span',{key:'n'})];})()),
React.createElement('p',{style:{fontFamily:'var(--font-body)',fontSize:13,color:'var(--text-muted)',maxWidth:860,margin:'40px auto 0',paddingTop:18,borderTop:'1px solid var(--border-default)',lineHeight:1.6}},'Built for CAT sentence correction and para-jumbles and IPMAT/JIPMAT error spotting, fill-in-the-blanks and sentence improvement. Every answer in the key carries the rule number it comes from — revise the rule, not the question.')));
}
window.GrammarPage=GrammarPage;
