const { Icon } = window.PryzeDesignSystem_b2bad9;
const { LEADERBOARD_PEERS, ALL_GOALS, USER, COMPANIES } = window.PryzeData;

const TIPS = [
  'Greet before they reach you. Eye contact does half the work.',
  'Face the shelf as you pass it — never walk empty-handed.',
  'Ask one extra question before you ring someone up.',
  'A teammate covering you? Send kudos before you forget.',
  'Restock at the tail of a rush, not the middle.',
  'Use the customer\'s name once. Just once.',
  'Two-minute rule: if it takes under two, do it now.',
  'Break rooms are for breaks. Take yours fully.',
  'Smile lands even behind a mask. They hear it.',
  'Walk the floor once an hour with fresh eyes.',
  'The best upsell is the honest one.',
  'Learn one product deeply this week.',
  'Clock in three minutes early — you start calm.',
  'Tag your manager early on a problem, not late.',
  'Ask a regular how their week went.',
  'Zone your section before the shift dies down.',
  'Hydrate. Focus drops before you notice it.',
  'One clean pass beats three rushed ones.',
  'If you spot it, fix it — don\'t log it for later.',
  'Say "let me find out" instead of guessing.',
  'Cover a teammate before they ask.',
  'Reset the fitting room after every single guest.',
  'Watch how your best coworker opens a conversation.',
  'Thank the closing crew. They inherit your shift.',
  'A tidy register reads as a tidy store.',
  'Escalate calmly. The tone is the message.',
  'Take the awkward task first, while you have energy.',
  'Check the top shelf — nobody else does.',
  'Ask for the sale. Politely, but ask.',
  'End your shift by setting up the next person.',
];

const POINT_LINES = [
  { label: 'Clock in on time', pts: 40, max: 40 },
  { label: 'Goals completed', pts: 180, max: 240 },
  { label: 'Kudos given', pts: 45, max: 60 },
  { label: 'Kudos received', pts: 60, max: 60 },
  { label: 'Focus loops', pts: 75, max: 100 },
];
const DAILY_MAX = 500;

function LockedSheet({ title, sub, onClose, children }) {
  return (
    <div className="lk-sheet-back" onClick={onClose}>
      <div className="lk-sheet" onClick={e => e.stopPropagation()}>
        <span className="lk-sheet-grab" />
        <p className="lk-sheet-title">{title}</p>
        {sub && <p className="lk-sheet-sub">{sub}</p>}
        {children}
      </div>
    </div>
  );
}

