// Desktop chrome: MenuBar, Folder icon (draggable), Window.

const FolderIcon = ({ open }) => (
  <svg width="44" height="38" viewBox="0 0 44 38" style={{display: "block"}}>
    {/* back tab */}
    <rect x="2" y="6" width="18" height="6" fill="var(--ink)" />
    {/* body */}
    <rect x="2" y="10" width="40" height="26" fill={open ? "var(--accent)" : "var(--paper)"} stroke="var(--ink)" strokeWidth="2" />
    {/* highlight strip */}
    <rect x="2" y="14" width="40" height="2" fill="var(--ink)" />
    {/* shadow */}
    <rect x="6" y="36" width="38" height="2" fill="var(--ink)" opacity=".15" />
  </svg>
);

const FolderIconOpen = () => (
  <svg width="44" height="38" viewBox="0 0 44 38" style={{display: "block"}}>
    <polygon points="2,12 14,12 18,8 42,8 42,14 2,14" fill="var(--ink)"/>
    <polygon points="2,14 42,14 38,36 6,36" fill="var(--paper)" stroke="var(--ink)" strokeWidth="2"/>
  </svg>
);

function Folder({ id, label, x, y, hint, isOpen, onMove, onOpen, gridSize }) {
  const [dragging, setDragging] = React.useState(false);
  const [pos, setPos] = React.useState({ x, y });
  const [hover, setHover] = React.useState(false);
  const movedRef = React.useRef(false);
  const startRef = React.useRef(null);
  const posRef = React.useRef({ x, y });

  React.useEffect(() => { setPos({ x, y }); posRef.current = { x, y }; }, [x, y]);

  const onMouseDown = (e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    movedRef.current = false;
    startRef.current = {
      mx: e.clientX, my: e.clientY,
      ox: e.clientX - posRef.current.x,
      oy: e.clientY - posRef.current.y,
    };
    setDragging(true);
  };

  React.useEffect(() => {
    if (!dragging) return;
    const move = (e) => {
      const s = startRef.current;
      const dx = e.clientX - s.mx;
      const dy = e.clientY - s.my;
      if (!movedRef.current && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) {
        movedRef.current = true;
      }
      const nx = e.clientX - s.ox;
      const ny = e.clientY - s.oy;
      posRef.current = { x: nx, y: ny };
      setPos(posRef.current);
    };
    const up = () => {
      setDragging(false);
      if (movedRef.current) {
        onMove(id, posRef.current.x, posRef.current.y);
      }
    };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
    };
  }, [dragging, id, onMove]);

  const handleClick = (e) => {
    if (movedRef.current) { movedRef.current = false; return; }
    onOpen(id);
  };

  return (
    <div
      onMouseDown={onMouseDown}
      onClick={handleClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "absolute",
        left: pos.x, top: pos.y,
        width: 88,
        textAlign: "center",
        cursor: dragging ? "grabbing" : "pointer",
        userSelect: "none",
        zIndex: dragging ? 50 : 2,
        transition: dragging ? "none" : "transform .12s ease",
        transform: hover && !dragging ? "translateY(-2px)" : "translateY(0)",
      }}
    >
      <div style={{display: "flex", justifyContent: "center", marginBottom: 4, filter: isOpen ? "none" : "none"}}>
        {isOpen ? <FolderIconOpen/> : <FolderIcon open={hover}/>}
      </div>
      <div style={{
        display: "inline-block",
        padding: "1px 5px",
        background: hover ? "var(--ink)" : "transparent",
        color: hover ? "var(--paper)" : "var(--ink)",
        fontSize: 11,
        fontWeight: 500,
        letterSpacing: ".02em",
      }}>{label}</div>
      {hover && hint && (
        <div style={{
          fontSize: 10, color: "var(--muted)", marginTop: 4, fontStyle: "italic",
          maxWidth: 120, marginLeft: "auto", marginRight: "auto",
        }}>{hint}</div>
      )}
    </div>
  );
}

