/* board.jsx — Board, Column, Card + pointer-based drag & drop (mouse + touch) */
const { MEMBERS, LABELS, STAGE_DOTS, fmtDue, dueState, fmtMoney, memberById, usersByIds, labelById } = window.PlannerData;
const Ic = window.Icons;
const BPerms = window.Auth.Perms;

/* ---------- Avatar ---------- */
function Avatar({ member, size = "", title, active }) {
  if (!member) return <div className={"avatar empty " + size} title={title || "Unassigned"}><Ic.User s={size === "lg" ? 17 : 13} /></div>;
  return (
    <div className={"avatar " + size + (active ? " active" : "")} style={{ background: member.color }}
      title={title || (active ? member.name + " · active now" : member.name)}>
      {member.initials}
      {active && <span className="av-dot" />}
    </div>
  );
}

/* stacked member avatars */
function MemberStack({ ids, size = "sm", max = 3 }) {
  const users = usersByIds(ids);
  if (users.length === 0) return null;   // unassigned tasks show no avatar at all
  const shown = users.slice(0, max);
  const extra = users.length - shown.length;
  return (
    <div className="av-stack">
      {shown.map((u) => <Avatar key={u.id} member={u} size={size} />)}
      {extra > 0 && <div className={"avatar more " + size} title={users.slice(max).map((u) => u.name).join(", ")}>+{extra}</div>}
    </div>
  );
}

/* ---------- Card ---------- */
function Card({ task, showAvatars, onLift, lifting, ghost, locked }) {
  const dl = task.due ? dueState(task.due) : "";
  const checkTotal = task.check.length;
  const checkDone = task.check.filter((c) => c.done).length;
  const allDone = checkTotal > 0 && checkDone === checkTotal;

  return (
    <div
      className={"card" + (task.prio && task.prio !== "none" ? " flag-" + task.prio : "") + (lifting ? " lifting" : "") + (locked ? " locked" : "")}
      data-card-id={task.id}
      onPointerDown={ghost ? undefined : (e) => onLift(e, task)}
      style={ghost ? { width: "100%" } : undefined}
    >
      {task.labels.length > 0 && (
        <div className="card-labels">
          {task.labels.map((id) => {
            const l = labelById(id); if (!l) return null;
            return <span key={id} className="lbl" style={{ color: l.fg, background: l.bg }}>{l.name}</span>;
          })}
        </div>
      )}
      <p className="card-title">{task.title}</p>

      {(task.due || task.budget != null || task.vols != null) && (
        <div className="card-meta">
          {task.due && (
            <span className={"chip " + (dl === "over" ? "due-over" : dl === "soon" ? "due-soon" : "")}>
              <Ic.Cal s={13} /> {fmtDue(task.due)}
            </span>
          )}
          {task.budget != null && <span className="chip budget"><Ic.Money s={13} /> {fmtMoney(task.budget)}</span>}
          {task.vols != null && task.vols > 0 && <span className="chip vol"><Ic.Users s={13} /> {task.vols}</span>}
        </div>
      )}

      <div className="card-foot">
        {checkTotal > 0 && (
          <span className={"checkbar" + (allDone ? " done" : "")} title={checkDone + " of " + checkTotal + " done"}>
            <Ic.ListChk s={14} />
            <span className="mini-prog"><i style={{ width: (checkDone / checkTotal * 100) + "%" }} /></span>
            {checkDone}/{checkTotal}
          </span>
        )}
        <span className="sp" />
        {showAvatars && task.members && task.members.length > 0 && <MemberStack ids={task.members} size="sm" />}
      </div>
    </div>
  );
}

