// =============================================================
// StoriesPage — zigzag timeline + types
// =============================================================
const STORY_TYPES = ["📱聊天截图", "📖事件叙述", "🎤名场面", "💭梦境/想法"];

const StoriesPage = ({ stories, onChange, settings }) => {
  const [adding, setAdding] = useState(null); // boolean | story to edit
  const [search, setSearch] = useState("");
  const [tagFilter, setTagFilter] = useState(null);
  const [detail, setDetail] = useState(null);

  const allTags = useMemo(() => [...new Set(stories.flatMap(s => s.tags || []))], [stories]);
  const filtered = useMemo(() => {
    let l = [...stories];
    if (tagFilter) l = l.filter(s => (s.tags || []).includes(tagFilter));
    if (search) {
      const q = search.toLowerCase();
      l = l.filter(s => s.title.toLowerCase().includes(q) || (s.content || "").toLowerCase().includes(q));
    }
    return l.sort((a, b) => b.date.localeCompare(a.date));
  }, [stories, search, tagFilter]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <SectionHeader title="故事本" sub={`Stories · 我们的趣事 · ${stories.length} 条`} action={<Button onClick={() => setAdding(true)}>＋ 写一段</Button>}/>

      {/* search + tags */}
      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ flex: "1 1 240px", minWidth: 220 }}>
          <Field value={search} onChange={(e) => setSearch(e.target.value)} placeholder="🔍 搜一句话…"/>
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Chip tone={!tagFilter ? "solid" : "cream"} onClick={() => setTagFilter(null)}>全部</Chip>
          {allTags.map(t => <Chip key={t} tone={tagFilter === t ? "solid" : "cream"} onClick={() => setTagFilter(t)}>#{t}</Chip>)}
        </div>
      </div>

      {filtered.length === 0
        ? <Empty motif="ribbon" text="还没有故事呀" sub="一句话也好，写下来就不会忘了" action={<div style={{ marginTop: 8 }}><Button onClick={() => setAdding(true)}>＋ 写第一段</Button></div>}/>
        : <ZigzagTimeline stories={filtered} settings={settings} onOpen={(s) => setDetail(s)}/>
      }

      <StoryEditor open={adding === true} story={typeof adding === "object" ? adding : null} onClose={() => setAdding(false)} onSave={(s) => {
        const exists = stories.some(x => x.id === s.id);
        onChange(exists ? stories.map(x => x.id === s.id ? s : x) : [s, ...stories]);
        setAdding(false);
      }}/>

      <StoryDetail s={detail} onClose={() => setDetail(null)} settings={settings}
        onEdit={(s) => { setDetail(null); setAdding(s); }}
        onDelete={(id) => { onChange(stories.filter(x => x.id !== id)); setDetail(null); }}
        related={detail ? stories.filter(x => x.id !== detail.id && (x.date === detail.date || (x.tags || []).some(t => (detail.tags || []).includes(t)))).slice(0, 3) : []}
      />
    </div>
  );
};

