/* ============================================================
   Builder wizard — steps 6-8 (Equipment, Spells, Review)
   ============================================================ */

/* ---------------- STEP 6: EQUIPMENT ---------------- */
function EquipmentStep({ char, patch }){
  const cls = DND.klass(char.classKey);
  const bg = DND.background(char.backgroundKey);
  const gear = char.gear || { armor:"(None)", shield:false, weapons:[] };
  const pkg = char.equipPackage || "A";
  const ac = DND.armorClass(char);

  const setGear = (g)=>patch({ gear:{...gear, ...g} });
  const armorAllowed = (a)=>{
    // basic gating by class proficiency
    const k = char.classKey;
    if (a.type==="none") return true;
    if (["wizard","sorcerer"].includes(k)) return false;
    if (["monk"].includes(k)) return false;
    if (["bard","rogue","warlock","druid"].includes(k)) return a.type==="light" || (k==="druid"&&a.type==="medium");
    if (["ranger"].includes(k)) return a.type!=="heavy";
    if (["barbarian"].includes(k)) return a.type!=="heavy";
    if (["cleric"].includes(k)) return a.type!=="heavy";
    return true; // fighter, paladin
  };
  const toggleWeapon = (name)=>{
    const has = gear.weapons.includes(name);
    setGear({ weapons: has ? gear.weapons.filter(w=>w!==name) : [...gear.weapons, name] });
  };

  return (
    <div>
      <StepHeader eyebrow="Step 6 · Equipment" title="Gear up"
        sub="Choose a starting equipment package, then set the armor and weapons your sheet should track. AC and attack rolls update live." />

      <SectionCap>Class equipment — {cls?cls.name:""}</SectionCap>
      <div className="opt-grid cols-2">
        {(cls?cls.equipment:[]).map((e,i)=>{
          const letter = e.trim()[0];
          return (
            <button key={i} className={"opt"+(pkg===letter?" sel":"")} onClick={()=>patch({ equipPackage:letter })}>
              <span className="o-check"><Ic.check/></span>
              <div className="o-name" style={{fontSize:15}}>Option {letter}</div>
              <div className="o-blurb">{e.replace(/^[AB]\s—\s/,"")}</div>
            </button>
          );
        })}
      </div>

      <SectionCap>Background equipment — {bg?bg.name:""}</SectionCap>
      <Callout>{bg?bg.equipment:""} <b>— or take 50 GP instead.</b></Callout>

      <SectionCap>Sheet loadout · live AC <span className="tag acc" style={{marginLeft:8,fontFamily:"var(--mono)"}}>AC {ac.value} · {ac.label}</span></SectionCap>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:18,alignItems:"start"}} className="loadout-grid">
        <div>
          <div className="hint" style={{marginBottom:7}}>Armor</div>
          <select value={gear.armor} onChange={e=>setGear({armor:e.target.value})}>
            {DND.ARMOR.filter(armorAllowed).map(a=>(
              <option key={a.name} value={a.name}>{a.name}{a.type!=="none"?` (${a.type})`:""}</option>
            ))}
          </select>
          {!["wizard","sorcerer","monk"].includes(char.classKey) && (
            <label style={{display:"flex",alignItems:"center",gap:9,marginTop:12,fontSize:14,color:"var(--ink-2)"}}>
              <input type="checkbox" checked={!!gear.shield} style={{width:"auto"}} onChange={e=>setGear({shield:e.target.checked})} />
              Carry a Shield (+2 AC)
            </label>
          )}
        </div>
        <div>
          <div className="hint" style={{marginBottom:7}}>Weapons (tap to add/remove)</div>
          <div className="chip-row">
            {DND.WEAPONS.filter(w=>!w.unarmed).map(w=>(
              <Chip key={w.name} label={w.name} on={gear.weapons.includes(w.name)} dot={gear.weapons.includes(w.name)}
                onClick={()=>toggleWeapon(w.name)} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- STEP 7: SPELLS ---------------- */
function SpellsStep({ char, patch }){
  const cls = DND.klass(char.classKey);
  const sc = cls && cls.spellcasting;
  if (!sc){
    return (
      <div>
        <StepHeader eyebrow="Step 7 · Spells" title="No spells to prepare"
          sub={`${cls?cls.name:"This class"} doesn't cast spells at level 1. You can skip ahead — though your background's Origin feat may grant a cantrip or two.`} />
        <div style={{marginTop:24}}><Callout>Martial classes shine through Weapon Mastery, Fighting Styles, and class features rather than spell slots. Onward to review!</Callout></div>
      </div>
    );
  }
  const lists = DND.CLASS_SPELLS[sc.list] || { cantrips:[], level1:[] };
  const nCantrip = DND.cantripsKnownFor(char);
  const nSpell = DND.spellsToPick(char);
  const cantrips = char.cantrips || [];
  const spells = char.spells || [];
  const verb = sc.type.includes("Prepared") ? "prepare" : "know";

  const toggle = (arr, key, max, name)=>{
    const has = arr.includes(name);
    const next = has ? arr.filter(n=>n!==name) : (arr.length<max?[...arr,name]:arr);
    patch({ [key]: next });
  };

  const SpellList = ({title, names, picked, max, keyName})=>(
    <div>
      <SectionCap>{title} — choose {max} <span style={{color:picked.length===max?"var(--good)":"var(--accent)",marginLeft:8}}>({picked.length}/{max})</span></SectionCap>
      <div className="opt-grid cols-2">
        {names.map(name=>{
          const s = DND.SPELLBOOK[name]||{};
          const on = picked.includes(name);
          const full = picked.length>=max && !on;
          return (
            <button key={name} className={"opt"+(on?" sel":"")+(full?" ":"")} style={full?{opacity:.5}:{}}
              onClick={()=>!full && toggle(picked, keyName, max, name)}>
              <span className="o-check"><Ic.check/></span>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8}}>
                <div className="o-name" style={{fontSize:15}}>{name}</div>
                <span className="o-meta">{s.school}</span>
              </div>
              <div className="o-blurb">{s.text}</div>
            </button>
          );
        })}
      </div>
    </div>
  );

  return (
    <div>
      <StepHeader eyebrow="Step 7 · Spells" title={`Choose your spells`}
        sub={`As a ${cls.name}, you ${verb} spells with ${abilName(sc.ability)}. Pick your starting cantrips and level-1 spells.`} />
      {char.level>=2 && (()=>{ const ss=DND.spellSlots(char); return (
        <div style={{marginTop:18}}><Callout>At level {char.level} you have {ss.pact?`${ss.n} Pact Magic slot(s) of level ${ss.level}`:`spell slots: ${ss.slots.map((n,i)=>`${n}×L${i+1}`).join(", ")}`}. This builder curates <b>cantrips and level-1 spells</b>; track higher-level prepared spells in your sheet's Notes.</Callout></div>
      ); })()}
      {nCantrip>0 && <SpellList title="Cantrips" names={lists.cantrips} picked={cantrips} max={nCantrip} keyName="cantrips" />}
      <SpellList title="Level 1 spells" names={lists.level1} picked={spells} max={nSpell} keyName="spells" />
    </div>
  );
}

/* ---------------- STEP 8: REVIEW ---------------- */
function ReviewStep({ char, patch, openSheet }){
  const cls=DND.klass(char.classKey), sp=DND.species(char.speciesKey), bg=DND.background(char.backgroundKey);
  const final = DND.finalScores(char);
  const ac = DND.armorClass(char), hp = DND.maxHp(char);
  const sc = DND.spellStats(char);
  const need = cls?cls.skillCount:0;
  const issues = [];
  if (!cls) issues.push("Choose a class");
  if (cls && char.level>=DND.SUBCLASS_LEVEL && !char.subclass) issues.push(`Choose your ${DND.SUBCLASS_LABEL[cls.key]} (level 3+)`);
  if (!sp) issues.push("Choose a species");
  if (sp && sp.choice && !(char.speciesChoice||{})[sp.choice.id]) issues.push(`Pick your ${sp.choice.label}`);
  if (sp && sp.key==="elf" && !char.elfKeenSense) issues.push("Pick a Keen Senses skill");
  if (sp && sp.key==="human" && !char.humanSkill) issues.push("Pick your Human skill");
  if (!bg) issues.push("Choose a background");
  if (bg && !char.asiMode) issues.push("Apply your background ability increase");
  if (bg && char.asiMode==="2-1" && (!char.asiPrimary||!char.asiSecondary)) issues.push("Finish your +2 / +1 increase");
  if ((char.classSkills||[]).length<need) issues.push(`Choose ${need-(char.classSkills||[]).length} more class skill(s)`);
  if (char.classKey==="rogue" && (char.expertise||[]).length<2) issues.push("Choose 2 Expertise skills");
  if (cls && cls.spellcasting){
    if ((char.cantrips||[]).length<DND.cantripsKnownFor(char)) issues.push("Choose your cantrips");
    if ((char.spells||[]).length<DND.spellsToPick(char)) issues.push("Choose your level-1 spells");
  }
  const ready = issues.length===0;

  return (
    <div>
      <StepHeader eyebrow="Step 8 · Review" title="Your hero, at a glance"
        sub="A final check before the sheet. Edit your name and alignment, then open your character sheet." />

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14,marginTop:22}} className="loadout-grid">
        <div>
          <div className="hint" style={{marginBottom:7}}>Character name</div>
          <input type="text" placeholder="e.g. Brenna Stormhand" value={char.name||""} onChange={e=>patch({name:e.target.value})} />
        </div>
        <div>
          <div className="hint" style={{marginBottom:7}}>Alignment</div>
          <select value={char.alignment} onChange={e=>patch({alignment:e.target.value})}>
            {DND.ALIGNMENTS.map(a=><option key={a}>{a}</option>)}
          </select>
        </div>
      </div>

      <SectionCap>Summary</SectionCap>
      <div className="detail">
        <div className="kv"><span className="k">Identity</span><span className="v">Level {char.level} {sp?sp.name:"—"} {cls?cls.name:"—"}{char.subclass?` (${DND.subclass(cls.key,char.subclass).name})`:""} · {bg?bg.name:"—"}</span></div>
        <div className="kv"><span className="k">Ability Scores</span><span className="v mono">{ABK.map(k=>`${k.toUpperCase()} ${final[k]} (${DND.fmt(DND.mod(final[k]))})`).join("   ")}</span></div>
        <div className="kv"><span className="k">Combat</span><span className="v">AC {ac.value} · {hp} HP · Init {DND.fmt(DND.initiative(char))} · Speed {DND.speed(char)} ft · Prof {DND.fmt(DND.profBonus(DND.totalLevel(char)))}</span></div>
        {sc && <div className="kv"><span className="k">Spellcasting</span><span className="v">{abilName(sc.ability)} · Save DC {sc.dc} · Atk {sc.atk}</span></div>}
        {bg && <div className="kv"><span className="k">Origin Feat</span><span className="v">{bg.feat}</span></div>}
      </div>

      {!ready && (
        <div style={{marginTop:18}}>
          <Callout amber>
            <b>A few things left:</b>
            <ul style={{margin:"8px 0 0",paddingLeft:18}}>{issues.map((x,i)=><li key={i} style={{marginBottom:3}}>{x}</li>)}</ul>
          </Callout>
        </div>
      )}

      <div style={{marginTop:26,display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"}}>
        <button className="btn primary lg" disabled={!ready} onClick={openSheet}><Ic.sheet/> Open character sheet</button>
        {ready && <span className="hint">Everything checks out — your sheet is ready.</span>}
      </div>
    </div>
  );
}

Object.assign(window, { EquipmentStep, SpellsStep, ReviewStep });