function Window({ id, title, x, y, w, h, z, onFocus, onClose, onMove, onResize, children }) {
  const [drag, setDrag] = React.useState(null);
  const [pos, setPos] = React.useState({ x, y });
  const [size, setSize] = React.useState({ w, h });
  const [resizing, setResizing] = React.useState(null);

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

  const onTitleDown = (e) => {
    if (e.target.closest("button")) return;
    onFocus(id);
    setDrag({ ox: e.clientX - pos.x, oy: e.clientY - pos.y });
  };

  React.useEffect(() => {
    if (!drag) return;
    const move = (e) => setPos({ x: e.clientX - drag.ox, y: e.clientY - drag.oy });
    const up = () => { setDrag(null); onMove(id, pos.x, pos.y); };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
    };
  }, [drag, pos, id, onMove]);

  const onResizeDown = (e) => {
    e.stopPropagation();
    onFocus(id);
    setResizing({ sx: e.clientX, sy: e.clientY, sw: size.w, sh: size.h });
  };
  React.useEffect(() => {
    if (!resizing) return;
    const move = (e) => {
      setSize({
        w: Math.max(280, resizing.sw + (e.clientX - resizing.sx)),
        h: Math.max(200, resizing.sh + (e.clientY - resizing.sy)),
      });
    };
    const up = () => { setResizing(null); onResize(id, size.w, size.h); };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
    };
  }, [resizing, size, id, onResize]);

  return (
    <div
      onMouseDown={() => onFocus(id)}
      style={{
        position: "absolute",
        left: pos.x, top: pos.y, width: size.w, height: size.h,
        background: "var(--paper)",
        border: "1.5px solid var(--ink)",
        boxShadow: "6px 6px 0 var(--ink)",
        display: "flex",
        flexDirection: "column",
        zIndex: z,
      }}
    >
      {/* Title bar */}
      <div
        onMouseDown={onTitleDown}
        style={{
          height: 26,
          borderBottom: "1.5px solid var(--ink)",
          background: "repeating-linear-gradient(0deg, var(--ink) 0 1px, transparent 1px 3px)",
          display: "flex",
          alignItems: "center",
          padding: "0 8px",
          gap: 8,
          cursor: drag ? "grabbing" : "grab",
        }}
      >
        <button onClick={(e) => { e.stopPropagation(); onClose(id); }}
          aria-label="close"
          style={{
            width: 14, height: 14, padding: 0,
            border: "1.5px solid var(--ink)",
            background: "var(--paper)",
            cursor: "pointer",
            display: "grid", placeItems: "center",
            fontSize: 10, lineHeight: 1,
          }}>×</button>
        <div style={{
          flex: 1, textAlign: "center",
          background: "var(--paper)",
          padding: "1px 10px",
          fontSize: 11,
          fontWeight: 600,
          letterSpacing: ".02em",
        }}>{title}</div>
        <div style={{width: 14}}/>
      </div>

      {/* Content */}
      <div className="winscroll" style={{
        flex: 1, overflow: "auto",
        cursor: "default", userSelect: "text",
      }}>
        {children}
      </div>

      {/* Resize handle */}
      <div onMouseDown={onResizeDown}
        style={{
          position: "absolute", right: 0, bottom: 0,
          width: 14, height: 14,
          cursor: "nwse-resize",
          background: `linear-gradient(135deg, transparent 0 6px, var(--ink) 6px 7px, transparent 7px 9px, var(--ink) 9px 10px, transparent 10px 12px, var(--ink) 12px 13px, transparent 13px)`,
        }}/>
    </div>
  );
}

function Clock() {
  const [t, setT] = React.useState(new Date());
  React.useEffect(() => {
    const i = setInterval(() => setT(new Date()), 1000 * 30);
    return () => clearInterval(i);
  }, []);
  const pad = n => String(n).padStart(2, "0");
  const time = `${pad(t.getHours())}:${pad(t.getMinutes())}`;
  const date = t.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" }).toLowerCase();
  return (
    <span style={{fontVariantNumeric: "tabular-nums"}}>
      {date} <span style={{color: "var(--muted)"}}>·</span> {time}
    </span>
  );
}

