/* =========================================================================
   LIFE OS — overlays.jsx
   Onboarding egg-hatch, Soul/Breakthrough, Multiverse Breach minigame,
   Welcome-back, Creature detail, Toasts. window.LifeOverlays
   ========================================================================= */
(function () {
  const { useState, useEffect, useRef } = React;
  const D = window.LifeData, EN = window.LifeEngine, Art = window.LifeArt;
  const { CreatureSprite, Coin } = Art;

  // ----------------------------------------------------------- ONBOARDING
  function Onboarding({ dispatch }) {
    const [step, setStep] = useState(0);
    const [taps, setTaps] = useState(0);
    const need = 4;
    const baseKeys = ['joy', 'sadness', 'anger', 'fear', 'disgust'];

    const crack = () => {
      SFX.play('pop');
      const t = taps + 1; setTaps(t);
      if (t >= need) { SFX.play('hatch'); setTimeout(() => setStep(2), 500); }
    };

    return (
      <div className="overlay">
        <div className="scrim" style={{ background: 'rgba(20,15,28,.82)' }} />
        <div className="modal pop-in" style={{ maxWidth: 520, textAlign: 'center', background: 'var(--card)' }}>
          {step === 0 && <div className="modal-pad">
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.22em', color: 'var(--ink-faint)' }}>YOU, INC. · ONBOARDING</div>
            <div style={{ margin: '14px 0' }}><CreatureSprite emo={{ c: ['#B6A4EE', '#8C77D6'], body: 'orb' }} mood="content" size={96} /></div>
            <h2 style={{ fontSize: 26 }}>Welcome to Life OS</h2>
            <p style={{ textAlign: 'left' }}>{D.GUS.boot[0]}</p>
            <p style={{ textAlign: 'left' }} className="hand">Your brain got incorporated. You're the CEO now. Your feelings are the staff. Let's hatch the first one.</p>
            <button className="btn pink wide" onClick={() => { SFX.play('ui'); setStep(1); }}>Begin →</button>
          </div>}

          {step === 1 && <div className="modal-pad">
            <h2>An egg appears.</h2>
            <p>Something's in there. Tap it awake. {need - taps > 0 ? `(${need - taps} more)` : ''}</p>
            <div style={{ height: 180, display: 'grid', placeItems: 'center', cursor: 'pointer' }} onClick={crack}>
              <div className="csprite bob" style={{ filter: taps ? 'none' : 'none', transform: `scale(${1 + taps * 0.04})`, transition: 'transform .2s' }}>
                <svg width="130" height="150" viewBox="0 0 100 120">
                  <defs><radialGradient id="egg" cx="40%" cy="32%" r="75%"><stop offset="0%" stopColor="#FFF4E6" /><stop offset="100%" stopColor="#F0D9BD" /></radialGradient></defs>
                  <ellipse cx="50" cy="108" rx="22" ry="5" fill="#2B2434" opacity=".18" />
                  <path d="M50 8 C74 8 84 54 84 74 a34 34 0 0 1 -68 0 C16 54 26 8 50 8 Z" fill="url(#egg)" stroke="#E0C39E" strokeWidth="1.5" />
                  {taps >= 1 && <path d="M38 50 l8 6 l-6 8 l10 4" stroke="#C9A877" strokeWidth="2" fill="none" />}
                  {taps >= 2 && <path d="M60 44 l-6 8 l8 6 l-8 6" stroke="#C9A877" strokeWidth="2" fill="none" />}
                  {taps >= 3 && <path d="M30 70 l12 -2 l4 8 l10 -4" stroke="#C9A877" strokeWidth="2.4" fill="none" />}
                  <ellipse cx="40" cy="40" rx="12" ry="9" fill="#fff" opacity=".4" />
                </svg>
              </div>
            </div>
            <div className="hand muted">Gus: “Gentle. It's been in there a while.”</div>
          </div>}

          {step === 2 && <div className="modal-pad">
            <h2>Who clocked in first?</h2>
            <p>The first feeling to show up sets the tone. There are no wrong answers — they'll all join eventually.</p>
            <div className="pick-grid" style={{ gridTemplateColumns: 'repeat(5,1fr)', marginBottom: 8 }}>
              {baseKeys.map(k => (
                <div key={k} className="pick" title={D.E[k].name}
                  onClick={() => { SFX.play('hatch'); dispatch({ type: 'START_GAME', key: k }); }}>
                  <CreatureSprite emo={D.E[k]} mood="happy" size={46} idle={false} />
                  <span className="pl">{D.E[k].name.slice(0, 3)}</span>
                </div>
              ))}
            </div>
            <div className="hand muted">Pick one to start your team.</div>
          </div>}
        </div>
      </div>
    );
  }

  // ----------------------------------------------------------- SOUL / BREAKTHROUGH
  function SoulOverlay({ state, dispatch }) {
    const owned = state.sparksOwned || [];
    const keys = Object.keys(D.SPARKS);
    return (
      <div className="overlay">
        <div className="scrim" style={{ background: 'rgba(22,18,31,.55)' }} />
        <div className="soul-glow" />
        <div className="modal pop-in" style={{ maxWidth: 600, background: 'rgba(40,30,60,.85)', color: '#F3EEFF', border: '1.5px solid #5a4a7e', backdropFilter: 'blur(8px)' }}>
          <div className="modal-pad">
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.22em', color: '#b6a4ee' }}>SOUL MODE · THERAPEUTIC BREAKTHROUGH</div>
            <h2 style={{ color: '#fff', fontSize: 28 }}>You found your Spark.</h2>
            <p style={{ color: '#cfc3e8' }}>The org chart turned translucent. For a second you saw the feelings for what they are — energy, not enemies. Choose how you process at your best. This becomes permanent.</p>
            <div className="croster">
              {keys.map(k => {
                const sp = D.SPARKS[k], have = owned.includes(k);
                return (
                  <div key={k} className="ccard" style={{ background: have ? 'rgba(120,110,150,.25)' : 'rgba(60,48,90,.6)', borderColor: '#5a4a7e', color: '#F3EEFF', opacity: have ? .5 : 1, cursor: have ? 'default' : 'pointer' }}
                    onClick={() => !have && dispatch({ type: 'BREAKTHROUGH', spark: k })}>
                    <span style={{ fontSize: 30 }}>{sp.icon}</span>
                    <div className="cmeta"><div className="cname" style={{ fontSize: 14, color: '#fff' }}>{sp.name}{have ? ' ✓' : ''}</div>
                      <div className="tiny" style={{ color: '#cabbe6', lineHeight: 1.4 }}>{sp.desc}</div></div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  function CapstoneOverlay({ dispatch }) {
    return (
      <div className="overlay">
        <div className="scrim" style={{ background: 'rgba(22,18,31,.75)' }} />
        <div className="soul-glow" />
        <div className="modal pop-in center" style={{ maxWidth: 560, background: 'rgba(40,30,60,.9)', color: '#fff', border: '1.5px solid #6a5a9e' }}>
          <div className="modal-pad">
            <div style={{ margin: '6px 0 12px' }}><CreatureSprite emo={D.E.acceptance} mood="happy" size={120} /></div>
            <h2 style={{ color: '#fff', fontSize: 30 }}>Acceptance</h2>
            <p style={{ color: '#d6cdec' }}>{D.GUS.capstone[0]}</p>
            <button className="btn pink" onClick={() => { SFX.play('ui'); dispatch({ type: 'CLOSE_SOUL' }); }}>Touch grass (continue)</button>
          </div>
        </div>
      </div>
    );
  }

  // ----------------------------------------------------------- BREACH MINIGAME
  function BreachOverlay({ state, dispatch }) {
    const ev = state.event;
    const fieldRef = useRef(null);
    const [orbs, setOrbs] = useState([]);
    useEffect(() => {
      const list = [];
      for (let i = 0; i < ev.orbs; i++) list.push({ id: i, x: 8 + Math.random() * 78, y: 8 + Math.random() * 70, k: ['joy', 'sadness', 'anger', 'fear', 'anxiety'][i % 5] });
      setOrbs(list);
    }, []);
    const remaining = ev.orbs - ev.popped;
    return (
      <div className="overlay">
        <div className="scrim" />
        <div className="modal pop-in" style={{ maxWidth: 560, background: '#1a1030', color: '#fff', border: '1.5px solid #6a2d8a' }}>
          <div className="modal-pad">
            <div className="glitch-text" data-t="MULTIVERSE BREACH" style={{ fontFamily: 'var(--font-mono)', fontSize: 13, letterSpacing: '.2em', color: '#ff6ea8' }}>MULTIVERSE BREACH</div>
            <h2 style={{ color: '#fff', fontSize: 24, marginTop: 6 }}>Seal the leaks · {remaining} left</h2>
            <p style={{ color: '#cbb6e0' }}>Anxieties from timelines where you took the other job are bleeding through. Tap them shut. One feeling at a time.</p>
            <div className="breach-field" ref={fieldRef}>
              {orbs.slice(0, remaining).map(o => (
                <div key={o.id} className="breach-orb" style={{ left: o.x + '%', top: o.y + '%', background: `radial-gradient(circle at 38% 32%, ${D.E[o.k].c[0]}, ${D.E[o.k].c[1]})` }}
                  onClick={() => { dispatch({ type: 'BREACH_POP' }); }}>
                  <CreatureSprite emo={D.E[o.k]} mood="worried" size={40} idle={false} />
                </div>
              ))}
            </div>
            <div className="hand" style={{ color: '#cbb6e0', marginTop: 8 }}>Reward: +30 Clarity for keeping it together.</div>
          </div>
        </div>
        <div className="glitch-bars" />
      </div>
    );
  }

  // ----------------------------------------------------------- WELCOME BACK
  function WelcomeBack({ state, dispatch }) {
    const w = state.welcome; if (!w) return null;
    const mins = Math.round(w.dt / 60);
    const time = mins >= 60 ? Math.floor(mins / 60) + 'h ' + (mins % 60) + 'm' : mins + 'm';
    return (
      <div className="overlay">
        <div className="scrim" />
        <div className="modal pop-in center" style={{ maxWidth: 440 }}>
          <div className="modal-pad">
            <div style={{ fontSize: 40, marginBottom: 6 }}>☕</div>
            <h2>You were away {time}</h2>
            <p>Your feelings kept working at half speed. Gus locked up, watered the plants, and judged you lovingly.</p>
            <div className="row" style={{ justifyContent: 'center', gap: 18, margin: '6px 0 16px' }}>
              <div className="row" style={{ gap: 6 }}><Coin kind="energy" /><b>+{LifePanels.fmt(w.energy)}</b></div>
              <div className="row" style={{ gap: 6 }}><Coin kind="clarity" /><b>+{LifePanels.fmt(w.clarity)}</b></div>
              {w.wonder ? <div className="row" style={{ gap: 6 }}><Coin kind="wonder" /><b>+{LifePanels.fmt(w.wonder)}</b></div> : null}
            </div>
            <button className="btn pink wide" onClick={() => { SFX.play('ui'); dispatch({ type: 'CLEAR_WELCOME' }); }}>Back to work</button>
          </div>
        </div>
      </div>
    );
  }

  // ----------------------------------------------------------- CREATURE DETAIL
  function CreatureModal({ k, onClose, state, dispatch }) {
    if (!k) return null;
    const e = D.E[k];
    if (!e) return null;
    const tierName = { '-1': 'Shadow Form', 0: 'Raw Feeling', 1: 'Tier I', 2: 'Tier II', 3: 'Tier III · Legendary', 4: 'Mutation · Hunch-only' }[e.tier];
    const recipe = D.MERGE_LIST.find(([, , r]) => r === k);
    const isShadowForm = e.shadow === true;       // base feelings store the shadow KEY here (truthy) — don't treat them as shadows
    const WhyLayer = window.LifeV2UI && window.LifeV2UI.WhyLayer;
    const canWhy = WhyLayer && state && dispatch && D.V2 && D.V2.MEMORIES[k];
    return (
      <div className="overlay" onClick={onClose}>
        <div className="scrim" />
        <div className="modal pop-in" style={{ maxWidth: 420 }} onClick={e2 => e2.stopPropagation()}>
          <button className="x-close" onClick={onClose}>×</button>
          <div style={{ background: `linear-gradient(160deg, ${e.c[0]}22, ${e.c[1]}33)`, padding: '22px 0', display: 'grid', placeItems: 'center' }}>
            <CreatureSprite emo={e} mood="happy" size={120} />
          </div>
          <div className="modal-pad">
            <div className="row between">
              <h2 style={{ margin: 0 }}>{e.name}</h2>
              <span className="lvl" style={{ background: e.c[1] }}>{tierName}</span>
            </div>
            <div className="muted tiny" style={{ margin: '4px 0 10px', fontFamily: 'var(--font-mono)' }}>processes “{e.raw}”</div>
            <p style={{ margin: 0 }}>{e.blurb}</p>
            {recipe && D.E[recipe[0]] && D.E[recipe[1]] && <div className="hand mt" style={{ color: 'var(--lav-deep)' }}>Recipe: {D.E[recipe[0]].name} + {D.E[recipe[1]].name}</div>}
            {e.mutant && <div className="hand mt" style={{ color: 'var(--wonder-deep)' }}>A Mutation — only a hunch could find it.</div>}
            {isShadowForm && D.E[e.healFrom] && <div className="hand mt" style={{ color: 'var(--pink-deep)' }}>Heal it back to {D.E[e.healFrom].name} with care + Clarity.</div>}
            <div className="row mt" style={{ gap: 14 }}>
              {e.out && e.out.energy ? <div className="row" style={{ gap: 5 }}><Coin kind="energy" size={15} /><span className="tiny">{e.out.energy}/s</span></div> : null}
              {e.out && e.out.clarity ? <div className="row" style={{ gap: 5 }}><Coin kind="clarity" size={15} /><span className="tiny">{e.out.clarity}/s</span></div> : null}
              {e.out && e.out.wonder ? <div className="row" style={{ gap: 5 }}><Coin kind="wonder" size={15} /><span className="tiny">{e.out.wonder}/s</span></div> : null}
            </div>
            {canWhy && <div className="mt"><WhyLayer k={k} state={state} dispatch={dispatch} /></div>}
          </div>
        </div>
      </div>
    );
  }

  // ----------------------------------------------------------- TOASTS
  function Toasts({ toasts }) {
    return <div className="toasts">{toasts.map(t => <div key={t.id} className="toast"><span>{t.icon}</span>{t.text}</div>)}</div>;
  }

  window.LifeOverlays = { Onboarding, SoulOverlay, CapstoneOverlay, BreachOverlay, WelcomeBack, CreatureModal, Toasts };
})();
