// bdk-phone.jsx — mobile experience: KevOS as a phone. Lock screen → swipe up → home grid → app sheets.

const BDK_HOME_APPS = ['cta', 'leader', 'tiers', 'tiermatch', 'bounty', 'slots', 'free'];

function BdkStatusBar({ clock, live, sound, onSound }) {
  return (
    <div className="bdk-statusbar">
      <span className="bdk-sb-time">{clock ? clock.slice(0, 5) : ''}</span>
      <span className="bdk-sb-right">
        <button className="bdk-sb-snd" title={sound ? 'Sound on' : 'Muted'} onClick={() => { window.BDKSOUND.play('click'); onSound(!sound); }}><BdkSoundIcon on={sound}></BdkSoundIcon></button>
        <span className="bdk-sb-net">BDK</span>
        <span className="bdk-sb-bars"><i></i><i></i><i></i><i className="off"></i></span>
        <span className={'bdk-sb-batt' + (live ? '' : ' low')}>{live ? '2%' : '1%'}</span>
      </span>
    </div>
  );
}

function BdkLockScreen({ clock, onUnlock, live }) {
  const [dy, setDy] = React.useState(0);
  const [leaving, setLeaving] = React.useState(false);
  const start = React.useRef(null);
  const cur = React.useRef(0);
  const now = new Date();
  const date = now.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });

  const down = (e) => { start.current = e.clientY; cur.current = 0; };
  const move = (e) => {
    if (start.current == null) return;
    cur.current = Math.min(0, e.clientY - start.current);
    setDy(cur.current);
  };
  const up = () => {
    if (start.current == null) return;
    start.current = null;
    if (cur.current < -70) {
      setLeaving(true);
      window.BDKSOUND.play('pop');
      setTimeout(onUnlock, 280);
    } else {
      setDy(0);
    }
  };

  return (
    <div
      className={'bdk-lock' + (leaving ? ' leaving' : '')}
      data-screen-label="Lock screen"
      style={{ transform: leaving ? 'translateY(-100%)' : 'translateY(' + dy + 'px)', transition: start.current == null ? 'transform .3s cubic-bezier(.3,1,.4,1)' : 'none' }}
      onPointerDown={down}
      onPointerMove={move}
      onPointerUp={up}
      onPointerCancel={up}
    >
      <div className="bdk-lock-clock">
        <div className="bdk-lock-time">{clock ? clock.slice(0, 5) : ''}</div>
        <div className="bdk-lock-date">{date}</div>
      </div>
      <div className="bdk-lock-notif">
        <div className="bdk-lock-notif-app"><span>◆</span> KevOS · now</div>
        <div className="bdk-lock-notif-body"><b>ERROR 0x485:</b> profits not found. Tap to ignore for the 4th time today.</div>
      </div>
      <div className="bdk-lock-kev">
        <div className="bdk-lock-kev-face"><img src="bdk/assets/kev.jpg" alt="Biz Dev Kev" /></div>
        <div className="bdk-lock-kev-name">BIZ DEV KEV {live ? '· LIVE NOW' : ''}</div>
      </div>
      <div className="bdk-lock-hint">
        <span className="bdk-lock-chevron">⌃</span>
        <span>SWIPE UP TO ENTER</span>
        <div className="bdk-lock-bar"></div>
      </div>
    </div>
  );
}

function BdkAppIcon({ def, onOpen, delay }) {
  return (
    <button className="bdk-appicon" style={{ animationDelay: delay + 'ms' }} onClick={() => { window.BDKSOUND.play('blip'); onOpen(def.id); }}>
      <span className={'bdk-appicon-tile' + (def.hot ? ' hot' : '')}><img src={'bdk/icons/' + def.id + '.svg'} alt="" draggable="false" /></span>
      <span className="bdk-appicon-label">{def.title.replace(/\.(EXE|TXT)$/, '')}</span>
    </button>
  );
}

