/* global React, ReactDOM, window */
const { ARTICLES, AUTHORS } = window.cynixDataExt;
const { SharedMasthead, Breadcrumb, Colophon, findCategory } = window.cynixShared;

// 著者 slug の優先順:
//   1. window.__CYNIX_AUTHOR_SLUG__ (静的 HTML 内 inline で設定。 /authors/<slug>/index.html に置く形)
//   2. window.location.pathname の /authors/<slug> 部 (_redirects rewrite が機能している場合)
//   3. ?author= query (旧形式 fallback)
function detectAuthorSlug() {
  if (typeof window.__CYNIX_AUTHOR_SLUG__ === "string" && window.__CYNIX_AUTHOR_SLUG__) {
    return window.__CYNIX_AUTHOR_SLUG__.toLowerCase();
  }
  const path = (window.location.pathname || "").toLowerCase();
  const m = path.match(/\/authors\/([^/?#]+)/);
  if (m) return m[1];
  const qs = new URLSearchParams(window.location.search);
  return (qs.get("author") || "").toLowerCase();
}
const AUTHOR_PARAM = detectAuthorSlug();
const AUTH =
  AUTHORS.find((a) => a.slug === AUTHOR_PARAM) ||
  AUTHORS.find((a) => a.slug.startsWith(AUTHOR_PARAM)) ||
  AUTHORS.find((a) => AUTHOR_PARAM && a.name_en.toLowerCase().includes(AUTHOR_PARAM)) ||
  AUTHORS[0]; // fallback: 編集長
// HIS_ARTICLES: author / coAuthor のいずれかにこの著者がいる記事を担当扱い
const HIS_ARTICLES = ARTICLES.filter(
  (a) => a.author === AUTH.slug || a.coAuthor === AUTH.slug
);

// 動的メトリクス:
// - articles  = 担当記事の実数
// - tested    = 各記事タイトル「N社比較 / N選」の N を合算 (見つからない記事は 5 でフォールバック)
// - since     = AUTHORS.metrics.since (在籍開始は記事生成日とは別。ハードコード継続)
const HIS_TESTED = HIS_ARTICLES.reduce((sum, a) => {
  const t = (a.title || "") + " " + (a.deck || "");
  const m = t.match(/(\d+)\s*(?:社|選|本|つ|個)/);
  return sum + (m ? parseInt(m[1], 10) : 5);
}, 0);

const authorHref = (slug) => "/authors/" + slug;

const App = () => (
  <div className="mag mag-archive">
    <SharedMasthead section={`AUTHOR · ${AUTH.name_en.toUpperCase()}`} />
    <Breadcrumb items={[
      { label: "HOME", href: "cynix-jp.html" },
      { label: "AUTHORS", href: "#" },
      { label: AUTH.name_en },
    ]} />

    {/* Author cover */}
    <section className="author-cover">
      <div className="author-portrait">
        <div className="author-portrait-mark">EDITOR-IN-CHIEF</div>
        <div className="author-portrait-img" style={{ backgroundImage: `url(${AUTH.avatar})` }}></div>
        <div className="author-portrait-overlay"></div>
        <div className="author-portrait-en">{AUTH.name_en}.</div>
      </div>
      <div className="author-info">
        <div>
          <div className="author-role">{AUTH.role_en} · since {AUTH.metrics.since}</div>
          <h1 className="author-name">
            {AUTH.name_jp.split(" ")[0]}<br />
            <em style={{ fontStyle: "italic", color: "var(--vermilion)" }}>{AUTH.name_jp.split(" ")[1]}</em>。
          </h1>
        </div>
        <p className="author-bio">{AUTH.bio_long}</p>
        <p className="author-creed">「{AUTH.creed}」</p>
        <div className="author-expertise">
          {AUTH.expertise.map((e) => <span key={e}>{e}</span>)}
        </div>
        <div className="author-stats">
          <div><span className="lab">articles</span><span className="val">{HIS_ARTICLES.length}</span></div>
          <div><span className="lab">products tested</span><span className="val">{HIS_TESTED}</span></div>
          <div><span className="lab">since</span><span className="val" style={{ fontStyle: "italic", fontSize: 22 }}>{AUTH.metrics.since}</span></div>
        </div>
        <div style={{ display: "flex", gap: 12, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase" }}>
          <a href={AUTH.sns.x} style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--ink)" }}>X / TWITTER</a>
          <a href={AUTH.sns.note} style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--ink)" }}>NOTE</a>
          <a href={AUTH.sns.github} style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--ink)" }}>GITHUB</a>
        </div>
      </div>
    </section>

    {/* Article list */}
    <section className="cat-list">
      <div className="cat-list-head">
        <h3>{AUTH.name_en} の<em>記事</em>。</h3>
        <div className="cat-list-filters">
          <a href="#" className="on">最新</a>
          <a href="#">人気</a>
          <a href="#">カテゴリ別</a>
        </div>
      </div>
      <div className="cat-list-rows">
        {HIS_ARTICLES.map((a, i) => (
          <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>{a.type.toUpperCase()} · {a.readTime} MIN</span>
              <span>{a.published}</span>
            </span>
            <span className="row-arrow">→</span>
          </a>
        ))}
      </div>
    </section>

    {/* Manifesto block */}
    <section style={{ background: "var(--ink)", color: "var(--paper)", padding: 80, borderBottom: "1px solid var(--ink)", display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 64, alignItems: "center" }}>
      <div>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--cyan)", marginBottom: 24 }}>
          MANIFESTO №01 · NAOTO MIYAKE
        </div>
        <p style={{ fontFamily: "'Noto Sans JP', serif", fontWeight: 900, fontStyle: "italic", fontSize: 64, lineHeight: 1.1, letterSpacing: "-0.04em", margin: 0 }}>
          スペック表は、<br />
          <span style={{ color: "var(--vermilion)" }}>嘘をつかない。</span><br />
          ただ、全部は教えない。
        </p>
      </div>
      <div style={{ borderLeft: "1px solid var(--paper)", paddingLeft: 48 }}>
        <p style={{ fontSize: 16, lineHeight: 1.85, opacity: 0.9, marginBottom: 20 }}>
          だから編集部は、自分たちで契約して、自分たちで深夜2時にApache Bench を叩く。月額1,000円のVPSも、月額10万円の専用サーバーも、同じ条件で測る。
        </p>
        <p style={{ fontSize: 16, lineHeight: 1.85, opacity: 0.9, marginBottom: 20 }}>
          私が前職で運用していた頃、ベンダー資料を信じて選定した結果、本番環境で泣いた経験は何度もある。だから cynix.jp の記事には、必ず実測値を入れる。それが、編集長としての約束です。
        </p>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--cyan)", marginTop: 32 }}>
          ↳ 編集長 / NAOTO MIYAKE · {AUTH.metrics.since}—
        </div>
      </div>
    </section>

    {/* Other authors */}
    <section className="related">
      <div className="related-head">
        <h3>編集部の<em>もう一人</em>。</h3>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.6 }}>EDITORIAL TEAM · 02 PEOPLE</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 0 }}>
        {AUTHORS.filter((a) => a.slug !== AUTH.slug).map((a) => (
          <a key={a.slug} href={authorHref(a.slug)} className="author-related-card" style={{ display: "grid", gridTemplateColumns: "240px 1fr auto", gap: 32, padding: 32, border: "1px solid var(--ink)", textDecoration: "none", color: "var(--ink)", alignItems: "center" }}>
            <div style={{ width: 200, height: 240, backgroundImage: `url(${a.avatar})`, backgroundSize: "cover", backgroundPosition: "center top", border: "1px solid var(--ink)" }}></div>
            <div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--vermilion)", marginBottom: 8 }}>{a.role_en}</div>
              <h4 style={{ fontFamily: "'Noto Sans JP', serif", fontWeight: 900, fontSize: 48, letterSpacing: "-0.03em", margin: "0 0 12px", lineHeight: 0.95 }}>{a.name_jp}</h4>
              <p style={{ fontSize: 15, lineHeight: 1.75, margin: 0, maxWidth: 600 }}>{a.bio_long}</p>
              <div style={{ display: "flex", gap: 6, marginTop: 16, flexWrap: "wrap" }}>
                {a.expertise.map((e) => (
                  <span key={e} style={{ border: "1px solid var(--ink)", padding: "4px 10px", fontSize: 11, fontWeight: 700, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.05em" }}>{e}</span>
                ))}
              </div>
            </div>
            <div style={{ fontFamily: "'Noto Sans JP', serif", fontStyle: "italic", fontWeight: 900, fontSize: 64, color: "var(--vermilion)" }}>→</div>
          </a>
        ))}
      </div>
    </section>

    <Colophon />
  </div>
);

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