/* ===========================================================
   Reiktable — Combat (initiative tracker) + Bestiary
   Exposes (window): CombatView, BestiaryView, addToCombat
   =========================================================== */
(function () {
  const { useState } = React;

  function ensureCombat(s) {
    if (!s.combat) s.combat = { active: false, round: 1, turn: 0, combatants: [] };
    return s.combat;
  }

  window.addToCombat = function (entry) {
    window.Store.update(s => {
      ensureCombat(s);
      s.combat.combatants.push({
        id: window.WFRP.ID(), name: entry.name, init: entry.init || 0,
        w: { cur: entry.w || 10, max: entry.w || 10 }, color: entry.color || "#5e6878",
        kind: entry.kind || "npc", conditions: [], down: false, note: entry.note || "",
      });
    });
    window.toast(`${entry.name} added to combat`, "grn");
  };

  // ---------------- Combat View ----------------
  window.CombatView = function () {
    const [s, update] = window.useStore();
    const combat = s.combat || { active: false, round: 1, turn: 0, combatants: [] };
    const [addOpen, setAddOpen] = useState(false);

    const sorted = [...combat.combatants].sort((a, b) => b.init - a.init);
    const activeId = sorted[combat.turn % Math.max(1, sorted.length)]?.id;

    function nextTurn() {
      update(s => {
        const c = ensureCombat(s);
        const n = c.combatants.length; if (!n) return;
        c.turn = (c.turn + 1);
        if (c.turn >= n) { c.turn = 0; c.round += 1; }
      });
    }
    function rollInit() {
      update(s => {
        const c = ensureCombat(s);
        c.combatants.forEach(m => {
          const pc = s.characters.find(x => x.id === m.srcId);
          let ib = 3;
          if (pc) ib = window.WFRP.bonus(window.charTotal(pc.chars, "I"));
          else if (m.iBonus != null) ib = m.iBonus;
          m.init = ib + Math.floor(Math.random() * 10) + 1;
        });
        c.turn = 0; c.round = 1;
      });
      window.toast("Initiative rolled", "grn");
    }
    function setHP(id, d) { update(s => { const m = ensureCombat(s).combatants.find(x => x.id === id); if (m) { m.w.cur = Math.max(0, Math.min(m.w.max, m.w.cur + d)); m.down = m.w.cur <= 0; } }); }
    function setInit(id, v) { update(s => { const m = ensureCombat(s).combatants.find(x => x.id === id); if (m) m.init = v; }); }
    function remove(id) { update(s => { ensureCombat(s).combatants = s.combat.combatants.filter(x => x.id !== id); }); }
    function toggleCond(id, cond) {
      update(s => { const m = ensureCombat(s).combatants.find(x => x.id === id); if (!m) return; m.conditions = m.conditions.includes(cond) ? m.conditions.filter(c => c !== cond) : [...m.conditions, cond]; });
    }
    function clearAll() { update(s => { s.combat = { active: false, round: 1, turn: 0, combatants: [] }; }); }

    const CONDS = ["Prone", "Stunned", "Bleeding", "Broken", "Entangled", "Blinded", "Fatigued", "Surprised"];

    return (
      <div className="content fade-in">
        <div className="page-h">
          <div><h1>Combat Tracker</h1><p>Initiative order, wounds and conditions for the whole encounter.</p></div>
          <div className="sp"></div>
          <Btn icon="users" onClick={() => setAddOpen(true)}>Add Combatant</Btn>
          <Btn icon="refresh" onClick={rollInit}>Roll Initiative</Btn>
          <Btn className="pri" icon="chevR" onClick={nextTurn}>Next Turn</Btn>
        </div>

        <div className="between card" style={{ padding: "12px 16px", marginBottom: 14 }}>
          <div className="center g16">
            <div><div className="eyebrow">Round</div><div className="mono" style={{ fontSize: 24, color: "var(--amb)" }}>{combat.round}</div></div>
            <div className="divider" style={{ width: 1, height: 36, margin: 0 }}></div>
            <div><div className="eyebrow">Combatants</div><div className="mono" style={{ fontSize: 24 }}>{combat.combatants.length}</div></div>
            {sorted[combat.turn % Math.max(1, sorted.length)] && (
              <><div className="divider" style={{ width: 1, height: 36, margin: 0 }}></div>
                <div><div className="eyebrow">Active</div><div style={{ fontSize: 18, color: "var(--acc-2)", fontWeight: 600 }}>{sorted[combat.turn % sorted.length].name}</div></div></>
            )}
          </div>
          <Btn className="ghost danger sm" icon="trash" onClick={clearAll}>End Encounter</Btn>
        </div>

        {combat.combatants.length === 0 ? (
          <Empty icon="swords" title="No combatants">Add the party and some foes, then roll initiative.</Empty>
        ) : (
          <div className="col g8">
            {sorted.map(m => (
              <div key={m.id} className={cls("combatant", m.id === activeId && "active", m.down && "down")}>
                <input className="input num sm" style={{ width: 44 }} value={m.init} onChange={e => setInit(m.id, parseInt(e.target.value || 0))} title="Initiative" />
                <Avatar name={m.name} color={m.color} size="sm" />
                <div className="grow">
                  <div className="center g8"><span className="nm">{m.name}</span>{m.kind === "pc" ? <span className="tag acc">PC</span> : <span className="tag">NPC</span>}{m.down && <span className="tag red">Down</span>}</div>
                  {m.conditions.length > 0 && <div className="center g6 wrap" style={{ marginTop: 5 }}>{m.conditions.map(c => <span key={c} className="tag amb" onClick={() => toggleCond(m.id, c)} style={{ cursor: "pointer" }}>{c} ✕</span>)}</div>}
                </div>
                <div className="center g10">
                  <div className="hp-ctrl">
                    <button onClick={() => setHP(m.id, -1)}>−</button>
                    <span style={{ minWidth: 54, textAlign: "center", color: m.w.cur <= m.w.max * 0.33 ? "var(--red)" : "var(--tx)" }}>{m.w.cur}/{m.w.max}</span>
                    <button onClick={() => setHP(m.id, +1)}>+</button>
                  </div>
                  <details style={{ position: "relative" }}>
                    <summary className="btn icon sm" style={{ listStyle: "none" }}><Icon name="bolt" size={14} /></summary>
                    <div className="card" style={{ position: "absolute", right: 0, top: 32, zIndex: 10, width: 200, padding: 8 }}>
                      <div className="eyebrow" style={{ padding: "2px 4px 6px" }}>Conditions</div>
                      <div className="center wrap g6">{CONDS.map(c => <span key={c} className={cls("tag", m.conditions.includes(c) ? "amb" : "")} style={{ cursor: "pointer" }} onClick={() => toggleCond(m.id, c)}>{c}</span>)}</div>
                    </div>
                  </details>
                  <button className="btn icon sm ghost" onClick={() => remove(m.id)}><Icon name="x" size={14} /></button>
                </div>
              </div>
            ))}
          </div>
        )}

        {addOpen && <AddCombatant s={s} onClose={() => setAddOpen(false)} />}
      </div>
    );
  };

  function AddCombatant({ s, onClose }) {
    const [tab, setTab] = useState("party");
    const [custom, setCustom] = useState({ name: "", init: 0, w: 10 });
    function addPc(pc) {
      window.Store.update(st => {
        ensureCombat(st);
        st.combat.combatants.push({ id: window.WFRP.ID(), srcId: pc.id, name: pc.name, init: window.WFRP.bonus(window.charTotal(pc.chars, "I")), w: { cur: pc.wounds.cur, max: pc.wounds.max }, color: pc.color, kind: "pc", conditions: [], down: false });
      });
      window.toast(`${pc.name} joined the fray`, "grn");
    }
    function addBeast(b) {
      window.Store.update(st => {
        ensureCombat(st);
        st.combat.combatants.push({ id: window.WFRP.ID(), name: b.name, iBonus: Math.floor(b.i / 10), init: Math.floor(b.i / 10) + Math.floor(Math.random() * 10) + 1, w: { cur: b.w, max: b.w }, color: "#ef5f5f", kind: "npc", conditions: [], down: false });
      });
      window.toast(`${b.name} added`, "grn");
    }
    return (
      <Modal title="Add to Combat" icon="users" onClose={onClose} footer={<Btn className="ghost" onClick={onClose}>Done</Btn>}>
        <Tabs tabs={[{ k: "party", label: "Party" }, { k: "bestiary", label: "Bestiary" }, { k: "custom", label: "Custom" }]} active={tab} onChange={setTab} />
        <div style={{ marginTop: 14 }}>
          {tab === "party" && <div className="col g8">{s.characters.map(pc => (
            <div key={pc.id} className="between row b"><div className="center g10"><Avatar name={pc.name} color={pc.color} size="sm" /><span>{pc.name}</span><span className="tx3" style={{ fontSize: 12 }}>W {pc.wounds.cur}/{pc.wounds.max}</span></div><Btn className="sm" icon="plus" onClick={() => addPc(pc)}>Add</Btn></div>
          ))}</div>}
          {tab === "bestiary" && <div className="col g8">{(s.bestiary || []).map(b => (
            <div key={b.id} className="between row b"><div className="center g10"><span>{b.name}</span><span className="tx3" style={{ fontSize: 12 }}>W {b.w} · I {b.i}</span></div><Btn className="sm" icon="plus" onClick={() => addBeast(b)}>Add</Btn></div>
          ))}{(s.bestiary || []).length === 0 && <div className="tx3">Bestiary is empty.</div>}</div>}
          {tab === "custom" && <div className="col g10">
            <Field label="Name"><input className="input" value={custom.name} onChange={e => setCustom({ ...custom, name: e.target.value })} placeholder="Bandit, Wolf…" /></Field>
            <div className="grid g2"><Field label="Initiative"><input className="input num" value={custom.init} onChange={e => setCustom({ ...custom, init: parseInt(e.target.value || 0) })} /></Field>
              <Field label="Wounds"><input className="input num" value={custom.w} onChange={e => setCustom({ ...custom, w: parseInt(e.target.value || 0) })} /></Field></div>
            <Btn className="pri" icon="plus" onClick={() => { if (custom.name.trim()) { window.addToCombat({ name: custom.name, init: custom.init, w: custom.w }); setCustom({ name: "", init: 0, w: 10 }); } }}>Add Combatant</Btn>
          </div>}
        </div>
      </Modal>
    );
  }

  // ---------------- Bestiary ----------------
  window.BestiaryView = function () {
    const [s, update] = window.useStore();
    const list = s.bestiary || [];
    const [edit, setEdit] = useState(null);
    const blank = { name: "", type: "Monster", ws: 30, bs: 0, s: 30, t: 30, i: 30, ag: 30, w: 10, m: 4, traits: "", note: "" };

    function save(b) {
      update(st => {
        if (!st.bestiary) st.bestiary = [];
        const i = st.bestiary.findIndex(x => x.id === b.id);
        if (i >= 0) st.bestiary[i] = b; else st.bestiary.push({ ...b, id: window.WFRP.ID() });
      });
      setEdit(null); window.toast("Saved to bestiary", "grn");
    }
    function del(id) { update(st => { st.bestiary = st.bestiary.filter(x => x.id !== id); }); }

    return (
      <div className="content fade-in">
        <div className="page-h">
          <div><h1>Bestiary</h1><p>Stat blocks for the foes and beasts of your campaign.</p></div>
          <div className="sp"></div>
          <Btn className="pri" icon="plus" onClick={() => setEdit({ ...blank, id: null })}>New Entry</Btn>
        </div>
        {list.length === 0 ? <Empty icon="skull" title="Empty bestiary">Add monsters and beasts to drop them into combat fast.</Empty> : (
          <div className="grid g2">
            {list.map(b => (
              <div key={b.id} className="card">
                <div className="card-h"><Icon name={b.type === "Beast" ? "paw" : "skull"} /><h3>{b.name}</h3><span className="tag">{b.type}</span>
                  <div className="sp"></div>
                  <button className="btn icon sm ghost" onClick={() => setEdit(b)}><Icon name="edit" size={14} /></button>
                  <button className="btn icon sm ghost" onClick={() => window.addToCombat({ name: b.name, init: Math.floor(b.i / 10) + 5, w: b.w, color: "#ef5f5f" })} title="Add to combat"><Icon name="swords" size={14} /></button>
                  <button className="btn icon sm danger" onClick={() => del(b.id)}><Icon name="trash" size={14} /></button>
                </div>
                <div className="card-b">
                  <div className="chars" style={{ gridTemplateColumns: "repeat(8,1fr)" }}>
                    {[["WS", b.ws], ["BS", b.bs], ["S", b.s], ["T", b.t], ["I", b.i], ["Ag", b.ag], ["W", b.w], ["M", b.m]].map(([k, v]) => (
                      <div key={k} className="ch"><div className="nm">{k}</div><div className="v" style={{ fontSize: 18 }}>{v}</div></div>
                    ))}
                  </div>
                  {b.traits && <div className="mt10"><span className="eyebrow">Traits</span><div className="tx2" style={{ fontSize: 13.5 }}>{b.traits}</div></div>}
                  {b.note && <div className="tx3 mt6" style={{ fontSize: 13 }}>{b.note}</div>}
                </div>
              </div>
            ))}
          </div>
        )}
        {edit && <BeastEdit b={edit} onSave={save} onClose={() => setEdit(null)} />}
      </div>
    );
  };

  function BeastEdit({ b, onSave, onClose }) {
    const [d, setD] = useState(b);
    const set = (k, v) => setD({ ...d, [k]: v });
    const num = ["ws", "bs", "s", "t", "i", "ag", "w", "m"];
    return (
      <Modal title={b.id ? "Edit Entry" : "New Bestiary Entry"} icon="skull" onClose={onClose} size="lg"
        footer={<><Btn className="ghost" onClick={onClose}>Cancel</Btn><Btn className="pri" icon="check" onClick={() => d.name.trim() && onSave(d)}>Save</Btn></>}>
        <div className="grid g2" style={{ marginBottom: 14 }}>
          <Field label="Name"><input className="input" value={d.name} onChange={e => set("name", e.target.value)} /></Field>
          <Field label="Type"><select className="input" value={d.type} onChange={e => set("type", e.target.value)}><option>Monster</option><option>Beast</option><option>Humanoid</option><option>Undead</option><option>Daemon</option></select></Field>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginBottom: 14 }}>
          {num.map(k => <Field key={k} label={k.toUpperCase()}><input className="input num" value={d[k]} onChange={e => set(k, parseInt(e.target.value || 0))} /></Field>)}
        </div>
        <Field label="Traits"><input className="input" value={d.traits} onChange={e => set("traits", e.target.value)} placeholder="Weapon+7, Night Vision, Infected…" /></Field>
        <div className="mt10"><Field label="Notes"><textarea className="textarea" value={d.note} onChange={e => set("note", e.target.value)} /></Field></div>
      </Modal>
    );
  }
})();