function BdkAppSheet({ def, children, onClose }) {
  const [leaving, setLeaving] = React.useState(false);
  const start = React.useRef(null);
  const cur = React.useRef(0);
  const [dy, setDy] = React.useState(0);
  const close = () => { setLeaving(true); window.BDKSOUND.play('click'); setTimeout(onClose, 240); };
  return (
    <div className={'bdk-sheet-overlay' + (leaving ? ' leaving' : '')} onClick={(e) => { if (e.target.classList.contains('bdk-sheet-overlay')) close(); }}>
      <div className="bdk-sheet" data-screen-label={'App: ' + def.title} style={{ transform: dy ? 'translateY(' + dy + 'px)' : undefined }}>
        <header
          className="bdk-sheet-bar"
          onPointerDown={(e) => { start.current = e.clientY; cur.current = 0; }}
          onPointerMove={(e) => { if (start.current != null) { cur.current = Math.max(0, e.clientY - start.current); setDy(cur.current); } }}
          onPointerUp={() => { start.current = null; if (cur.current > 80) close(); else setDy(0); }}
          onPointerCancel={() => { setDy(0); start.current = null; }}
        >
          <span className="bdk-sheet-grab"></span>
          <span className="bdk-sheet-name"><span className="bdkwin-glyph">{def.glyph}</span> {def.title}</span>
          <button className="bdk-sheet-done" onClick={close}>✕</button>
        </header>
        <div className="bdk-sheet-body">{children}</div>
      </div>
    </div>
  );
}

function BdkPhone({ t, APPS, clock, live, sound, onSound, popups, closePopup, retryPopup }) {
  const [phase, setPhase] = React.useState('lock');
  const [appId, setAppId] = React.useState(null);
  const def = appId ? BDK_DEFS.find((d) => d.id === appId) : null;

  return (
    <div className="bdk-phone" data-screen-label="KevOS Mobile" style={{ backgroundImage: 'url(/backgrounds/mobile-bg.png)' }}>
      <BdkStatusBar clock={clock} live={live} sound={sound} onSound={onSound}></BdkStatusBar>

      {phase === 'home' && (
        <div className="bdk-home" data-screen-label="Home screen">
          <div className="bdk-home-widget">
            <div className="bdk-home-w-text">
              <div className="bdk-home-w-title">KevOS</div>
              <div className="bdk-home-w-sub">{live ? '● LIVE NOW ON KICK' : 'A BIZ DEV KEV EXPERIENCE'}</div>
              <button className="bdk-home-w-cta" onClick={() => { window.BDKSOUND.play('blip'); setAppId('cta'); }}>JOIN YEET · CODE BDKev →</button>
            </div>
          </div>
          <div className="bdk-appgrid">
            {BDK_HOME_APPS.map((id, i) => (
              <BdkAppIcon key={id} def={BDK_DEFS.find((d) => d.id === id)} onOpen={setAppId} delay={i * 45}></BdkAppIcon>
            ))}
          </div>
          <div className="bdk-dock">
            {BDK_SOCIALS.map((s) => (
              <a key={s.k} className="bdk-dock-soc" href={s.href} target="_blank" rel="noreferrer" title={s.label}><img src={s.ic} alt={s.k} /></a>
            ))}
          </div>
        </div>
      )}

      {def && (
        <BdkAppSheet def={def} onClose={() => setAppId(null)}>{APPS[def.app]()}</BdkAppSheet>
      )}

      {popups.map((p) => (
        <div className="bdk-popup-wrap" key={p.id}>
          <BdkPopup p={p} onClose={closePopup} onRetry={retryPopup}></BdkPopup>
        </div>
      ))}

      {phase === 'lock' && (
        <BdkLockScreen clock={clock} live={live} onUnlock={() => setPhase('home')}></BdkLockScreen>
      )}

      {phase === 'home' && <div className="bdk-home-indicator" onClick={() => { if (appId) setAppId(null); }}></div>}
    </div>
  );
}

Object.assign(window, { BdkPhone });
