// =============================================================
// 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]);
};

// ---- icon picker for "已经过去" cards (stable per story id) ----
const PAST_ICONS = ["heart", "sakura", "ribbon", "star", "cloud", "strawberry"];
const pickPastIcon = (id) => {
  let h = 0;
  for (let i = 0; i < (id || "").length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
  return PAST_ICONS[h % PAST_ICONS.length];
};

// ---- compute anniversary occurrences ----
// For each milestone-type anniversary we generate 3 candidate countdowns:
// next month-anniversary, next 100-day milestone, next year-anniversary.
// The home page merges all candidates across all anniversaries and picks the closest few.
function nextMonthlyMilestone(anchor, title) {
  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);
  const months = (next.getFullYear() - a.getFullYear()) * 12 + (next.getMonth() - a.getMonth());
  return { date: next, days: daysUntil(next), label: `${title} · 第 ${months} 个月` };
}
function nextHundredDayMilestone(anchor, title) {
  const a = toDate(anchor);
  const now = new Date();
  const elapsed = Math.max(0, daysBetween(a, now)); // floor of (now - anchor) in days
  const nextN = (Math.floor(elapsed / 100) + 1) * 100;
  const next = new Date(a);
  next.setDate(next.getDate() + nextN);
  return { date: next, days: daysUntil(next), label: `${title} · 第 ${nextN} 天` };
}
function nextYearlyMilestone(anchor, title) {
  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: `${title} · ${years} 周年` };
}
// Anniversary -> list of candidate countdowns
function candidatesFor(anniv) {
  if (anniv.kind === "countdown") {
    const days = daysUntil(anniv.date);
    if (days < 0) return []; // expired countdowns hide from the home page
    return [{ date: toDate(anniv.date), days, label: anniv.title, kind: "countdown" }];
  }
  return [
    nextMonthlyMilestone(anniv.date, anniv.title),
    nextHundredDayMilestone(anniv.date, anniv.title),
    nextYearlyMilestone(anniv.date, anniv.title),
  ];
}

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 className="xm-home-counter" style={{ display: "flex", alignItems: "baseline", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
      <div className="xm-home-counter-big" style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
        <span className="xm-home-counter-num" style={{ font: "700 80px/1 'Quicksand', sans-serif", color: "#B8852E", fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}>{d}</span>
        <span className="xm-home-counter-label" style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", letterSpacing: "0.08em", marginTop: 4 }}>天 ♡</span>
      </div>
      <span className="xm-home-counter-sep" style={{ font: "300 36px 'Quicksand', sans-serif", color: "#F0D6A6" }}>·</span>
      <div className="xm-home-counter-cells" style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
        <Cell n={h} label="hours"/>
        <Cell n={m} label="mins"/>
        <Cell n={s} label="secs"/>
      </div>
    </div>
  );
};

const HomePage = ({ settings, photos, promises, stories, onNav, onPhotoOpen, onEditAnniversaries, onEditImportantEvents, onPetOpen }) => {
  // Implicit "在一起" anniversary (always present, derived from togetherDate)
  // + user-defined anniversaries from settings.anniversaries
  const upcoming = useMemo(() => {
    const implicit = { id: "_together", title: "在一起", date: settings.togetherDate, kind: "milestone" };
    const all = [implicit, ...(settings.anniversaries || [])];
    return all.flatMap(candidatesFor).sort((a,b) => a.days - b.days).slice(0, 5);
  }, [settings.togetherDate, settings.anniversaries]);

  // 已经过去 — driven by starred stories (重要事件)
  const importantEvents = useMemo(() =>
    (stories || [])
      .filter(s => s.isAnniversary)
      .map(s => ({ ...s, days: daysSince(s.date) }))
      .sort((a,b) => a.days - b.days),
    [stories]
  );

  // 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 className="xm-home-hero-card" 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>

      {/* Pixel pet preview — 电子宠物灰度开关 */}
      {(window.XM_FEATURES && window.XM_FEATURES.pet) && (
        <PetHomePanel mood={window.xmInitialPetMood()} onOpen={() => onPetOpen && onPetOpen()}/>
      )}

      {/* Today's pick */}
      {todayPick && (
        <div>
          <SectionHeader title="今日推荐" sub={`Today's pick · 在一起的第 ${daysBetween(settings.togetherDate, todayPick.date)} 天`}/>
          <Card onClick={() => onPhotoOpen(todayPick)} className="xm-home-hero" 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" action={<Button variant="cream" size="sm" onClick={onEditAnniversaries}>♡ 编辑</Button>}/>
        {upcoming.length === 0
          ? <Card style={{ padding: 20, textAlign: "center", font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>还没有纪念日，点上面的「♡ 编辑」加一个吧</Card>
          : <div className="xm-home-anniv-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12 }}>
              {upcoming.map((a, i) => {
                const soon = a.days <= 7;
                const isCountdown = a.kind === "countdown";
                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)}
                      {isCountdown && <span style={{ marginLeft: 6, color: "#4A6FA0" }}>⏱ 倒数</span>}
                      {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>

      {/* Important events (starred stories) */}
      <div>
        <SectionHeader title="已经过去" sub="Days since · 重要事件" action={<Button variant="cream" size="sm" onClick={onEditImportantEvents}>♡ 编辑</Button>}/>
        {importantEvents.length === 0
          ? <Card style={{ padding: 20, textAlign: "center", font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>还没有标记的重要事件，去故事里给一段打上 ★ 吧</Card>
          : <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 12 }}>
              {importantEvents.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={pickPastIcon(p.id)} 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 className="xm-home-main-grid" 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 });
