// =============================================================
// PromisesPage — 小本本
// =============================================================
const PROMISE_CATS = ["🍰小事", "🌟中等", "💎重大", "🎁惊喜", "🌍长期目标"];

const PromisesPage = ({ promises, onChange, onConfetti }) => {
  const [tab, setTab] = useState("todo"); // todo | done | all
  const [adding, setAdding] = useState(false);
  const [detail, setDetail] = useState(null);

  // mark overdue
  const today = new Date();
  const list = useMemo(() => promises.map(p => {
    if (p.status !== "todo" && p.status !== "doing") return p;
    if (p.due && toDate(p.due) < today) return { ...p, _overdue: daysSince(p.due) };
    return p;
  }), [promises]);

  const filtered = list.filter(p => tab === "all" ? true : tab === "done" ? p.status === "done" : (p.status === "todo" || p.status === "doing"));
  const sorted = [...filtered].sort((a,b) => b.created.localeCompare(a.created));

  const totalDone = list.filter(p => p.status === "done").length;
  const rate = list.length ? Math.round((totalDone / list.length) * 100) : 0;
  const fastest = list.filter(p => p.status === "done" && p.completedAt).sort((a,b) => daysBetween(a.created, a.completedAt) - daysBetween(b.created, b.completedAt))[0];
  const slowest = list.filter(p => p.status === "done" && p.completedAt).sort((a,b) => daysBetween(b.created, b.completedAt) - daysBetween(a.created, a.completedAt))[0];
  const monthKey = new Date().toISOString().slice(0,7);
  const newThisMonth = list.filter(p => p.created.slice(0,7) === monthKey).length;
  const doneThisMonth = list.filter(p => p.completedAt && p.completedAt.slice(0,7) === monthKey).length;

  const update = (id, patch) => onChange(promises.map(p => p.id === id ? { ...p, ...patch } : p));
  const complete = (id) => {
    update(id, { status: "done", completedAt: new Date().toISOString().slice(0,10) });
    onConfetti();
  };

  const TabBtn = ({ k, label, n }) => (
    <button onClick={() => setTab(k)} style={{
      padding: "8px 18px", borderRadius: 999, border: "none", cursor: "pointer",
      background: tab === k ? "#B8852E" : "transparent",
      color: tab === k ? "#FFFDF6" : "#6B4A2E",
      font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", letterSpacing: "0.04em",
    }}>{label} <span style={{ opacity: 0.7, fontSize: 12, marginLeft: 4 }}>{n}</span></button>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <SectionHeader title="承诺画饼簿" sub={`Promises · 小本本 · 兑现率 ${rate}%`} action={<Button onClick={() => setAdding(true)}>＋ 画一个饼</Button>}/>

      {/* Stats */}
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
        <Card tinted style={{ padding: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em", textTransform: "uppercase" }}>FULFILLMENT</div>
              <div style={{ font: "600 18px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 2 }}>已经实现的小宇宙</div>
            </div>
            <div style={{ font: "700 38px 'Quicksand', sans-serif", color: "#B8852E", fontVariantNumeric: "tabular-nums" }}>{totalDone}<span style={{ fontSize: 20, color: "#B5946D" }}>/{list.length}</span></div>
          </div>
          <div style={{ height: 14, background: "#FFF1D4", borderRadius: 999, marginTop: 14, overflow: "hidden", position: "relative" }}>
            <div style={{ position: "absolute", inset: 0, width: `${rate}%`, background: "linear-gradient(90deg,#D9A256,#B8852E)", borderRadius: 999, transition: "width 600ms cubic-bezier(0.34,1.56,0.64,1)", display: "flex", alignItems: "center", justifyContent: "flex-end", paddingRight: 6 }}>
              {rate > 8 && <span style={{ color: "#FFFDF6", fontSize: 10 }}>♡</span>}
            </div>
          </div>
        </Card>
        <Card style={{ padding: 14, textAlign: "center" }}>
          <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em" }}>本月新画</div>
          <div style={{ font: "700 28px 'Quicksand', sans-serif", color: "#4A2A1A", marginTop: 4 }}>{newThisMonth}</div>
          <div style={{ font: "400 11px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>个新承诺</div>
        </Card>
        <Card style={{ padding: 14, textAlign: "center" }}>
          <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em" }}>本月吃掉</div>
          <div style={{ font: "700 28px 'Quicksand', sans-serif", color: "#6FCBA0", marginTop: 4 }}>{doneThisMonth}</div>
          <div style={{ font: "400 11px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>个已兑现</div>
        </Card>
      </div>

      {(fastest || slowest) && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {fastest && <Card style={{ padding: 14, display: "flex", gap: 12, alignItems: "center" }}>
            <Motif name="star" size={32}/>
            <div style={{ flex: 1 }}>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em" }}>最快兑现</div>
              <div style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 2 }}>{fastest.text}</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B8852E", marginTop: 2 }}>{daysBetween(fastest.created, fastest.completedAt)} 天就实现啦</div>
            </div>
          </Card>}
          {slowest && <Card style={{ padding: 14, display: "flex", gap: 12, alignItems: "center" }}>
            <Motif name="cloud" size={32}/>
            <div style={{ flex: 1 }}>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em" }}>慢工出细活</div>
              <div style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 2 }}>{slowest.text}</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#6B4A2E", marginTop: 2 }}>等了 {daysBetween(slowest.created, slowest.completedAt)} 天</div>
            </div>
          </Card>}
        </div>
      )}

      <div style={{ display: "flex", gap: 6, background: "#FFFDF6", borderRadius: 999, padding: 4, alignSelf: "flex-start", boxShadow: "inset 0 0 0 1px rgba(217,162,86,0.32)" }}>
        <TabBtn k="todo" label="待完成" n={list.filter(p => p.status !== "done").length}/>
        <TabBtn k="done" label="已兑现" n={list.filter(p => p.status === "done").length}/>
        <TabBtn k="all"  label="全部"   n={list.length}/>
      </div>

      {sorted.length === 0
        ? <Empty motif="strawberry" text="还没有偷偷许下的小承诺" sub="要不要现在写一个？" action={<div style={{ marginTop: 8 }}><Button onClick={() => setAdding(true)}>＋ 画一个饼</Button></div>}/>
        : <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
            {sorted.map(p => <PromiseCard key={p.id} p={p} onComplete={complete} onOpen={() => setDetail(p)}/>)}
          </div>}

      <PromiseEditor open={adding} onClose={() => setAdding(false)} onSave={(np) => { onChange([np, ...promises]); setAdding(false); }}/>
      <PromiseDetail p={detail} onClose={() => setDetail(null)} onSave={(u) => { update(u.id, u); setDetail(null); }} onComplete={(id) => { complete(id); setDetail(null); }} onDelete={(id) => { onChange(promises.filter(x => x.id !== id)); setDetail(null); }}/>
    </div>
  );
};

const PromiseCard = ({ p, onComplete, onOpen }) => {
  const done = p.status === "done";
  const overdue = !done && p._overdue;
  const daysLeft = !done && p.due ? daysUntil(p.due) : null;
  return (
    <Card style={{ padding: 16, position: "relative", background: done ? "#F4FAF5" : (overdue ? "#FFF1F2" : "#FFFDF6") }} onClick={onOpen}>
      {done && <div style={{
        position: "absolute", top: 14, right: 14, transform: "rotate(-12deg)",
        border: "3px double #6FCBA0", color: "#2D6B4F", padding: "4px 10px", borderRadius: 8,
        font: "700 11px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", letterSpacing: "0.1em",
        background: "rgba(255,252,248,0.9)", boxShadow: "0 2px 6px rgba(111,203,160,0.25)",
      }}>已兑现 ♡</div>}
      <div style={{ display: "flex", gap: 6, marginBottom: 8, flexWrap: "wrap" }}>
        <Chip tone={done ? "mint" : "pink"}>{p.category}</Chip>
        {Array.from({ length: p.importance || 1 }).map((_, i) => <span key={i} style={{ fontSize: 12, color: "#B8852E" }}>♥</span>)}
      </div>
      <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em", textDecoration: done ? "line-through" : "none", textDecorationColor: "#E5BA75" }}>{p.text}</div>
      {p.note && <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", marginTop: 4 }}>{p.note}</div>}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
        <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.06em" }}>
          {done ? `兑现于 ${fmtDate(p.completedAt)}` : overdue ? <span style={{ color: "#B8852E" }}>逾期 {p._overdue} 天</span> : daysLeft != null ? `还有 ${daysLeft} 天` : `${fmtDate(p.created)}`}
        </div>
        {!done && <Button size="sm" variant="mint" onClick={(e) => { e.stopPropagation(); onComplete(p.id); }}>✓ 兑现</Button>}
      </div>
    </Card>
  );
};

const PromiseEditor = ({ open, onClose, onSave, initial }) => {
  const blank = { id: window.xm.uid(), text: "", created: new Date().toISOString().slice(0,10), due: "", category: "🍰小事", importance: 3, status: "todo", note: "" };
  const [d, setD] = useState(initial || blank);
  useEffect(() => { setD(initial || blank); }, [open]);

  return (
    <Modal open={open} onClose={onClose} title={initial ? "编辑承诺" : "画一个饼 🥧"}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <Field label="承诺内容" multiline value={d.text} onChange={(e) => setD({ ...d, text: e.target.value })} placeholder="想给你做点什么呢…"/>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <Field label="许下日期" type="date" value={d.created} onChange={(e) => setD({ ...d, created: e.target.value })}/>
          <Field label="截止日期（可选）" type="date" value={d.due || ""} onChange={(e) => setD({ ...d, due: e.target.value })}/>
        </div>
        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 4 }}>类别</div>
          <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>{PROMISE_CATS.map(c => <Chip key={c} tone={d.category === c ? "solid" : "cream"} onClick={() => setD({ ...d, category: c })}>{c}</Chip>)}</div>
        </div>
        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 4 }}>重要程度</div>
          <div style={{ display: "flex", gap: 6 }}>
            {[1,2,3,4,5].map(n => (
              <button key={n} onClick={() => setD({ ...d, importance: n })} style={{ background: "transparent", border: "none", cursor: "pointer", fontSize: 22, color: n <= d.importance ? "#B8852E" : "#FBE3B0" }}>♥</button>
            ))}
          </div>
        </div>
        <Field label="小备注" value={d.note} onChange={(e) => setD({ ...d, note: e.target.value })} placeholder="一些细节…"/>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 8 }}>
          <Button variant="ghost" onClick={onClose}>取消</Button>
          <Button disabled={!d.text.trim()} onClick={() => onSave(d)}>藏起来 ♡</Button>
        </div>
      </div>
    </Modal>
  );
};

