// =============================================================
// SettingsModal — nickname + anchor date (slim profile/preferences)
// AnniversariesModal — recurring milestones + one-shot countdowns (home edit)
// ImportantEventsModal — manage which stories are starred (home edit)
// =============================================================

const SettingsModal = ({ open, onClose, settings, onChange, onForgetDevice, onContact }) => {
  const [d, setD] = useState(settings);
  useEffect(() => { setD(settings); }, [open]);

  return (
    <Modal open={open} onClose={onClose} title="小屋的设置 ⚙">
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="她的昵称" value={d.nickname} onChange={(e) => setD({ ...d, nickname: e.target.value })}/>
        <Field label="正式在一起的日期（用于全局倒计时）" type="date" value={d.togetherDate} onChange={(e) => setD({ ...d, togetherDate: e.target.value })}/>
        <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", padding: "8px 12px", background: "#FBEFC2", borderRadius: 12 }}>
          纪念日和重要事件请到首页对应卡片右上角的「♡ 编辑」管理。
        </div>
        {onContact && <button
          type="button"
          onClick={onContact}
          style={{
            width: "100%", textAlign: "left", cursor: "pointer",
            border: "1px solid rgba(217,162,86,0.32)", borderRadius: 14,
            background: "#FFFDF6", color: "#8B6B43",
            padding: "11px 13px", display: "flex", alignItems: "center", gap: 9,
            font: "500 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", letterSpacing: "0.04em",
          }}
        >
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#B8852E" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.4"/><path d="m3.5 6.5 8.5 6 8.5-6"/></svg>
          联系作者 · 提建议 / 想要的新功能
        </button>}
        {onForgetDevice && <button
          type="button"
          onClick={() => {
            if (window.confirm("要让这台设备忘记小暗号吗？刷新后需要重新输入配对码。")) onForgetDevice();
          }}
          style={{
            width: "100%", textAlign: "left", cursor: "pointer",
            border: "1px dashed #D6BD9A", borderRadius: 14,
            background: "#FFFDF6", color: "#8B6B43",
            padding: "11px 13px",
            font: "500 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif",
            letterSpacing: "0.04em",
          }}
        >忘记这台设备</button>}
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>取消</Button>
          <Button onClick={() => { onChange(d); onClose(); }}>保存 ♡</Button>
        </div>
      </div>
    </Modal>
  );
};

// =============================================================
// AnniversariesModal — manage recurring milestones + countdowns
// =============================================================
const ANNIV_KIND_LABEL = { milestone: "✨ 永远", countdown: "⏱ 倒数" };

const AnniversariesModal = ({ open, onClose, settings, onChange }) => {
  const [d, setD] = useState(settings);
  useEffect(() => { setD(settings); }, [open]);

  const list = d.anniversaries || [];
  const updateAnniv = (id, patch) => setD({ ...d, anniversaries: list.map(a => a.id === id ? { ...a, ...patch } : a) });
  const addAnniv = () => setD({
    ...d,
    anniversaries: [
      ...list,
      { id: window.xm.uid(), title: "新的纪念日", date: new Date().toISOString().slice(0,10), kind: "milestone" },
    ],
  });
  const removeAnniv = (id) => setD({ ...d, anniversaries: list.filter(a => a.id !== id) });

  const today = new Date().toISOString().slice(0,10);

  return (
    <Modal open={open} onClose={onClose} title="编辑纪念日 ♡">
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="正式在一起的日期（首页实时计数器锚点）" type="date" value={d.togetherDate} onChange={(e) => setD({ ...d, togetherDate: e.target.value })}/>
        <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", padding: "8px 12px", background: "#FBEFC2", borderRadius: 12 }}>
          ✨ 永远：自动生成「整月 / 整百天 / 整年」三种里程碑，最近的会在首页倒数置顶。<br/>
          ⏱ 倒数：只对这一天倒数一次，日期过去后从首页自动消失。
        </div>
        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 6 }}>纪念日</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {list.map(a => <AnniversaryRow key={a.id} a={a} today={today} onUpdate={updateAnniv} onRemove={removeAnniv}/>)}
            <Button variant="cream" size="sm" onClick={addAnniv}>＋ 加一个纪念日</Button>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>取消</Button>
          <Button onClick={() => { onChange(d); onClose(); }}>保存 ♡</Button>
        </div>
      </div>
    </Modal>
  );
};