/* ---------- Column ---------- */
function Column({ stage, dotColor, tasks, showAvatars, onLift, dragId, placeholder, canManage, canAddTask, onAddTask, onRenameStage, onDeleteStage, onColLift }) {
  const [composing, setComposing] = React.useState(false);
  const [draft, setDraft] = React.useState("");
  const [menuOpen, setMenuOpen] = React.useState(false);
  const nameRef = React.useRef(null);
  const taRef = React.useRef(null);

  React.useEffect(() => { if (composing && taRef.current) taRef.current.focus(); }, [composing]);

  const visible = tasks.filter((t) => t.id !== dragId);
  const phIndex = placeholder && placeholder.stageId === stage.id ? placeholder.index : -1;

  function commitName() {
    const v = nameRef.current.textContent.trim();
    nameRef.current.contentEditable = "false";
    if (v && v !== stage.name) onRenameStage(stage.id, v);
    else nameRef.current.textContent = stage.name;
  }
  function startRename() {
    if (!canManage) return;
    setMenuOpen(false);
    const el = nameRef.current;
    el.contentEditable = "true"; el.focus();
    const r = document.createRange(); r.selectNodeContents(el);
    const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(r);
  }
  function addDraft() { const v = draft.trim(); if (v) { onAddTask(stage.id, v); setDraft(""); } }

  const cards = [];
  visible.forEach((t, i) => {
    if (i === phIndex) cards.push(<div key="__ph" className="card-ph" data-ph="1" />);
    cards.push(<Card key={t.id} task={t} showAvatars={showAvatars} onLift={onLift} lifting={t.id === dragId} />);
  });
  if (phIndex >= visible.length) cards.push(<div key="__ph" className="card-ph" data-ph="1" />);

  return (
    <div className={"col" + (placeholder && placeholder.stageId === stage.id ? " drop-active" : "")} data-stage-id={stage.id}>
      <div className={"col-hd" + (canManage ? " draggable" : "")} onPointerDown={canManage ? (e) => onColLift(e, stage) : undefined}>
        <span className="col-dot" style={{ background: dotColor }} />
        <span
          ref={nameRef} className="col-name" suppressContentEditableWarning
          onBlur={commitName}
          onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitName(); } if (e.key === "Escape") { nameRef.current.textContent = stage.name; commitName(); } }}
          onDoubleClick={startRename}
        >{stage.name}</span>
        <span className="col-count">{tasks.length}</span>
        <span className="sp" />
        {canAddTask && <button className="icon-btn" title="Add task" onClick={() => setComposing(true)}><Ic.Plus s={17} /></button>}
        {canManage && (
          <div style={{ position: "relative" }}>
            <button className="icon-btn" title="Stage options" onClick={() => setMenuOpen((v) => !v)}><Ic.Dots s={17} /></button>
            {menuOpen && (
              <>
                <div style={{ position: "fixed", inset: 0, zIndex: 40 }} onClick={() => setMenuOpen(false)} />
                <div className="menu right" style={{ minWidth: 180 }}>
                  <button className="menu-item" onClick={startRename}><span className="ic"><Ic.Edit s={15} /></span>Rename stage</button>
                  <button className="menu-item" onClick={() => { setMenuOpen(false); setComposing(true); }}><span className="ic"><Ic.Plus s={15} /></span>Add task</button>
                  <div className="menu-sep" />
                  <button className="menu-item danger" onClick={() => { setMenuOpen(false); onDeleteStage(stage.id); }}><span className="ic"><Ic.Trash s={15} /></span>Delete stage</button>
                </div>
              </>
            )}
          </div>
        )}
      </div>

      <div className="col-list" data-list>
        {cards}
        {visible.length === 0 && phIndex < 0 && <div className="col-empty">{(canManage || canAddTask) ? "Drop tasks here" : "No tasks"}</div>}
      </div>

      {canAddTask && (composing ? (
        <div className="composer">
          <textarea
            ref={taRef} value={draft} placeholder="Enter a task title…"
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); addDraft(); } if (e.key === "Escape") { setComposing(false); setDraft(""); } }}
          />
          <div className="composer-row">
            <button className="btn primary" onClick={addDraft}>Add task</button>
            <button className="btn ghost" onClick={() => { setComposing(false); setDraft(""); }}>Cancel</button>
          </div>
        </div>
      ) : (
        <button className="add-card" onClick={() => setComposing(true)}><Ic.Plus s={16} /> Add a task</button>
      ))}
    </div>
  );
}

