// bdk-windows.jsx — window chrome, desktop icons, menubar, taskbar, start menu.

function BdkSoundIcon({ on }) {
  return on ? (
    <svg className="bdk-snd-ic" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M4 9v6h4l5 5V4L8 9H4z" fill="currentColor" />
      <path d="M16 8.8a4 4 0 0 1 0 6.4M18.7 6.3a7.5 7.5 0 0 1 0 11.4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  ) : (
    <svg className="bdk-snd-ic" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M4 9v6h4l5 5V4L8 9H4z" fill="currentColor" />
      <path d="M16.5 9.5l6 5M22.5 9.5l-6 5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

function BdkWindow({ def, st, delay = 0, scale = 1, onFocus, onMove, onResize, onClose, onMin, children }) {
  const drag = React.useRef(null);
  const rsz = React.useRef(null);
  const secRef = React.useRef(null);

  const down = (e) => {
    if (e.target.closest('.bdkwin-light')) return;
    onFocus(def.id);
    drag.current = { sx: e.clientX, sy: e.clientY, ox: st.x, oy: st.y };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const move = (e) => {
    if (!drag.current) return;
    onMove(def.id, drag.current.ox + (e.clientX - drag.current.sx) / scale, drag.current.oy + (e.clientY - drag.current.sy) / scale);
  };
  const up = () => { drag.current = null; };

  const rDown = (e) => {
    e.stopPropagation();
    onFocus(def.id);
    rsz.current = { sx: e.clientX, sy: e.clientY, ow: secRef.current.offsetWidth, oh: secRef.current.offsetHeight };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const rMove = (e) => {
    if (!rsz.current) return;
    onResize(def.id, rsz.current.ow + (e.clientX - rsz.current.sx) / scale, rsz.current.oh + (e.clientY - rsz.current.sy) / scale);
  };
  const rUp = () => { rsz.current = null; };

  return (
    <section
      ref={secRef}
      className={'bdkwin' + (def.hot ? ' hot' : '')}
      data-screen-label={def.title}
      style={{ left: st.x, top: st.y, width: st.w || def.w, height: st.h || undefined, zIndex: st.z, animationDelay: delay + 'ms' }}
      onPointerDown={() => onFocus(def.id)}
    >
      <header className="bdkwin-title" onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}>
        <div className="bdkwin-lights">
          <button className="bdkwin-light red" title="Close" onClick={(e) => { e.stopPropagation(); window.BDKSOUND.play('click'); onClose(def.id); }}></button>
          <button className="bdkwin-light yellow" title="Minimize" onClick={(e) => { e.stopPropagation(); window.BDKSOUND.play('click'); onMin(def.id); }}></button>
          <span className="bdkwin-light green"></span>
        </div>
        <span className="bdkwin-name">{def.title}</span>
        <span className="bdkwin-lights-sp"></span>
      </header>
      <div className="bdkwin-body">{children}</div>
      <div className="bdkwin-resize" title="Resize" onPointerDown={rDown} onPointerMove={rMove} onPointerUp={rUp} onPointerCancel={rUp}></div>
    </section>
  );
}

function BdkDesktopIcon({ id, glyph, label, delay = 0, onOpen }) {
  return (
    <button className="bdk-icon" style={{ animationDelay: delay + 'ms' }} onClick={() => { window.BDKSOUND.play('blip'); onOpen(); }}>
      <span className="bdk-icon-glyph">
        {id ? <img src={'bdk/icons/' + id + '.svg'} alt="" draggable="false" /> : glyph}
      </span>
      <span>{label}</span>
    </button>
  );
}

const BDK_MENU_ITEMS = ['FILE', 'EDIT', 'VIEW', 'GAMBLE', 'HELP'];

function BdkMenubar({ onItem, sound, onSound, live, clock }) {
  const socials = BDK_SOCIALS.slice().sort((a, b) => (a.k === 'KICK' ? 1 : 0) - (b.k === 'KICK' ? 1 : 0));
  return (
    <nav className="bdk-menu" data-screen-label="Menubar">
      <span className="bdk-menu-brand"> KevOS</span>
      {BDK_MENU_ITEMS.map((m) => (
        <button key={m} className="bdk-menu-item" onClick={() => { window.BDKSOUND.play('click'); onItem(m); }}>{m}</button>
      ))}
      <span className="bdk-menu-spacer"></span>
      <BdkCodeChip small={true}></BdkCodeChip>
      <button className="bdk-soc bdk-snd" title={sound ? 'Sound on' : 'Muted'} onClick={() => { window.BDKSOUND.play('click'); onSound(!sound); }}><BdkSoundIcon on={sound}></BdkSoundIcon></button>
      {socials.map((s) => (
        <a key={s.k} className="bdk-soc" href={s.href} target="_blank" rel="noreferrer" title={s.label}><img className="bdk-soc-ic" src={s.ic} alt={s.k} /></a>
      ))}
      <span className={'bdk-live-ind' + (live ? ' on' : '')} title={live ? 'Live now' : 'Offline'}><i></i>{live ? 'LIVE' : 'OFFLINE'}</span>
      <span className="bdk-menu-clock">{clock}</span>
    </nav>
  );
}

function BdkDock({ defs, wins, onOpen }) {
  const ref = React.useRef(null);
  const onMove = (e) => {
    const dock = ref.current; if (!dock) return;
    dock.querySelectorAll('.bdk-dock-item').forEach((it) => {
      const ico = it.querySelector('.bdk-dock-ico'); if (!ico) return;
      const r = it.getBoundingClientRect();
      const dist = Math.abs(e.clientX - (r.left + r.width / 2));
      const boost = Math.max(0, 1 - dist / 140);
      ico.style.transform = 'translateY(' + (-18 * boost) + 'px) scale(' + (1 + 0.45 * boost) + ')';
    });
  };
  const reset = () => {
    const dock = ref.current; if (!dock) return;
    dock.querySelectorAll('.bdk-dock-ico').forEach((it) => { it.style.transform = ''; });
  };
  return (
    <div className="bdk-dock-mac" ref={ref} onMouseMove={onMove} onMouseLeave={reset} data-screen-label="Dock">
      {defs.map((d) => (
        <button key={d.id} className="bdk-dock-item" title={d.title} onClick={() => { window.BDKSOUND.play('blip'); onOpen(d.id); }}>
          <span className="bdk-dock-ico">
            <img src={'bdk/icons/' + d.id + '.svg'} alt={d.title} draggable="false" />
            <span className={'bdk-dock-dot' + (wins[d.id] && wins[d.id].open ? ' on' : '')}></span>
          </span>
          <span className="bdk-dock-label">{d.title}</span>
        </button>
      ))}
    </div>
  );
}

function BdkTaskbar({ defs, wins, onTask, onStart, startOpen, clock, isMobile }) {
  return (
    <div className="bdk-bar" data-screen-label="Taskbar">
      {!isMobile && (
        <button className={'bdk-start' + (startOpen ? ' on' : '')} onClick={() => { window.BDKSOUND.play('click'); onStart(); }}>◆ START</button>
      )}
      {!isMobile && wins && defs.filter((d) => wins[d.id] && wins[d.id].open).map((d) => (
        <button
          key={d.id}
          className={'bdk-task' + (wins[d.id].min ? '' : ' on')}
          onClick={() => { window.BDKSOUND.play('click'); onTask(d.id); }}
        >{d.title}</button>
      ))}
      <span className="bdk-bar-spacer"></span>
      <span className="bdk-clock">{clock}</span>
    </div>
  );
}

function BdkStartMenu({ defs, onOpen, onReboot }) {
  return (
    <nav className="bdk-startmenu" data-screen-label="Start menu">
      <p className="bdk-sm-head">KevOS v0.485 — HUB OF VALUE</p>
      {defs.map((d) => (
        <button key={d.id} className="bdk-sm-item" onClick={() => { window.BDKSOUND.play('blip'); onOpen(d.id); }}>
          <span className="bdk-sm-glyph">{d.glyph}</span>{d.title}
        </button>
      ))}
      <div className="bdk-sm-div"></div>
      {BDK_SOCIALS.map((s) => (
        <a key={s.k} className="bdk-sm-item" href={s.href} target="_blank" rel="noreferrer">
          <img className="bdk-sm-ic" src={s.ic} alt="" />{s.label}
        </a>
      ))}
      <div className="bdk-sm-div"></div>
      <button className="bdk-sm-item" onClick={onReboot}>
        <span className="bdk-sm-glyph">⟳</span>REBOOT KevOS
      </button>
      <p className="bdk-sm-foot">18+ only. Gambling can be addictive — play responsibly. BeGambleAware.org</p>
    </nav>
  );
}

Object.assign(window, { BdkWindow, BdkDesktopIcon, BdkMenubar, BdkTaskbar, BdkStartMenu, BdkSoundIcon, BdkDock });
