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

/* Locked in — the on-shift screen. No nav, no live point counter: the bank
   screen is the payoff. Two bars carry the whole loop. */
const LOOP_MS = 5 * 60 * 1000;
const SESSION_MS = 4 * 60 * 60 * 1000;
const DAILY_CAP = 500;

const TIPS = [
  'Greet within 10 seconds. It sets the whole interaction.',
  'Use their name once. People remember it.',
  'Walk the customer to the aisle, don\'t point.',
  'Ask what they\'re shopping for, not if they need help.',
  'Face the shelf while you talk — hands busy, ears open.',
  'A tidy endcap sells more than a sign.',
  'Say the price out loud before they ask.',
  'Offer the second item once. Never twice.',
  'Thank the person behind them in line too.',
  'Slow hands, calm voice, at the register.',
  'Restock while you wait. Idle looks bad, feels worse.',
  'Kudos costs nothing. Give one this hour.',
  'If it\'s on the floor, it\'s yours to pick up.',
  'Learn one new SKU per shift.',
  'Eye contact beats a scripted greeting.',
  'Ask a coworker how their day is going.',
  'Break the awkward silence with the weather. It works.',
  'Confirm the return policy before they walk away.',
  'Two carts out, two carts back. Keep the loop.',
  'Smile before you speak — they hear it.',
  'Hand the bag, don\'t slide it.',
  'Point out the deal they missed. They come back.',
  'Reset your section before your break.',
  'If you don\'t know, say so and go find out.',
  'A quick apology fixes most of it.',
  'Watch the line, not your phone.',
  'Refill the bags before the rush.',
  'Cover a coworker for 60 seconds. They\'ll return it.',
  'Take the water. Dehydrated shifts drag.',
  'End the shift with your area better than you found it.',
];

