// =============================================================
// HomePage / Dashboard — live counter, anniversaries, recent feeds
// =============================================================
const { daysSince, daysUntil, daysBetween, fmtDate, fmtDateCN, toDate, ymd } = window.xm.util;

// ---- live timer (re-renders every second) ----
const useTick = (interval = 1000) => {
  const [, setT] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setT(t => t + 1), interval);
    return () => clearInterval(id);
  }, [interval]);
};

// ---- compute anniversary occurrences ----
function nextMonthlyAnniversary(anchor) {
  const a = toDate(anchor);
  const now = new Date();
  const day = a.getDate();
  let next = new Date(now.getFullYear(), now.getMonth(), day);
  if (next <= now) next = new Date(now.getFullYear(), now.getMonth() + 1, day);
  // monthly count
  let months = (next.getFullYear() - a.getFullYear()) * 12 + (next.getMonth() - a.getMonth());
  return { date: next, days: daysUntil(next), label: `第 ${months} 个月纪念日` };
}
function nextYearlyAnniversary(anchor) {
  const a = toDate(anchor);
  const now = new Date();
  let next = new Date(now.getFullYear(), a.getMonth(), a.getDate());
  if (next <= now) next = new Date(now.getFullYear() + 1, a.getMonth(), a.getDate());
  const years = next.getFullYear() - a.getFullYear();
  return { date: next, days: daysUntil(next), label: `${years} 周年纪念日` };
}
function nextYearlyOf(d, label) {
  const a = toDate(d);
  const now = new Date();
  let next = new Date(now.getFullYear(), a.getMonth(), a.getDate());
  if (next <= now) next = new Date(now.getFullYear() + 1, a.getMonth(), a.getDate());
  return { date: next, days: daysUntil(next), label };
}