function HoldBank({ onEnd }) {
  const [p, setP] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const raf = React.useRef(null), t0 = React.useRef(0), fired = React.useRef(false);
  const HOLD = 900;
  const stop = () => { cancelAnimationFrame(raf.current); if (!fired.current) setP(0); };
  const start = () => {
    if (fired.current) return;
    t0.current = performance.now();
    const tick = t => {
      const v = Math.min(1, (t - t0.current) / HOLD);
      setP(v);
      if (v >= 1) { fired.current = true; setDone(true); setTimeout(onEnd, 620); return; }
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
  };
  React.useEffect(() => () => cancelAnimationFrame(raf.current), []);
  return (
    <button className={'lk-bank' + (p > 0 ? ' is-held' : '') + (p > 0.5 ? ' lk-bank-hot' : '') + (done ? ' is-done' : '')} style={{ '--p': p }} onPointerDown={start} onPointerUp={stop} onPointerLeave={stop} onPointerCancel={stop}>
      <span className="lk-bank-fill" style={{ width: p * 100 + '%' }}><i /></span>
      <span className="lk-bank-txt">{p > 0.04 ? (done ? 'banked' : 'keep holding…') : 'hold to bank points'}</span>
      {done && <span className="lk-bank-sparks">{Array.from({ length: 10 }, (_, i) => <i key={i} style={{ '--a': (i * 36) + 'deg' }} />)}</span>}
    </button>
  );
}

function LoopBurst({ n, onDone }) {
  const [ph, setPh] = React.useState('charge');
  React.useEffect(() => {
    const a = setTimeout(() => setPh('pop'), 950);
    const b = setTimeout(() => setPh('rest'), 1500);
    const c = setTimeout(onDone, 3300);
    return () => { clearTimeout(a); clearTimeout(b); clearTimeout(c); };
  }, []);
  return (
    <div className={'lb lb-' + ph}>
      <span className="lb-flash" />
      <div className="lb-core">
        <span className="lb-ring" /><span className="lb-ring lb-ring2" />
        <span className="lb-rays">{Array.from({ length: 14 }, (_, i) => <i key={i} style={{ '--r': (i * 25.7) + 'deg' }} />)}</span>
        <span className="lb-num">{n}</span>
      </div>
      <p className="lb-t">loop {n} in the bag</p>
      <p className="lb-p">+25 pts · {n === 1 ? 'first one down' : n + ' loops today'}</p>
    </div>
  );
}

function LockedInScreen({ goals, onEnd, onOrbit }) {
  const [sec, setSec] = React.useState(0);
  const [sheet, setSheet] = React.useState(null);
  const [tip, setTip] = React.useState(() => Math.floor(Math.random() * TIPS.length));
  const [washGone, setWashGone] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setWashGone(true), 620); return () => clearTimeout(t); }, []);
  React.useEffect(() => { const t = setInterval(() => setSec(s => s + 1), 1000); return () => clearInterval(t); }, []);
  React.useEffect(() => { const t = setInterval(() => setTip(v => (v + 1) % TIPS.length), 7000); return () => clearInterval(t); }, []);

  const LOOP = 150;
  const loopLeft = LOOP - (sec % LOOP);
  const loopPct = (sec % LOOP) / LOOP;
  const loops = Math.floor(sec / LOOP);
  const crew = LEADERBOARD_PEERS.slice(0, 4);
  const active = 34;
  const pad = n => String(n).padStart(2, '0');
  const list = goals.length ? goals : ALL_GOALS.slice(0, 6);
  const SESSION = 4 * 3600;
  const sessionPct = Math.min(1, sec / SESSION);
  const railRef = React.useRef(null);
  const [card, setCard] = React.useState(0);
  const onRail = () => {
    const r = railRef.current;
    if (!r || r.children.length < 2) return;
    const pitch = r.children[1].offsetLeft - r.children[0].offsetLeft;
    const atEnd = r.scrollLeft >= r.scrollWidth - r.clientWidth - 2;
    const n = atEnd ? r.children.length - 1
      : Math.max(0, Math.min(r.children.length - 1, Math.round(r.scrollLeft / pitch)));
    setCard(v => (n === v ? v : n));
  };
  const START = 17, TARGET = 40, STORE_AVG = 24, PER_BOTTLE = 4;
  const lifts = 3 + Math.floor(sec / 420);
  const banked = START + loops;
  const [pop, setPop] = React.useState(null);
  const prevLoops = React.useRef(0);
  const bodyRef = React.useRef(null), tankRef = React.useRef(null);
  const fire = n => {
    let d = { dx: 10, dy: 260 };
    const b = bodyRef.current, t = tankRef.current;
    if (b && t) {
      const br = b.getBoundingClientRect(), tr = t.getBoundingClientRect();
      const slot = t.children[Math.min(t.children.length - 1, Math.floor((START + n) / 4))];
      const sr = slot ? slot.getBoundingClientRect() : tr;
      d = { dx: Math.round(sr.left + sr.width / 2 - (br.left + 44 + 9)), dy: Math.round(sr.top + sr.height / 2 - (br.top + br.height * 0.3)) };
    }
    setPop({ n, k: Date.now(), ...d });
    setTimeout(() => setPop(p => (p && p.n === n ? null : p)), 3400);
  };
  React.useEffect(() => {
    if (loops > prevLoops.current) { prevLoops.current = loops; fire(loops); }
  }, [loops]);
  const closing = loopLeft <= 6;

  const hype = loops >= 6 ? { t: 'big', h: 'day' }
    : loops >= 4 ? { t: 'strong', h: 'shift' }
    : loops >= 2 ? { t: 'good', h: 'rhythm' }
    : loops >= 1 ? { t: 'first one', h: 'down' }
    : { t: 'settling', h: 'in' };

  return (
    <div className="lk-screen">
      {!washGone && <span className="lk-wash" />}
{pop && <div className="lk-pop" key={pop.k}><b>can {pop.n} cracked</b><em>+25 pts</em></div>}
      <div className="lk-top">
        <span className="lk-live"><i />locked in</span>
        <div className="lk-tools-right">
          <button className="lk-tool" onClick={() => setSheet('goals')} aria-label="Your goals this session"><Icon name="target" size={17} weight="fill" color="#FF5A2E" /></button>
          <button className="lk-tool" onClick={() => setSheet('points')} aria-label="How today pays"><Icon name="coins" size={17} weight="fill" color="var(--orange-500)" /></button>
          <button className="lk-tool lk-tool-orbit" onClick={() => setSheet('orbit')} aria-label={active + ' locked in with you'}><Icon name="planet" size={17} weight="fill" color="var(--violet-300)" /><span className="lk-tool-badge">{active}</span></button>
        </div>
      </div>

      <div className="lk-hype">
        <p className="lk-hype-line">{hype.t} <b>{hype.h}</b></p>
        <p className="lk-hype-sub">{banked} cans · {Math.floor(banked / PER_BOTTLE)} of {TARGET / PER_BOTTLE} packs</p>
      </div>

      <div className={'lk-core' + (closing ? ' is-closing' : '')}>
        <div className="lk-nrg" onClick={() => fire(loops + 1)}>
          <span className="lk-lid"><i className="lk-lid-tab" /></span>
          <div className="lk-nrg-body" ref={bodyRef}>
            <div className="lk-nrg-liquid" style={{ height: loopPct * 100 + '%' }}>
              <span className="lk-nrg-surf" />
              <span className="lk-nrg-surf lk-nrg-surf2" />
            </div>
            <div className="lk-nrg-fizz">
              {Array.from({ length: 9 }).map((_, i) => (
                <i key={i} style={{ '--x': (10 + i * 9.4) + '%', '--s': (3 + (i % 3) * 2) + 'px', '--d': (i * 0.44).toFixed(2) + 's', '--t': (2.8 + (i % 4) * 0.6).toFixed(2) + 's' }} />
              ))}
            </div>
            <span className="lk-wrap">
              <b>PRYZE</b>
              <em><Icon name="lightning" size={11} weight="fill" color="currentColor" />energy</em>
            </span>
            <span className="lk-cyl" />
            <span className="lk-ribs" />
          </div>
          <span className="lk-can-shadow" />
          <span className="lk-rider" style={{ bottom: `calc(26px + ${loopPct} * (100% - 74px))` }}>
            {USER.photo ? <img src={USER.photo} alt="" /> : (USER.name || 'You')[0]}
          </span>
        </div>
        <div className="lk-core-side">
          <div className={'lk-next' + (closing ? ' is-closing' : '')}>
            <span className="lk-next-lbl">can {banked + 1} lands in</span>
            <span className="lk-next-time" key={loopLeft}>{pad(Math.floor(loopLeft / 60))}:{pad(loopLeft % 60)}</span>
            <span className="lk-next-bar"><i style={{ width: loopPct * 100 + '%' }} /></span>
            <span className="lk-next-foot">{Math.round(loopPct * 100)}% full · <b>+25 pts</b> when it seals</span>
          </div>
          <div className="lk-lifts">
            <span className="lk-lifts-n">{lifts}</span>
            <span className="lk-lifts-lbl">phone pickups</span>
            <span className="lk-lifts-pts">−{lifts * 5} pts</span>
          </div>
        </div>
        {pop && <span className="lk-fly" key={'f' + pop.k} style={{ '--c': 'var(--nrg)', '--dx': pop.dx + 'px', '--dy': pop.dy + 'px' }} />}
      </div>

      <div className="lk-tank">
        <div className="lk-tank-top">
          <p className="lk-tank-label">stash today</p>
          <p className="lk-tank-count">{Math.floor(banked / PER_BOTTLE)}<em>/{TARGET / PER_BOTTLE} packs</em></p>
        </div>
        <div className={'lk-tank-glass' + (pop ? ' is-catching' : '')} ref={tankRef}>
          {Array.from({ length: 10 }, (_, i) => {
            const f = Math.max(0, Math.min(1, banked / PER_BOTTLE - i));
            return <span className={'lk-can' + (f >= 1 ? ' is-full' : '')} key={i} style={{ '--f': (f * 100) + '%' }}><i /></span>;
          })}
        </div>
        <p className="lk-tank-note">{TARGET - banked} more cans and you cash out <b>$10</b>.</p>
      </div>

      <p className="lk-intel" key={tip}><span className="lk-intel-tag">tip</span><span className="lk-intel-txt">{TIPS[tip]}</span></p>

      <div className="lk-foot">
        <HoldBank onEnd={() => onEnd({
          batteries: banked, bottles: Math.floor(banked / PER_BOTTLE), lifts,
          goals: list.length, mins: Math.max(1, Math.round(banked * (LOOP / 60)) + Math.round((sec % LOOP) / 60)),
          total: banked * 25 + Math.floor(banked / PER_BOTTLE) * 40 + list.length * 30 - lifts * 5,
          streak: 6, vsAvg: 18,
        })} />
      </div>
      {sheet === 'orbit' && (
        <div className="lk-peek" onClick={() => setSheet(null)}>
          <div className="lk-peek-card" onClick={e => e.stopPropagation()}>
            <p className="lk-peek-title">Orbit, right now</p>
            <p className="lk-peek-sub">{active} on shift at {USER.store}</p>
            <div className="lk-peek-ring">
              <span className="lk-peek-spin">{LEADERBOARD_PEERS.slice(0, 6).map((p, i) => (
                <span className="lk-peek-dot" key={p.id} style={{ '--a': (i * 60) + 'deg' }}>
                  <span className="lk-peek-face">{p.photo ? <img src={p.photo} alt="" /> : p.name[0]}</span>
                </span>
              ))}</span>
              <span className="lk-peek-center">{COMPANIES[USER.company] && COMPANIES[USER.company].logo
                ? <img src={COMPANIES[USER.company].logo} alt="" />
                : ((COMPANIES[USER.company] && COMPANIES[USER.company].initials) || 'P')}</span>
            </div>
            <button className="lk-peek-back" onClick={() => setSheet(null)}>Back to my shift</button>
          </div>
        </div>
      )}
      {sheet === 'goals' && (
        <LockedSheet title="stuff that pays today" sub={`${list.length} goals on your card`} onClose={() => setSheet(null)}>
          <div className="lk-list">
            {list.map(g => (
              <div className="lk-item" key={g.id}>
                <span className="lk-item-emoji">{g.emoji || '\u{1F3AF}'}</span>
                <span className="lk-item-name">{g.short || g.title}</span>
                <span className="lk-item-pts">+{g.pts}</span>
              </div>
            ))}
          </div>
        </LockedSheet>
      )}
      {sheet === 'points' && (
        <LockedSheet title="How today pays" sub={`Up to ${DAILY_MAX} points a day`} onClose={() => setSheet(null)}>
          <div className="lk-list">
            {POINT_LINES.map(l => (
              <div className="lk-item" key={l.label}>
                <span className="lk-item-name">{l.label}</span>
                <span className="lk-item-cap">{l.pts} / {l.max}</span>
                <span className="lk-item-bar"><i style={{ width: (l.pts / l.max) * 100 + '%' }} /></span>
              </div>
            ))}
          </div>
          <p className="lk-note">Your total lands on the bank screen when you end the shift.</p>
        </LockedSheet>
      )}
    </div>
  );
}

window.PryzeShift = { LockedInScreen };
