// win95.jsx — Win95 chrome components

function Win95Window({
  title, icon, children, onClose, onMinimize, onMaximize,
  width, height, x = 20, y = 60, zIndex = 10,
  draggable = true, resizable = true, marquee = false, active = true,
  menubar, statusbar, onActivate, noPadding = false,
  maximized = false, hidden = false,
  minWidth = 220, minHeight = 140,
}) {
  const [pos, setPos] = React.useState({ x, y });
  const [size, setSize] = React.useState({ w: width, h: height });
  const [isDragging, setDragging] = React.useState(false);
  const [isResizing, setResizing] = React.useState(false);
  const [zoom, setZoom] = React.useState(1);
  const dragRef = React.useRef(null);

  React.useEffect(() => {
    setPos({ x, y });
  }, [x, y]);

  React.useEffect(() => {
    setSize({ w: width, h: height });
  }, [width, height]);

  React.useEffect(() => {
    if (!maximized) { setZoom(1); return; }
    const update = () => {
      const parent = dragRef.current && dragRef.current.parentElement;
      if (!parent) return;
      const pw = parent.clientWidth;
      const ph = parent.clientHeight;
      const w = size.w || width || 320;
      const h = size.h || height || 480;
      // chrome eats roughly 26px (titlebar) + 18px (statusbar if present) + padding; estimate generously
      const z = Math.max(1, Math.min(pw / w, (ph - 50) / (h - 50)));
      setZoom(z);
    };
    update();
    const parent = dragRef.current && dragRef.current.parentElement;
    let ro;
    if (parent && typeof ResizeObserver !== 'undefined') {
      ro = new ResizeObserver(update);
      ro.observe(parent);
    }
    window.addEventListener('resize', update);
    return () => {
      if (ro) ro.disconnect();
      window.removeEventListener('resize', update);
    };
  }, [maximized, width, height]);

  const onDragStart = (e) => {
    if (!draggable || maximized) return;
    if (e.target.closest('.w95-title-btn')) return;
    e.preventDefault();
    onActivate && onActivate();
    setDragging(true);
    const startX = e.clientX || (e.touches && e.touches[0].clientX);
    const startY = e.clientY || (e.touches && e.touches[0].clientY);
    const startPos = { ...pos };
    const move = (ev) => {
      const cx = ev.clientX || (ev.touches && ev.touches[0].clientX);
      const cy = ev.clientY || (ev.touches && ev.touches[0].clientY);
      setPos({
        x: startPos.x + (cx - startX),
        y: startPos.y + (cy - startY),
      });
    };
    const up = () => {
      setDragging(false);
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', up);
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, { passive: false });
    window.addEventListener('touchend', up);
  };

  const onResizeStart = (dir) => (e) => {
    if (!resizable || maximized) return;
    e.preventDefault();
    e.stopPropagation();
    onActivate && onActivate();
    setResizing(true);
    const startX = e.clientX || (e.touches && e.touches[0].clientX);
    const startY = e.clientY || (e.touches && e.touches[0].clientY);
    const rect = dragRef.current ? dragRef.current.getBoundingClientRect() : { width: size.w || 320, height: size.h || 240 };
    const startW = rect.width;
    const startH = rect.height;
    const startPos = { ...pos };
    const move = (ev) => {
      const cx = ev.clientX || (ev.touches && ev.touches[0].clientX);
      const cy = ev.clientY || (ev.touches && ev.touches[0].clientY);
      const dx = cx - startX;
      const dy = cy - startY;
      let nw = startW;
      let nh = startH;
      let nx = startPos.x;
      let ny = startPos.y;
      if (dir.includes('e')) nw = Math.max(minWidth, startW + dx);
      if (dir.includes('s')) nh = Math.max(minHeight, startH + dy);
      if (dir.includes('w')) {
        nw = Math.max(minWidth, startW - dx);
        nx = startPos.x + (startW - nw);
      }
      if (dir.includes('n')) {
        nh = Math.max(minHeight, startH - dy);
        ny = startPos.y + (startH - nh);
      }
      setSize({ w: nw, h: nh });
      setPos({ x: nx, y: ny });
    };
    const up = () => {
      setResizing(false);
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', up);
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, { passive: false });
    window.addEventListener('touchend', up);
  };

  const winStyle = maximized ? {
    position: 'absolute',
    left: 0, top: 0, right: 0, bottom: 0,
    width: 'auto', height: 'auto',
    zIndex,
    display: hidden ? 'none' : 'flex', flexDirection: 'column',
    userSelect: 'auto',
  } : {
    position: 'absolute',
    left: pos.x, top: pos.y,
    width: size.w, height: size.h,
    zIndex,
    userSelect: (isDragging || isResizing) ? 'none' : 'auto',
    display: hidden ? 'none' : undefined,
  };

  const contentStyle = {
    ...(noPadding ? { padding: 0 } : {}),
    ...(maximized ? { flex: 1, minHeight: 0, overflow: 'auto', zoom } : {}),
  };

  const showResizeHandles = resizable && !maximized;

  return (
    <div
      ref={dragRef}
      className={`w95-window${maximized ? ' maximized' : ''}`}
      onMouseDown={onActivate}
      style={winStyle}
    >
      <div
        className={`w95-titlebar ${active ? '' : 'inactive'}`}
        onMouseDown={onDragStart}
        onTouchStart={onDragStart}
      >
        <div className="w95-title-text">
          {icon && <span className="w95-title-icon">{icon}</span>}
          {marquee ? (
            <div className="w95-marquee" style={{ flex: 1 }}>
              <span>{title} ★ {title} ★ {title} ★ </span>
            </div>
          ) : (
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</span>
          )}
        </div>
        <div className="w95-title-buttons">
          {onMinimize && (
            <button className="w95-title-btn" onClick={onMinimize} aria-label="Minimize">_</button>
          )}
          {onMaximize && (
            <button className="w95-title-btn" onClick={onMaximize}
                    aria-label={maximized ? 'Restore' : 'Maximize'}>{maximized ? '❐' : '□'}</button>
          )}
          {onClose && (
            <button className="w95-title-btn" onClick={onClose} aria-label="Close">✕</button>
          )}
        </div>
      </div>
      {menubar && <div className="w95-menubar">{menubar}</div>}
      <div className="w95-content w95-scroll" style={contentStyle}>
        {children}
      </div>
      {statusbar && (
        <div className="w95-statusbar">
          {statusbar.map((s, i) => <div key={i} className="w95-status-cell">{s}</div>)}
        </div>
      )}
      {showResizeHandles && (
        <>
          <div className="w95-resize w95-resize-n" onMouseDown={onResizeStart('n')} onTouchStart={onResizeStart('n')} />
          <div className="w95-resize w95-resize-s" onMouseDown={onResizeStart('s')} onTouchStart={onResizeStart('s')} />
          <div className="w95-resize w95-resize-e" onMouseDown={onResizeStart('e')} onTouchStart={onResizeStart('e')} />
          <div className="w95-resize w95-resize-w" onMouseDown={onResizeStart('w')} onTouchStart={onResizeStart('w')} />
          <div className="w95-resize w95-resize-ne" onMouseDown={onResizeStart('ne')} onTouchStart={onResizeStart('ne')} />
          <div className="w95-resize w95-resize-nw" onMouseDown={onResizeStart('nw')} onTouchStart={onResizeStart('nw')} />
          <div className="w95-resize w95-resize-se" onMouseDown={onResizeStart('se')} onTouchStart={onResizeStart('se')} />
          <div className="w95-resize w95-resize-sw" onMouseDown={onResizeStart('sw')} onTouchStart={onResizeStart('sw')} />
        </>
      )}
    </div>
  );
}