const LiveCounter = ({ togetherDate }) => {
  useTick(1000);
  const ms = Date.now() - toDate(togetherDate).getTime();
  const d = Math.floor(ms / 86400000);
  const h = Math.floor((ms % 86400000) / 3600000);
  const m = Math.floor((ms % 3600000) / 60000);
  const s = Math.floor((ms % 60000) / 1000);
  const Cell = ({ n, label }) => (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", minWidth: 64 }}>
      <span style={{ font: "700 36px/1 'Quicksand', sans-serif", color: "#B8852E", fontVariantNumeric: "tabular-nums" }}>{String(n).padStart(2, "0")}</span>
      <span style={{ font: "500 11px 'Quicksand', sans-serif", color: "#8B6B43", letterSpacing: "0.12em", textTransform: "uppercase", marginTop: 4 }}>{label}</span>
    </div>
  );
  return (
    <div style={{ display: "flex", alignItems: "baseline", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
        <span style={{ font: "700 80px/1 'Quicksand', sans-serif", color: "#B8852E", fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}>{d}</span>
        <span style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", letterSpacing: "0.08em", marginTop: 4 }}>天 ♡</span>
      </div>
      <span style={{ font: "300 36px 'Quicksand', sans-serif", color: "#F0D6A6" }}>·</span>
      <Cell n={h} label="hours"/>
      <Cell n={m} label="mins"/>
      <Cell n={s} label="secs"/>
    </div>
  );
};

const HomePage = ({ settings, photos, promises, stories, onNav, onPhotoOpen }) => {
  const monthly = useMemo(() => nextMonthlyAnniversary(settings.togetherDate), [settings.togetherDate]);
  const yearly  = useMemo(() => nextYearlyAnniversary(settings.togetherDate), [settings.togetherDate]);
  const customs = useMemo(() => settings.keyDates.map(k => nextYearlyOf(k.date, k.title + "（每年）")), [settings.keyDates]);
  const storyAnnivs = useMemo(() =>
    stories.filter(s => s.isAnniversary).map(s => nextYearlyOf(s.date, s.title)),
    [stories]
  );
  const upcoming = [monthly, yearly, ...customs, ...storyAnnivs].sort((a,b) => a.days - b.days).slice(0, 5);

  // Past key milestones
  const pastDates = settings.keyDates.map(k => ({ ...k, days: daysSince(k.date) })).sort((a,b) => a.days - b.days);

  // Today's pick
  const todayPick = useMemo(() => {
    if (!photos.length) return null;
    const seed = new Date().toISOString().slice(0,10).split("-").reduce((a,b) => a + parseInt(b), 0);
    return photos[seed % photos.length];
  }, [photos]);

  const recentPhotos = useMemo(() => [...photos].sort((a,b) => b.date.localeCompare(a.date)).slice(0,3), [photos]);
  const todoCount = promises.filter(p => p.status === "todo" || p.status === "doing").length;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* Hero */}
      <Card tinted style={{ padding: "32px 28px", textAlign: "center", overflow: "visible" }}>
        <Motif name="ribbon" size={44} style={{ position: "absolute", top: -10, left: 24, transform: "rotate(-12deg)" }}/>
        <Motif name="sakura" size={36} style={{ position: "absolute", top: 14, right: 20, opacity: 0.85 }}/>
        <div style={{ font: "500 12px 'Quicksand', sans-serif", color: "#8B6B43", letterSpacing: "0.16em", textTransform: "uppercase" }}>{fmtDateCN(new Date())}</div>
        <h1 style={{ font: "600 36px/1.2 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", margin: "8px 0 4px", letterSpacing: "0.06em" }}>
          欢迎回来，{settings.nickname} <span style={{ color: "#B8852E" }}>💕</span>
        </h1>
        <div style={{ font: "400 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", marginBottom: 22 }}>我们已经在一起</div>
        <LiveCounter togetherDate={settings.togetherDate}/>
      </Card>

      {/* Today's pick */}
      {todayPick && (
        <div>
          <SectionHeader title="今日推荐" sub={`Today's pick · 在一起的第 ${daysBetween(settings.togetherDate, todayPick.date)} 天`}/>
          <Card onClick={() => onPhotoOpen(todayPick)} style={{ display: "flex", gap: 16, padding: 16 }}>
            <PhotoTile photo={todayPick} size={140}/>
            <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", gap: 6, minWidth: 0 }}>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                <Chip tone="solid">{todayPick.mood}</Chip>
                {todayPick.album && <Chip tone="cream">{todayPick.album}</Chip>}
              </div>
              <div style={{ font: "600 20px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>{todayPick.title}</div>
              <div style={{ font: "400 14px/1.6 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E" }}>{todayPick.note}</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.08em", marginTop: 2 }}>{fmtDate(todayPick.date)} · {todayPick.place} · {daysSince(todayPick.date)} 天前</div>
            </div>
          </Card>
        </div>
      )}

      {/* Upcoming anniversaries */}
      <div>
        <SectionHeader title="纪念日倒数" sub="Upcoming anniversaries"/>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12 }}>
          {upcoming.map((a, i) => {
            const soon = a.days <= 7;
            return (
              <Card key={i} gold={soon} style={{ padding: 16, animation: soon ? "xm-pulse 2s ease-in-out infinite" : "none" }}>
                <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4 }}>
                  {fmtDate(a.date)}
                  {soon && <span style={{ marginLeft: 6, color: "#B8852E" }}>♡ 即将到来</span>}
                </div>
                <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em", marginBottom: 8 }}>{a.label}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span style={{ font: "700 36px/1 'Quicksand', sans-serif", color: soon ? "#B8852E" : "#6B4A2E", fontVariantNumeric: "tabular-nums" }}>{a.days}</span>
                  <span style={{ font: "500 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>天后</span>
                </div>
              </Card>
            );
          })}
        </div>
      </div>

      {/* Past milestones */}
      <div>
        <SectionHeader title="已经过去" sub="Days since"/>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 12 }}>
          {pastDates.map((p) => (
            <Card key={p.id} style={{ padding: 14, display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 48, height: 48, borderRadius: 14, background: "linear-gradient(135deg,#FFF1D4,#FBE3B0)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Motif name={p.icon} size={28}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.title}</div>
                <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.06em", marginTop: 2 }}>已 {p.days} 天 · {fmtDate(p.date)}</div>
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* Recent activity */}
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
        <div>
          <SectionHeader title="最近的回忆" sub="Recent" action={<Button variant="ghost" size="sm" onClick={() => onNav("album")}>去相册</Button>}/>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {recentPhotos.map(p => (
              <Card key={p.id} onClick={() => onPhotoOpen(p)} style={{ display: "flex", gap: 12, padding: 12 }}>
                <PhotoTile photo={p} size={68}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: "600 15px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>{p.title}</div>
                  <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.note}</div>
                  <div style={{ font: "500 10px 'Quicksand', sans-serif", color: "#B5946D", marginTop: 2, letterSpacing: "0.06em" }}>{fmtDate(p.date)}</div>
                </div>
              </Card>
            ))}
          </div>
        </div>
        <div>
          <SectionHeader title="待兑现" sub="Pending"/>
          <Card style={{ padding: 18, textAlign: "center" }}>
            <Motif name="strawberry" size={42}/>
            <div style={{ font: "700 36px 'Quicksand', sans-serif", color: "#B8852E", marginTop: 6, fontVariantNumeric: "tabular-nums" }}>{todoCount}</div>
            <div style={{ font: "500 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E" }}>个承诺还没兑现</div>
            <div style={{ marginTop: 10 }}><Button size="sm" variant="primary" onClick={() => onNav("promises")}>去看看</Button></div>
          </Card>
          <div style={{ marginTop: 14 }}>
            <Card dashed onClick={() => onNav("stories")} style={{ textAlign: "center", padding: 18 }}>
              <Motif name="heart" size={32}/>
              <div style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginTop: 6, letterSpacing: "0.04em" }}>写一段我们的故事 →</div>
            </Card>
          </div>
        </div>
      </div>

      <style>{`@keyframes xm-pulse { 0%,100% { box-shadow: 0 4px 20px rgba(255,210,122,0.3), inset 0 0 0 2px #FFD27A } 50% { box-shadow: 0 8px 30px rgba(184,133,46,0.30), inset 0 0 0 2px #D9A256 } }`}</style>
    </div>
  );
};

// Tile used by Home + Album — displays uploaded image (data URL) or motif placeholder
const PhotoTile = ({ photo, size = 80 }) => {
  if (photo.src) {
    return <img src={photo.src} alt="" style={{ width: size, height: size, borderRadius: 14, objectFit: "cover", flexShrink: 0, boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.6)" }}/>;
  }
  return (
    <div style={{ width: size, height: size, borderRadius: 14, background: "linear-gradient(135deg,#FFF1D4,#FBE3B0)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Motif name={photo.tone || "sakura"} size={size * 0.5}/>
    </div>
  );
};

Object.assign(window, { HomePage, PhotoTile, useTick });
