/* ============================================================
   cm_drawer.jsx — 項目詳情抽屜（可編輯 / 狀態 / checklist / 你↔AI 留言）
   支援 type: inbox | todo | dogfood | spec | bug | audit
   ============================================================ */

function Segmented({ value, options, onChange }) {
  return (
    <div style={{ display: "inline-flex", background: "var(--surface-2)", borderRadius: 9, padding: 3, gap: 2 }}>
      {options.map((o) => (
        <button key={o.v} onClick={() => onChange(o.v)} style={{
          border: "none", borderRadius: 7, padding: "5px 11px", fontSize: 12, fontWeight: 700, cursor: "pointer",
          background: value === o.v ? "var(--surface)" : "transparent",
          color: value === o.v ? (o.color || "var(--accent-2)") : "var(--ink-3)",
          boxShadow: value === o.v ? "var(--shadow-sm)" : "none",
        }}>{o.label}</button>
      ))}
    </div>
  );
}

/* 抽屜內小段落：標籤 + 內容 */
function DSec({ label, children, color }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".04em", color: color || "var(--ink-3)", marginBottom: 6, textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.7 }}>{children}</div>
    </div>
  );
}

/* dogfood 詳情：目的 / 怎麼開 / 步驟(說明+舉例) / 預期 / 老闆白話 / 工程師 / 註記 */
function DogfoodDetail({ item, onToggle }) {
  const steps = item.steps || [];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      {item.purpose && <DSec label="目的">{item.purpose}</DSec>}
      {item.howTo && <DSec label="怎麼開">{item.howTo}</DSec>}
      {steps.length > 0 && (
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <span style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".04em", color: "var(--c-blush)", textTransform: "uppercase" }}>測試步驟</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{steps.filter((x) => x.done).length}/{steps.length}</span>
            <div style={{ flex: 1, maxWidth: 160 }}><Bar value={steps.length ? steps.filter((x) => x.done).length / steps.length : 0} color="var(--c-blush)" /></div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {steps.map((st, i) => (
              <div key={i} style={{ display: "flex", gap: 10, padding: "10px 12px", border: "1px solid var(--line)", borderRadius: 12, background: st.done ? "var(--ok-soft)" : "var(--surface)" }}>
                <button onClick={() => onToggle(i)} aria-label="toggle" style={{ flexShrink: 0, width: 20, height: 20, marginTop: 1, borderRadius: 6, border: st.done ? "none" : "2px solid var(--line-strong, #ccc)", background: st.done ? "var(--ok)" : "transparent", display: "grid", placeItems: "center", cursor: "pointer", color: "#fff" }}>{st.done && <Icon name="check" size={13} />}</button>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: st.done ? "var(--ink-3)" : "var(--ink)", textDecoration: st.done ? "line-through" : "none" }}>{i + 1}. {st.t}</div>
                  {st.desc && <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.6, marginTop: 3 }}>{st.desc}</div>}
                  {st.example && <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55, marginTop: 4, paddingLeft: 9, borderLeft: "2px solid var(--c-blush)" }}>💡 {st.example}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      {item.expected && <DSec label="預期結果" color="var(--ok)">{item.expected}</DSec>}
      {item.bossPlain && (
        <div style={{ display: "flex", gap: 10, padding: "12px 14px", background: "var(--accent-soft)", borderRadius: 12 }}>
          <AIAvatar size={26} /><div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.65 }}><span style={{ fontWeight: 800 }}>老闆白話：</span>{item.bossPlain}</div>
        </div>
      )}
      {item.engineer && <DSec label="工程師備註">{item.engineer}</DSec>}
      {item.note && (
        <div style={{ fontSize: 12.5, color: "var(--warn)", lineHeight: 1.6, background: "var(--warn-soft)", padding: "10px 12px", borderRadius: 10 }}>{item.note}</div>
      )}
    </div>
  );
}

/* 夜審白話 3 段：以前 → 怎麼修 → 修好後 */
function FixStory({ item }) {
  const rows = [
    { label: "以前會發生什麼", text: item.before, color: "var(--block)" },
    { label: "怎麼修", text: item.fix, color: "var(--accent-2)" },
    { label: "修好後", text: item.after, color: "var(--ok)" },
  ].filter((r) => r.text);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {rows.map((r) => (
        <div key={r.label} style={{ borderLeft: `3px solid ${r.color}`, paddingLeft: 12 }}>
          <div style={{ fontSize: 11.5, fontWeight: 800, color: r.color, marginBottom: 4 }}>{r.label}</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.7 }}>{r.text}</div>
        </div>
      ))}
    </div>
  );
}