const AnniversaryRow = ({ a, today, onUpdate, onRemove }) => {
  const expired = a.kind === "countdown" && a.date < today;
  return (
    <Card className="xm-anniv-row" style={{ padding: 12, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", opacity: expired ? 0.7 : 1 }}>
      <input
        value={a.title}
        onChange={(e) => onUpdate(a.id, { title: e.target.value })}
        style={{ flex: "1 1 140px", minWidth: 0, fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 14, padding: "8px 12px", borderRadius: 12, border: "2px solid #FBE3B0", background: "#FFFDF6", outline: "none", color: "#4A2A1A" }}
      />
      <input
        type="date"
        value={a.date}
        onChange={(e) => onUpdate(a.id, { date: e.target.value })}
        style={{ fontFamily: "Quicksand, sans-serif", padding: "8px 12px", borderRadius: 12, border: "2px solid #FBE3B0", background: "#FFFDF6", outline: "none", color: "#4A2A1A" }}
      />
      <button
        onClick={() => onUpdate(a.id, { kind: a.kind === "milestone" ? "countdown" : "milestone" })}
        title="切换循环 / 一次性"
        style={{
          background: a.kind === "milestone" ? "#FBE3B0" : "#E6F1F8",
          border: "none", cursor: "pointer", padding: "6px 12px", borderRadius: 999,
          font: "600 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif",
          color: a.kind === "milestone" ? "#8B6B43" : "#4A6FA0",
          letterSpacing: "0.04em",
        }}
      >{ANNIV_KIND_LABEL[a.kind] || ANNIV_KIND_LABEL.milestone}</button>
      {expired && <span style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.08em" }}>· 已过去</span>}
      <button onClick={() => onRemove(a.id)} aria-label="删除" style={{ background: "transparent", border: "none", color: "#B5946D", cursor: "pointer", fontSize: 18, lineHeight: 1, padding: "4px 8px", marginLeft: "auto" }}>×</button>
    </Card>
  );
};

// =============================================================
// ImportantEventsModal — manage which stories are starred (重要事件)
// =============================================================
const { fmtDate: fmtDateUtil, daysSince: daysSinceUtil } = window.xm.util;

const ImportantEventsModal = ({ open, onClose, stories, onChange, onNav }) => {
  const [draftTitle, setDraftTitle] = useState("");
  const [draftDate, setDraftDate] = useState(new Date().toISOString().slice(0,10));
  useEffect(() => { if (!open) { setDraftTitle(""); setDraftDate(new Date().toISOString().slice(0,10)); } }, [open]);

  const starred = (stories || []).filter(s => s.isAnniversary).sort((a,b) => b.date.localeCompare(a.date));

  const unstar = (id) => onChange(stories.map(s => s.id === id ? { ...s, isAnniversary: false } : s));
  const quickAdd = () => {
    if (!draftTitle.trim()) return;
    const newStory = {
      id: window.xm.uid(),
      title: draftTitle.trim(),
      date: draftDate,
      type: "📖事件叙述",
      content: "",
      tags: [],
      isAnniversary: true,
    };
    onChange([newStory, ...(stories || [])]);
    setDraftTitle("");
    setDraftDate(new Date().toISOString().slice(0,10));
  };

  return (
    <Modal open={open} onClose={onClose} title="编辑重要事件 ♡">
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 6 }}>已标记的故事</div>
          {starred.length === 0
            ? <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#B5946D", padding: "12px 0" }}>还没有标记过任何故事</div>
            : <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {starred.map(s => (
                  <Card key={s.id} style={{ padding: "10px 12px", display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div onClick={() => onNav && onNav("stories")} style={{ font: "600 14px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", letterSpacing: "0.04em", cursor: "pointer", textDecoration: "underline", textDecorationColor: "rgba(184,133,46,0.32)", textUnderlineOffset: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.title || "（无标题）"}</div>
                      <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", marginTop: 2, letterSpacing: "0.06em" }}>{fmtDateUtil(s.date)} · 已 {daysSinceUtil(s.date)} 天</div>
                    </div>
                    <button
                      onClick={() => unstar(s.id)}
                      title="取消标记"
                      style={{ background: "transparent", border: "1px solid rgba(217,162,86,0.32)", color: "#8B6B43", cursor: "pointer", fontSize: 12, padding: "6px 10px", borderRadius: 999, font: "600 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif" }}
                    >取消 ★</button>
                  </Card>
                ))}
              </div>}
        </div>

        <div>
          <div style={{ font: "600 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", marginBottom: 6 }}>快速加一条</div>
          <Card className="xm-anniv-row" style={{ padding: 12, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
            <input
              value={draftTitle}
              onChange={(e) => setDraftTitle(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); quickAdd(); } }}
              placeholder="比如：第一次牵手"
              style={{ flex: "1 1 160px", minWidth: 0, fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 14, padding: "8px 12px", borderRadius: 12, border: "2px solid #FBE3B0", background: "#FFFDF6", outline: "none", color: "#4A2A1A" }}
            />
            <input
              type="date"
              value={draftDate}
              onChange={(e) => setDraftDate(e.target.value)}
              style={{ fontFamily: "Quicksand, sans-serif", padding: "8px 12px", borderRadius: 12, border: "2px solid #FBE3B0", background: "#FFFDF6", outline: "none", color: "#4A2A1A" }}
            />
            <Button variant="cream" size="sm" onClick={quickAdd} disabled={!draftTitle.trim()}>＋ 加一个</Button>
          </Card>
          <div style={{ font: "400 11px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#B5946D", marginTop: 6 }}>会创建一条新故事并打上 ★。点上面的标题可以跳到故事页补充内容。</div>
        </div>

        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
          <Button onClick={onClose}>完成 ♡</Button>
        </div>
      </div>
    </Modal>
  );
};

Object.assign(window, { SettingsModal, AnniversariesModal, ImportantEventsModal, AnniversaryRow });
