/* ============================================================
   cm_ui.jsx — ChefsMate 主控台 共用元件（掛 window）
   依賴 ui.jsx（Icon / AIAvatar / BossAvatar / ProgressRing / Bar）
   ============================================================ */
const CAT = { sage: "var(--c-sage)", mint: "var(--c-mint)", blush: "var(--c-blush)", coral: "var(--c-coral)", taupe: "var(--c-taupe)", tan: "var(--c-tan)", sand: "var(--c-sand)", bluegrey: "var(--c-bluegrey)", purple: "var(--c-purple)" };

const SEV = {
  critical: { label: "Critical", color: "var(--block)", soft: "var(--block-soft)" },
  high: { label: "High", color: "var(--warn)", soft: "var(--warn-soft)" },
  medium: { label: "Medium", color: "var(--c-tan)", soft: "var(--warn-soft)" },
  low: { label: "Low", color: "var(--info)", soft: "var(--info-soft)" },
  P0: { label: "P0", color: "var(--block)", soft: "var(--block-soft)" },
  P1: { label: "P1", color: "var(--warn)", soft: "var(--warn-soft)" },
  P2: { label: "P2", color: "var(--info)", soft: "var(--info-soft)" },
};
function SevBadge({ s }) {
  const x = SEV[s] || SEV.medium;
  return <span className="chip" style={{ background: x.soft, color: x.color }}><span className="dot" style={{ background: x.color }} />{x.label}</span>;
}

const CM_PRIO = { high: { label: "高", color: "var(--block)", soft: "var(--block-soft)" }, medium: { label: "中", color: "var(--warn)", soft: "var(--warn-soft)" }, low: { label: "低", color: "var(--ink-3)", soft: "var(--surface-2)" } };
function PrioTag({ p }) {
  const x = CM_PRIO[p] || CM_PRIO.medium;
  return <span className="chip prio" style={{ background: x.soft, color: x.color }}><Icon name="flag" size={11} />{x.label}</span>;
}

function AuthorChip({ author }) {
  const ai = author === "ai";
  return (
    <span className="author">
      {ai ? <AIAvatar size={17} /> : <BossAvatar size={17} />}
      {ai ? "AI" : "你"}
    </span>
  );
}

function StatusPill({ label, color = "var(--ink-3)", soft = "var(--surface-2)" }) {
  return <span className="chip" style={{ background: soft, color }}><span className="dot" style={{ background: color }} />{label}</span>;
}

/* checklist with live progress */
function Checklist({ items, onToggle, color = "var(--accent)" }) {
  if (!items || !items.length) return <div style={{ fontSize: 12.5, color: "var(--ink-3)", padding: "4px 2px" }}>尚無項目</div>;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
      {items.map((it, i) => (
        <button key={i} onClick={(e) => { e.stopPropagation(); onToggle && onToggle(i); }} className="subtask-row" style={{
          display: "flex", alignItems: "center", gap: 10, padding: "7px 6px", border: "none", background: "none",
          textAlign: "left", borderRadius: 8, cursor: onToggle ? "pointer" : "default", width: "100%",
        }}>
          <span style={{ width: 18, height: 18, borderRadius: 6, flexShrink: 0, border: it.done ? "none" : "1.8px solid var(--line)", background: it.done ? color : "transparent", display: "grid", placeItems: "center", color: "#fff", transition: "all 0.15s" }}>{it.done && <Icon name="check" size={12} />}</span>
          <span style={{ fontSize: 13.5, color: it.done ? "var(--ink-3)" : "var(--ink)", textDecoration: it.done ? "line-through" : "none" }}>{it.text}</span>
        </button>
      ))}
    </div>
  );
}
function checklistProgress(items) {
  if (!items || !items.length) return 0;
  return items.filter((x) => x.done).length / items.length;
}

/* you <-> AI comment thread */
function CommentThread({ comments, onSend, placeholder = "留言給 AI…" }) {
  const [text, setText] = useState("");
  const endRef = useRef(null);
  useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [comments.length]);
  function submit() { const v = text.trim(); if (!v) return; onSend(v); setText(""); }
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0 }}>
      <div ref={endRef} style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 14, paddingBottom: 6 }}>
        {!comments.length && <div style={{ textAlign: "center", padding: "32px 12px", color: "var(--ink-3)", fontSize: 13 }}>還沒有討論，開個頭吧</div>}
        {comments.map((m, i) => {
          const me = m.author === "boss";
          return (
            <div key={i} style={{ display: "flex", gap: 10, flexDirection: me ? "row-reverse" : "row" }}>
              {me ? <BossAvatar size={28} /> : <AIAvatar size={28} />}
              <div style={{ maxWidth: "80%" }}>
                <div style={{ display: "flex", gap: 7, marginBottom: 3, justifyContent: me ? "flex-end" : "flex-start" }}>
                  <span style={{ fontSize: 12, fontWeight: 700 }}>{me ? "你" : "AI 助理"}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{m.time}</span>
                </div>
                <div style={{ padding: "9px 13px", borderRadius: 13, fontSize: 13.5, lineHeight: 1.55, background: me ? "var(--accent)" : "var(--surface)", color: me ? "#fff" : "var(--ink)", border: me ? "none" : "1px solid var(--line)", borderTopRightRadius: me ? 4 : 13, borderTopLeftRadius: me ? 13 : 4 }}>{m.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", gap: 8, paddingTop: 11, borderTop: "1px solid var(--line)" }}>
        <input className="input" placeholder={placeholder} 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>
  );
}

/* page header */
function PageHead({ icon, color, title, desc, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 14, marginBottom: 18 }}>
      {icon && <div style={{ width: 40, height: 40, borderRadius: 12, background: (color || "var(--accent)") + "22", color: color || "var(--accent)", display: "grid", placeItems: "center", flexShrink: 0, border: `1px solid ${color || "var(--accent)"}33` }}><Icon name={icon} size={21} /></div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <h2 style={{ margin: 0, fontSize: 19, fontWeight: 700, letterSpacing: "-0.01em" }}>{title}</h2>
        {desc && <p className="section-intro" style={{ margin: "3px 0 0" }}>{desc}</p>}
      </div>
      {right}
    </div>
  );
}

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

Object.assign(window, { CAT, SEV, SevBadge, PrioTag, AuthorChip, StatusPill, Checklist, checklistProgress, CommentThread, PageHead, EmptyState, CM_PRIO });