function Wallpaper({ variant = 'car' }) {
  if (variant === 'statue') {
    return (
      <div className="wp-base wp-statue">
        <div className="clouds" />
        <svg className="statue" viewBox="0 0 100 200" preserveAspectRatio="xMidYMax meet"
             style={{ display: 'block', margin: '0 auto' }}>
          {/* simple bust silhouette */}
          <ellipse cx="50" cy="40" rx="22" ry="26" fill="#f4d6e8"/>
          <path d="M30 38 Q28 28 38 22 Q42 14 52 14 Q62 12 68 22 Q78 28 74 42 Q70 50 68 56 L70 64 L60 70 L40 70 L32 62 Z"
                fill="#e8c0d8"/>
          <path d="M28 70 L72 70 L80 110 L70 130 L78 200 L22 200 L30 130 L20 110 Z"
                fill="#d8aac8"/>
          <ellipse cx="42" cy="42" rx="2" ry="3" fill="#5a2845"/>
          <ellipse cx="58" cy="42" rx="2" ry="3" fill="#5a2845"/>
          <path d="M44 52 Q50 56 56 52" fill="none" stroke="#5a2845" strokeWidth="1"/>
        </svg>
        <div className="checker" />
      </div>
    );
  }
  if (variant === 'grid') {
    return (
      <div className="wp-base wp-grid">
        <div className="sun" />
        <div className="mountains" />
        <div className="floor" />
      </div>
    );
  }
  // default: car
  return (
    <div className="wp-base wp-car">
      <div className="moon" />
      <div className="palms">
        <PalmTree />
        <PalmTree mirror />
      </div>
      <div className="grid" />
      <PixelCar className="car" />
    </div>
  );
}

