/* ============================================================
   views_detail.jsx — 任務細項抽屜 + 新增任務表單
   ============================================================ */

function TabBar({ tabs, active, onChange }) {
  return (
    <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--line)", padding: "0 24px" }}>
      {tabs.map((t) => (
        <button key={t.k} onClick={() => onChange(t.k)} style={{
          padding: "13px 4px", marginRight: 16, border: "none", background: "none",
          fontSize: 13.5, fontWeight: 600, cursor: "pointer",
          color: active === t.k ? "var(--accent)" : "var(--ink-3)",
          borderBottom: active === t.k ? "2px solid var(--accent)" : "2px solid transparent",
          marginBottom: -1, display: "flex", alignItems: "center", gap: 6,
        }}>
          {t.label}
          {t.count != null && <span className="mono" style={{ fontSize: 10.5, background: active === t.k ? "var(--accent-soft)" : "var(--surface-2)", color: active === t.k ? "var(--accent-2)" : "var(--ink-3)", padding: "1px 6px", borderRadius: 20 }}>{t.count}</span>}
        </button>
      ))}
    </div>
  );
}

/* ---------- subtask list with drag reorder ---------- */
function SubtaskList({ task, stage, onToggle, onReorder }) {
  const color = STAGE_COLOR[stage.key];
  const [dragIdx, setDragIdx] = useState(null);
  const [overIdx, setOverIdx] = useState(null);
  if (!stage.subtasks.length) return <div style={{ fontSize: 12.5, color: "var(--ink-3)", padding: "4px 6px" }}>尚無子任務</div>;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
      {stage.subtasks.map((sub, i) => (
        <div key={sub.id}
          draggable
          onDragStart={(e) => { setDragIdx(i); e.dataTransfer.effectAllowed = "move"; }}
          onDragOver={(e) => { e.preventDefault(); if (overIdx !== i) setOverIdx(i); }}
          onDragEnd={() => { setDragIdx(null); setOverIdx(null); }}
          onDrop={(e) => { e.preventDefault(); if (dragIdx != null && dragIdx !== i) onReorder(task.id, stage.key, dragIdx, i); setDragIdx(null); setOverIdx(null); }}
          className={"subtask-row" + (dragIdx === i ? " dragging" : "") + (overIdx === i && dragIdx !== null && dragIdx !== i ? " drop-target" : "")}
          style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 6px", borderRadius: 7, cursor: "pointer", width: "100%" }}>
          <svg className="grip" width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="6" r="1.6"/><circle cx="15" cy="6" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="18" r="1.6"/><circle cx="15" cy="18" r="1.6"/></svg>
          <button onClick={() => onToggle(task.id, stage.key, sub.id)} style={{
            display: "flex", alignItems: "center", gap: 10, border: "none", background: "none",
            textAlign: "left", cursor: "pointer", flex: 1, padding: 0,
          }}>
            <span style={{
              width: 18, height: 18, borderRadius: 6, flexShrink: 0,
              border: sub.done ? "none" : "1.8px solid var(--line)",
              background: sub.done ? color : "transparent",
              display: "grid", placeItems: "center", color: "white", transition: "all 0.15s ease",
            }}>{sub.done && <Icon name="check" size={12} />}</span>
            <span style={{ fontSize: 13.5, color: sub.done ? "var(--ink-3)" : "var(--ink)", textDecoration: sub.done ? "line-through" : "none" }}>{sub.text}</span>
          </button>
        </div>
      ))}
    </div>
  );
}

