/* global React, window */
const { SharedMasthead, Breadcrumb, Colophon } = window.cynixShared;
const { ARTICLES, AUTHORS, CATEGORIES_EXT } = window.cynixDataExt;
const { useState, useEffect, useMemo } = React;

const KEY = "cynix.bookmarks.v1";
const PRESET = ["vps-2026-comparison", "ssl-cert-guide", "saas-burnout", "ai-prompt-engineering", "ec-shopify-vs-base"];

const findAuth = (id) => AUTHORS.find(a => a.slug === id) || AUTHORS[0];
const findCat = (id) => CATEGORIES_EXT.find(c => c.id === id);

const loadBookmarks = () => {
  try {
    const raw = localStorage.getItem(KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) { /* noop */ }
  // seed with preset
  const seed = PRESET.filter(slug => ARTICLES.find(a => a.slug === slug))
    .map((slug, i) => ({ slug, savedAt: Date.now() - i * 86400000 * 3, folder: i < 2 ? "あとで読む" : i < 4 ? "業務調査" : "保存" }));
  localStorage.setItem(KEY, JSON.stringify(seed));
  return seed;
};

const fmtDate = (ts) => {
  const d = new Date(ts);
  const now = Date.now();
  const diff = (now - ts) / 86400000;
  if (diff < 1) return "今日";
  if (diff < 2) return "昨日";
  if (diff < 7) return `${Math.floor(diff)}日前`;
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};

const App = () => {
  const [bms, setBms] = useState(loadBookmarks);
  const [folder, setFolder] = useState("ALL");
  const [sort, setSort] = useState("recent");

  useEffect(() => {
    localStorage.setItem(KEY, JSON.stringify(bms));
  }, [bms]);

  const folders = useMemo(() => {
    const fs = new Set(["ALL"]);
    bms.forEach(b => fs.add(b.folder || "保存"));
    return Array.from(fs);
  }, [bms]);

  const items = useMemo(() => {
    let list = bms.map(b => ({ ...b, art: ARTICLES.find(a => a.slug === b.slug) })).filter(x => x.art);
    if (folder !== "ALL") list = list.filter(x => x.folder === folder);
    if (sort === "recent") list.sort((a, b) => b.savedAt - a.savedAt);
    else if (sort === "title") list.sort((a, b) => a.art.title.localeCompare(b.art.title, "ja"));
    else if (sort === "category") list.sort((a, b) => (a.art.category || "").localeCompare(b.art.category || ""));
    return list;
  }, [bms, folder, sort]);

  const remove = (slug) => setBms(bms.filter(b => b.slug !== slug));
  const moveTo = (slug, f) => setBms(bms.map(b => b.slug === slug ? { ...b, folder: f } : b));
  const clear = () => { if (confirm("すべてのブックマークを削除しますか？")) setBms([]); };

  return (
    <>
      <SharedMasthead section="MY BOOKMARKS" />
      <main className="mod-shell">
        <Breadcrumb items={[{ label: "TOP", href: "index.html" }, { label: "ブックマーク" }]} />

        <section style={{ borderTop: "4px double var(--ink)", borderBottom: "4px double var(--ink)", padding: "44px 0 52px", margin: "16px 0 40px", display: "grid", gridTemplateColumns: "1fr auto", alignItems: "end", gap: 32 }}>
          <div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.3em", color: "var(--vermilion)", marginBottom: 12 }}>READER LIBRARY</div>
            <h1 style={{ fontFamily: "'Crimson Pro', serif", fontSize: 80, fontWeight: 500, lineHeight: 0.95, margin: 0, letterSpacing: "-0.03em" }}>ブックマーク</h1>
            <div style={{ fontFamily: "'Crimson Pro', serif", fontSize: 22, fontStyle: "italic", marginTop: 4, opacity: 0.7 }}>My Saved Articles</div>
            <p style={{ maxWidth: 540, margin: "16px 0 0", fontSize: 13, lineHeight: 1.85, opacity: 0.85 }}>
              気になった記事を <span style={{ background: "var(--ink)", color: "var(--paper)", padding: "1px 6px", fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.1em" }}>★ SAVE</span> ボタンで保存できます。データはブラウザにのみ保存され、サーバーには送信されません。
            </p>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontFamily: "'Crimson Pro', serif", fontSize: 96, fontWeight: 600, lineHeight: 1, color: "var(--vermilion)" }}>{String(bms.length).padStart(2, "0")}</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.2em", marginTop: 4 }}>SAVED ITEMS</div>
          </div>
        </section>

        {/* Toolbar */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "2px solid var(--ink)", borderBottom: "1px solid var(--ink)", padding: "12px 0", marginBottom: 24 }}>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.2em", opacity: 0.6, marginRight: 4 }}>FOLDER:</span>
            {folders.map(f => (
              <button key={f} onClick={() => setFolder(f)} style={{
                padding: "5px 12px",
                border: "1px solid var(--ink)",
                background: folder === f ? "var(--ink)" : "var(--paper)",
                color: folder === f ? "var(--paper)" : "var(--ink)",
                fontFamily: f === "ALL" ? "'JetBrains Mono', monospace" : "inherit",
                fontSize: 11,
                cursor: "pointer",
                letterSpacing: f === "ALL" ? "0.15em" : "0",
              }}>{f}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.2em", opacity: 0.6 }}>SORT:</span>
            <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ border: "1px solid var(--ink)", padding: "4px 8px", background: "var(--paper)", fontSize: 12 }}>
              <option value="recent">保存日 新しい順</option>
              <option value="title">タイトル順</option>
              <option value="category">カテゴリ順</option>
            </select>
            <button onClick={clear} style={{ border: "1px solid var(--ink)", background: "transparent", padding: "4px 12px", fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.15em", cursor: "pointer" }}>CLEAR ALL</button>
          </div>
        </div>

        {/* List */}
        {items.length === 0 ? (
          <div style={{ textAlign: "center", padding: "100px 0", border: "2px dashed var(--ink)", opacity: 0.7 }}>
            <div style={{ fontFamily: "'Crimson Pro', serif", fontSize: 36, fontStyle: "italic", marginBottom: 8 }}>Empty Shelf</div>
            <p style={{ fontSize: 13 }}>このフォルダにはまだ何も保存されていません。<br />記事ページの <b style={{ color: "var(--vermilion)" }}>★ SAVE</b> ボタンから追加してください。</p>
          </div>
        ) : (
          <div style={{ display: "grid", gap: 0, borderTop: "1px solid var(--ink)" }}>
            {items.map((item, idx) => {
              const a = item.art;
              const auth = findAuth(a.author);
              const cat = findCat(a.category);
              return (
                <article key={item.slug} style={{ display: "grid", gridTemplateColumns: "60px 1fr 200px 80px", borderBottom: "1px solid var(--ink)", padding: "20px 0", gap: 24, alignItems: "start" }}>
                  <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: "var(--vermilion)", paddingTop: 4 }}>
                    {String(idx + 1).padStart(2, "0")}
                    <div style={{ marginTop: 4, fontSize: 9, color: "var(--ink)", opacity: 0.6, letterSpacing: "0.1em" }}>{fmtDate(item.savedAt)}</div>
                  </div>
                  <div>
                    <div style={{ display: "flex", gap: 8, marginBottom: 6, alignItems: "center" }}>
                      <span style={{ background: cat?.color || "var(--ink)", color: "var(--paper)", padding: "2px 8px", fontSize: 10, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.1em" }}>{cat?.label_jp || a.category}</span>
                      <span style={{ fontSize: 11, opacity: 0.7 }}>{a.deck}</span>
                    </div>
                    <a href={`/server/vps/vps-best/?slug=${a.slug}`} style={{ color: "var(--ink)" }}>
                      <h3 style={{ fontFamily: "'Crimson Pro', serif", fontSize: 26, fontWeight: 500, lineHeight: 1.25, margin: "0 0 8px" }}>{a.title}</h3>
                    </a>
                    <div style={{ fontSize: 12, opacity: 0.75, lineHeight: 1.7 }}>
                      <span style={{ color: "var(--vermilion)" }}>{auth.name_jp}</span> · {auth.role_jp} · {(a.tags || []).slice(0, 3).map(t => `#${t}`).join(" ")}
                    </div>
                  </div>
                  <div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.18em", opacity: 0.6, marginBottom: 4 }}>FOLDER</div>
                    <select value={item.folder} onChange={(e) => moveTo(item.slug, e.target.value)} style={{ width: "100%", border: "1px solid var(--ink)", padding: "4px 8px", background: "var(--paper)", fontSize: 12 }}>
                      <option>あとで読む</option>
                      <option>業務調査</option>
                      <option>保存</option>
                      <option>引用素材</option>
                    </select>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <button onClick={() => remove(item.slug)} title="削除" style={{ border: "1px solid var(--ink)", background: "var(--paper)", padding: "6px 10px", fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.15em", cursor: "pointer" }}>REMOVE</button>
                  </div>
                </article>
              );
            })}
          </div>
        )}

        {/* Privacy note */}
        <div style={{ background: "var(--cream)", border: "2px solid var(--ink)", padding: "20px 28px", marginTop: 32, fontSize: 12, lineHeight: 1.85, display: "grid", gridTemplateColumns: "auto 1fr", gap: 18, alignItems: "center" }}>
          <div style={{ fontFamily: "'Crimson Pro', serif", fontSize: 48, fontStyle: "italic", color: "var(--vermilion)", lineHeight: 1 }}>P</div>
          <div>
            <b style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.18em", display: "block", marginBottom: 4 }}>PRIVACY — ローカル保存</b>
            ブックマークは <code style={{ background: "var(--paper)", padding: "1px 6px", fontFamily: "'JetBrains Mono', monospace", border: "1px solid var(--ink)" }}>localStorage</code> に保存され、サーバーには送信されません。ブラウザ・端末を変えると引き継がれない代わりに、編集部・第三者からは見えない設計です。
          </div>
        </div>

        <Colophon />
      </main>
    </>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
