// =============================================================
// AlbumPage — grid + timeline, upload, detail
// =============================================================
const MOOD_TAGS = ["💕甜蜜", "🥰幸福", "😆搞笑", "🥺感动", "🌟特别", "🍦日常"];
const ALBUMS = ["全部", "日常", "第一次旅行", "节日", "收藏 ⭐"];

const AlbumPage = ({ photos, onChange, settings, onPhotoOpen }) => {
  const [view, setView] = useState("grid"); // grid | timeline | place
  const [filter, setFilter] = useState("全部");
  const [adding, setAdding] = useState(false);

  const filtered = useMemo(() => {
    if (filter === "全部") return photos;
    if (filter === "收藏 ⭐") return photos.filter(p => p.fav);
    return photos.filter(p => p.album === filter);
  }, [photos, filter]);

  const sorted = useMemo(() => [...filtered].sort((a,b) => b.date.localeCompare(a.date)), [filtered]);
  const grouped = useMemo(() => {
    const m = {};
    sorted.forEach(p => {
      const key = p.date.slice(0,7);
      (m[key] = m[key] || []).push(p);
    });
    return m;
  }, [sorted]);

  const groupedByPlace = useMemo(() => {
    const m = {};
    sorted.forEach(p => {
      const key = p.place || "未知地点";
      (m[key] = m[key] || []).push(p);
    });
    return m;
  }, [sorted]);

  const togglefav = (id) => onChange(photos.map(p => p.id === id ? { ...p, fav: !p.fav } : p));

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <SectionHeader title="相册" sub={`Album · 我们的回忆胶卷 · ${photos.length} 张`} action={<Button onClick={() => setAdding(true)}>＋ 上传照片</Button>}/>

      {/* Albums + view toggle */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {ALBUMS.map(a => <Chip key={a} tone={filter === a ? "solid" : "cream"} onClick={() => setFilter(a)}>{a}</Chip>)}
        </div>
        <div style={{ display: "flex", gap: 6, background: "#FFFDF6", borderRadius: 999, padding: 4, boxShadow: "inset 0 0 0 1px rgba(217,162,86,0.32)" }}>
          {[["grid", "🌸 网格"], ["timeline", "📜 时间轴"], ["place", "🗺 地点"]].map(([k, l]) => (
            <button key={k} onClick={() => setView(k)} style={{
              padding: "6px 14px", borderRadius: 999, border: "none", cursor: "pointer",
              background: view === k ? "#B8852E" : "transparent",
              color: view === k ? "#FFFDF6" : "#6B4A2E",
              font: "600 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", letterSpacing: "0.04em",
            }}>{l}</button>
          ))}
        </div>
      </div>

      {sorted.length === 0 && <Empty motif="cloud" text="还没有回忆呀，快上传第一张吧 🥺" sub="拖拽图片进来 或 点上传" action={<div style={{ marginTop: 8 }}><Button onClick={() => setAdding(true)}>＋ 上传照片</Button></div>}/>}

      {view === "grid" && Object.entries(grouped).map(([month, list]) => (
        <div key={month}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <span style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>{month.replace("-", " 年 ")} 月</span>
            <span style={{ flex: 1, height: 12, background: "url('../assets/wavy-divider.svg') center/100% 100% no-repeat", opacity: 0.5 }}/>
            <span style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D" }}>{list.length} 张</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 12 }}>
            {list.map(p => (
              <Card key={p.id} style={{ padding: 12, position: "relative" }} onClick={() => onPhotoOpen(p)}>
                {p.fav && <span style={{ position: "absolute", top: 16, right: 16, fontSize: 16, zIndex: 2 }}>⭐</span>}
                <PhotoTile photo={p} size={"100%"} />
                <div style={{ display: "flex", gap: 4, marginTop: 8, flexWrap: "wrap" }}>
                  <Chip tone="pink" style={{ fontSize: 10, padding: "2px 8px" }}>{p.mood}</Chip>
                </div>
                <div style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 6, letterSpacing: "0.04em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.title}</div>
                <div style={{ font: "500 10px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.06em", marginTop: 2 }}>{fmtDate(p.date)} · {p.place}</div>
              </Card>
            ))}
          </div>
        </div>
      ))}

      {view === "timeline" && (
        <div style={{ position: "relative", paddingLeft: 28 }}>
          <div style={{ position: "absolute", left: 12, top: 0, bottom: 0, width: 2, background: "repeating-linear-gradient(180deg,#F0D6A6,#F0D6A6 6px,transparent 6px,transparent 12px)" }}/>
          {sorted.map((p, i) => (
            <div key={p.id} style={{ position: "relative", marginBottom: 14 }}>
              <div style={{ position: "absolute", left: -22, top: 18, width: 24, height: 24, borderRadius: 999, background: "#FFFDF6", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 2px 6px rgba(184,133,46,0.26)" }}>
                <Motif name={p.tone || "heart"} size={14}/>
              </div>
              <Card onClick={() => onPhotoOpen(p)} style={{ display: "flex", gap: 14, padding: 14 }}>
                <PhotoTile photo={p} size={88}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", gap: 6, marginBottom: 4 }}>
                    <Chip tone="pink">{p.mood}</Chip>
                    {p.fav && <Chip tone="gold">⭐ 收藏</Chip>}
                  </div>
                  <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>{p.title}</div>
                  <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E" }}>{p.note}</div>
                  <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", marginTop: 4, letterSpacing: "0.06em" }}>{fmtDate(p.date)} · {p.place} · 在一起的第 {daysBetween(settings.togetherDate, p.date)} 天</div>
                </div>
              </Card>
            </div>
          ))}
        </div>
      )}

      {view === "place" && Object.entries(groupedByPlace).map(([place, list]) => (
        <div key={place}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <span style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em" }}>📍 {place}</span>
            <span style={{ flex: 1, height: 12, background: "url('../assets/wavy-divider.svg') center/100% 100% no-repeat", opacity: 0.5 }}/>
            <span style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D" }}>{list.length} 张</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: 10 }}>
            {list.map(p => (
              <Card key={p.id} onClick={() => onPhotoOpen(p)} style={{ padding: 10 }}>
                <PhotoTile photo={p} size={"100%"} />
                <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 6, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.title}</div>
              </Card>
            ))}
          </div>
        </div>
      ))}

      <PhotoUploader open={adding} onClose={() => setAdding(false)} onSave={(arr) => { onChange([...arr, ...photos]); setAdding(false); }}/>
    </div>
  );
};

// Upload modal — supports drag & drop, multi-file, then per-photo metadata
const PhotoUploader = ({ open, onClose, onSave }) => {
  const [drafts, setDrafts] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState(null);
  const inputRef = useRef();

  useEffect(() => { if (!open) { setDrafts([]); setUploadError(null); } }, [open]);

  const handleFiles = (files) => {
    Array.from(files).forEach(f => {
      if (!f.type.startsWith("image/")) return;
      const reader = new FileReader();
      reader.onload = (e) => {
        // Base64 preview only — the real File is stashed for upload at save time.
        setDrafts(d => [...d, {
          id: window.xm.uid(),
          src: e.target.result,    // base64 preview (replaced with public URL after upload)
          _file: f,                // File handle for Supabase upload (stripped before save)
          title: f.name.replace(/\.[^.]+$/, ""),
          date: new Date().toISOString().slice(0,10),
          place: "",
          mood: "💕甜蜜",
          note: "",
          album: "日常",
          fav: false,
          tone: "sakura",
        }]);
      };
      reader.readAsDataURL(f);
    });
  };

  const update = (id, patch) => setDrafts(d => d.map(p => p.id === id ? { ...p, ...patch } : p));
  const remove = (id) => setDrafts(d => d.filter(p => p.id !== id));

  const handleSave = async () => {
    setUploading(true);
    setUploadError(null);
    try {
      // Upload all File objects in parallel; replace base64 src with the public URL.
      const finalDrafts = await Promise.all(drafts.map(async (d) => {
        if (!d._file) return { ...d, _file: undefined };
        const { publicUrl } = await window.xm.store.uploadPhoto(d._file);
        const { _file, ...rest } = d;
        return { ...rest, src: publicUrl };
      }));
      onSave(finalDrafts);
    } catch (err) {
      console.error(err);
      setUploadError("有照片上传失败了，再试一次？");
    } finally {
      setUploading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="上传新的回忆 🌸" wide>
      {drafts.length === 0 ? (
        <div
          onDragOver={(e) => { e.preventDefault(); e.currentTarget.style.background = "#FFF1D4"; }}
          onDragLeave={(e) => { e.currentTarget.style.background = "#FFFDF6"; }}
          onDrop={(e) => { e.preventDefault(); e.currentTarget.style.background = "#FFFDF6"; handleFiles(e.dataTransfer.files); }}
          style={{
            border: "2px dashed #E5BA75", borderRadius: 24, padding: 40, textAlign: "center",
            background: "#FFFDF6", cursor: "pointer", transition: "background 200ms",
          }}
          onClick={() => inputRef.current.click()}
        >
          <Motif name="cloud" size={56}/>
          <div style={{ font: "600 18px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", marginTop: 10, letterSpacing: "0.04em" }}>把照片轻轻放进来吧</div>
          <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", marginTop: 4 }}>支持拖拽 或 点击选择 · 可多张</div>
          <input ref={inputRef} type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => handleFiles(e.target.files)}/>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {drafts.map(d => (
            <Card key={d.id} style={{ padding: 14, display: "flex", gap: 14 }}>
              <img src={d.src} style={{ width: 110, height: 110, borderRadius: 14, objectFit: "cover", flexShrink: 0 }}/>
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
                <Field label="标题" value={d.title} onChange={(e) => update(d.id, { title: e.target.value })}/>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  <Field label="日期" type="date" value={d.date} onChange={(e) => update(d.id, { date: e.target.value })}/>
                  <Field label="地点" value={d.place} onChange={(e) => update(d.id, { place: e.target.value })} placeholder="在哪呢"/>
                </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" }}>
                    {MOOD_TAGS.map(m => <Chip key={m} tone={d.mood === m ? "solid" : "cream"} onClick={() => update(d.id, { mood: m })}>{m}</Chip>)}
                  </div>
                </div>
                <Field label="备注" multiline value={d.note} onChange={(e) => update(d.id, { note: e.target.value })} placeholder="想悄悄说的话…"/>
              </div>
              <button onClick={() => remove(d.id)} style={{ background: "transparent", border: "none", color: "#B5946D", cursor: "pointer", fontSize: 18, alignSelf: "flex-start" }}>×</button>
            </Card>
          ))}
          <input ref={inputRef} type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => handleFiles(e.target.files)}/>
          {uploadError && <div style={{ font: "500 13px 'Jiangcheng Yuan', sans-serif", color: "#E36F88", textAlign: "right" }}>{uploadError}</div>}
          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
            <Button variant="ghost" onClick={() => inputRef.current.click()} disabled={uploading}>＋ 再加几张</Button>
            <Button variant="primary" onClick={handleSave} disabled={uploading}>{uploading ? "正在收藏……" : "藏起来 ♡"}</Button>
          </div>
        </div>
      )}
    </Modal>
  );
};

