/* =========================================================================
   LIFE OS — v2ui.jsx   ·   THE CURIOSITY EXPANSION (UI)
   Loads AFTER overlays.jsx, BEFORE app.jsx. New React surfaces for V2:
     · CuriosityRoamer  — the comet that darts across HQ (Pillar 1)
     · CuriosityPanel   — Question Board + Rooms + Fragments (Pillars 2 & 4)
     · WhyLayer         — "why are you here?" memory peel (Pillar 5)
     · HunchResult      — overlay shown after a hunch (Pillar 3)
     · CuriosityIntro / RoomOpened overlays
   Everything hangs on window.LifeV2UI.
   ========================================================================= */
(function () {
  const { useState } = React;
  const D = window.LifeData, EN = window.LifeEngine, Art = window.LifeArt;
  const { CreatureSprite, Coin, Meter } = Art;
  const V2 = D.V2;
  const fmt = window.LifePanels.fmt;

  /* ------------------------------------------------- the roaming comet */
  function CuriosityRoamer({ creature, active, dispatch }) {
    if (!creature) return null;
    const e = D.E[creature.key];
    return (
      <div className={'curi-roamer' + (active ? ' active' : '')}
        title="Curiosity · click to focus"
        onClick={() => { dispatch({ type: 'SET_ACTIVE', uid: creature.uid }); window.SFX && SFX.play('ui'); }}>
        <div className="curi-float">
          <CreatureSprite emo={e} mood="happy" size={46} />
        </div>
      </div>
    );
  }

  /* ------------------------------------------------- the "Why?" memory peel */
  function WhyLayer({ k, state, dispatch }) {
    const mem = V2.MEMORIES[k];
    if (!mem) return null;
    const depth = (state.memories && state.memories[k]) || 0;
    const cost = 8 + depth * 4;
    const done = depth >= mem.length;
    const afford = (state.res.wonder || 0) >= cost;
    return (
      <div className="why-box">
        <div className="why-head"><span>🛰</span> Why are you here?</div>
        {depth === 0 && <div className="hand muted" style={{ marginBottom: 8 }}>Nobody asks the feelings why. Spend a little Wonder and listen.</div>}
        <div className="why-layers">
          {mem.slice(0, depth).map((line, i) => (
            <div key={i} className="why-layer pop-in"><span className="why-n">{i + 1}</span>{line}</div>
          ))}
        </div>
        {!done
          ? <button className="btn wonder wide" disabled={!afford}
              onClick={() => dispatch({ type: 'ASK_WHY', key: k })}>
              {depth === 0 ? 'Ask why' : 'Ask deeper'} <span className="cost">· {cost} ◇</span>
            </button>
          : <div className="why-done">You’ve heard the whole story. That’s the most anyone can do — listen all the way down.</div>}
      </div>
    );
  }

  /* ------------------------------------------------- a single question card */
  function QuestionCard({ Q, state, dispatch }) {
    const asked = !Q.deep || state.questions.asked.includes(Q.id);
    const answered = state.questions.answered.includes(Q.id);
    const [cur, max] = Q.p(state);
    const complete = cur >= max;
    const afford = (state.res.wonder || 0) >= (Q.askCost || 0);
    return (
      <div className={'q-card' + (answered ? ' answered' : '') + (complete && asked && !answered ? ' ready' : '')}>
        <div className="q-top">
          <span className="q-cat">{Q.cat}</span>
          {Q.deep && !answered && <span className="q-deep">◇ deep</span>}
          {answered && <span className="q-check">✓ answered</span>}
        </div>
        <div className="q-text">{Q.q}</div>
        {asked && <div className="q-hint">{Q.hint}</div>}
        {!asked
          ? <button className="btn ghost sm wide" disabled={!afford}
              onClick={() => dispatch({ type: 'ASK_QUESTION', id: Q.id })}>
              Ask this question {Q.askCost ? <span className="cost">· {Q.askCost} ◇</span> : null}
            </button>
          : !answered
            ? <>
                <div className="q-prog"><Meter v={cur / max * 100} color={complete ? 'var(--good)' : 'var(--wonder)'} h={7} />
                  <span className="q-frac">{cur}/{max}</span></div>
                <button className="btn wonder sm wide" disabled={!complete}
                  onClick={() => dispatch({ type: 'CLAIM_QUESTION', id: Q.id })}>
                  {complete ? 'Claim answer' : 'Investigating…'}
                  {Q.reward && Q.reward.wonder ? <span className="cost">· +{Q.reward.wonder} ◇</span> : null}
                </button>
              </>
            : <div className="q-reward-done">{Q.reward && D.V2.LORE[Q.reward.lore] ? '📜 ' + D.V2.LORE[Q.reward.lore].t : 'Reward claimed.'}</div>}
      </div>
    );
  }

  /* ------------------------------------------------- a room card */
  function RoomCard({ R, state, dispatch }) {
    const open = !!state.rooms[R.id];
    const afford = (state.res.wonder || 0) >= R.cost;
    return (
      <div className={'room-card' + (open ? ' open' : '')}>
        <div className="room-ico">{R.icon}</div>
        <div className="room-meta">
          <div className="room-name">{R.name}<span className="room-tag">{R.tag}</span></div>
          <div className="room-blurb">{R.blurb}</div>
          {open
            ? <div className="room-effect">✓ {R.effect}</div>
            : <button className="btn wonder sm" disabled={!afford}
                onClick={() => dispatch({ type: 'OPEN_ROOM', id: R.id })}>
                Open <span className="cost">· {R.cost} ◇</span>
              </button>}
        </div>
      </div>
    );
  }

  /* ------------------------------------------------- the Curiosity panel */
  function CuriosityPanel({ state, dispatch }) {
    const hasCuri = state.creatures.some(c => c.key === 'curiosity' && !c.shadow);
    const rates = EN.sel.totals(state);
    const expl = EN.sel.explorationMult(state);
    const hunchCost = Math.round(V2.HUNCH.cost * Math.pow(V2.HUNCH.costGrowth, state.stats.hunches || 0));
    const visibleQs = V2.QUESTIONS.filter(q => q.gate(state) || state.questions.asked.includes(q.id) || state.questions.answered.includes(q.id));
    const unlockedLore = Object.keys(state.lore || {}).filter(id => state.lore[id] && D.V2.LORE[id]);
    const archiveOpen = !!state.rooms.archive;

    if (!hasCuri) {
      return (
        <div className="empty-note" style={{ paddingTop: 40 }}>
          <span className="big">🛰</span>
          Curiosity hasn’t arrived yet.<br />
          <span className="hand" style={{ display: 'block', marginTop: 8, fontSize: 16 }}>
            Discover your first merge in the Lab. Curiosity shows up once you start finding things — and brings Wonder with it.
          </span>
        </div>
      );
    }

    return (
      <div>
        {/* Wonder status */}
        <div className="wonder-hero">
          <div className="wh-coin"><Coin kind="wonder" size={30} /></div>
          <div className="wh-main">
            <div className="wh-val">{fmt(state.res.wonder || 0)} <span className="wh-unit">Wonder</span></div>
            <div className="wh-rate">+{rates.wonder.toFixed(2)}/s · curiosity ×{expl.toFixed(2)} for what you’ve explored</div>
          </div>
          <button className={'btn sm' + (state.wonderMode ? ' wonder' : ' ghost')}
            onClick={() => dispatch({ type: 'TOGGLE_WONDER' })} title="See the threads between everything">
            {state.wonderMode ? '◇ Wonder Mode' : '◇ See threads'}
          </button>
        </div>

        <div className="hand muted center" style={{ margin: '2px 0 4px' }}>
          Wonder is the one thing you earn by poking at what you were told to leave alone.
        </div>

        {/* Question board */}
        <div className="section-h" style={{ marginTop: 16 }}>The Question Board · {state.questions.answered.length} answered</div>
        <div className="q-grid">
          {visibleQs.map(Q => <QuestionCard key={Q.id} Q={Q} state={state} dispatch={dispatch} />)}
          {!visibleQs.length && <div className="hand muted center">Gus hasn’t posted any questions yet. Keep playing — he’s thinking.</div>}
        </div>

        {/* Hunch nudge */}
        <div className="hunch-nudge">
          <div><b>Got a hunch?</b><div className="tiny muted">Combine two feelings that "don’t merge" in the Lab — spend {hunchCost} ◇ to see what happens anyway.</div></div>
          <span className="hunch-dice">🎲</span>
        </div>

        {/* Rooms */}
        <div className="section-h" style={{ marginTop: 18 }}>Rooms Off the Org Chart · {Object.keys(state.rooms).length}/{V2.ROOMS.length}</div>
        <div className="rooms-grid">
          {V2.ROOMS.map(R => <RoomCard key={R.id} R={R} state={state} dispatch={dispatch} />)}
        </div>

        {/* Fragments (Archive) */}
        {(archiveOpen || unlockedLore.length > 0) && <>
          <div className="section-h" style={{ marginTop: 18 }}>
            Fragments {archiveOpen ? '· The Archive' : ''} · {unlockedLore.length} found
          </div>
          {archiveOpen
            ? <div className="lore-list">
                {unlockedLore.map(id => (
                  <div key={id} className="lore-card">
                    <div className="lore-t">📜 {D.V2.LORE[id].t}</div>
                    <div className="lore-x">{D.V2.LORE[id].x}</div>
                  </div>
                ))}
                {!unlockedLore.length && <div className="hand muted center">No fragments yet. Answer questions and play hunches to collect them.</div>}
              </div>
            : <div className="hand muted center" style={{ fontSize: 15 }}>
                Open <b>The Archive</b> to re-read every fragment you’ve found.
              </div>}
        </>}
      </div>
    );
  }

  /* ------------------------------------------------- hunch result overlay */
  function HunchResult({ state, dispatch }) {
    const h = state._hunch; if (!h) return null;
    const close = () => { window.SFX && SFX.play('ui'); dispatch({ type: 'CLOSE_HUNCH' }); };
    let body;
    if (h.type === 'mutation' && h.mutKey) {
      const e = D.E[h.mutKey];
      body = <>
        <div className="hunch-tag" style={{ background: 'var(--wonder-deep)' }}>OFF THE BOOKS · NEW</div>
        <div style={{ margin: '8px 0' }}><CreatureSprite emo={e} mood="happy" size={110} /></div>
        <h2>{e.name}</h2>
        <p>{e.blurb}</p>
        <div className="hunch-sub">A Mutation — you can’t hatch or recipe this. Only a hunch could find it.</div>
      </>;
    } else if (h.type === 'wonder') {
      body = <><div className="hunch-emoji">◇</div><h2>+{h.amt} Wonder</h2><p>{h.line}</p></>;
    } else if (h.type === 'clarity') {
      body = <><div className="hunch-emoji">◆</div><h2>+{h.amt} Clarity</h2><p>{h.line}</p></>;
    } else if (h.type === 'hint' && h.hint) {
      body = <>
        <div className="hunch-emoji">🗂</div><h2>A recipe revealed</h2>
        <p>{h.line}</p>
        <div className="hint-recipe">
          <CreatureSprite emo={D.E[h.hint[0]]} mood="content" size={48} idle={false} />
          <span className="lab-plus">+</span>
          <CreatureSprite emo={D.E[h.hint[1]]} mood="content" size={48} idle={false} />
          <span className="lab-eq">→</span>
          <div className="hint-q"><span className="qmark">?</span></div>
        </div>
        <div className="hunch-sub">{D.E[h.hint[0]].name} + {D.E[h.hint[1]].name} make something. Go try it in the Lab.</div>
      </>;
    } else if (h.type === 'lore' && h.loreId) {
      const L = D.V2.LORE[h.loreId];
      body = <><div className="hunch-emoji">📜</div><h2>{L.t}</h2><p>{L.x}</p><div className="hunch-sub">Filed in Fragments.</div></>;
    } else { // fizzle
      body = <><div className="hunch-emoji">💨</div><h2>…nothing</h2><p>{h.fizzle}</p>
        <div className="hunch-sub">+{h.amt} ◇ back. Trying the weird thing is the entire personality of this place.</div></>;
    }
    return (
      <div className="overlay" onClick={close}>
        <div className="scrim" />
        <div className="modal pop-in center hunch-modal" onClick={e => e.stopPropagation()}>
          <div className="modal-pad">
            {body}
            <button className="btn wonder wide" style={{ marginTop: 8 }} onClick={close}>Go on then</button>
          </div>
        </div>
      </div>
    );
  }

  /* ------------------------------------------------- curiosity arrival intro */
  function CuriosityIntro({ state, dispatch }) {
    const migrated = state._migratedCuriosity;
    return (
      <div className="overlay">
        <div className="scrim" style={{ background: 'rgba(10,28,32,.8)' }} />
        <div className="modal pop-in center" style={{ maxWidth: 520, background: 'linear-gradient(160deg,#0E2A30,#10363E)', color: '#DFFAF6', border: '1.5px solid #2BA8C8' }}>
          <div className="modal-pad">
            <div className="curi-stage"><CreatureSprite emo={D.E.curiosity} mood="happy" size={110} /></div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.22em', color: '#6FE6E0' }}>UNSCHEDULED ARRIVAL</div>
            <h2 style={{ color: '#fff' }}>Something wandered in.</h2>
            <p style={{ color: '#bfe9e4' }}>{migrated
              ? 'While you were away, Curiosity found its way in — drawn by everything you’ve already discovered. It doesn’t belong to any department. It roams. And it makes Wonder: the one resource you earn purely by poking at what you were told to leave alone.'
              : D.GUS.curiosityArrived[0]}</p>
            <button className="btn wonder wide" onClick={() => { window.SFX && SFX.play('hatch'); dispatch({ type: 'CLEAR_CURIOSITY_INTRO' }); }}>
              Let it roam →
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ------------------------------------------------- room opened reveal */
  function RoomOpened({ state, dispatch }) {
    const R = D.V2.ROOMS.find(r => r.id === state._roomOpened); if (!R) return null;
    return (
      <div className="overlay" onClick={() => dispatch({ type: 'CLOSE_ROOM' })}>
        <div className="scrim" style={{ background: 'rgba(14,10,22,.82)' }} />
        <div className="modal pop-in center room-modal" onClick={e => e.stopPropagation()}>
          <div className="modal-pad">
            <div className="room-big-ico">{R.icon}</div>
            <h2>{R.name}</h2>
            <p>{R.openLine}</p>
            <div className="room-effect big">✦ {R.effect}</div>
            <button className="btn wonder wide" style={{ marginTop: 6 }}
              onClick={() => { window.SFX && SFX.play('ui'); dispatch({ type: 'CLOSE_ROOM' }); }}>Step inside</button>
          </div>
        </div>
      </div>
    );
  }

  window.LifeV2UI = { CuriosityRoamer, CuriosityPanel, WhyLayer, HunchResult, CuriosityIntro, RoomOpened };
})();