function PalmTree({ mirror }) {
  return (
    <svg width="60" height="120" viewBox="0 0 60 120" style={{ transform: mirror ? 'scaleX(-1)' : 'none' }}>
      <rect x="27" y="40" width="6" height="80" fill="#1a0033" />
      <rect x="26" y="50" width="8" height="2" fill="#3a1055" />
      <rect x="26" y="70" width="8" height="2" fill="#3a1055" />
      <rect x="26" y="90" width="8" height="2" fill="#3a1055" />
      {/* fronds */}
      <path d="M30 40 Q5 30 0 40 Q15 38 30 45 Z" fill="#1a0033"/>
      <path d="M30 40 Q55 30 60 40 Q45 38 30 45 Z" fill="#1a0033"/>
      <path d="M30 35 Q10 15 5 25 Q20 25 30 40 Z" fill="#1a0033"/>
      <path d="M30 35 Q50 15 55 25 Q40 25 30 40 Z" fill="#1a0033"/>
      <path d="M30 30 Q25 5 20 10 Q28 18 30 35 Z" fill="#1a0033"/>
      <path d="M30 30 Q35 5 40 10 Q32 18 30 35 Z" fill="#1a0033"/>
    </svg>
  );
}

function PixelCar({ className }) {
  return (
    <svg className={className} viewBox="0 0 140 60" shapeRendering="crispEdges">
      {/* underglow */}
      <ellipse cx="70" cy="55" rx="60" ry="6" fill="#ff3a8e" opacity="0.6"/>
      {/* body */}
      <path d="M10 40 L25 25 L100 25 L130 40 L130 50 L10 50 Z" fill="#0a0028" stroke="#ff3a8e" strokeWidth="1"/>
      {/* roof window */}
      <path d="M30 28 L42 18 L92 18 L106 28 Z" fill="#3a0a5a" stroke="#ff3a8e" strokeWidth="0.5"/>
      {/* headlights */}
      <rect x="120" y="32" width="8" height="6" fill="#fff8c0"/>
      <rect x="125" y="34" width="6" height="3" fill="#ffe14d"/>
      {/* tail glow */}
      <rect x="12" y="34" width="6" height="4" fill="#ff3a8e"/>
      {/* wheels */}
      <circle cx="35" cy="50" r="7" fill="#000" stroke="#ff3a8e" strokeWidth="1"/>
      <circle cx="35" cy="50" r="3" fill="#ff3a8e"/>
      <circle cx="105" cy="50" r="7" fill="#000" stroke="#ff3a8e" strokeWidth="1"/>
      <circle cx="105" cy="50" r="3" fill="#ff3a8e"/>
      {/* stripe */}
      <rect x="20" y="42" width="100" height="1" fill="#ff3a8e"/>
    </svg>
  );
}

Object.assign(window, {
  Win95Window, Wallpaper, PalmTree, PixelCar,
});
