// Checklist.jsx — 08 체크리스트: 담당자 / 마감 / 상태별 할 일 (인터랙티브)
const { Card, StatusBadge, Tag, Button, Tabs } = window.DesignSystem_7d5e72;

function ChecklistScreen({ data, patch }) {
  const [filter, setFilter] = React.useState("all");

  // id, 할 일, 담당, 마감, 기본상태
  const GROUPS = [
    {
      phase: "지금 · 기준 확정", items: [
        ["c1", "예식 월·지역·하객·예산 4개 기준 입력", "공동", "이번 주", "active"],
        ["c2", "우선순위 가중치 합의", "공동", "이번 주", "hold"],
      ],
    },
    {
      phase: "상담 전 · 후보 압축", items: [
        ["c3", "후보 5곳 선정", "오승하", "6/12", "active"],
        ["c4", "상담 질문지 준비·복사", "소영", "6/12", "hold"],
        ["c5", "방문 동선 짜기", "오승하", "6/14", "hold"],
      ],
    },
    {
      phase: "상담 후 · 리스크 입력", items: [
        ["c6", "견적 같은 기준으로 정리", "공동", "상담 후", "hold"],
        ["c7", "환불·위약 조항 확인", "소영", "상담 후", "check"],
        ["c8", "1차 후보 계약 의사결정", "공동", "—", "hold"],
      ],
    },
  ];

  const done = data.done || {};
  const isDone = (id) => !!done[id];
  const toggle = (id) => patch((prev) => ({ ...prev, done: { ...prev.done, [id]: !prev.done[id] } }));

  const allItems = GROUPS.flatMap((g) => g.items);
  const total = allItems.length;
  const completed = allItems.filter((it) => isDone(it[0])).length;

  const TABS = [
    { key: "all",    label: "전체",   count: total },
    { key: "todo",   label: "남은 일", count: total - completed },
    { key: "done",   label: "완료",   count: completed },
  ];

  const itemRow = {
    display: "grid", gridTemplateColumns: "22px 1fr auto auto auto", gap: "14px",
    alignItems: "center", padding: "13px 4px", borderBottom: "1px solid var(--line-soft)",
  };
  const box = (d) => ({
    width: "20px", height: "20px", borderRadius: "6px", border: "1.5px solid",
    borderColor: d ? "var(--st-done-dot)" : "var(--line-strong)",
    background: d ? "var(--st-done-dot)" : "transparent", display: "inline-flex",
    alignItems: "center", justifyContent: "center", color: "#FFF", fontSize: "12px",
    fontWeight: 700, cursor: "pointer", flex: "none",
    transition: "background var(--dur-fast), border-color var(--dur-fast)",
  });

  const match = (it) => filter === "all" ? true : filter === "done" ? isDone(it[0]) : !isDone(it[0]);

  return (
    <div>
      {/* progress + tabs */}
      <Card style={{ marginBottom: "16px" }} padding="18px 20px">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "16px", flexWrap: "wrap" }}>
          <div>
            <div style={{ fontSize: "11px", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 700 }}>전체 진행률</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: "8px", marginTop: "6px" }}>
              <span style={{ fontSize: "28px", fontWeight: 700, color: "var(--primary)", fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}>{completed}</span>
              <span style={{ fontSize: "15px", color: "var(--ink-3)", fontWeight: 600 }}>/ {total} 완료</span>
            </div>
          </div>
          <div style={{ flex: 1, minWidth: "180px", maxWidth: "420px" }}>
            <div style={{ height: "10px", borderRadius: "var(--radius-pill)", background: "var(--paper-3)", overflow: "hidden", boxShadow: "var(--shadow-inset)" }}>
              <div style={{ width: `${total ? (completed / total) * 100 : 0}%`, height: "100%", background: "var(--primary)", borderRadius: "var(--radius-pill)", transition: "width var(--dur-slow) var(--ease-out)" }} />
            </div>
          </div>
        </div>
      </Card>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px", marginBottom: "16px", flexWrap: "wrap" }}>
        <Tabs items={TABS} active={filter} onSelect={setFilter} style={{ border: "none" }} />
        <Button variant="quiet" size="md" iconLeft={<span>＋</span>}>할 일 추가</Button>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
        {GROUPS.map((g, gi) => {
          const items = g.items.filter(match);
          if (items.length === 0) return null;
          return (
            <Card key={gi} eyebrow={`단계 ${gi + 1}`} title={g.phase} accent={gi === 0 ? "primary" : null}>
              <div>
                {items.map((it, i) => {
                  const d = isDone(it[0]);
                  return (
                    <div key={it[0]} style={{ ...itemRow, borderBottom: i === items.length - 1 ? "none" : itemRow.borderBottom }}>
                      <span role="checkbox" aria-checked={d} tabIndex={0} style={box(d)}
                            onClick={() => toggle(it[0])}
                            onKeyDown={(e) => { if (e.key === " " || e.key === "Enter") { e.preventDefault(); toggle(it[0]); } }}>
                        {d ? "✓" : ""}
                      </span>
                      <span style={{ fontSize: "14.5px", color: d ? "var(--ink-4)" : "var(--ink-1)", textDecoration: d ? "line-through" : "none", cursor: "pointer" }}
                            onClick={() => toggle(it[0])}>{it[1]}</span>
                      <Tag tone={it[2] === "오승하" ? "rose" : it[2] === "소영" ? "sage" : "neutral"}>{it[2]}</Tag>
                      <span style={{ fontSize: "13px", color: "var(--ink-3)", fontVariantNumeric: "tabular-nums", width: "64px", textAlign: "right" }}>{it[3]}</span>
                      <StatusBadge status={d ? "done" : it[4]} size="sm" />
                    </div>
                  );
                })}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

window.ChecklistScreen = ChecklistScreen;
