const { useState, useEffect, useRef } = React;

function Win({ id, title, icon, x, y, w, h, z, active, onFocus, onClose, onMin, children, menus, statusBar, resizable=true }) {
  const ref = useRef(null);
  const [pos, setPos] = useState({ x, y });
  const [size, setSize] = useState({ w, h });
  const drag = useRef(null);

  useEffect(() => setPos({ x, y }), [x, y]);
  useEffect(() => setSize({ w, h }), [w, h]);

  const onTitleDown = (e) => {
    if (e.button !== 0) return;
    if (e.target.closest('.win-title-btn')) return;
    onFocus && onFocus(id);
    drag.current = { sx: e.clientX, sy: e.clientY, px: pos.x, py: pos.y, kind: 'move' };
    e.preventDefault();
  };

  const onResizeDown = (e) => {
    e.stopPropagation();
    onFocus && onFocus(id);
    drag.current = { sx: e.clientX, sy: e.clientY, pw: size.w, ph: size.h, kind: 'resize' };
    e.preventDefault();
  };

  useEffect(() => {
    const move = (e) => {
      if (!drag.current) return;
      const dx = e.clientX - drag.current.sx;
      const dy = e.clientY - drag.current.sy;
      if (drag.current.kind === 'move') {
        setPos({
          x: Math.max(-50, Math.min(window.innerWidth - 100, drag.current.px + dx)),
          y: Math.max(0, Math.min(window.innerHeight - 60, drag.current.py + dy)),
        });
      } else {
        setSize({
          w: Math.max(280, drag.current.pw + dx),
          h: Math.max(180, drag.current.ph + dy),
        });
      }
    };
    const up = () => { drag.current = null; };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    };
  }, []);

  return (
    <div
      ref={ref}
      className={`win ${active ? '' : 'inactive'}`}
      style={{ left: pos.x, top: pos.y, width: size.w, height: size.h, zIndex: z }}
      onMouseDown={() => onFocus && onFocus(id)}
    >
      <div className="win-title" onMouseDown={onTitleDown} onDoubleClick={() => {
        const maxW = window.innerWidth - 8, maxH = window.innerHeight - 40;
        if (size.w >= maxW - 4 && size.h >= maxH - 4) {
          setSize({ w, h });
          setPos({ x, y });
        } else {
          setSize({ w: maxW, h: maxH });
          setPos({ x: 4, y: 4 });
        }
      }}>
        {icon && <img className="win-title-icon" src={icon} alt="" />}
        <span className="win-title-text">{title}</span>
        <div className="win-title-btns">
          <button className="win-title-btn" onClick={() => onMin && onMin(id)} title="Minimize">
            <svg width="8" height="8" viewBox="0 0 8 8" shapeRendering="crispEdges"><rect x="1" y="6" width="6" height="2" fill="#000"/></svg>
          </button>
          <button className="win-title-btn" onClick={() => onClose && onClose(id)} title="Close">
            <svg width="8" height="8" viewBox="0 0 8 8" shapeRendering="crispEdges">
              <rect x="1" y="1" width="1" height="1" fill="#000"/><rect x="2" y="2" width="1" height="1" fill="#000"/><rect x="3" y="3" width="1" height="1" fill="#000"/><rect x="4" y="3" width="1" height="1" fill="#000"/><rect x="5" y="2" width="1" height="1" fill="#000"/><rect x="6" y="1" width="1" height="1" fill="#000"/>
              <rect x="3" y="4" width="1" height="1" fill="#000"/><rect x="4" y="4" width="1" height="1" fill="#000"/>
              <rect x="2" y="5" width="1" height="1" fill="#000"/><rect x="5" y="5" width="1" height="1" fill="#000"/>
              <rect x="1" y="6" width="1" height="1" fill="#000"/><rect x="6" y="6" width="1" height="1" fill="#000"/>
            </svg>
          </button>
        </div>
      </div>
      {menus && (
        <div className="win-menu">
          {menus.map((m, i) => (
            <div className="item" key={i}><u>{m[0]}</u>{m.slice(1)}</div>
          ))}
        </div>
      )}
      <div className="win-body">
        {children}
      </div>
      {statusBar && (
        <div className="win-statusbar">{statusBar}</div>
      )}
      {resizable && (
        <div
          onMouseDown={onResizeDown}
          style={{
            position: 'absolute', right: 0, bottom: 0, width: 16, height: 16,
            cursor: 'nwse-resize',
            background:
              "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' shape-rendering='crispEdges'><rect x='9' y='2' width='1' height='1' fill='%23808080'/><rect x='6' y='5' width='1' height='1' fill='%23808080'/><rect x='9' y='5' width='1' height='1' fill='%23808080'/><rect x='3' y='8' width='1' height='1' fill='%23808080'/><rect x='6' y='8' width='1' height='1' fill='%23808080'/><rect x='9' y='8' width='1' height='1' fill='%23808080'/><rect x='10' y='3' width='1' height='1' fill='%23ffffff'/><rect x='7' y='6' width='1' height='1' fill='%23ffffff'/><rect x='10' y='6' width='1' height='1' fill='%23ffffff'/><rect x='4' y='9' width='1' height='1' fill='%23ffffff'/><rect x='7' y='9' width='1' height='1' fill='%23ffffff'/><rect x='10' y='9' width='1' height='1' fill='%23ffffff'/></svg>\")",
            backgroundSize: '12px 12px',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'right bottom',
          }}
        />
      )}
    </div>
  );
}
