/* ===================================================================
   rulebook.jsx — in-app quick reference (SRD 5.1)

   Concise, original-summary rules reference for players and DMs. Content
   is drawn from the System Reference Document 5.1, released by Wizards of
   the Coast under the Creative Commons Attribution 4.0 International
   licence (CC-BY-4.0). These are short paraphrased reminders, NOT the
   Player's Handbook text. Exposed as window.RuleBook (loaded before
   app.jsx) so the shell can open it as a modal for everyone.
   =================================================================== */
const SRD_SECTIONS = [
  {
    id: 'conditions',
    title: 'Conditions',
    blurb: 'A condition lasts until it is countered (e.g. the prone condition by standing) or for a stated duration.',
    entries: [
      { name: 'Blinded', text: 'Can’t see; auto-fails sight checks. Attacks against it have advantage; its attacks have disadvantage.' },
      { name: 'Charmed', text: 'Can’t attack the charmer; the charmer has advantage on social checks with it.' },
      { name: 'Deafened', text: 'Can’t hear; auto-fails hearing checks.' },
      { name: 'Frightened', text: 'Disadvantage on checks and attacks while the source is in sight; can’t willingly move closer to it.' },
      { name: 'Grappled', text: 'Speed 0; ends if the grappler is incapacitated or moved away.' },
      { name: 'Incapacitated', text: 'Can’t take actions or reactions.' },
      { name: 'Invisible', text: 'Heavily obscured for hiding. Attacks against it have disadvantage; its attacks have advantage.' },
      { name: 'Paralyzed', text: 'Incapacitated, can’t move/speak, auto-fails STR/DEX saves. Attacks have advantage; melee hits within 5 ft are crits.' },
      { name: 'Petrified', text: 'Turned to solid; incapacitated, weight ×10, resistant to all damage, immune to poison/disease.' },
      { name: 'Poisoned', text: 'Disadvantage on attack rolls and ability checks.' },
      { name: 'Prone', text: 'Can only crawl. Disadvantage on attacks. Melee attacks against it have advantage; ranged have disadvantage.' },
      { name: 'Restrained', text: 'Speed 0; disadvantage on DEX saves and attacks; attacks against it have advantage.' },
      { name: 'Stunned', text: 'Incapacitated, can’t move, auto-fails STR/DEX saves; attacks against it have advantage.' },
      { name: 'Unconscious', text: 'Incapacitated, prone, drops everything, auto-fails STR/DEX saves; melee hits within 5 ft are crits.' },
      { name: 'Exhaustion', text: 'Six cumulative levels, from disadvantage on checks up to death; a long rest removes one level.' },
    ],
  },
  {
    id: 'actions',
    title: 'Actions in Combat',
    blurb: 'On your turn you can move and take one action, plus a bonus action and reaction if available.',
    entries: [
      { name: 'Attack', text: 'Make one melee or ranged attack (more with the Extra Attack feature).' },
      { name: 'Cast a Spell', text: 'Cast a spell with a casting time of one action.' },
      { name: 'Dash', text: 'Gain extra movement equal to your speed for the turn.' },
      { name: 'Disengage', text: 'Your movement doesn’t provoke opportunity attacks this turn.' },
      { name: 'Dodge', text: 'Attacks against you have disadvantage; you have advantage on DEX saves. Lost if incapacitated or speed 0.' },
      { name: 'Help', text: 'Give an ally advantage on a check, or on their next attack against a foe within 5 ft of you.' },
      { name: 'Hide', text: 'Make a Stealth check to become hidden.' },
      { name: 'Ready', text: 'Choose a trigger and a prepared action/move to use as a reaction when it occurs.' },
      { name: 'Search', text: 'Make a Perception or Investigation check to find something.' },
      { name: 'Use an Object', text: 'Interact with a second object, or use one that needs an action.' },
      { name: 'Opportunity Attack', text: 'Reaction: when a foe leaves your reach, make one melee attack against it.' },
      { name: 'Two-Weapon Fighting', text: 'Bonus action: attack with a light weapon in your other hand (no ability bonus to damage unless negative).' },
    ],
  },
  {
    id: 'checks',
    title: 'Ability Checks & Skills',
    blurb: 'Roll d20 + ability modifier (+ proficiency if proficient) and compare to a Difficulty Class (DC). Typical DCs: Easy 10, Medium 15, Hard 20.',
    entries: [
      { name: 'Strength', text: 'Athletics — climbing, jumping, swimming, grappling.' },
      { name: 'Dexterity', text: 'Acrobatics, Sleight of Hand, Stealth.' },
      { name: 'Constitution', text: 'Raw stamina; rarely a skill, often a saving throw (concentration).' },
      { name: 'Intelligence', text: 'Arcana, History, Investigation, Nature, Religion.' },
      { name: 'Wisdom', text: 'Animal Handling, Insight, Medicine, Perception, Survival.' },
      { name: 'Charisma', text: 'Deception, Intimidation, Performance, Persuasion.' },
      { name: 'Passive Check', text: '10 + modifiers, used for ongoing tasks like noticing hidden threats (passive Perception).' },
      { name: 'Saving Throw', text: 'd20 + ability modifier (+ proficiency if proficient) to resist an effect.' },
      { name: 'Contest', text: 'Both sides roll a check; higher result wins (ties = no change).' },
    ],
  },
  {
    id: 'core',
    title: 'Core Rules',
    blurb: 'The fundamentals that govern most rolls and combat moments.',
    entries: [
      { name: 'Advantage / Disadvantage', text: 'Roll 2d20 and take the higher (advantage) or lower (disadvantage). Multiple sources don’t stack; if both apply, roll one d20.' },
      { name: 'Critical Hit', text: 'A natural 20 hits and you roll the attack’s damage dice twice.' },
      { name: 'Cover', text: 'Half cover +2 AC/DEX saves; three-quarters cover +5; total cover can’t be targeted directly.' },
      { name: 'Initiative', text: 'At the start of combat each creature rolls DEX (d20 + DEX mod) to set turn order.' },
      { name: 'Death Saving Throws', text: 'At 0 HP, roll d20 each turn: 10+ succeeds, under 10 fails. Three successes stabilise; three failures die. A 1 = two failures, a 20 = revive at 1 HP.' },
      { name: 'Resting', text: 'Short rest (1 hour): spend Hit Dice to heal. Long rest (8 hours): regain all HP and half your Hit Dice; removes one exhaustion level.' },
      { name: 'Concentration', text: 'Some spells require concentration; taking damage forces a CON save (DC 10 or half the damage, whichever is higher) to maintain it.' },
      { name: 'Movement', text: 'Difficult terrain costs double; standing from prone costs half your speed.' },
    ],
  },
];