const PhotoDetail = ({ photo, photos, onClose, onChange, settings }) => {
  if (!photo) return null;
  const idx = photos.findIndex(p => p.id === photo.id);
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(photo);
  useEffect(() => { setDraft(photo); setEditing(false); }, [photo?.id]);
  const nav = (delta) => {
    const next = photos[(idx + delta + photos.length) % photos.length];
    onClose(next);
  };
  const save = () => { onChange(photos.map(p => p.id === draft.id ? draft : p)); setEditing(false); };
  const togglefav = () => { const u = { ...photo, fav: !photo.fav }; onChange(photos.map(p => p.id === u.id ? u : p)); setDraft(u); };

  return (
    <Modal open={!!photo} onClose={() => onClose(null)} title={photo.title} wide>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
        <div style={{ position: "relative" }}>
          {photo.src
            ? <img src={photo.src} style={{ width: "100%", borderRadius: 18, boxShadow: "0 8px 30px rgba(184,133,46,0.24)" }}/>
            : <div style={{ aspectRatio: "1", borderRadius: 18, background: "linear-gradient(135deg,#FFF1D4,#FBE3B0)", display: "flex", alignItems: "center", justifyContent: "center" }}><Motif name={photo.tone || "sakura"} size={140}/></div>
          }
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10 }}>
            <Button variant="cream" size="sm" onClick={() => nav(-1)}>← 上一张</Button>
            <Button variant="cream" size="sm" onClick={() => nav(1)}>下一张 →</Button>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {!editing ? <>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              <Chip tone="pink">{photo.mood}</Chip>
              <Chip tone="cream">{photo.album}</Chip>
              <Chip tone={photo.fav ? "gold" : "cream"} onClick={togglefav}>{photo.fav ? "⭐ 已收藏" : "☆ 收藏"}</Chip>
            </div>
            <div style={{ font: "400 14px/1.7 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>{photo.note || "（还没有备注呀）"}</div>
            <div style={{ font: "500 12px 'Quicksand', sans-serif", color: "#8B6B43", letterSpacing: "0.06em" }}>{fmtDateCN(photo.date)}</div>
            {photo.place && <div style={{ font: "500 12px 'Quicksand', sans-serif", color: "#8B6B43" }}>📍 {photo.place}</div>}
            <Card tinted style={{ padding: 12, marginTop: 6 }}>
              <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em", textTransform: "uppercase" }}>那一天</div>
              <div style={{ font: "600 22px 'Quicksand', sans-serif", color: "#B8852E", marginTop: 4 }}>在一起的第 {daysBetween(settings.togetherDate, photo.date)} 天</div>
              <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginTop: 4 }}>距今 {daysSince(photo.date)} 天</div>
            </Card>
            <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
              <Button variant="ghost" onClick={() => setEditing(true)}>编辑</Button>
              <Button variant="secondary" onClick={() => { window.xm.store.deletePhotoFile(photo.src); onChange(photos.filter(p => p.id !== photo.id)); onClose(null); }}>删除</Button>
            </div>
          </> : <>
            <Field label="标题" value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })}/>
            <Field label="日期" type="date" value={draft.date} onChange={(e) => setDraft({ ...draft, date: e.target.value })}/>
            <Field label="地点" value={draft.place} onChange={(e) => setDraft({ ...draft, place: 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" }}>{MOOD_TAGS.map(m => <Chip key={m} tone={draft.mood === m ? "solid" : "cream"} onClick={() => setDraft({ ...draft, mood: m })}>{m}</Chip>)}</div>
            </div>
            <Field label="备注" multiline value={draft.note} onChange={(e) => setDraft({ ...draft, note: e.target.value })}/>
            <div style={{ display: "flex", gap: 8 }}>
              <Button variant="ghost" onClick={() => { setDraft(photo); setEditing(false); }}>取消</Button>
              <Button onClick={save}>保存 ♡</Button>
            </div>
          </>}
        </div>
      </div>
    </Modal>
  );
};

Object.assign(window, { AlbumPage, PhotoUploader, PhotoDetail, MOOD_TAGS });