function MenuBar({ wallpaper, setWallpaper, wallpapers, onShuffle }) {
  const [open, setOpen] = React.useState(null);
  React.useEffect(() => {
    const close = () => setOpen(null);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, []);

  const Menu = ({ name, items }) => (
    <div style={{position: "relative"}}>
      <button onClick={(e) => { e.stopPropagation(); setOpen(open === name ? null : name); }}
        style={{
          padding: "4px 10px",
          background: open === name ? "var(--ink)" : "transparent",
          color: open === name ? "var(--paper)" : "var(--ink)",
          border: "none",
          fontWeight: 500,
          fontSize: 12,
          cursor: "pointer",
          fontFamily: "inherit",
        }}>{name}</button>
      {open === name && (
        <div style={{
          position: "absolute", left: 0, top: "100%",
          background: "var(--paper)",
          border: "1.5px solid var(--ink)",
          boxShadow: "4px 4px 0 var(--ink)",
          minWidth: 180,
          zIndex: 200,
          padding: 4,
        }}>
          {items.map((it, i) => (
            it.divider ? (
              <div key={i} style={{height: 1, background: "var(--ink)", margin: "4px 2px", opacity: .3}}/>
            ) : (
              <button key={i} onClick={(e) => { e.stopPropagation(); it.onClick && it.onClick(); setOpen(null); }}
                disabled={it.disabled}
                style={{
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  width: "100%",
                  padding: "5px 10px",
                  border: "none", background: "transparent",
                  textAlign: "left",
                  fontFamily: "inherit", fontSize: 12,
                  color: it.disabled ? "var(--muted)" : "var(--ink)",
                  cursor: it.disabled ? "default" : "pointer",
                }}
                onMouseEnter={(e) => { if (!it.disabled) { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "var(--paper)"; } }}
                onMouseLeave={(e) => { if (!it.disabled) { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink)"; } }}
              >
                <span>{it.label}</span>
                {it.right && <span style={{opacity: .6, fontSize: 10}}>{it.right}</span>}
                {it.checked && <span>●</span>}
              </button>
            )
          ))}
        </div>
      )}
    </div>
  );

  return (
    <div style={{
      position: "fixed", top: 0, left: 0, right: 0,
      height: 28,
      background: "var(--paper)",
      borderBottom: "1.5px solid var(--ink)",
      display: "flex", alignItems: "center", padding: "0 12px",
      zIndex: 300,
      fontSize: 12,
    }}>
      <div style={{
        fontWeight: 700, marginRight: 16, letterSpacing: "-.01em",
        display: "flex", alignItems: "center", gap: 6,
      }}>
        <span style={{
          display: "inline-block", width: 10, height: 10,
          background: "var(--accent)",
          border: "1.5px solid var(--ink)",
        }}/>
        hyderfm.os
      </div>
      <Menu name="file" items={[
        { label: "new project…", disabled: true, right: "⌘N" },
        { label: "open readme", onClick: () => window.dispatchEvent(new CustomEvent("os:open", { detail: "readme" })) },
        { divider: true },
        { label: "log out", disabled: true },
      ]}/>
      <Menu name="view" items={wallpapers.map(w => ({
        label: w.name,
        checked: w.id === wallpaper,
        onClick: () => setWallpaper(w.id),
      })).concat([
        { divider: true },
        { label: "shuffle desktop", onClick: onShuffle },
        { label: "reset layout", onClick: () => { localStorage.removeItem("flayd.layout"); location.reload(); } },
      ])}/>
      <Menu name="help" items={[
        { label: "about this site", onClick: () => window.dispatchEvent(new CustomEvent("os:open", { detail: "readme" })) },
        { label: "drag the folders. click to open. that's it." , disabled: true },
      ]}/>
      <div style={{marginLeft: "auto", color: "var(--ink-2)", fontSize: 11}}>
        <Clock/>
      </div>
    </div>
  );
}

window.Desktop = { Folder, Window, MenuBar };