function ItemDrawer({ item, type, onClose, actions }) {
  const [tab, setTab] = useState("content");
  const [editing, setEditing] = useState(false);
  const [draftTitle, setDraftTitle] = useState(item.title || "");
  const [draftBody, setDraftBody] = useState(item.body || item.desc || item.note || "");

  useEffect(() => {
    function esc(e) { if (e.key === "Escape") onClose(); }
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, []);
  useEffect(() => { setDraftTitle(item.title || ""); setDraftBody(item.body || item.desc || item.note || ""); setEditing(false); }, [item.id]);

  const meta = {
    inbox: { icon: "inbox", color: "var(--block)", label: "收件匣" },
    todo: { icon: "grid", color: "var(--accent)", label: "待辦" },
    dogfood: { icon: "beaker", color: "var(--c-blush)", label: "Dogfood" },
    spec: { icon: "file", color: "var(--c-bluegrey)", label: "Spec" },
    bug: { icon: "bug", color: "var(--c-tan)", label: "Bug" },
    audit: { icon: "moon", color: "var(--c-purple)", label: "夜審" },
  }[type];

  const editable = type === "todo" || type === "spec";
  const checklist = type === "todo" ? item.checklist : null;
  const comments = item.comments || [];

  function saveEdit() { actions.onEdit(item.id, type, { title: draftTitle, body: draftBody }); setEditing(false); }

  const tabs = [{ k: "content", label: "內容" }, { k: "talk", label: "討論", count: comments.length }];

  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <div className="drawer" role="dialog" data-screen-label={meta.label + "細項"}>
        {/* header */}
        <div style={{ padding: "18px 22px 14px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
            <div style={{ width: 30, height: 30, borderRadius: 9, background: meta.color + "22", color: meta.color, display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name={meta.icon} size={17} /></div>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-3)" }}>{meta.label}</span>
            {item.area && <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{item.area}</span>}
            {item.id && type === "bug" && <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{item.id}</span>}
            <div style={{ marginLeft: "auto", display: "flex", gap: 4 }}>
              {editable && !editing && <button className="btn btn-ghost btn-icon" onClick={() => setEditing(true)} title="編輯"><Icon name="edit" size={16} /></button>}
              <button className="btn btn-ghost btn-icon" onClick={onClose}><Icon name="x" size={18} /></button>
            </div>
          </div>

          {editing ? (
            <input className="input" value={draftTitle} onChange={(e) => setDraftTitle(e.target.value)} style={{ fontSize: 17, fontWeight: 700, marginBottom: 8 }} />
          ) : (
            <h2 style={{ margin: 0, fontSize: 18.5, fontWeight: 700, letterSpacing: "-0.01em", lineHeight: 1.35 }}>{item.title}</h2>
          )}

          {/* status controls */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 12, flexWrap: "wrap" }}>
            {type === "todo" && <>
              <AuthorChip author={item.author} />
              <PrioTag p={item.priority} />
              <Segmented value={item.status} onChange={(v) => actions.onSetStatus(item.id, type, v)} options={[{ v: "doing", label: "進行中", color: "var(--accent-2)" }, { v: "todo", label: "待處理" }, { v: "done", label: "完成", color: "var(--ok)" }]} />
            </>}
            {type === "spec" && <>
              <AuthorChip author={item.author} />
              <Segmented value={item.status} onChange={(v) => actions.onSetStatus(item.id, type, v)} options={[{ v: "draft", label: "草稿" }, { v: "review", label: "審查中", color: "var(--warn)" }, { v: "locked", label: "定稿", color: "var(--ok)" }]} />
            </>}
            {type === "dogfood" && <>
              <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>第 {item.session} 輪</span>
              <Segmented value={item.passed ? "y" : "n"} onChange={(v) => actions.onSetStatus(item.id, type, v === "y")} options={[{ v: "n", label: "測試中", color: "var(--warn)" }, { v: "y", label: "通過", color: "var(--ok)" }]} />
            </>}
            {type === "bug" && <>
              <SevBadge s={item.severity} />
              <Segmented value={item.status} onChange={(v) => actions.onSetStatus(item.id, type, v)} options={[{ v: "open", label: "未修", color: "var(--block)" }, { v: "fixed", label: "已修", color: "var(--ok)" }]} />
            </>}
            {type === "audit" && <>
              <SevBadge s={item.severity} />
              <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{item.cat}</span>
              <Segmented value={item.status} onChange={(v) => actions.onSetStatus(item.id, type, v)} options={[{ v: "new", label: "待覆核", color: "var(--warn)" }, { v: "reviewed", label: "已覆核", color: "var(--ok)" }]} />
            </>}
            {type === "inbox" && <>
              <span className="chip" style={{ background: item.kind === "decision" ? "var(--block-soft)" : "var(--info-soft)", color: item.kind === "decision" ? "var(--block)" : "var(--info)" }}>{item.kind === "decision" ? "待決策" : "待回覆"}</span>
            </>}
          </div>
        </div>

        {/* tabs */}
        <div style={{ display: "flex", gap: 18, borderBottom: "1px solid var(--line)", padding: "0 22px" }}>
          {tabs.map((tb) => (
            <button key={tb.k} onClick={() => setTab(tb.k)} style={{ padding: "12px 0", border: "none", background: "none", fontSize: 13.5, fontWeight: 700, cursor: "pointer", color: tab === tb.k ? "var(--accent-2)" : "var(--ink-3)", borderBottom: tab === tb.k ? "2px solid var(--accent)" : "2px solid transparent", marginBottom: -1, display: "flex", alignItems: "center", gap: 6 }}>
              {tb.label}{tb.count != null && <span className="mono" style={{ fontSize: 10.5, background: tab === tb.k ? "var(--accent-soft)" : "var(--surface-2)", color: tab === tb.k ? "var(--accent-2)" : "var(--ink-3)", padding: "1px 6px", borderRadius: 20 }}>{tb.count}</span>}
            </button>
          ))}
        </div>

        {/* body */}
        <div style={{ flex: 1, overflowY: "auto", minHeight: 0, padding: tab === "talk" ? "14px 22px 18px" : "18px 22px 26px" }}>
          {tab === "content" ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {/* dogfood：完整詳情（目的/怎麼開/步驟/預期/白話/工程師） */}
              {type === "dogfood" && <DogfoodDetail item={item} onToggle={(i) => actions.onToggleChecklist(item.id, "dogfood", i)} />}

              {/* body / description（bug 的 note 等） */}
              {type !== "dogfood" && (item.body || item.desc || item.note || editing) && (
                <div>
                  {editing && type === "spec" ? (
                    <textarea className="textarea" value={draftBody} onChange={(e) => setDraftBody(e.target.value)} style={{ minHeight: 120 }} />
                  ) : (
                    <p style={{ margin: 0, fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.7 }}>{item.body || item.desc || item.note}</p>
                  )}
                </div>
              )}

              {/* spec 流程圖（pre 保留排版） */}
              {item.flow && (
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", marginBottom: 8 }}>流程圖</div>
                  <pre style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--ink-2)", background: "var(--surface-2)", borderRadius: 10, padding: "12px 14px", overflowX: "auto", fontFamily: "ui-monospace, Menlo, monospace", whiteSpace: "pre" }}>{item.flow}</pre>
                </div>
              )}

              {/* bug 的修法 */}
              {type === "bug" && item.fix && <DSec label={item.status === "fixed" ? "怎麼修的" : "處理方向"} color={item.status === "fixed" ? "var(--ok)" : "var(--accent-2)"}>{item.fix}</DSec>}

              {editing && <div style={{ display: "flex", gap: 8 }}><button className="btn btn-primary btn-sm" onClick={saveEdit}><Icon name="check" size={13} />儲存</button><button className="btn btn-sm" onClick={() => setEditing(false)}>取消</button></div>}

              {/* inbox options */}
              {type === "inbox" && (
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", marginBottom: 9 }}>{item.chosen ? "你的選擇" : "請選擇"}</div>
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                    {item.options.map((o) => {
                      const picked = item.chosen === o.v;
                      return <button key={o.v} className="btn opt-btn" onClick={() => actions.onAnswer(item.id, o.v, o.label)} style={{ background: picked ? "var(--accent)" : undefined, color: picked ? "#fff" : undefined, borderColor: picked ? "transparent" : undefined }}>{picked && <Icon name="check" size={14} />}{o.label}</button>;
                    })}
                  </div>
                </div>
              )}

              {/* checklist */}
              {checklist && (
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)" }}>{type === "dogfood" ? "測試步驟" : "子項目"}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{checklist.filter((x) => x.done).length}/{checklist.length}</span>
                    <div style={{ flex: 1, maxWidth: 160 }}><Bar value={checklistProgress(checklist)} color={meta.color} /></div>
                  </div>
                  <Checklist items={checklist} color={meta.color} onToggle={(i) => actions.onToggleChecklist(item.id, type, i)} />
                </div>
              )}

              {/* audit details */}
              {type === "audit" && (
                <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.7, display: "flex", flexDirection: "column", gap: 12 }}>
                  {item.plain && (
                    <div style={{ display: "flex", gap: 10, padding: "11px 13px", background: "var(--accent-soft)", borderRadius: 12 }}>
                      <AIAvatar size={26} /><div style={{ color: "var(--ink)" }}><span style={{ fontWeight: 700 }}>白話：</span>{item.plain}</div>
                    </div>
                  )}
                  {(item.before || item.fix || item.after) && <FixStory item={item} />}
                  {(item.finding || item.suggestion || item.file) && (
                    <div>
                      {item.finding && <div><span style={{ fontWeight: 700, color: "var(--ink)" }}>發現：</span>{item.finding}</div>}
                      {item.suggestion && <div style={{ marginTop: 4 }}><span style={{ fontWeight: 700, color: "var(--ink)" }}>建議：</span>{item.suggestion}</div>}
                      {item.file && <div className="mono" style={{ marginTop: 6, fontSize: 11.5, color: "var(--ink-3)" }}>{item.file}</div>}
                    </div>
                  )}
                </div>
              )}
            </div>
          ) : (
            <CommentThread comments={comments} onSend={(text) => actions.onComment(item.id, type, text)} placeholder="留言 / @AI 提問…" />
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { ItemDrawer });