const ZigzagTimeline = ({ stories, settings, onOpen }) => (
  <div style={{ position: "relative", padding: "10px 0" }}>
    <div style={{ position: "absolute", left: "50%", top: 0, bottom: 0, width: 2, background: "repeating-linear-gradient(180deg,#F0D6A6,#F0D6A6 6px,transparent 6px,transparent 12px)", transform: "translateX(-50%)" }}/>
    {stories.map((s, i) => {
      const left = i % 2 === 0;
      return (
        <div key={s.id} style={{ display: "flex", justifyContent: left ? "flex-start" : "flex-end", marginBottom: 18, position: "relative" }}>
          <div style={{ position: "absolute", left: "50%", top: 22, width: 26, height: 26, borderRadius: 999, background: s.isAnniversary ? "linear-gradient(135deg,#FFE89E,#FFD27A)" : "#FFFDF6", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: s.isAnniversary ? "0 4px 14px rgba(255,210,122,0.5)" : "0 2px 6px rgba(184,133,46,0.26)", transform: "translateX(-50%)", zIndex: 1, fontSize: 12 }}>
            {s.isAnniversary ? "★" : "♡"}
          </div>
          <div style={{ width: "calc(50% - 28px)" }}>
            <Card gold={s.isAnniversary} onClick={() => onOpen(s)} style={{ padding: 14 }}>
              <div style={{ display: "flex", gap: 6, marginBottom: 6, flexWrap: "wrap" }}>
                <Chip tone={s.isAnniversary ? "gold" : "pink"}>{s.type}</Chip>
                {s.isAnniversary && <Chip tone="gold">★ 纪念日</Chip>}
              </div>
              <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>{s.title}</div>
              <div style={{ font: "400 13px/1.6 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginTop: 4, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{s.content}</div>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", marginTop: 8, letterSpacing: "0.06em" }}>{fmtDate(s.date)} · 第 {daysBetween(settings.togetherDate, s.date)} 天</div>
              {s.tags && s.tags.length > 0 && <div style={{ display: "flex", gap: 4, marginTop: 6, flexWrap: "wrap" }}>{s.tags.map(t => <span key={t} style={{ font: "500 10px 'Quicksand', sans-serif", color: "#B8852E" }}>#{t}</span>)}</div>}
            </Card>
          </div>
        </div>
      );
    })}
  </div>
);

const StoryEditor = ({ open, story, onClose, onSave }) => {
  const blank = { id: window.xm.uid(), title: "", date: new Date().toISOString().slice(0,10), type: "📖事件叙述", content: "", tags: [], isAnniversary: false };
  const [d, setD] = useState(story || blank);
  const [tagInput, setTagInput] = useState("");
  useEffect(() => { setD(story || blank); setTagInput(""); }, [open, story]);

  const addTag = () => {
    if (!tagInput.trim()) return;
    setD({ ...d, tags: [...(d.tags || []), tagInput.trim()] });
    setTagInput("");
  };

  return (
    <Modal open={open || !!story} onClose={onClose} title={story ? "编辑故事" : "写一段我们的故事 ✨"}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <Field label="标题" value={d.title} onChange={(e) => setD({ ...d, title: e.target.value })} placeholder="给这一段起个名字…"/>
        <Field label="日期" type="date" value={d.date} onChange={(e) => setD({ ...d, date: e.target.value })}/>
        <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" }}>{STORY_TYPES.map(t => <Chip key={t} tone={d.type === t ? "solid" : "cream"} onClick={() => setD({ ...d, type: t })}>{t}</Chip>)}</div>
        </div>
        <Field label="内容" multiline value={d.content} onChange={(e) => setD({ ...d, content: e.target.value })} placeholder="慢慢写，我等你…"/>
        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 4 }}>标签</div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 6 }}>
            {(d.tags || []).map(t => <Chip key={t} tone="pink" onClick={() => setD({ ...d, tags: d.tags.filter(x => x !== t) })}>#{t} ×</Chip>)}
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <input value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTag(); } }} placeholder="加个标签…" style={{ flex: 1, fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 14, padding: "8px 12px", borderRadius: 12, border: "2px solid #FBE3B0", background: "#FFFDF6", outline: "none", color: "#4A2A1A" }}/>
            <Button variant="cream" size="sm" onClick={addTag}>＋</Button>
          </div>
        </div>
        <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", padding: "10px 12px", background: "#FFF1D4", borderRadius: 14 }}>
          <span style={{ position: "relative", display: "inline-block", width: 44, height: 26, borderRadius: 999, background: d.isAnniversary ? "#B8852E" : "#F4E29A", transition: "background 200ms" }}>
            <span style={{ position: "absolute", top: 3, left: d.isAnniversary ? 21 : 3, width: 20, height: 20, borderRadius: 999, background: "#FFFDF6", boxShadow: "0 2px 4px rgba(0,0,0,0.15)", transition: "left 200ms cubic-bezier(0.34,1.56,0.64,1)" }}/>
          </span>
          <input type="checkbox" checked={d.isAnniversary} onChange={(e) => setD({ ...d, isAnniversary: e.target.checked })} style={{ display: "none" }}/>
          <span style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>设为纪念日 ★ <span style={{ font: "400 11px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", marginLeft: 4 }}>会出现在首页倒计时</span></span>
        </label>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>取消</Button>
          <Button disabled={!d.title.trim()} onClick={() => onSave(d)}>藏起来 ♡</Button>
        </div>
      </div>
    </Modal>
  );
};

const StoryDetail = ({ s, onClose, settings, onEdit, onDelete, related }) => {
  if (!s) return null;
  return (
    <Modal open={!!s} onClose={onClose} title={s.title}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Chip tone={s.isAnniversary ? "gold" : "pink"}>{s.type}</Chip>
          {s.isAnniversary && <Chip tone="gold">★ 纪念日</Chip>}
          {(s.tags || []).map(t => <Chip key={t} tone="cream">#{t}</Chip>)}
        </div>
        <div style={{ font: "400 16px/1.8 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", whiteSpace: "pre-wrap" }}>{s.content}</div>
        <Card tinted style={{ padding: 12 }}>
          <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em", textTransform: "uppercase" }}>那一天</div>
          <div style={{ font: "600 18px 'Quicksand', sans-serif", color: "#B8852E", marginTop: 4 }}>在一起的第 {daysBetween(settings.togetherDate, s.date)} 天</div>
          <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginTop: 4 }}>{fmtDateCN(s.date)} · 距今 {daysSince(s.date)} 天</div>
        </Card>
        {related.length > 0 && (
          <div>
            <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 6 }}>相关故事</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {related.map(r => (
                <div key={r.id} style={{ padding: 10, background: "#FBEFC2", borderRadius: 12 }}>
                  <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>{r.title}</div>
                  <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#8B6B43", marginTop: 2 }}>{fmtDate(r.date)}</div>
                </div>
              ))}
            </div>
          </div>
        )}
        <div style={{ display: "flex", gap: 8, justifyContent: "space-between", marginTop: 6 }}>
          <Button variant="secondary" onClick={() => onDelete(s.id)}>删除</Button>
          <Button variant="primary" onClick={() => onEdit(s)}>编辑</Button>
        </div>
      </div>
    </Modal>
  );
};

Object.assign(window, { StoriesPage, STORY_TYPES });
