"use client";

import { useCallback, useEffect, useRef, useState } from "react";

const INK = "#111318", SUB = "#5b626c", FAINT = "#8a8f99";
const LINE = "rgba(17,19,24,.09)", LINE_SOFT = "rgba(17,19,24,.06)";
const MARS = "#c2452a", MONO = "ui-monospace, SFMono-Regular, Menlo, monospace";

// ── draggable / resizable modal window ─────────────────────────────────────────
function ArtifactModal({ artifact, onClose }) {
  const [pos, setPos] = useState(() => ({
    x: Math.max(24, Math.round((typeof window !== "undefined" ? window.innerWidth : 1200) * 0.5 - 470)),
    y: 64,
  }));
  const [size, setSize] = useState({ w: 940, h: 640 });
  const drag = useRef(null);

  const onPointerMove = useCallback((e) => {
    const d = drag.current;
    if (!d) return;
    if (d.mode === "move") {
      setPos({ x: d.ox + (e.clientX - d.sx), y: Math.max(8, d.oy + (e.clientY - d.sy)) });
    } else {
      setSize({
        w: Math.max(360, d.ow + (e.clientX - d.sx)),
        h: Math.max(240, d.oh + (e.clientY - d.sy)),
      });
    }
  }, []);
  const onPointerUp = useCallback(() => { drag.current = null; }, []);

  useEffect(() => {
    window.addEventListener("pointermove", onPointerMove);
    window.addEventListener("pointerup", onPointerUp);
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("pointermove", onPointerMove);
      window.removeEventListener("pointerup", onPointerUp);
      window.removeEventListener("keydown", onKey);
    };
  }, [onPointerMove, onPointerUp, onClose]);

  const startMove = (e) => {
    if (e.target.closest("button, a")) return;
    drag.current = { mode: "move", sx: e.clientX, sy: e.clientY, ox: pos.x, oy: pos.y };
  };
  const startResize = (e) => {
    e.stopPropagation();
    drag.current = { mode: "resize", sx: e.clientX, sy: e.clientY, ow: size.w, oh: size.h };
  };

  return (
    <div
      onMouseDown={onClose}
      style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(17,19,24,.34)", backdropFilter: "blur(2px)" }}
    >
      <div
        onMouseDown={(e) => e.stopPropagation()}
        style={{
          position: "absolute", left: pos.x, top: pos.y, width: size.w, height: size.h,
          display: "flex", flexDirection: "column", background: "#fff", borderRadius: 14,
          border: `1px solid ${LINE}`, boxShadow: "0 24px 70px -18px rgba(17,19,24,.4)", overflow: "hidden",
        }}
      >
        <div
          onPointerDown={startMove}
          style={{
            display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", cursor: "grab",
            borderBottom: `1px solid ${LINE_SOFT}`, background: "#fcfcfb", userSelect: "none", flexShrink: 0,
          }}
        >
          <span style={{ display: "inline-flex", gap: 6 }}>
            <button
              onClick={onClose} aria-label="Close"
              style={{ width: 12, height: 12, borderRadius: "50%", border: "none", background: MARS, cursor: "pointer", padding: 0 }}
            />
            <span style={{ width: 12, height: 12, borderRadius: "50%", background: "rgba(17,19,24,.14)" }} />
            <span style={{ width: 12, height: 12, borderRadius: "50%", background: "rgba(17,19,24,.14)" }} />
          </span>
          <b style={{ fontSize: 13, fontWeight: 650, color: INK, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{artifact.title || "Artifact"}</b>
          <span style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: FAINT, fontFamily: MONO }}>{artifact.kind}</span>
          <a
            href={`/api/artifacts/${artifact.id}/raw`} target="_blank" rel="noreferrer"
            style={{ marginLeft: "auto", fontSize: 11, color: FAINT, fontWeight: 600, textDecoration: "none", fontFamily: MONO }}
          >raw ↗</a>
        </div>
        <iframe
          title={artifact.title}
          srcDoc={artifact.content}
          sandbox="allow-scripts allow-same-origin allow-popups"
          style={{ flex: 1, width: "100%", border: 0, background: "#fff" }}
        />
        <span
          onPointerDown={startResize}
          aria-hidden
          style={{
            position: "absolute", right: 0, bottom: 0, width: 18, height: 18, cursor: "nwse-resize",
            background: "linear-gradient(135deg, transparent 50%, rgba(17,19,24,.22) 50%)",
          }}
        />
      </div>
    </div>
  );
}