/* ---------- stages + subtasks (with checkboxes) ---------- */
function StagesPanel({ task, onToggle, onReorder }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {task.stages.map((s) => {
        const def = window.STAGE_DEFS.find((x) => x.key === s.key);
        const prog = stageProgress(s);
        const color = STAGE_COLOR[s.key];
        const statusLabel = { done: "完成", active: "進行中", blocked: "卡關", upcoming: "待開始" }[s.status];
        return (
          <div key={s.key} className="card" style={{ padding: "15px 17px", borderLeft: `3px solid ${color}` }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <span style={{ width: 9, height: 9, borderRadius: 3, background: color }} />
              <span style={{ fontWeight: 700, fontSize: 14 }}>{def.label}</span>
              <span className="chip" style={{
                fontSize: 10.5,
                background: s.status === "blocked" ? "var(--block-soft)" : s.status === "done" ? "var(--ok-soft)" : s.status === "active" ? "var(--accent-soft)" : "var(--surface-2)",
                color: s.status === "blocked" ? "var(--block)" : s.status === "done" ? "var(--ok)" : s.status === "active" ? "var(--accent-2)" : "var(--ink-3)",
              }}>{statusLabel}</span>
              <span className="mono" style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--ink-3)" }}>{fmtDate(s.start)}–{fmtDate(s.end)}</span>
            </div>
            <div style={{ marginBottom: 11 }}><Bar value={prog} color={color} /></div>
            <SubtaskList task={task} stage={s} onToggle={onToggle} onReorder={onReorder} />
          </div>
        );
      })}
    </div>
  );
}