function RuleBook({ onClose }) {
  const [section, setSection] = React.useState(SRD_SECTIONS[0].id);
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); onClose(); } };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const active = SRD_SECTIONS.find(s => s.id === section) || SRD_SECTIONS[0];

  return (
    <div className="lobby-overlay rulebook-overlay" onMouseDown={e => e.target === e.currentTarget && onClose()}>
      <div ref={dialogRef} className="rulebook leather stitched" role="dialog" aria-modal="true" aria-label="Rulebook quick reference">
        <div className="rulebook-hd">
          <div>
            <div className="eyebrow">Quick reference</div>
            <h2 className="display rulebook-title">Rulebook</h2>
          </div>
          <button className="composer-x" onClick={onClose} aria-label="Close rulebook">✕</button>
        </div>
        <div className="rulebook-body">
          <nav className="rulebook-nav" aria-label="Rule categories">
            {SRD_SECTIONS.map(s => (
              <button key={s.id} className={`rb-tab ${section === s.id ? 'on' : ''}`}
                aria-pressed={section === s.id} onClick={() => setSection(s.id)}>{s.title}</button>
            ))}
          </nav>
          <div className="rulebook-content parchment">
            <p className="rb-blurb">{active.blurb}</p>
            <dl className="rb-list">
              {active.entries.map((e, i) => (
                <div className="rb-entry" key={i}>
                  <dt>{e.name}</dt>
                  <dd>{e.text}</dd>
                </div>
              ))}
            </dl>
          </div>
        </div>
        <div className="rulebook-ft">
          Summaries adapted from the System Reference Document 5.1 by Wizards of the Coast,
          licensed under <a href="https://creativecommons.org/licenses/by/4.0/legalcode" target="_blank" rel="noreferrer noopener">CC&nbsp;BY&nbsp;4.0</a>.
          Not affiliated with or endorsed by Wizards of the Coast.
        </div>
      </div>
    </div>
  );
}
window.RuleBook = RuleBook;