const PromiseDetail = ({ p, onClose, onSave, onComplete, onDelete }) => {
  if (!p) return null;
  const done = p.status === "done";
  return (
    <Modal open={!!p} onClose={onClose} title={p.text.slice(0, 24)}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Chip tone={done ? "mint" : "pink"}>{p.category}</Chip>
          <Chip tone="cream">{Array.from({ length: p.importance }).fill("♥").join("")}</Chip>
          {done && <Chip tone="mint">已兑现 ✨</Chip>}
        </div>
        <div style={{ font: "400 16px/1.7 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>{p.text}</div>
        {p.note && <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", padding: 12, background: "#FBEFC2", borderRadius: 14 }}>📝 {p.note}</div>}

        {/* timeline */}
        <Card tinted style={{ padding: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 999, background: "#FBE3B0", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12 }}>🥧</div>
            <div>
              <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>画饼于</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#8B6B43" }}>{fmtDate(p.created)}</div>
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 28, height: 28, borderRadius: 999, background: done ? "#B5E5CF" : "#FBEFC2", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12 }}>{done ? "✨" : "⏳"}</div>
            <div>
              <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>{done ? "兑现于" : "还在路上"}</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#8B6B43" }}>{done ? `${fmtDate(p.completedAt)} · 等了 ${daysBetween(p.created, p.completedAt)} 天` : (p.due ? `截止 ${fmtDate(p.due)}` : "没设截止日")}</div>
            </div>
          </div>
        </Card>

        <div style={{ display: "flex", gap: 8, justifyContent: "space-between" }}>
          <Button variant="secondary" onClick={() => onDelete(p.id)}>删除</Button>
          {!done && <Button onClick={() => onComplete(p.id)}>✓ 标记兑现</Button>}
        </div>
      </div>
    </Modal>
  );
};

Object.assign(window, { PromisesPage, PROMISE_CATS });