/* ---------- AI update log ---------- */
function UpdatesPanel({ task }) {
  if (!task.updates.length) return <Empty text="AI 還沒有進度更新" />;
  return (
    <div style={{ position: "relative", paddingLeft: 8 }}>
      <div style={{ position: "absolute", left: 21, top: 10, bottom: 10, width: 2, background: "var(--line)" }} />
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {task.updates.map((u, i) => {
          const def = window.STAGE_DEFS.find((x) => x.key === u.stage);
          return (
            <div key={i} className={u.fresh ? "update-fresh" : ""} style={{ display: "flex", gap: 13, position: "relative" }}>
              <div style={{ zIndex: 1 }}><AIAvatar size={28} /></div>
              <div style={{ flex: 1, paddingTop: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5, flexWrap: "wrap" }}>
                  <span style={{ fontWeight: 700, fontSize: 13 }}>AI 助理</span>
                  <span className="chip" style={{ fontSize: 10.5, background: "var(--surface-2)", color: "var(--ink-2)" }}>
                    <span className="dot" style={{ background: STAGE_COLOR[u.stage] }} />{def.short}
                  </span>
                  <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>{u.time}</span>
                </div>
                <div className="card update-bubble" style={{ padding: "11px 14px", fontSize: 13.5, lineHeight: 1.6, color: "var(--ink)" }}>{u.text}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- blockers / decisions ---------- */
function BlockersPanel({ task, onResolve }) {
  const open = task.blockers.filter((b) => !b.resolved);
  const closed = task.blockers.filter((b) => b.resolved);
  if (!task.blockers.length) return <Empty text="目前沒有卡關或待決策事項 🎉" />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {open.map((b) => (
        <div key={b.id} className="card" style={{ padding: "16px 18px", borderLeft: "3px solid var(--block)", background: "var(--block-soft)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
            <Icon name="alert" size={16} style={{ color: "var(--block)" }} />
            <span style={{ fontWeight: 700, fontSize: 13.5, color: "var(--block)" }}>{b.needsDecision ? "待您決策" : "卡關中"}</span>
          </div>
          <div style={{ fontSize: 13.5, lineHeight: 1.65, color: "var(--ink)", marginBottom: 14 }}>{b.text}</div>
          <button className="btn btn-primary" style={{ fontSize: 12.5 }} onClick={() => onResolve(task.id, b.id)}>
            <Icon name="check" size={14} /> 已給方向，標記解決
          </button>
        </div>
      ))}
      {closed.map((b) => (
        <div key={b.id} className="card" style={{ padding: "14px 18px", opacity: 0.66 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <Icon name="check" size={15} style={{ color: "var(--ok)" }} />
            <span style={{ fontWeight: 700, fontSize: 13, color: "var(--ok)" }}>已解決</span>
          </div>
          <div style={{ fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)", textDecoration: "line-through" }}>{b.text}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------- comments ---------- */
function CommentsPanel({ task, onSend }) {
  const [text, setText] = useState("");
  const endRef = useRef(null);
  useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [task.comments.length]);
  function submit() {
    const v = text.trim();
    if (!v) return;
    onSend(task.id, v);
    setText("");
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div ref={endRef} style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 16, paddingBottom: 8 }}>
        {!task.comments.length && <Empty text="開始與 AI 的對話" />}
        {task.comments.map((c, i) => {
          const me = c.author === "me";
          return (
            <div key={i} style={{ display: "flex", gap: 11, flexDirection: me ? "row-reverse" : "row" }}>
              {me ? <BossAvatar size={30} /> : <AIAvatar size={30} />}
              <div style={{ maxWidth: "78%" }}>
                <div style={{ display: "flex", gap: 8, marginBottom: 4, justifyContent: me ? "flex-end" : "flex-start" }}>
                  <span style={{ fontSize: 12.5, fontWeight: 700 }}>{me ? "您" : "AI 助理"}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{c.time}</span>
                </div>
                <div style={{
                  padding: "10px 14px", borderRadius: 13, fontSize: 13.5, lineHeight: 1.6,
                  background: me ? "var(--accent)" : "var(--surface)",
                  color: me ? "white" : "var(--ink)",
                  border: me ? "none" : "1px solid var(--line)",
                  borderTopRightRadius: me ? 4 : 13, borderTopLeftRadius: me ? 13 : 4,
                  fontFamily: me ? "var(--sans)" : "var(--serif)",
                }}>{c.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", gap: 9, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
        <input className="input" placeholder="留言給 AI 助理…" value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } }} />
        <button className="btn btn-primary btn-icon" onClick={submit}><Icon name="send" size={16} /></button>
      </div>
    </div>
  );
}

function Empty({ text }) {
  return <div style={{ textAlign: "center", padding: "44px 20px", color: "var(--ink-3)", fontSize: 13.5 }}>{text}</div>;
}

/* ---------- the drawer ---------- */
function TaskDrawer({ task, onClose, onToggle, onResolve, onSend, onReorder }) {
  const [tab, setTab] = useState("stages");
  useEffect(() => {
    function esc(e) { if (e.key === "Escape") onClose(); }
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, []);
  if (!task) return null;
  const prog = taskProgress(task);
  const cnt = taskCounts(task);
  const openBlockers = task.blockers.filter((b) => !b.resolved).length;
  const tabs = [
    { k: "stages", label: "階段與子任務", count: cnt.total },
    { k: "updates", label: "進度紀錄", count: task.updates.length },
    { k: "blockers", label: "卡關 / 決策", count: openBlockers || null },
    { k: "comments", label: "留言討論", count: task.comments.length },
  ];
  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <div className="drawer" role="dialog" aria-label="任務細項" data-screen-label="任務細項">
        {/* header */}
        <div style={{ padding: "20px 24px 16px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
            <ProgressRing value={prog} size={54} stroke={5} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 6, flexWrap: "wrap" }}>
                <h2 style={{ margin: 0, fontSize: 19, fontWeight: 700, letterSpacing: "-0.02em" }}>{task.title}</h2>
                <PriorityTag priority={task.priority} />
                <StatusChip task={task} />
              </div>
              <p style={{ margin: "0 0 10px", fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.6 }}>{task.desc}</p>
              <div style={{ display: "flex", gap: 16, flexWrap: "wrap", fontSize: 12, color: "var(--ink-3)" }}>
                <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="calendar" size={13} />期限 {fmtFull(task.deadline)}</span>
                <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="user" size={13} />{task.owner}</span>
              </div>
            </div>
            <button className="btn btn-ghost btn-icon" onClick={onClose} aria-label="關閉"><Icon name="x" size={18} /></button>
          </div>
        </div>

        <TabBar tabs={tabs} active={tab} onChange={setTab} />

        <div style={{ flex: 1, overflowY: "auto", padding: tab === "comments" ? "16px 24px 18px" : "18px 24px 28px", display: "flex", flexDirection: "column" }}>
          {tab === "stages" && <StagesPanel task={task} onToggle={onToggle} onReorder={onReorder} />}
          {tab === "updates" && <UpdatesPanel task={task} />}
          {tab === "blockers" && <BlockersPanel task={task} onResolve={onResolve} />}
          {tab === "comments" && <CommentsPanel task={task} onSend={onSend} />}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { TaskDrawer });
