const STEPS = ['What to make','Pick a look','Choose questions','Review and make'];
function StepBar({ step, maxVisited, onJump }) {
  return <div style={{display:'flex',gap:0,marginBottom:30,borderBottom:'1px solid var(--sitm-border)'}}>
    {STEPS.map((s,i) => {
      const done = i < step, on = i === step, reachable = i <= maxVisited;
      return <button key={s} onClick={()=>reachable&&onJump(i)} style={{fontFamily:'var(--sitm-font-body)',display:'flex',alignItems:'center',gap:9,padding:'12px 22px 14px 0',marginRight:22,
        background:'none',border:'none',cursor:reachable?'pointer':'default',boxShadow:on?'inset 0 -3px 0 var(--sitm-teal)':'none'}}>
        <span style={{width:24,height:24,borderRadius:'50%',flex:'none',display:'flex',alignItems:'center',justifyContent:'center',fontSize:12,fontWeight:600,
          background:done?'var(--sitm-teal)':on?'var(--sitm-navy)':'var(--sitm-bg-dim)',color:done||on?'#fff':'var(--sitm-text)'}}>
          {done ? <Icon name="check" size={12} stroke={3}/> : i+1}</span>
        <span style={{fontSize:13.5,fontWeight:on?600:500,color:on?'var(--sitm-navy)':reachable?'var(--sitm-text)':'rgba(62,71,97,.45)'}}>{s}</span>
      </button>;
    })}
  </div>;
}
function StepType({ sel, onSel }) {
  const D = window.CS_DATA;
  return <div>
    <H2>What do you want to make?</H2>
    <Sub style={{marginTop:6,marginBottom:22}}>This choice decides which of your questions can be used. Puzzles need short answers, so fewer questions fit them.</Sub>
    <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:16}}>
      {D.contentTypes.map(t => { const on = sel===t.id;
        return <div key={t.id} onClick={()=>onSel(t.id)} style={{background:'#fff',border:on?'2px solid var(--sitm-teal)':'1px solid var(--sitm-border)',padding:on?17:18,cursor:'pointer',position:'relative',borderRadius:14}}>
          {on && <span style={{position:'absolute',top:10,right:10,width:22,height:22,background:'var(--sitm-teal)',color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',borderRadius:7}}><Icon name="check" size={13} stroke={3}/></span>}
          <TypePreview kind={t.preview} big/>
          <div style={{display:'flex',alignItems:'center',gap:8,marginTop:12}}>
            <span style={{fontFamily:'var(--sitm-font-heading)',fontSize:16.5,color:'var(--sitm-navy)'}}>{t.name}</span>
            <Chip tone={t.out==='HTML'?'gold':'teal'}>{t.out==='HTML'?'Saves as a web page':'Saves as a PDF'}</Chip>
          </div>
          <div style={{fontSize:12.5,lineHeight:1.55,color:'var(--sitm-text)',marginTop:6}}>{t.desc}</div>
          <div style={{fontSize:12,fontWeight:600,color:'var(--sitm-teal-deep)',marginTop:10}}>{t.eligible.toLocaleString()} of your questions fit this</div>
        </div>; })}
    </div>
  </div>;
}
function StepTemplate({ type, sel, onSel, templates, onUploadSaved, toast }) {
  const D = window.CS_DATA;
  const [upload,setUpload] = React.useState(false);
  const t = D.contentTypes.find(c=>c.id===type);
  const list = templates.filter(x => x.types.includes(type));
  return <div>
    <H2>Pick a look for your {t.name.toLowerCase()}</H2>
    <Sub style={{marginTop:6,marginBottom:22}}>The template sets the layout and style. Do not worry about getting it perfect. You can change anything in the editor after it is made.</Sub>
    <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:16}}>
      {list.map(x => <TemplateCard key={x.id} tpl={x} selected={sel===x.id} onClick={()=>onSel(x.id)}/>)}
      <div onClick={()=>setUpload(true)} style={{border:'1.5px dashed var(--sitm-teal)',background:'rgba(97,189,183,.05)',padding:16,cursor:'pointer',textAlign:'center',display:'flex',flexDirection:'column',justifyContent:'center',borderRadius:12}}>
        <TemplateThumb kind="upload"/>
        <div style={{fontSize:13.5,fontWeight:600,color:'var(--sitm-teal-deep)',marginTop:10}}>Add your own</div>
        <div style={{fontSize:11.5,color:'var(--sitm-text)',marginTop:3}}>From a PDF or web page</div>
      </div>
    </div>
    <UploadTemplateModal open={upload} onClose={()=>setUpload(false)} onSaved={(name)=>{ const id='up-'+Date.now(); onUploadSaved({id,types:[type],name,desc:'Added by you',thumb:'clean'}); onSel(id); setUpload(false); toast('Saved. '+name+' is selected below.'); }}/>
  </div>;
}
function Field({ label, children }) {
  return <label style={{display:'block'}}>
    <span style={{display:'block',fontSize:12.5,fontWeight:600,marginBottom:6,color:'var(--sitm-text)'}}>{label}</span>
    {children}
  </label>;
}
function SelectBox({ value, onChange, options }) {
  return <span style={{position:'relative',display:'block'}}>
    <select value={value} onChange={e=>onChange(e.target.value)} style={{width:'100%',appearance:'none',WebkitAppearance:'none',fontFamily:'var(--sitm-font-body)',fontSize:13.5,color:'var(--sitm-text)',padding:'9px 32px 9px 11px',background:'#fff',border:'1px solid rgba(62,71,97,.2)',outline:'none',cursor:'pointer'}}>
      {options.map(o=><option key={o} value={o}>{o}</option>)}
    </select>
    <span style={{position:'absolute',right:10,top:'50%',transform:'translateY(-50%)',pointerEvents:'none',color:'var(--sitm-text)'}}><Icon name="chevR" size={13} style={{transform:'rotate(90deg)'}}/></span>
  </span>;
}
function hashStr(s){let h=0;for(let i=0;i<s.length;i++){h=(h*31+s.charCodeAt(i))|0;}return Math.abs(h);}
function StepQuestions({ type, f, setF, picked, setPicked }) {
  const D = window.CS_DATA;
  const t = D.contentTypes.find(c=>c.id===type);
  const isPuzzle = type==='crossword'||type==='wordsearch';
  const topicList = f.specialty==='Physics' ? D.topics['Physics'] : f.specialty==='All specialties' ? ['All topics'] : D.topics._default;
  // fake but stable match count
  let matches = t.eligible;
  if (f.specialty!=='All specialties') matches = Math.round(matches * (0.12 + (hashStr(f.specialty)%20)/100));
  if (f.topic!=='All topics') matches = Math.round(matches * (0.2 + (hashStr(f.topic)%25)/100));
  if (f.diff!=='Any difficulty') matches = Math.round(matches * 0.38);
  if (f.qtype!=='Any format') matches = Math.round(matches * 0.55);
  if (f.search.trim()) matches = Math.max(3, Math.round(matches * 0.06));
  matches = Math.max(matches, 3);
  const pool = D.questions.filter(q =>
    (!isPuzzle || q.puzzle) &&
    (f.specialty==='All specialties' || q.specialty===f.specialty) &&
    (f.topic==='All topics' || q.topic===f.topic) &&
    (f.diff==='Any difficulty' || q.diff===f.diff) &&
    (f.qtype==='Any format' || q.qtype===f.qtype) &&
    (!f.search.trim() || (q.stem+' '+q.answer).toLowerCase().includes(f.search.toLowerCase())));
  const countNum = Math.min(parseInt(f.count)||0, matches);
  return <div style={{display:'flex',gap:26,alignItems:'flex-start'}}>
    <div style={{flex:'none',width:340}}>
      <H2 style={{fontSize:20}}>Narrow it down</H2>
      <Sub style={{marginTop:6,marginBottom:18}}>Use as many or as few filters as you like.</Sub>
      {isPuzzle && <div style={{background:'rgba(253,189,50,.14)',border:'1px solid var(--sitm-gold)',padding:'11px 14px',fontSize:12.5,lineHeight:1.55,marginBottom:16,borderRadius:10}}>{D.puzzleNote}</div>}
      <div style={{display:'flex',flexDirection:'column',gap:14,background:'#fff',border:'1px solid var(--sitm-border)',padding:18,borderRadius:12}}>
        <Field label="Search for a word or phrase">
          <div style={{position:'relative'}}>
            <span style={{position:'absolute',left:10,top:9,color:'var(--sitm-text)',opacity:.6}}><Icon name="search" size={14}/></span>
            <input value={f.search} onChange={e=>setF({...f,search:e.target.value})} placeholder="Try Doppler, liver, kidney"
              style={{width:'100%',boxSizing:'border-box',fontFamily:'var(--sitm-font-body)',fontSize:13.5,padding:'8px 11px 8px 31px',border:'1px solid rgba(62,71,97,.2)',outline:'none',color:'var(--sitm-text)'}}/>
          </div>
        </Field>
        <Field label="Specialty"><SelectBox value={f.specialty} onChange={v=>setF({...f,specialty:v,topic:'All topics'})} options={D.specialties}/></Field>
        <Field label="Topic"><SelectBox value={f.topic} onChange={v=>setF({...f,topic:v})} options={topicList}/></Field>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
          <Field label="Difficulty"><SelectBox value={f.diff} onChange={v=>setF({...f,diff:v})} options={D.difficulties}/></Field>
          <Field label="Question format"><SelectBox value={f.qtype} onChange={v=>setF({...f,qtype:v})} options={D.qtypes}/></Field>
        </div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:14,background:'#fff',border:'1px solid var(--sitm-border)',padding:18,marginTop:14,borderRadius:12}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1.4fr',gap:12}}>
          <Field label="How many">
            <input type="number" min="1" max="60" value={f.count} onChange={e=>setF({...f,count:e.target.value})}
              style={{width:'100%',boxSizing:'border-box',fontFamily:'var(--sitm-font-body)',fontSize:13.5,padding:'8px 11px',border:'1px solid rgba(62,71,97,.2)',outline:'none',color:'var(--sitm-text)'}}/>
          </Field>
          <Field label="In what order"><SelectBox value={f.order} onChange={v=>setF({...f,order:v})} options={D.orders}/></Field>
        </div>
      </div>
    </div>
    <div style={{flex:1}}>
      <div style={{background:'#fff',border:'1px solid var(--sitm-border)',padding:'18px 22px',display:'flex',alignItems:'center',gap:18,marginBottom:14,borderRadius:12}}>
        <div>
          <div style={{fontFamily:'var(--sitm-font-heading)',fontSize:26,color:'var(--sitm-teal-deep)',lineHeight:1}}>{matches.toLocaleString()}</div>
          <div style={{fontSize:12,color:'var(--sitm-text)',marginTop:3}}>questions match your filters</div>
        </div>
        <div style={{width:1,alignSelf:'stretch',background:'var(--sitm-border)'}}></div>
        <div style={{fontSize:13,lineHeight:1.55,flex:1}}>
          The studio will pick <b>{countNum || '...'}</b> of them, <span style={{textTransform:'lowercase'}}>{f.order === 'Mix them up' ? 'mixed up so no two sets are alike' : f.order.toLowerCase()}</span>.
          {matches > 0 && countNum >= matches && ' That is all of them.'}
        </div>
      </div>
      <div style={{background:'#fff',border:'1px solid var(--sitm-border)',borderRadius:12,overflow:'hidden'}}>
        <button onClick={()=>setF({...f,manual:!f.manual})} style={{display:'flex',alignItems:'center',gap:10,width:'100%',textAlign:'left',background:'none',border:'none',cursor:'pointer',padding:'15px 20px',fontFamily:'var(--sitm-font-body)'}}>
          <span style={{width:34,height:19,borderRadius:10,flex:'none',position:'relative',transition:'background .2s ease',background:f.manual?'var(--sitm-teal)':'rgba(62,71,97,.25)'}}>
            <span style={{position:'absolute',top:2,left:f.manual?17:2,width:15,height:15,borderRadius:'50%',background:'#fff',transition:'left .2s ease'}}></span>
          </span>
          <span style={{fontSize:13.5,fontWeight:600,color:'var(--sitm-navy)'}}>Pick the questions myself</span>
          <span style={{fontSize:12.5,color:'var(--sitm-text)'}}>Optional. Otherwise the studio picks for you.</span>
        </button>
        {f.manual && <div style={{borderTop:'1px solid var(--sitm-border)'}}>
          <div style={{padding:'10px 20px',fontSize:12,color:'var(--sitm-text)',background:'var(--sitm-bg-light-dim)'}}>Showing the first {pool.length} matches. Checked questions go in first, then the studio fills up to your count.</div>
          <div style={{maxHeight:340,overflow:'auto'}}>
            {pool.map(q => { const on = picked.includes(q.id);
              return <label key={q.id} style={{display:'flex',gap:12,alignItems:'flex-start',padding:'12px 20px',borderTop:'1px solid var(--sitm-border)',cursor:'pointer',background:on?'rgba(97,189,183,.06)':'#fff'}}>
                <span onClick={(e)=>{e.preventDefault();setPicked(on?picked.filter(x=>x!==q.id):[...picked,q.id]);}}
                  style={{width:17,height:17,flex:'none',marginTop:1,boxSizing:'border-box',border:on?'1px solid var(--sitm-teal)':'1px solid rgba(62,71,97,.35)',background:on?'var(--sitm-teal)':'#fff',display:'flex',alignItems:'center',justifyContent:'center',borderRadius:5}}>
                  {on && <Icon name="check" size={11} stroke={3} style={{color:'#fff'}}/>}
                </span>
                <span style={{flex:1}}>
                  <span style={{display:'block',fontSize:13.5,lineHeight:1.45,color:'var(--sitm-text-price)'}}>{q.stem}</span>
                  <span style={{display:'block',fontSize:12,color:'var(--sitm-text)',marginTop:3}}>Answer: {q.answer} &middot; {q.topic} &middot; {q.diff}</span>
                </span>
              </label>; })}
            {pool.length===0 && <div style={{padding:'22px 20px',fontSize:13,color:'var(--sitm-text)'}}>No questions match these filters. Loosen one and try again.</div>}
          </div>
        </div>}
      </div>
    </div>
  </div>;
}
function StepReview({ type, template, f, picked, templates }) {
  const D = window.CS_DATA;
  const t = D.contentTypes.find(c=>c.id===type);
  const tpl = templates.find(x=>x.id===template);
  const rows = [
    ['Making', t.name + (t.out==='HTML' ? ', saved as a web page' : ', saved as a PDF')],
    ['Look', tpl ? tpl.name : 'Not picked yet'],
    ['Questions', f.count + ' questions, ' + f.order.toLowerCase()],
    ['Filters', [f.specialty!=='All specialties'?f.specialty:null, f.topic!=='All topics'?f.topic:null, f.diff!=='Any difficulty'?f.diff:null, f.qtype!=='Any format'?f.qtype:null, f.search.trim()?('matching "'+f.search.trim()+'"'):null].filter(Boolean).join(', ') || 'None, using your whole bank'],
    ['Picked by hand', picked.length ? picked.length + ' questions go in first' : 'No, the studio picks']
  ];
  return <div style={{maxWidth:640}}>
    <H2>Ready when you are</H2>
    <Sub style={{marginTop:6,marginBottom:22}}>Here is what you asked for. Making it takes about half a minute, and it opens in the editor so you can look it over and change anything.</Sub>
    <div style={{background:'#fff',border:'1px solid var(--sitm-border)',borderRadius:12,overflow:'hidden'}}>
      {rows.map(([k,v],i)=><div key={k} style={{display:'flex',gap:16,padding:'14px 20px',borderTop:i?'1px solid var(--sitm-border)':'none'}}>
        <div style={{width:130,flex:'none',fontSize:12.5,fontWeight:600,color:'var(--sitm-teal-deep)'}}>{k}</div>
        <div style={{fontSize:13.5,color:'var(--sitm-text-price)'}}>{v}</div>
      </div>)}
    </div>
    <div style={{fontSize:12.5,color:'var(--sitm-text)',marginTop:14,display:'flex',gap:8,alignItems:'center'}}><Icon name="edit" size={14}/>An answer key comes along automatically where it makes sense.</div>
  </div>;
}
function GeneratingOverlay({ type }) {
  const D = window.CS_DATA;
  const t = D.contentTypes.find(c=>c.id===type);
  return <div style={{position:'fixed',inset:0,zIndex:110,background:'rgba(255,255,255,.96)',display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:18}}>
    <div className="cs-spin" style={{width:46,height:46,border:'4px solid rgba(97,189,183,.25)',borderTopColor:'var(--sitm-teal)',borderRadius:'50%'}}></div>
    <div style={{fontFamily:'var(--sitm-font-heading)',fontSize:22,color:'var(--sitm-navy)'}}>Putting your {t.name.toLowerCase()} together</div>
    <div style={{fontSize:13.5,color:'var(--sitm-text)'}}>Picking questions, pouring them into the template, checking the layout.</div>
  </div>;
}
function CreatePage({ initialType, initialTemplate, go, toast, templates, addTemplate }) {
  const D = window.CS_DATA;
  const [step,setStep] = React.useState(initialTemplate?2:initialType?1:0);
  const [maxVisited,setMaxVisited] = React.useState(initialTemplate?2:initialType?1:0);
  const [type,setType] = React.useState(initialType||null);
  const [template,setTemplate] = React.useState(initialTemplate||null);
  const [f,setF] = React.useState({search:'',specialty:'Physics',topic:'All topics',diff:'Any difficulty',qtype:'Any format',count:'10',order:'Mix them up',manual:false});
  const [picked,setPicked] = React.useState([]);
  const [working,setWorking] = React.useState(false);
  const jump = (i)=>{ setStep(i); setMaxVisited(Math.max(maxVisited,i)); };
  const canNext = step===0 ? !!type : step===1 ? !!template : step===2 ? (parseInt(f.count)>0) : true;
  const next = ()=>{ if (step<3) jump(step+1); };
  const make = ()=>{ setWorking(true); setTimeout(()=>{ setWorking(false);
    go('editor',{ made:{ type, template, f, picked } }); toast('Done. Look it over, then save it.'); }, 1800); };
  React.useEffect(()=>{ if(type){ const list=templates.filter(x=>x.types.includes(type)); if(!list.find(x=>x.id===template)) setTemplate(null);} },[type]);
  return <div style={{maxWidth:1240,margin:'0 auto',padding:'32px 28px 120px'}}>
    <PageHead kicker="Make materials" title="Make study materials"/>
    <StepBar step={step} maxVisited={maxVisited} onJump={jump}/>
    {step===0 && <StepType sel={type} onSel={(t)=>{setType(t);}}/>}
    {step===1 && <StepTemplate type={type} sel={template} onSel={setTemplate} templates={templates} onUploadSaved={addTemplate} toast={toast}/>}
    {step===2 && <StepQuestions type={type} f={f} setF={setF} picked={picked} setPicked={setPicked}/>}
    {step===3 && <StepReview type={type} template={template} f={f} picked={picked} templates={templates}/>}
    <div style={{position:'fixed',left:0,right:0,bottom:0,background:'#fff',borderTop:'1px solid var(--sitm-border)',zIndex:30}}>
      <div style={{maxWidth:1240,margin:'0 auto',padding:'14px 28px',display:'flex',alignItems:'center',gap:12}}>
        {step>0 ? <Btn kind="ghost" icon="chevL" onClick={()=>setStep(step-1)}>Back</Btn> : <span></span>}
        <div style={{flex:1,fontSize:12.5,color:'var(--sitm-text)'}}>
          {step===0 && !type && 'Pick one to keep going.'}
          {step===1 && !template && 'Pick a look, or add your own.'}
          {step===1 && template && 'You can change anything in the editor later.'}
          {step===2 && 'Good enough is fine here. Nothing is final until you save.'}
        </div>
        {step<3 ? <Btn disabled={!canNext} onClick={next}>Continue</Btn>
          : <Btn size="lg" icon="spark" onClick={make}>Make it</Btn>}
      </div>
    </div>
    {working && <GeneratingOverlay type={type}/>}
  </div>;
}
Object.assign(window, { CreatePage });
