/* global React, window */
const { CATEGORIES_EXT, AUTHORS, ARTICLES } = window.cynixDataExt;
const { SharedMasthead, Breadcrumb, Colophon, RelatedArticles, ArticleVisual, findAuthor, findCategory } = window.cynixShared;

// Read ?dept= or ?dept name from query, default 'server'
const QS = new URLSearchParams(window.location.search);
const DEPT_ID = QS.get("dept") || "server";
const CAT = CATEGORIES_EXT.find((c) => c.id === DEPT_ID) || CATEGORIES_EXT[0];
const DEPT_INDEX = CATEGORIES_EXT.findIndex((c) => c.id === CAT.id);
const CAT_ARTICLES = ARTICLES.filter((a) => a.category === CAT.id);
const ALL_LIST = CAT_ARTICLES.length ? CAT_ARTICLES : ARTICLES;

const PILLAR_GRADS = [
  ["#1A2E80", "#0066FF", "#00D4FF"],
  ["#0066FF", "#4FCBA9"],
  ["#FFB800", "#FF6B2B"],
];
const PILLAR_LABELS = ["FEATURE №01", "TUTORIAL", "GUIDE"];

// PILLAR_CARDS are derived from the live ARTICLES dataset filtered by this
// category. The first three entries (priority order) become the pillars.
const PILLAR_CARDS = CAT_ARTICLES.slice(0, 3).map((a, i) => ({
  slug: a.slug,
  lead: i === 0,
  title: a.title,
  deck: a.deck,
  cat: PILLAR_LABELS[i] || "ARTICLE",
  page: "p." + a.pageNum,
  read: a.readTime + " min",
  author: a.author,
  grad: PILLAR_GRADS[i] || ["#0066FF", "#00D4FF"],
  n: String(i + 1).padStart(2, "0"),
  img: a.cover,
  href: "/" + a.category + (a.subcategory ? "/" + a.subcategory : "") + "/" + a.slug + "/",
}));

const PillarVis = ({ grad, n, lead, img, title }) => (
  <div className="pillar-img-svg" style={{ position: "relative", overflow: "hidden", background: `linear-gradient(135deg, ${grad.join(", ")})` }}>
    {img && (
      <img
        src={img}
        alt={title || ""}
        loading="lazy"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 0 }}
      />
    )}
    <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice" style={{ width: "100%", height: "100%", position: "relative", zIndex: 1, mixBlendMode: "multiply", opacity: 0.55 }}>
      <ellipse cx="200" cy="240" rx="280" ry="100" fill="white" opacity="0.15" />
      <path d="M 60 200 Q 140 200 165 150 L 195 90 Q 200 80 205 90 L 235 150 Q 260 200 340 200 Z" fill="white" opacity="0.18" />
      <path d="M -10 130 Q 100 100 200 135 T 410 120" stroke="white" strokeOpacity="0.5" strokeWidth="1.2" fill="none" />
      <path d="M -10 170 Q 80 190 200 165 T 410 180" stroke="#00D4FF" strokeOpacity="0.6" strokeWidth="1" fill="none" strokeDasharray="2 4" />
      <text x={lead ? 360 : 360} y={lead ? 80 : 70} fontFamily='"Noto Sans JP", serif' fontStyle="italic" fontWeight="900" fontSize={lead ? 110 : 80} fill="white" opacity="0.22" textAnchor="end">{n}</text>
    </svg>
  </div>
);