// ── panel: space toolbar + artifact cards + modal ──────────────────────────────
export default function ArtifactsPanel({ artifacts, projectId, defaultSpaceId }) {
  const [open, setOpen] = useState(null);
  const [spaces, setSpaces] = useState([]);
  const [spaceId, setSpaceId] = useState(defaultSpaceId || "");
  const [busy, setBusy] = useState(false);
  const [notice, setNotice] = useState("");

  useEffect(() => {
    let alive = true;
    fetch("/api/dashboard/spaces")
      .then((r) => r.json())
      .then((j) => {
        if (!alive) return;
        const list = j?.data?.spaces || j?.spaces || [];
        setSpaces(list);
        if (!spaceId && list.length) setSpaceId(list.find((s) => s.is_active)?.id || list[0].id);
      })
      .catch(() => {});
    return () => { alive = false; };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  async function publish() {
    if (!spaceId || busy) return;
    setBusy(true); setNotice("");
    try {
      const r = await fetch(`/api/mines/projects/${projectId}/publish`, {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify({ space_id: spaceId }),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j?.error || "publish_failed");
      const sp = spaces.find((s) => s.id === spaceId);
      setNotice(`Published to “${sp?.name || spaceId}” — ${j.data.pinned_artifacts} artifacts pinned. Open the dashboard to arrange them.`);
    } catch (e) {
      setNotice(`Publish failed: ${e.message}`);
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      {/* space toolbar */}
      <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 10, marginBottom: 16, padding: "14px 16px", border: `1px solid ${LINE_SOFT}`, borderRadius: 14, background: "#fcfcfb" }}>
        <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".13em", textTransform: "uppercase", color: FAINT, fontFamily: MONO }}>Dashboard space</span>
        <select
          value={spaceId}
          onChange={(e) => setSpaceId(e.target.value)}
          style={{ fontSize: 13, padding: "7px 10px", borderRadius: 9, border: `1px solid ${LINE}`, background: "#fff", color: INK, fontFamily: "inherit" }}
        >
          {spaces.length === 0 && <option value="">No spaces</option>}
          {spaces.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
        <button
          onClick={publish} disabled={busy || !spaceId}
          style={{ fontSize: 13, fontWeight: 650, padding: "8px 16px", borderRadius: 9, border: "none", cursor: busy || !spaceId ? "default" : "pointer", background: busy || !spaceId ? "rgba(17,19,24,.18)" : MARS, color: "#fff" }}
        >{busy ? "Publishing…" : "Publish to space"}</button>
        {notice && <span style={{ fontSize: 12, color: notice.startsWith("Publish failed") ? MARS : SUB }}>{notice}</span>}
      </div>

      {/* artifact cards */}
      <div style={{ display: "grid", gap: 12 }}>
        {artifacts.map((a) => (
          <div key={a.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "14px 18px", border: `1px solid ${LINE_SOFT}`, borderRadius: 14, background: "#fff" }}>
            <span style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 0 }}>
              <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: FAINT, fontFamily: MONO }}>{a.kind}</span>
              <span style={{ fontSize: 15, fontWeight: 650, letterSpacing: "-.01em", color: INK }}>{a.title}</span>
            </span>
            <span style={{ display: "flex", gap: 8, flexShrink: 0 }}>
              <a href={`/api/artifacts/${a.id}/raw`} target="_blank" rel="noreferrer" style={{ fontSize: 11, color: FAINT, fontWeight: 600, textDecoration: "none", fontFamily: MONO, alignSelf: "center" }}>raw ↗</a>
              <button
                onClick={() => setOpen(a)}
                disabled={!a.content}
                style={{ fontSize: 12.5, fontWeight: 650, padding: "8px 16px", borderRadius: 9, border: `1px solid ${MARS}`, background: "#fff", color: MARS, cursor: a.content ? "pointer" : "default", opacity: a.content ? 1 : 0.4 }}
              >Open</button>
            </span>
          </div>
        ))}
      </div>

      {open && <ArtifactModal artifact={open} onClose={() => setOpen(null)} />}
    </>
  );
}
