/* eslint-disable */
// Odd Hours — step components for the wizard.
// Loaded AFTER components.jsx and data.js. Wrapped in IIFE.

(function () {

const {
  SectionHead, Field, TextInput, TextArea,
  PointsCounter, Dots, StatTile, SkillRow, BackgroundCard,
  capitalize, skillName,
  ATTRIBUTES, SKILLS, BACKGROUNDS, ARCHETYPES, SPECIALTIES, REACTIONS,
  FIRST_NAMES, LAST_NAMES, NICKNAMES, STATION_REMARKS,
} = window;

const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];

// ============================================================
// LANDING (step 0) — "Clock In"
// ============================================================
function LandingScreen({ onStart, onLoadArchetype, onResume, hasSaved }) {
  return (
    <div className="landing">
      <div className="landing__form-id">Form OH-1 · NEW HIRE PAPERWORK</div>
      <h1 className="landing__title">Welcome to your shift.</h1>
      <div className="landing__rule" />
      <p className="landing__lead">
        Before we put you on the floor, the station needs a few things on file.
        Six steps. Should take fifteen minutes. <em>Unless you really get into making that backstory.</em>
      </p>
      <div className="landing__actions">
        <button className="btn btn--primary" onClick={onStart}>Clock In →</button>
        <button className="btn btn--ghost" onClick={onLoadArchetype}>Pick a Pre-Rolled Hire</button>
        {hasSaved && <button className="btn btn--ghost" onClick={onResume}>Resume Saved Shift</button>}
      </div>
      <div className="landing__meta">
        <strong>OM Reference:</strong> &nbsp;Odd Hours v1 · 2d6 + Wit / Grit / Strangeness
      </div>
    </div>
  );
}

// ============================================================
// STEP 1 — CONCEPT
// ============================================================
function ConceptStep({ char, setChar }) {
  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 01 — Concept" title="Who is this person?">
        Three questions, one background. The numbers come later. Get the concept
        right and the rest will follow.
      </SectionHead>

      <Field
        label="Who were they before the station?"
        sub="Their old job. Their old life. The thing they tell people at parties, when they used to go to parties."
      >
        <TextArea
          value={char.before}
          onChange={(e) => setChar({ before: e.target.value })}
          placeholder="Used to teach high-school chemistry. Got laid off when the district consolidated."
        />
      </Field>

      <Field
        label="Why are they working here, now?"
        sub="The reason that's on the application, and the reason that's true."
      >
        <TextArea
          value={char.why}
          onChange={(e) => setChar({ why: e.target.value })}
          placeholder="Rent. Cash money. Saw the help-wanted sign on the way out of town and never finished leaving."
        />
      </Field>

      <Field
        label="How do they feel about the weirdness?"
        sub="Deny it. Joke about it. Lean into it. Run from it. Yours. Be specific."
      >
        <TextArea
          value={char.feel}
          onChange={(e) => setChar({ feel: e.target.value })}
          placeholder="Mostly looks the other way. Started leaving snacks on the back counter for whatever is taking them."
        />
      </Field>

      <div className="rule--full" />

      <SectionHead eyebrow="Pick a Background" title="What did they bring with them?">
        Your background gives a +1 attribute and +1 to two skills. Pick what fits.
        "Custom" lets you write your own — clear it with your OM.
      </SectionHead>

      <div className="bg-grid">
        {BACKGROUNDS.map((bg) => (
          <BackgroundCard
            key={bg.key}
            bg={bg}
            attrs={ATTRIBUTES}
            skills={SKILLS}
            selected={char.background === bg.key}
            onClick={() => setChar({ background: bg.key })}
          />
        ))}
      </div>

      {char.background === 'custom' && (
        <div style={{ marginTop: 18 }}>
          <Field label="Custom Background Name" sub="What do you call this kind of person? Run the bonus with your OM later.">
            <TextInput
              value={char.customBackgroundName}
              onChange={(e) => setChar({ customBackgroundName: e.target.value })}
              placeholder="Night-shift Locksmith / EMT Dropout / Long-haul Preacher"
            />
          </Field>

          <div className="field-row" style={{ marginTop: 18 }}>
            <Field label="Custom: +1 Attribute" sub="Pick one.">
              <select
                className="field__input"
                value={char.customAttr || ''}
                onChange={(e) => setChar({ customAttr: e.target.value })}
              >
                <option value="">— Select —</option>
                {ATTRIBUTES.map((a) => <option key={a.key} value={a.key}>{a.name}</option>)}
              </select>
            </Field>
            <Field label="Custom: +1 to Two Skills" sub="Pick two distinct skills.">
              <div style={{ display: 'flex', gap: 8 }}>
                {[0, 1].map((idx) => (
                  <select
                    key={idx}
                    className="field__input"
                    style={{ flex: 1 }}
                    value={(char.customSkills && char.customSkills[idx]) || ''}
                    onChange={(e) => {
                      const arr = [...(char.customSkills || ['', ''])];
                      arr[idx] = e.target.value;
                      setChar({ customSkills: arr });
                    }}
                  >
                    <option value="">— Select —</option>
                    {SKILLS.map((s) => <option key={s.key} value={s.key}>{s.name}</option>)}
                  </select>
                ))}
              </div>
            </Field>
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// STEP 2 — ATTRIBUTES
// Point-buy: each attribute starts at 1, 6 points to distribute, max 4 (incl bg).
// ============================================================
function AttributesStep({ char, setChar, bonuses }) {
  const ATTR_BUDGET = 6;
  const spent = ATTRIBUTES.reduce((sum, a) => sum + (char.attrs[a.key] - 1), 0);
  const remaining = ATTR_BUDGET - spent;

  const inc = (key) => {
    const cur = char.attrs[key];
    const eff = cur + (bonuses.attr[key] || 0);
    if (remaining <= 0) return;
    if (eff >= 4) return;
    setChar({ attrs: { ...char.attrs, [key]: cur + 1 } });
  };
  const dec = (key) => {
    if (char.attrs[key] <= 1) return;
    setChar({ attrs: { ...char.attrs, [key]: char.attrs[key] - 1 } });
  };

  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 02 — Attributes" title="Distribute 6 points.">
        Each attribute starts at 1. Spend 6 more between Wit, Grit, and Strangeness.
        No attribute can exceed 4 at creation — including the +1 your background gives you.
      </SectionHead>

      <PointsCounter label="Attribute Points" remaining={remaining} total={ATTR_BUDGET} />

      <div className="stat-grid">
        {ATTRIBUTES.map((attr) => {
          const value = char.attrs[attr.key] + (bonuses.attr[attr.key] || 0);
          const bg = bonuses.attr[attr.key] || 0;
          return (
            <StatTile
              key={attr.key}
              attr={attr}
              value={value}
              bgBonus={bg}
              canIncrease={remaining > 0 && value < 4}
              canDecrease={char.attrs[attr.key] > 1}
              onIncrease={() => inc(attr.key)}
              onDecrease={() => dec(attr.key)}
            />
          );
        })}
      </div>

      <p className="lead lead--muted" style={{ fontSize: 13, marginTop: 18, fontStyle: 'italic' }}>
        The dark squares on the left of each row are your background bonus — they
        come for free and don't cost from your budget.
      </p>
    </div>
  );
}

// ============================================================
// STEP 3 — SKILLS
// 3 points, max 3 per skill at creation (incl. bg bonus).
// ============================================================
function SkillsStep({ char, setChar, bonuses }) {
  const SKILL_BUDGET = 3;
  const spent = Object.values(char.skills).reduce((a, b) => a + b, 0);
  const remaining = SKILL_BUDGET - spent;

  const inc = (key) => {
    const cur = char.skills[key] || 0;
    const eff = cur + (bonuses.skills[key] || 0);
    if (remaining <= 0) return;
    if (eff >= 3) return;
    setChar({ skills: { ...char.skills, [key]: cur + 1 } });
  };
  const dec = (key) => {
    const cur = char.skills[key] || 0;
    if (cur <= 0) return;
    setChar({ skills: { ...char.skills, [key]: cur - 1 } });
  };

  // Group skills by attribute
  const grouped = ATTRIBUTES.map((attr) => ({
    attr,
    skills: SKILLS.filter((s) => s.attr === attr.key),
  }));

  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 03 — Skills" title="Spend 3 skill points.">
        Each skill starts at 0. Max 3 in any one skill at creation, including your
        background bonus. Bonuses appear in dark on the left of the dot row.
      </SectionHead>

      <PointsCounter label="Skill Points" remaining={remaining} total={SKILL_BUDGET} />

      {grouped.map(({ attr, skills }) => (
        <div className="skill-group" key={attr.key}>
          <div className="skill-group__head">
            <span className="skill-group__name">{attr.name}</span>
            <span className="skill-group__hint">{attr.name} Skills</span>
          </div>
          {skills.map((s) => {
            const value = (char.skills[s.key] || 0) + (bonuses.skills[s.key] || 0);
            const bg = bonuses.skills[s.key] || 0;
            return (
              <SkillRow
                key={s.key}
                skill={s}
                value={value}
                bgBonus={bg}
                canIncrease={remaining > 0 && value < 3}
                canDecrease={(char.skills[s.key] || 0) > 0}
                onIncrease={() => inc(s.key)}
                onDecrease={() => dec(s.key)}
              />
            );
          })}
        </div>
      ))}
    </div>
  );
}

// ============================================================
// STEP 4 — SPECIALTY
// Pick one specialty tied to a skill they have (effective value > 0).
// ============================================================
function SpecialtyStep({ char, setChar, bonuses }) {
  // Effective skill values (skill points + bg bonus)
  const effective = {};
  SKILLS.forEach((s) => {
    effective[s.key] = (char.skills[s.key] || 0) + (bonuses.skills[s.key] || 0);
  });
  const availableSkills = SKILLS.filter((s) => effective[s.key] > 0);
  const activeSkill = char.specialty?.skill || (availableSkills[0] && availableSkills[0].key);

  const options = SPECIALTIES[activeSkill] || [];

  const setSpec = (skill, name) => {
    setChar({ specialty: { skill, name } });
  };

  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 04 — Specialty" title="Pick one narrow focus.">
        A specialty grants +2 on rolls within its focus. Tie it to a skill you
        already have. You only get one at creation.
      </SectionHead>

      {availableSkills.length === 0 ? (
        <p className="lead">Go back and put at least one point into a skill first.</p>
      ) : (
        <div className="specialty-grid">
          <div className="spec-skill-list">
            {availableSkills.map((s) => (
              <button
                key={s.key}
                type="button"
                className={`spec-skill ${activeSkill === s.key ? 'is-active' : ''}`}
                onClick={() => setSpec(s.key, char.specialty?.skill === s.key ? char.specialty.name : '')}
              >
                <span>{s.name}</span>
                <span className="spec-skill__rank">{effective[s.key]}</span>
              </button>
            ))}
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>
              {activeSkill && SKILLS.find((s) => s.key === activeSkill)?.name} — Specialty Options
            </div>
            <div className="spec-options">
              {options.map((opt) => (
                <button
                  key={opt}
                  type="button"
                  className={`spec-option ${char.specialty?.skill === activeSkill && char.specialty?.name === opt ? 'is-selected' : ''}`}
                  onClick={() => setSpec(activeSkill, opt)}
                >
                  {opt}
                  <span className="spec-option__hint">+2 on focused rolls</span>
                </button>
              ))}
            </div>

            <div style={{ marginTop: 18 }}>
              <div className="field__sub">Or write your own. Clear it with your OM.</div>
              <div className="spec-custom">
                <input
                  type="text"
                  placeholder="Custom specialty (e.g. Hot-Wiring 1990s Sedans)"
                  value={char.specialty?.skill === activeSkill && !options.includes(char.specialty?.name) ? char.specialty?.name || '' : ''}
                  onChange={(e) => setSpec(activeSkill, e.target.value)}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// STEP 5 — STATE OF MIND
// Sanity (start 6), Absurdity (start 0), HP (10 + Grit), Mental State chip.
// Read-only review + reaction question.
// ============================================================
function StateStep({ char, setChar, totals, bonuses }) {
  const grit = char.attrs.grit + (bonuses.attr.grit || 0);
  const hp = 10 + grit;
  const initiative = grit;

  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 05 — State of Mind" title="What happens when it shows up.">
        Sanity and Absurdity are calculated. Pick how they react when the weird arrives —
        it'll color their first session and what the OM throws at them.
      </SectionHead>

      <div className="stat-grid">
        <ReadOnlyTile name="Sanity" value="6" sub="Starts full." />
        <ReadOnlyTile name="Absurdity" value="0" sub="Climbs as you lean in." />
        <ReadOnlyTile name="HP" value={String(hp)} sub={`10 + Grit (${grit})`} />
      </div>

      <div className="rule--full" />

      <SectionHead eyebrow="When something bizarre happens, they..." title="Reaction" />
      <div className="reaction-grid">
        {REACTIONS.map((r) => (
          <button
            key={r.key}
            type="button"
            className={`reaction-card ${char.reaction === r.key ? 'is-selected' : ''}`}
            onClick={() => setChar({ reaction: r.key })}
          >
            <div className="reaction-card__label">{r.label}</div>
            <div className="reaction-card__blurb">{r.blurb}</div>
          </button>
        ))}
      </div>

      <div className="rule--full" />

      <SectionHead eyebrow="Initiative" title={`+${initiative}`}>
        Initiative modifier equals your Grit. Roll 2d6 + {initiative} when combat starts.
      </SectionHead>
    </div>
  );
}

function ReadOnlyTile({ name, value, sub }) {
  return (
    <div className="stat-tile">
      <div className="stat-tile__head">
        <div className="stat-tile__name">{name}</div>
      </div>
      <div className="stat-tile__value">{value}</div>
      <p className="stat-tile__blurb">{sub}</p>
    </div>
  );
}

// ============================================================
// STEP 6 — DETAILS (Name, Appearance, Pockets, Counter)
// ============================================================
function DetailsStep({ char, setChar }) {
  const rollName = () => {
    const first = pick(FIRST_NAMES);
    const last = pick(LAST_NAMES);
    const useNick = Math.random() < 0.45;
    const nick = useNick ? `"${pick(NICKNAMES)}"` : '';
    const name = useNick ? `${first} ${nick} ${last}` : `${first} ${last}`;
    setChar({ name });
  };

  return (
    <div className="step-body">
      <SectionHead eyebrow="Step 06 — Name and Details" title="Make them a person.">
        Name. Appearance. A couple of details that make this character feel like
        someone instead of a stat block.
      </SectionHead>

      <Field label="Employee Name" sub="First, last, and a nickname if it earned one.">
        <div className="name-field">
          <input
            className="field__input"
            type="text"
            value={char.name}
            onChange={(e) => setChar({ name: e.target.value })}
            placeholder="Linda &quot;Lynx&quot; Thompson"
          />
          <button type="button" onClick={rollName} title="Generate a name">Roll Name</button>
        </div>
      </Field>

      <Field label="Appearance" sub="Two or three details. Specific beats general.">
        <TextArea
          value={char.appearance}
          onChange={(e) => setChar({ appearance: e.target.value })}
          placeholder="Mid-thirties, cropped black hair, scar down left cheek. Skeptical."
        />
      </Field>

      <div className="field-row">
        <Field label="In their pockets" sub="Something they carry that they shouldn't.">
          <TextArea
            value={char.pockets}
            onChange={(e) => setChar({ pockets: e.target.value })}
            placeholder="A flask. Three quarters that don't match the dates on them."
          />
        </Field>
        <Field label="Behind the counter" sub="Their thing. The one nobody else touches.">
          <TextArea
            value={char.counter}
            onChange={(e) => setChar({ counter: e.target.value })}
            placeholder="A revolver with the serial filed off."
          />
        </Field>
      </div>

      <Field label="Starting inventory" sub="Anything else in your bag, your locker, your truck. One per line.">
        <TextArea
          rows={4}
          value={char.inventory}
          onChange={(e) => setChar({ inventory: e.target.value })}
          placeholder={"flashlight\\nzippo\\nyour name tag, slightly bent\\na photo you don't remember taking"}
        />
      </Field>

      <Field label="Starting weapons" sub="What you can swing. One per line. e.g. &quot;Crowbar | 2&quot;.">
        <TextArea
          rows={3}
          value={char.weapons}
          onChange={(e) => setChar({ weapons: e.target.value })}
          placeholder={"Bare-handed | 1\\nCrowbar (improvised) | 2"}
        />
      </Field>
    </div>
  );
}

// Attach
Object.assign(window, {
  LandingScreen,
  ConceptStep, AttributesStep, SkillsStep, SpecialtyStep, StateStep, DetailsStep,
});

})();
