/* cli-sim.jsx — Cisco IOS CLI Simulator component */

function normC(s){ return s.trim().toLowerCase().replace(/\s+/g,' '); }

function CLISimulator({ question:q, onComplete, submitted, onLearnTopic, onSkip }) {
  const [history,setHistory]=React.useState([]);
  const [input,setInput]=React.useState('');
  const [stepIdx,setStepIdx]=React.useState(0);
  const [done,setDone]=React.useState(false);
  const [showHint,setShowHint]=React.useState(false);
  const [cmdHist,setCmdHist]=React.useState([]);
  const [histPtr,setHistPtr]=React.useState(-1);
  const termRef=React.useRef(null);
  const inputRef=React.useRef(null);

  React.useEffect(()=>{
    if(termRef.current) termRef.current.scrollTop=termRef.current.scrollHeight;
    if(!done && !submitted) inputRef.current?.focus();
  },[history,done]);

  const step=q.steps[stepIdx];
  const curPrompt=step?.pb||(q.steps[q.steps.length-1]?.pa||'R1#');

  function submit(cmdOverride){
    const cmd = cmdOverride!==undefined ? cmdOverride : input.trim();
    if(!cmd)return;
    if(cmdOverride===undefined){
      setCmdHist(h=>[cmd,...h].slice(0,30));
      setHistPtr(-1); setInput('');
    } else {
      setHistPtr(-1); setInput('');
    }
    if(!step||done)return;

    if(cmd==='?'){
      setHistory(h=>[...h,{prompt:curPrompt,cmd,out:`\n  Hint: ${step.hint||'Enter the expected command.'}`,type:'help'}]);
      return;
    }

    // Ctrl-Z aliases → treat as 'end' (IOS standard)
    const ctrlZAliases = ['^z','ctrl-z','cntl-z','ctrl/z','cntl/z','ctrlz','cntlz','^[z'];
    const isCtrlZ = ctrlZAliases.includes(cmd.toLowerCase().trim());

    const ok = step.accept.some(a=>normC(cmd)===normC(a))
            || (isCtrlZ && step.accept.some(a=>['end','exit'].includes(normC(a))));
    if(ok){
      setHistory(h=>[...h,{prompt:curPrompt,cmd,out:step.out||'',type:'ok'}]);
      if(stepIdx===q.steps.length-1){
        setDone(true);
        onComplete&&onComplete(true);
      } else {
        setStepIdx(i=>i+1);
      }
    } else {
      const spaces=' '.repeat(Math.min(curPrompt.length+cmd.length,36));
      setHistory(h=>[...h,{prompt:curPrompt,cmd,out:`${spaces}^\n% Invalid input detected at '^' marker.\n\nType '?' for a list of commands.`,type:'err'}]);
    }
  }

  function keyDown(e){
    if(e.key==='Enter'){e.preventDefault();submit();}
    else if(e.key==='ArrowUp'){e.preventDefault();const i=Math.min(histPtr+1,cmdHist.length-1);setHistPtr(i);setInput(cmdHist[i]||'');}
    else if(e.key==='ArrowDown'){e.preventDefault();const i=Math.max(histPtr-1,-1);setHistPtr(i);setInput(i===-1?'':cmdHist[i]||'');}
    else if((e.key==='z'||e.key==='Z')&&(e.ctrlKey||e.metaKey)){e.preventDefault();submit('^Z');}
    else if(e.key==='Tab'){e.preventDefault(); /* could add tab completion */ }
  }

  function resetSim(){setHistory([]);setStepIdx(0);setDone(false);setInput('');setHistPtr(-1);}

  const pctDone=done?100:Math.round((stepIdx/q.steps.length)*100);

  return(
    <div className="cli-sim">
      {/* Task card */}
      <div className="cli-task-card">
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:'12px'}}>
          <div>
            <div className="cli-task-label">▶ Task</div>
            <div className="cli-task-text">{q.task}</div>
            {onLearnTopic&&(
              <button className="btn btn-ghost btn-sm" onClick={onLearnTopic}
                style={{marginTop:'10px',color:'var(--cyan)',borderColor:'var(--border)'}}>
                📖 Read about it →
              </button>
            )}
          </div>
          <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:'4px',flexShrink:0}}>
            <div className="cli-step-pips">
              {q.steps.map((_,i)=>(
                <div key={i} className={`cli-pip ${i<stepIdx||done?'done':i===stepIdx&&!done?'active':''}`}/>
              ))}
            </div>
            <div style={{fontSize:'11px',color:'var(--fg-mute)'}}>{done?'Complete':stepIdx+1+'/'+q.steps.length}</div>
          </div>
        </div>
        {/* progress bar */}
        <div className="cli-prog"><div className="cli-prog-fill" style={{width:pctDone+'%'}}/></div>
      </div>

      {/* Terminal window */}
      <div className="cli-terminal" ref={termRef} onClick={()=>!done&&!submitted&&inputRef.current?.focus()}>
        <div className="cli-boot">
          <span style={{color:'var(--green)'}}>Cisco IOS</span>
          <span style={{color:'var(--fg-mute)'}}> — Type ? for help, ↑↓ for history</span>
        </div>
        {history.map((h,i)=>(
          <div key={i} className="cli-entry">
            <div className="cli-cmd-line">
              <span className="cli-prompt">{h.prompt}</span>
              <span className={`cli-cmd-text ${h.type==='err'?'cli-cmd-err':''}`}>{h.cmd}</span>
            </div>
            {h.out&&<pre className={`cli-pre ${h.type==='err'?'cli-pre-err':h.type==='help'?'cli-pre-help':''}`}>{h.out}</pre>}
          </div>
        ))}
        {done&&<div className="cli-success-line"><span style={{color:'var(--green)'}}>✓</span> All steps complete!</div>}
        {!done&&!submitted&&(
          <div className="cli-input-line">
            <span className="cli-prompt">{curPrompt}</span>
            <input ref={inputRef} className="cli-input-field" value={input}
              onChange={e=>setInput(e.target.value)} onKeyDown={keyDown}
              style={{width:Math.max(input.length,0)+'ch'}}
              spellCheck={false} autoComplete="off" autoCorrect="off" autoCapitalize="off"/>
            <span className="cli-cursor-block"/>
          </div>
        )}
        {submitted&&!done&&<div style={{color:'var(--fg-mute)',fontSize:'12px',padding:'6px 0'}}>-- session ended --</div>}
      </div>

      {/* Bottom bar */}
      <div style={{display:'flex',gap:'8px',marginTop:'10px',alignItems:'center'}}>
        {!done&&!submitted&&<button className="btn btn-ghost btn-sm" onClick={()=>setShowHint(h=>!h)}>{showHint?'Hide hint':'Hint'}</button>}
        {!submitted&&<button className="btn btn-ghost btn-sm" onClick={resetSim}>Reset</button>}
        {onSkip&&!done&&!submitted&&<button className="btn btn-ghost btn-sm" onClick={onSkip} style={{marginLeft:'auto'}}>Skip →</button>}
      </div>

      {showHint&&!done&&step&&(
        <div className="hint-item" style={{marginTop:'8px'}}>
          <span className="hint-num">Step {stepIdx+1} hint</span>
          {step.hint}
        </div>
      )}

      {done&&(
        <div className="q-feedback" style={{marginTop:'10px'}}>
          <div className="fb-head ok">✓ Task Complete</div>
          <div className="fb-text">{q.exp}</div>
        </div>
      )}
    </div>
  );
}

Object.assign(window,{CLISimulator});