/* ---------- Board + DnD ---------- */
function Board({ project, user, showAvatars, onOpenTask, onAddTask, onMoveTask, onRenameStage, onReorderStage, onDeleteStage, onAddStage }) {
  const boardRef = React.useRef(null);
  const scrollRef = React.useRef(null);
  const ghostRef = React.useRef(null);
  const drag = React.useRef(null);
  const [dragId, setDragId] = React.useState(null);
  const [placeholder, setPlaceholder] = React.useState(null);
  const [ghost, setGhost] = React.useState(null);

  const colGhostRef = React.useRef(null);
  const colDrag = React.useRef(null);
  const [colDragId, setColDragId] = React.useState(null);
  const [colTarget, setColTarget] = React.useState(null);

  const isAdmin = BPerms.isAdmin(user, project);
  const isContributor = BPerms.isContributor(user, project);
  const canDragTask = (task) => isAdmin || isContributor || BPerms.isMember(user, task);

  const tasksByStage = React.useMemo(() => {
    const m = {}; project.stages.forEach((s) => (m[s.id] = []));
    project.tasks.forEach((t) => { (m[t.stageId] || (m[t.stageId] = [])).push(t); });
    return m;
  }, [project]);

  function isInteractive(el) {
    return el.closest("button, a, input, textarea, select, [contenteditable='true'], [data-no-drag]");
  }

  function computeTarget(x, y) {
    const root = boardRef.current; if (!root) return null;
    const cols = [...root.querySelectorAll("[data-stage-id]")];
    let col = cols.find((c) => { const r = c.getBoundingClientRect(); return x >= r.left && x <= r.right; });
    if (!col) {
      let bd = Infinity;
      cols.forEach((c) => { const r = c.getBoundingClientRect(); const cx = (r.left + r.right) / 2; const d = Math.abs(cx - x); if (d < bd) { bd = d; col = c; } });
    }
    if (!col) return null;
    const stageId = col.dataset.stageId;
    const list = col.querySelector("[data-list]");
    const cards = [...list.querySelectorAll("[data-card-id]")].filter((el) => el.dataset.cardId !== drag.current.task.id);
    let index = cards.length;
    for (let i = 0; i < cards.length; i++) {
      const r = cards[i].getBoundingClientRect();
      if (y < r.top + r.height / 2) { index = i; break; }
    }
    return { stageId, index };
  }

  function moveGhost() {
    const d = drag.current; if (!d || !ghostRef.current) return;
    ghostRef.current.style.transform = `translate(${d.lastX - d.offX}px, ${d.lastY - d.offY}px) rotate(2.5deg)`;
  }

  function autoScroll() {
    const d = drag.current; if (!d || !d.started) return;
    const sc = scrollRef.current;
    if (sc) {
      const r = sc.getBoundingClientRect();
      const EDGE = 70, SPD = 16;
      if (d.lastX < r.left + EDGE) sc.scrollLeft -= SPD;
      else if (d.lastX > r.right - EDGE) sc.scrollLeft += SPD;
    }
    const el = document.elementFromPoint(d.lastX, d.lastY);
    const list = el && el.closest("[data-list]");
    if (list) {
      const r = list.getBoundingClientRect();
      if (d.lastY < r.top + 48) list.scrollTop -= 12;
      else if (d.lastY > r.bottom - 48) list.scrollTop += 12;
    }
    d.raf = requestAnimationFrame(autoScroll);
  }

  function beginDrag() {
    const d = drag.current; if (!d || d.started) return;
    d.started = true;
    setDragId(d.task.id);
    setGhost({ task: d.task, w: d.w });
    document.body.style.userSelect = "none";
    d.touchBlock = (e) => { if (e.cancelable) e.preventDefault(); };
    window.addEventListener("touchmove", d.touchBlock, { passive: false });
    requestAnimationFrame(() => { moveGhost(); });
    setPlaceholder(computeTarget(d.lastX, d.lastY));
    d.raf = requestAnimationFrame(autoScroll);
  }

  function onLift(e, task) {
    if (e.button != null && e.button !== 0 && e.pointerType === "mouse") return;
    if (isInteractive(e.target)) return;
    const r = e.currentTarget.getBoundingClientRect();
    drag.current = {
      task, pointerId: e.pointerId, pointerType: e.pointerType, canDrag: canDragTask(task),
      startX: e.clientX, startY: e.clientY, lastX: e.clientX, lastY: e.clientY,
      offX: e.clientX - r.left, offY: e.clientY - r.top, w: r.width,
      started: false, moved: false, longTimer: null, raf: null,
    };
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", onUp);
    window.addEventListener("pointercancel", onUp);
    if (e.pointerType === "touch" && drag.current.canDrag) {
      drag.current.longTimer = setTimeout(() => { if (drag.current && !drag.current.moved) beginDrag(); }, 200);
    }
  }

  function onMove(e) {
    const d = drag.current; if (!d) return;
    d.lastX = e.clientX; d.lastY = e.clientY;
    const dist = Math.hypot(e.clientX - d.startX, e.clientY - d.startY);
    if (!d.started) {
      if (d.pointerType === "touch") {
        if (dist > 12) { d.moved = true; clearTimeout(d.longTimer); cleanup(); } // treat as scroll
        return;
      }
      if (d.canDrag && dist > 5) beginDrag();
      else if (dist > 5) d.moved = true; // mouse drag on a locked card → cancel tap-open
      return;
    }
    moveGhost();
    const t = computeTarget(e.clientX, e.clientY);
    setPlaceholder((prev) => (prev && t && prev.stageId === t.stageId && prev.index === t.index ? prev : t));
  }

  function onUp() {
    const d = drag.current; if (!d) return;
    if (d.started) {
      const t = computeTarget(d.lastX, d.lastY);
      if (t) onMoveTask(d.task.id, t.stageId, t.index);
    } else if (!d.moved) {
      onOpenTask(d.task.id); // a tap (no drag) opens the task — viewers get a read-only modal
    }
    cleanup();
  }

  function cleanup() {
    const d = drag.current;
    window.removeEventListener("pointermove", onMove);
    window.removeEventListener("pointerup", onUp);
    window.removeEventListener("pointercancel", onUp);
    if (d) {
      clearTimeout(d.longTimer);
      if (d.raf) cancelAnimationFrame(d.raf);
      if (d.touchBlock) window.removeEventListener("touchmove", d.touchBlock, { passive: false });
    }
    document.body.style.userSelect = "";
    drag.current = null;
    setDragId(null); setPlaceholder(null); setGhost(null);
  }

  /* ---- column (stage) reorder — admin-only, dragged from the column header ---- */
  const dotColors = React.useMemo(() => {
    const m = {}; project.stages.forEach((s, i) => (m[s.id] = STAGE_DOTS[i % STAGE_DOTS.length])); return m;
  }, [project.stages]);

  function computeColTarget(x) {
    const root = boardRef.current; if (!root || !colDrag.current) return null;
    const cols = [...root.querySelectorAll("[data-stage-id]")].filter((c) => c.dataset.stageId !== colDrag.current.stage.id);
    let index = cols.length;
    for (let i = 0; i < cols.length; i++) {
      const r = cols[i].getBoundingClientRect();
      if (x < r.left + r.width / 2) { index = i; break; }
    }
    return index;
  }

  function moveColGhost() {
    const d = colDrag.current; if (!d || !colGhostRef.current) return;
    colGhostRef.current.style.transform = `translate(${d.lastX - d.offX}px, ${d.lastY - d.offY}px) rotate(1.5deg)`;
  }

  function colAutoScroll() {
    const d = colDrag.current; if (!d || !d.started) return;
    const sc = scrollRef.current;
    if (sc) {
      const r = sc.getBoundingClientRect();
      const EDGE = 70, SPD = 16;
      if (d.lastX < r.left + EDGE) sc.scrollLeft -= SPD;
      else if (d.lastX > r.right - EDGE) sc.scrollLeft += SPD;
    }
    d.raf = requestAnimationFrame(colAutoScroll);
  }

  function beginColDrag() {
    const d = colDrag.current; if (!d || d.started) return;
    d.started = true;
    setColDragId(d.stage.id);
    document.body.style.userSelect = "none";
    d.touchBlock = (e) => { if (e.cancelable) e.preventDefault(); };
    window.addEventListener("touchmove", d.touchBlock, { passive: false });
    requestAnimationFrame(() => { moveColGhost(); });
    setColTarget(computeColTarget(d.lastX));
    d.raf = requestAnimationFrame(colAutoScroll);
  }

  function onColLift(e, stage) {
    if (e.button != null && e.button !== 0 && e.pointerType === "mouse") return;
    if (isInteractive(e.target)) return;
    const r = e.currentTarget.getBoundingClientRect();
    colDrag.current = {
      stage, pointerId: e.pointerId, pointerType: e.pointerType,
      startX: e.clientX, startY: e.clientY, lastX: e.clientX, lastY: e.clientY,
      offX: e.clientX - r.left, offY: e.clientY - r.top, w: r.width,
      started: false, moved: false, longTimer: null, raf: null,
    };
    window.addEventListener("pointermove", onColMove);
    window.addEventListener("pointerup", onColUp);
    window.addEventListener("pointercancel", onColUp);
    if (e.pointerType === "touch") {
      colDrag.current.longTimer = setTimeout(() => { if (colDrag.current && !colDrag.current.moved) beginColDrag(); }, 200);
    }
  }

  function onColMove(e) {
    const d = colDrag.current; if (!d) return;
    d.lastX = e.clientX; d.lastY = e.clientY;
    const dist = Math.hypot(e.clientX - d.startX, e.clientY - d.startY);
    if (!d.started) {
      if (d.pointerType === "touch") {
        if (dist > 12) { d.moved = true; clearTimeout(d.longTimer); cleanupCol(); }
        return;
      }
      if (dist > 5) beginColDrag();
      return;
    }
    moveColGhost();
    const t = computeColTarget(e.clientX);
    setColTarget((prev) => (prev === t ? prev : t));
  }

  function onColUp() {
    const d = colDrag.current; if (!d) return;
    if (d.started) {
      const t = computeColTarget(d.lastX);
      if (t != null) onReorderStage(d.stage.id, t);
    }
    cleanupCol();
  }

  function cleanupCol() {
    const d = colDrag.current;
    window.removeEventListener("pointermove", onColMove);
    window.removeEventListener("pointerup", onColUp);
    window.removeEventListener("pointercancel", onColUp);
    if (d) {
      clearTimeout(d.longTimer);
      if (d.raf) cancelAnimationFrame(d.raf);
      if (d.touchBlock) window.removeEventListener("touchmove", d.touchBlock, { passive: false });
    }
    document.body.style.userSelect = "";
    colDrag.current = null;
    setColDragId(null); setColTarget(null);
  }

  React.useEffect(() => () => { cleanup(); cleanupCol(); }, []);

  const visibleStages = project.stages.filter((s) => s.id !== colDragId);
  const draggedStage = colDragId ? project.stages.find((s) => s.id === colDragId) : null;

  return (
    <div className="board-scroll" ref={scrollRef}>
      <div className="board" ref={boardRef}>
        {visibleStages.map((stage, i) => (
          <React.Fragment key={stage.id}>
            {colTarget === i && <div className="col-ph-v" />}
            <Column
              stage={stage} dotColor={dotColors[stage.id]}
              tasks={tasksByStage[stage.id] || []} showAvatars={showAvatars}
              onLift={onLift} dragId={dragId} placeholder={placeholder} canManage={isAdmin} canAddTask={isAdmin || isContributor}
              onAddTask={onAddTask} onRenameStage={onRenameStage} onDeleteStage={onDeleteStage} onColLift={onColLift}
            />
          </React.Fragment>
        ))}
        {colTarget === visibleStages.length && <div className="col-ph-v" />}
        {isAdmin && <button className="add-stage" onClick={onAddStage}><Ic.Plus s={17} /> Add stage</button>}
      </div>

      {ghost && ReactDOM.createPortal(
        <div className="drag-ghost" ref={ghostRef} style={{ width: ghost.w }}>
          <Card task={ghost.task} showAvatars={showAvatars} ghost />
        </div>,
        document.body
      )}

      {draggedStage && ReactDOM.createPortal(
        <div className="drag-col-ghost" ref={colGhostRef} style={{ width: colDrag.current ? colDrag.current.w : undefined }}>
          <div className="col-hd">
            <span className="col-dot" style={{ background: dotColors[draggedStage.id] }} />
            <span className="col-name">{draggedStage.name}</span>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
}

Object.assign(window, { Avatar, MemberStack, Board });