const App = () => {
  return (
    <div className="mag mag-category">
      <SharedMasthead section={`DEPARTMENT · ${CAT.en.toUpperCase()}`} />
      <Breadcrumb items={[
        { label: "HOME", href: "cynix-jp.html" },
        { label: CAT.en.toUpperCase() },
      ]} />

      {/* Cover */}
      <section className="cat-cover">
        <div className="cat-cover-text">
          <span className="cat-mark">DEPARTMENT №{String(DEPT_INDEX + 1).padStart(2, "0")} · pp.012—055 · {CAT.count} ARTICLES INDEXED</span>
          <h1 className="cat-h">
            {CAT.title}、<br />
            <em>その実測値。</em>
            <span className="en">{CAT.en} · DEPT.{String(DEPT_INDEX + 1).padStart(2, "0")}</span>
          </h1>
          <p className="cat-deck">{CAT.deck}</p>
          <div className="cat-bar">
            <div><span className="lab">indexed</span><span className="val">{CAT.count}</span></div>
            <div><span className="lab">target</span><span className="val">{CAT.target}</span></div>
            <div><span className="lab">tested</span><span className="val">42</span></div>
            <div><span className="lab">subcat</span><span className="val">{CAT.subcategories.length}</span></div>
            <div><span className="lab">editor</span><span className="val" style={{ fontStyle: "italic" }}>NAOTO</span></div>
          </div>
        </div>
        <div className="cat-cover-vis">
          <img src="hero-server.png" alt="" loading="lazy" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 0 }} />
          <div className="cat-cover-vis-glow" style={{ mixBlendMode: "multiply", opacity: 0.55 }}></div>
          <div className="cat-cover-deco" style={{ top: -40, right: -60, zIndex: 3 }}>速</div>
          <div className="cat-cover-stamp">
            CONTINUOUS<br /><span className="big">80</span>days<br />benchmark
          </div>
          <svg viewBox="0 0 600 480" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 2 }}>
            <path d="M 60 460 Q 180 460 240 320 L 320 100 Q 335 75 350 100 L 430 320 Q 490 460 580 460 Z" fill="#F4EFE3" opacity="0.18" />
            <path d="M -10 320 Q 180 280 360 310 T 610 290" stroke="#00D4FF" strokeOpacity="0.7" strokeWidth="1.5" fill="none" />
            <path d="M -10 360 Q 200 340 400 355 T 610 350" stroke="#FFF200" strokeOpacity="0.5" strokeWidth="1" fill="none" strokeDasharray="2 6" />
            <circle cx="460" cy="140" r="48" fill="#E63535" opacity="0.95" />
            <line x1="0" y1="380" x2="600" y2="380" stroke="#00D4FF" strokeOpacity="0.4" strokeWidth="1" strokeDasharray="4 8" />
          </svg>
          <div className="cat-cover-pull">
            <q>夜間2時、応答0.4秒以内。それが基準。</q>
            <div className="cat-cover-pull-attr">— EDITOR-IN-CHIEF NAOTO MIYAKE</div>
          </div>
        </div>
      </section>

      {/* Subcategories */}
      <div className="subcat-strip">
        {CAT.subcategories.map((s, i) => (
          <a key={s.id} className="subcat-cell" href={`/category-server.html?dept=${CAT.id}&sub=${s.id}`}>
            <span className="subcat-num">№ {String(i + 1).padStart(2, "0")} / {String(CAT.subcategories.length).padStart(2, "0")}</span>
            <h4>{s.title}</h4>
            <p>{s.deck}</p>
            <span className="ct">{s.count || 5} ARTICLES →</span>
          </a>
        ))}
      </div>

      {/* Cross-department nav */}
      <nav style={{ display: "flex", borderTop: "1px solid var(--ink)", borderBottom: "2px solid var(--ink)", background: "var(--paper)" }}>
        {CATEGORIES_EXT.map((c) => (
          <a key={c.id} href={`/${c.id === "domain" ? "domain-ssl" : c.id === "ai" ? "ai-tools" : c.id === "rsv" ? "reservation" : c.id}`} style={{
            flex: 1, padding: "16px 12px", textDecoration: "none", color: c.id === CAT.id ? "var(--paper)" : "var(--ink)",
            background: c.id === CAT.id ? "var(--ink)" : "transparent",
            borderRight: "1px solid var(--ink)",
            fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase",
            display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start"
          }}>
            <span style={{ opacity: 0.6, fontSize: 9 }}>DEPT.{String(CATEGORIES_EXT.indexOf(c) + 1).padStart(2, "0")}</span>
            <span style={{ fontWeight: 700 }}>{c.en}</span>
          </a>
        ))}
      </nav>

      {/* Pillar */}
      <section className="pillar">
        <div className="pillar-head">
          <h2 className="pillar-h">編集部の<br /><em>本命</em>3本。</h2>
          <div className="pillar-mark">FEATURED · pp.012—030<br />UPDATED 2026/04/25<br />NAOTO</div>
        </div>
        <div className="pillar-grid">
          {PILLAR_CARDS.map((p) => (
            <a key={p.slug} className={`pillar-card${p.lead ? " lead" : ""}`} href={p.href}>
              <PillarVis grad={p.grad} n={p.n} lead={p.lead} img={p.img} title={p.title} />
              <div className="pillar-meta">
                <span className="cat-tag">{p.cat}</span>
                <span className="pg">{p.page}</span>
              </div>
              <h3 className="pillar-title">{p.title}</h3>
              <p className="pillar-deck">{p.deck}</p>
              <div className="pillar-foot">
                <span>By {findAuthor(p.author).name_jp}</span>
                <span>{p.read}</span>
              </div>
            </a>
          ))}
        </div>
      </section>

      {/* List */}
      <section className="cat-list">
        <div className="cat-list-head">
          <h3>すべての<em>記事</em>。</h3>
          <div className="cat-list-filters">
            <a href="#" className="on">最新</a>
            <a href="#">人気</a>
            <a href="#">編集部選定</a>
            <a href="#">A→Z</a>
          </div>
        </div>
        <div className="cat-list-rows">
          {ALL_LIST.slice(0, 6).map((a, i) => {
            const auth = findAuthor(a.author);
            return (
              <a key={a.slug} className="cat-list-row" href={a.slug === "vps-night-bench-2026" ? "/server/vps/vps-best/" : "#"}>
                <span className="row-page">{String(i + 1).padStart(3, "0")}</span>
                <span className="row-cat">{findCategory(a.category).en}</span>
                <span className="row-title">{a.title}</span>
                <span className="row-meta">
                  <span>By {auth.name_jp} · {a.readTime || 10} MIN</span>
                  <span>{a.published}</span>
                </span>
                <span className="row-arrow">→</span>
              </a>
            );
          })}
        </div>
      </section>

      {/* Tag cloud */}
      <section className="tagcloud">
        <h3>関連<em>タグ</em>。</h3>
        <div className="tagcloud-list">
          {window.cynixDataExt.TAGS_EXT.filter((t) => !t.parent || t.parent === "server" || ["実機ベンチ", "セルフバック", "副業"].includes(t.label)).map((t) => (
            <a key={t.slug} href="#">#{t.label} <span className="ct">{t.count}</span></a>
          ))}
        </div>
      </section>

      {/* Newsletter */}
      <section className="cat-news">
        <div>
          <h3>毎週金曜、<br /><em>{CAT.title}</em>の本音を。</h3>
          <p style={{ marginTop: 16 }}>編集部が、その週に検証したプロダクトの実測値とサポート応答時間を、生のまま配信。</p>
        </div>
        <form className="cat-news-form" onSubmit={(e) => { e.preventDefault(); const email = (new FormData(e.target).get('email') || '').toString().trim(); if (!email || !email.includes('@')) { alert('メールアドレスを入力してください。'); return; } const s = encodeURIComponent('[cynix.jp] Newsletter Subscribe'); const b = encodeURIComponent('cynix.jp ニュースレター購読のお申し込み Email: ' + email); window.location.href = 'mailto:cynix@jpsm.ne.jp?subject=' + s + '&body=' + b; }}>
          <input type="email" name="email" placeholder="your@email.com" />
          <button type="submit">SUBSCRIBE</button>
        </form>
      </section>

      <Colophon />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