function LockedScreen({ goals, onEnd }) {
  const [ms, setMs] = React.useState(0);
  const [sheet, setSheet] = React.useState(null);
  const [tip, setTip] = React.useState(0);
  const [slide, setSlide] = React.useState(0);
  const drag = React.useRef(null);
  const track = React.useRef(null);

  React.useEffect(() => { const t = setInterval(() => setMs(v => v + 1000), 1000); return () => clearInterval(t); }, []);
  React.useEffect(() => { const t = setInterval(() => setTip(v => (v + 1) % TIPS.length), 12000); return () => clearInterval(t); }, []);

  const loops = Math.floor(ms / LOOP_MS);
  const loopPct = ((ms % LOOP_MS) / LOOP_MS) * 100;
  const sessPct = Math.min(100, (ms / SESSION_MS) * 100);
  const mins = Math.floor(ms / 60000);
  const active = LEADERBOARD_PEERS.slice(0, 4);
  const competing = 23 + (USER.streak % 7);

  const onDown = e => { drag.current = { x: e.clientX, w: track.current.offsetWidth - 62 }; e.currentTarget.setPointerCapture(e.pointerId); };
  const onMove = e => { if (!drag.current) return; setSlide(Math.max(0, Math.min(1, (e.clientX - drag.current.x) / drag.current.w))); };
  const onUp = () => { if (!drag.current) return; const done = slide > 0.88; drag.current = null; if (done) { setSlide(1); setTimeout(onEnd, 260); } else setSlide(0); };

  return (
    <div className="lk-screen">
      <span className="lk-wash" />
      <div className="lk-top">
        <button className={`lk-tool ${sheet === 'goals' ? 'lk-tool-on' : ''}`} onClick={() => setSheet(sheet === 'goals' ? null : 'goals')} aria-label="Your goals"><Icon name="target" size={20} weight="fill" color="currentColor" /></button>
        <button className={`lk-tool ${sheet === 'points' ? 'lk-tool-on' : ''}`} onClick={() => setSheet(sheet === 'points' ? null : 'points')} aria-label="Points breakdown"><Icon name="coin" size={20} weight="fill" color="currentColor" /></button>
        <button className="lk-tool" onClick={() => setSheet(sheet === 'orbit' ? null : 'orbit')} aria-label="Orbit"><Icon name="planet" size={20} weight="fill" color="currentColor" /></button>
      </div>

      <div className="lk-head">
        <span className="lk-live"><i />Locked in</span>
        <p className="lk-elapsed">{mins < 60 ? mins + ' min' : Math.floor(mins / 60) + 'h ' + (mins % 60) + 'm'} in</p>
      </div>

      <div className="lk-bars">
        <div className="lk-bar">
          <div className="lk-bar-top"><span className="lk-bar-name">Focus loop</span><span className="lk-bar-val">{Math.ceil((LOOP_MS - (ms % LOOP_MS)) / 60000)} min left</span></div>
          <div className="lk-track"><span className="lk-fill lk-fill-loop" style={{ width: loopPct + '%' }} /></div>
          <p className="lk-bar-sub">{loops} loop{loops === 1 ? '' : 's'} closed this shift</p>
        </div>
        <div className="lk-bar">
          <div className="lk-bar-top"><span className="lk-bar-name">Pryze session</span><span className="lk-bar-val">{Math.round(sessPct)}%</span></div>
          <div className="lk-track"><span className="lk-fill lk-fill-sess" style={{ width: sessPct + '%' }} /></div>
          <p className="lk-bar-sub">builds the whole shift</p>
        </div>
      </div>

      <div className="lk-others">
        <span className="lk-faces">
          {active.map((p, i) => p.photo
            ? <img key={p.name} src={p.photo} alt="" style={{ zIndex: 4 - i }} />
            : <span key={p.name} style={{ zIndex: 4 - i }}>{p.name[0]}</span>)}
        </span>
        <p className="lk-others-txt"><b>{competing} pryzers</b> on shift right now</p>
      </div>

      <div className="lk-tip">
        <span className="lk-tip-cap">Tip</span>
        <p className="lk-tip-txt" key={tip}>{TIPS[tip]}</p>
      </div>

      <div className="lk-slider" ref={track}>
        <span className="lk-slider-fill" style={{ width: `calc(${slide * 100}% + 62px)` }} />
        <span className="lk-slider-label" style={{ opacity: 1 - slide * 1.6 }}>Swipe to bank shift</span>
        <span className="lk-knob" style={{ transform: `translateX(calc(${slide} * (100% * 0 + var(--lk-w))))`, left: `calc(${slide} * (100% - 62px) + 4px)` }}
          onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
          <Icon name="arrow-right" size={18} weight="bold" color="#14122A" />
        </span>
      </div>

      {sheet && (
        <div className="lk-sheet-bg" onClick={() => setSheet(null)}>
          <div className="lk-sheet" onClick={e => e.stopPropagation()}>
            <span className="sheet-handle" />
            {sheet === 'goals' && (<>
              <p className="lk-sheet-title">This session's goals</p>
              <div className="lk-glist">
                {goals.map(g => (
                  <div className="lk-grow" key={g.id}>
                    <span className="lk-gemoji">{g.emoji}</span>
                    <span className="lk-gname">{g.short || g.title}</span>
                    <span className="lk-gpts">+{g.pts}</span>
                  </div>
                ))}
              </div>
            </>)}
            {sheet === 'points' && (<>
              <p className="lk-sheet-title">How you earn today</p>
              <div className="lk-glist">
                {[
                  { l: 'Session goals', v: goals.reduce((a, g) => a + g.pts, 0) },
                  { l: 'Focus loops', v: 60 },
                  { l: 'Kudos received', v: 40 },
                  { l: 'Kudos given', v: 20 },
                  { l: 'Shift completed', v: 100 },
                ].map(r => (
                  <div className="lk-grow" key={r.l}><span className="lk-gname">{r.l}</span><span className="lk-gpts">up to {r.v}</span></div>
                ))}
              </div>
              <p className="lk-cap">Daily max {DAILY_CAP} pts · roughly ${(DAILY_CAP / PTS_PER_DOLLAR).toFixed(0)}</p>
            </>)}
            {sheet === 'orbit' && (<>
              <p className="lk-sheet-title">Head to Orbit?</p>
              <p className="lk-cap">Your shift keeps running while you're there.</p>
              <button className="lk-go-orbit" onClick={() => setSheet(null)}>Open Orbit</button>
            </>)}
          </div>
        </div>
      )}
    </div>
  );
}

window.PryzeLocked = { LockedScreen };
