/* ============ ATHARV.OS — System Tray ============ */

/* ===== Tooltip wrapper ===== */
function Tip({ label, children, delay = 600 }) {
  const [show, setShow] = React.useState(false);
  const [pos, setPos] = React.useState({ x: 0, y: 0 });
  const tref = React.useRef();
  const enter = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    setPos({ x: r.left + r.width/2, y: r.top - 4 });
    tref.current = setTimeout(() => setShow(true), delay);
  };
  const leave = () => { clearTimeout(tref.current); setShow(false); };
  return (
    <span onMouseEnter={enter} onMouseLeave={leave} onMouseDown={leave} style={{display:'inline-flex'}}>
      {children}
      {show && (
        <div className="w95-tip" style={{ left: pos.x, top: pos.y }}>{label}</div>
      )}
    </span>
  );
}

/* ===== Pixel-art tray icons (16x16) ===== */
const TrayIcons = {
  speaker: (muted) => `<svg viewBox="0 0 16 16" width="16" height="16" shape-rendering="crispEdges">
    <rect x="2" y="6" width="2" height="4" fill="#000"/>
    <rect x="4" y="5" width="1" height="6" fill="#000"/>
    <rect x="5" y="4" width="1" height="8" fill="#000"/>
    <rect x="6" y="3" width="1" height="10" fill="#000"/>
    <rect x="2" y="6" width="2" height="4" fill="#C0C0C0"/>
    <rect x="4" y="5" width="1" height="6" fill="#C0C0C0"/>
    <rect x="5" y="4" width="1" height="8" fill="#C0C0C0"/>
    <rect x="6" y="3" width="1" height="10" fill="#C0C0C0"/>
    <rect x="2" y="6" width="1" height="4" fill="#000"/>
    <rect x="3" y="5" width="1" height="1" fill="#000"/>
    <rect x="3" y="10" width="1" height="1" fill="#000"/>
    <rect x="4" y="4" width="1" height="1" fill="#000"/>
    <rect x="4" y="11" width="1" height="1" fill="#000"/>
    <rect x="5" y="3" width="1" height="1" fill="#000"/>
    <rect x="5" y="12" width="1" height="1" fill="#000"/>
    <rect x="6" y="3" width="1" height="10" fill="#000"/>
    ${muted
      ? `<line x1="9" y1="4" x2="14" y2="12" stroke="#FF0000" stroke-width="1.5"/><line x1="14" y1="4" x2="9" y2="12" stroke="#FF0000" stroke-width="1.5"/>`
      : `<rect x="9" y="6" width="1" height="4" fill="#000"/>
         <rect x="11" y="4" width="1" height="8" fill="#000"/>
         <rect x="13" y="2" width="1" height="12" fill="#000"/>`}
  </svg>`,
  network: (active) => `<svg viewBox="0 0 16 16" width="16" height="16" shape-rendering="crispEdges">
    <!-- back monitor -->
    <rect x="1" y="2" width="7" height="5" fill="#C0C0C0"/>
    <rect x="1" y="2" width="7" height="1" fill="#FFFFFF"/>
    <rect x="1" y="2" width="1" height="5" fill="#FFFFFF"/>
    <rect x="7" y="2" width="1" height="5" fill="#404040"/>
    <rect x="1" y="6" width="7" height="1" fill="#404040"/>
    <rect x="2" y="3" width="5" height="3" fill="${active ? '#39FF39' : '#0000AA'}"/>
    <rect x="3" y="7" width="3" height="1" fill="#000"/>
    <rect x="2" y="8" width="5" height="1" fill="#000"/>
    <!-- cable -->
    <rect x="6" y="9" width="3" height="1" fill="#000"/>
    <rect x="8" y="10" width="1" height="1" fill="#000"/>
    <!-- front monitor -->
    <rect x="8" y="9" width="7" height="5" fill="#C0C0C0"/>
    <rect x="8" y="9" width="7" height="1" fill="#FFFFFF"/>
    <rect x="8" y="9" width="1" height="5" fill="#FFFFFF"/>
    <rect x="14" y="9" width="1" height="5" fill="#404040"/>
    <rect x="8" y="13" width="7" height="1" fill="#404040"/>
    <rect x="9" y="10" width="5" height="3" fill="${active ? '#39FF39' : '#0000AA'}"/>
    <rect x="10" y="14" width="3" height="1" fill="#000"/>
    <rect x="9" y="15" width="5" height="1" fill="#000"/>
  </svg>`,
  note: (pulse) => `<svg viewBox="0 0 16 16" width="16" height="16" shape-rendering="crispEdges">
    <rect x="6" y="2" width="1" height="9" fill="#000"/>
    <rect x="7" y="2" width="1" height="9" fill="#000"/>
    <rect x="8" y="2" width="4" height="1" fill="#000"/>
    <rect x="11" y="3" width="1" height="3" fill="#000"/>
    <rect x="8" y="6" width="3" height="1" fill="#000"/>
    <rect x="3" y="9" width="3" height="1" fill="#000"/>
    <rect x="2" y="10" width="5" height="3" fill="${pulse ? '#39FF39' : '#000'}"/>
    <rect x="3" y="13" width="3" height="1" fill="#000"/>
  </svg>`,
  langEn: () => `<svg viewBox="0 0 18 16" width="18" height="16" shape-rendering="crispEdges">
    <rect x="0" y="2" width="18" height="12" fill="#FFFFFF"/>
    <rect x="0" y="2" width="18" height="1" fill="#FFFFFF"/>
    <rect x="0" y="13" width="18" height="1" fill="#404040"/>
    <rect x="0" y="2" width="1" height="12" fill="#FFFFFF"/>
    <rect x="17" y="2" width="1" height="12" fill="#404040"/>
    <text x="9" y="12" text-anchor="middle" font-family="monospace" font-weight="700" font-size="9" fill="#000">EN</text>
  </svg>`,
  onlineDot: () => `<svg viewBox="0 0 8 8" width="8" height="8" shape-rendering="crispEdges">
    <rect x="2" y="2" width="4" height="4" fill="#39C739"/>
    <rect x="2" y="2" width="2" height="2" fill="#7FFF7F"/>
    <rect x="2" y="2" width="4" height="1" fill="#7FFF7F"/>
    <rect x="2" y="2" width="1" height="4" fill="#7FFF7F"/>
  </svg>`,
};

/* ===== Volume slider popup ===== */
function VolumePopup({ value, muted, onChange, onMute, onClose }) {
  const ref = React.useRef();
  React.useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    setTimeout(() => document.addEventListener('mousedown', onDoc), 0);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [onClose]);
  return (
    <div className="vol-popup" ref={ref}>
      <div className="vol-title">Volume</div>
      <div className="vol-slider">
        <input
          type="range" min="0" max="100" value={value}
          onChange={e => onChange(parseInt(e.target.value))}
          className="vol-range"
          orient="vertical"
        />
      </div>
      <div className="vol-pct">{muted ? 'Mute' : value + '%'}</div>
      <label className="vol-mute">
        <input type="checkbox" checked={muted} onChange={onMute}/> Mute
      </label>
    </div>
  );
}

/* ===== Date/Time Properties dialog ===== */
function DateTimeDialog({ onClose, zIndex }) {
  const [pos, setPos] = React.useState({ x: window.innerWidth/2 - 180, y: window.innerHeight/2 - 200 });
  const [drag, setDrag] = React.useState(null);
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  React.useEffect(() => {
    if (!drag) return;
    const onMove = (e) => setPos({ x: e.clientX - drag.dx, y: e.clientY - drag.dy });
    const onUp = () => setDrag(null);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, [drag]);
  const month = now.toLocaleString('en-US', { month: 'long' });
  const year = now.getFullYear();
  const day = now.getDate();
  const dim = new Date(year, now.getMonth()+1, 0).getDate();
  const firstDow = new Date(year, now.getMonth(), 1).getDay();
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= dim; d++) cells.push(d);
  const h = now.getHours(); const m = now.getMinutes(); const s = now.getSeconds();
  const ampm = h >= 12 ? 'PM' : 'AM';
  const h12 = ((h+11)%12)+1;
  return (
    <div className="dt-dialog win raised" style={{ left: pos.x, top: pos.y, zIndex: zIndex || 200000 }}>
      <div className="tbar focused" onMouseDown={e => setDrag({ dx: e.clientX - pos.x, dy: e.clientY - pos.y })}>
        <span className="ttl">Date/Time Properties</span>
        <div className="tctrls">
          <button className="tctrl" onClick={onClose}>✕</button>
        </div>
      </div>
      <div className="dt-body">
        <div className="dt-section">
          <div className="dt-lbl">Date</div>
          <div className="dt-row">
            <select className="w95-input" value={now.getMonth()} disabled style={{flex:1}}>
              <option>{month}</option>
            </select>
            <input className="w95-input" value={year} disabled style={{width:70}}/>
          </div>
          <div className="dt-cal">
            <div className="dt-cal-head">
              {['S','M','T','W','T','F','S'].map((d,i) => <div key={i} className="dt-dow">{d}</div>)}
            </div>
            <div className="dt-cal-grid">
              {cells.map((c,i) => (
                <div key={i} className={`dt-cell ${c === day ? 'today' : ''} ${c == null ? 'empty' : ''}`}>
                  {c || ''}
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="dt-section">
          <div className="dt-lbl">Time</div>
          <div className="dt-clock-face">
            <svg viewBox="0 0 100 100" width="120" height="120" shape-rendering="crispEdges">
              <circle cx="50" cy="50" r="46" fill="#fff" stroke="#000"/>
              {[...Array(12)].map((_,i) => {
                const a = (i * 30 - 90) * Math.PI / 180;
                const x1 = 50 + Math.cos(a) * 42, y1 = 50 + Math.sin(a) * 42;
                const x2 = 50 + Math.cos(a) * 46, y2 = 50 + Math.sin(a) * 46;
                return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="#000" strokeWidth="1"/>;
              })}
              {(() => {
                const ha = ((h%12 + m/60) * 30 - 90) * Math.PI/180;
                const ma = (m * 6 - 90) * Math.PI/180;
                const sa = (s * 6 - 90) * Math.PI/180;
                return <g>
                  <line x1="50" y1="50" x2={50 + Math.cos(ha)*22} y2={50 + Math.sin(ha)*22} stroke="#000" strokeWidth="3"/>
                  <line x1="50" y1="50" x2={50 + Math.cos(ma)*32} y2={50 + Math.sin(ma)*32} stroke="#000" strokeWidth="2"/>
                  <line x1="50" y1="50" x2={50 + Math.cos(sa)*36} y2={50 + Math.sin(sa)*36} stroke="#FF0000" strokeWidth="1"/>
                  <circle cx="50" cy="50" r="2" fill="#000"/>
                </g>;
              })()}
            </svg>
          </div>
          <div className="dt-time-display">
            {String(h12).padStart(2,'0')}:{String(m).padStart(2,'0')}:{String(s).padStart(2,'0')} {ampm}
          </div>
        </div>
      </div>
      <div className="dt-buttons">
        <button className="btn" onClick={onClose}>OK</button>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn" disabled>Apply</button>
      </div>
    </div>
  );
}

/* ===== Context menu ===== */
function TrayContextMenu({ x, y, items, onClose }) {
  const ref = React.useRef();
  React.useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    setTimeout(() => document.addEventListener('mousedown', onDoc), 0);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [onClose]);
  return (
    <div className="tray-ctx win raised" style={{ left: x, top: y }} ref={ref}>
      {items.map((it, i) => it === '-'
        ? <div key={i} className="tray-ctx-sep"/>
        : <div key={i} className="tray-ctx-item" onClick={() => { it.onClick && it.onClick(); onClose(); }}>{it.label}</div>
      )}
    </div>
  );
}

/* ===== System Tray ===== */
function SystemTray({ muted, setMuted, volume, setVolume, mp, onOpenMedia, onOpenNetwork }) {
  const [now, setNow] = React.useState(new Date());
  const [showDt, setShowDt] = React.useState(false);
  const [showVol, setShowVol] = React.useState(false);
  const [ctx, setCtx] = React.useState(null);
  const [netActive, setNetActive] = React.useState(false);
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  // Periodic network blink (simulates GitHub feed fetch)
  React.useEffect(() => {
    const id = setInterval(() => {
      setNetActive(true);
      setTimeout(() => setNetActive(false), 350);
    }, 6000);
    return () => clearInterval(id);
  }, []);

  const h = now.getHours(); const m = now.getMinutes();
  const ampm = h >= 12 ? 'PM' : 'AM';
  const h12 = ((h+11)%12)+1;
  const dateStr = now.toLocaleDateString('en-US', { weekday:'long', year:'numeric', month:'long', day:'numeric' });

  const rightClick = (e, items) => { e.preventDefault(); setCtx({ x: e.clientX, y: e.clientY, items }); };

  return (
    <>
      <div className="tray">
        <Tip label="Volume">
          <span className="tray-icon" onClick={() => setShowVol(s => !s)}
            onContextMenu={e => rightClick(e, [
              { label: 'Open Volume Control', onClick: () => setShowVol(true) },
              { label: muted ? 'Unmute' : 'Mute', onClick: () => setMuted(!muted) },
              '-',
              { label: 'Properties', onClick: () => {} },
            ])}
            dangerouslySetInnerHTML={{__html: TrayIcons.speaker(muted)}}/>
        </Tip>
        <Tip label="Network">
          <span className={`tray-icon ${netActive ? 'blinking' : ''}`} onClick={onOpenNetwork}
            onContextMenu={e => rightClick(e, [
              { label: 'Open Network Neighborhood', onClick: onOpenNetwork },
              { label: 'About', onClick: () => {} },
            ])}
            dangerouslySetInnerHTML={{__html: TrayIcons.network(netActive)}}/>
        </Tip>
        <Tip label={mp && mp.playing ? 'Now Playing' : 'Media Player'}>
          <span className={`tray-icon ${mp && mp.playing ? 'pulsing' : ''}`} onClick={onOpenMedia}
            onContextMenu={e => rightClick(e, [
              { label: 'Open Media Player', onClick: onOpenMedia },
              { label: 'Properties', onClick: () => {} },
            ])}
            dangerouslySetInnerHTML={{__html: TrayIcons.note(mp && mp.playing)}}/>
        </Tip>
        <Tip label="English (United States)">
          <span className="tray-icon tray-en" onContextMenu={e => rightClick(e, [
              { label: 'Properties', onClick: () => {} },
            ])} dangerouslySetInnerHTML={{__html: TrayIcons.langEn()}}/>
        </Tip>
        <Tip label="online · devarv · Manali, IN" delay={400}>
          <span className="tray-icon tray-dot" dangerouslySetInnerHTML={{__html: TrayIcons.onlineDot()}}/>
        </Tip>
        <Tip label={dateStr}>
          <span className="tray-clock" onClick={() => setShowDt(s => !s)}>
            {String(h12).padStart(2,'0')}:{String(m).padStart(2,'0')} {ampm}
          </span>
        </Tip>
      </div>
      {showVol && (
        <VolumePopup
          value={volume} muted={muted}
          onChange={v => { setVolume(v); if (muted && v > 0) setMuted(false); }}
          onMute={() => setMuted(!muted)}
          onClose={() => setShowVol(false)}
        />
      )}
      {showDt && <DateTimeDialog onClose={() => setShowDt(false)}/>}
      {ctx && <TrayContextMenu x={ctx.x} y={ctx.y} items={ctx.items} onClose={() => setCtx(null)}/>}
    </>
  );
}

Object.assign(window, { SystemTray, Tip });
