// single-post.jsx — 単一記事 (HBR 風 editorial layout)
// PHP 側で window.HB_POST = {
//   en, jp_label, title, content_html, date, thumbnail, summary,
//   archive_url, archive_label, related: [{id,title,date,permalink,thumbnail}],
//   cats: [{name,url}], tags: [{name,url}],
//   author: {name,avatar,bio} | null
// } を注入する前提
//
// レイアウト方針 (HBR articleモデル):
// - 記事カラム幅 720px に統一（画像も本文も同じ幅で「詰まった編集記事」の質感）
// - H1 は Mincho 系 serif で大きめ・行間広め
// - 冒頭に「この記事のポイント (Summary)」box（無ければ非表示）
// - 著者 byline は冒頭+末尾の2回表示（HBR 流）
// - sticky TOC は右レール、本文と並列

(function(){
  const { HBLayout, hbcp, fontEN, fontENSans, fontJP, fontMono, HB_BASE } = window;
  // 編集メディア向け Serif フォントスタック（タイトル・H2 用）
  const fontSerif = '"Shippori Mincho","Hiragino Mincho ProN","Yu Mincho",serif';

  function SinglePostPage() {
    const d = window.HB_POST || {};
    const {
      en='Article', jp_label='記事', title='', content_html='', date='', thumbnail='',
      summary='',
      archive_url='#', archive_label='一覧へ戻る', related=[],
      cats=[], tags=[], author=null,
    } = d;

    const articleRef = React.useRef(null);
    const [toc, setToc] = React.useState([]);
    const [shareUrl, setShareUrl] = React.useState('');

    React.useEffect(() => {
      try { setShareUrl(window.location.href); } catch(e){}
      const root = articleRef.current; if (!root) return;
      const items = [];
      root.querySelectorAll('h2, h3').forEach((h, i) => {
        if (!h.id) h.id = `hb-h-${i}`;
        items.push({ id: h.id, level: h.tagName === 'H2' ? 2 : 3, text: h.textContent });
      });
      setToc(items);
    }, [content_html]);

    return (
      <HBLayout>
        {/* ===== Article header (kicker + H1 + byline) ===== */}
        <section style={{padding:'48px 32px 32px', background:hbcp.white}}>
          <div style={{maxWidth:720, margin:'0 auto'}}>
            {/* Breadcrumb */}
            <nav style={{fontFamily:fontMono, fontSize:11, letterSpacing:'.04em', color:hbcp.inkLight, marginBottom:24, display:'flex', flexWrap:'wrap', gap:6}}>
              <a href={HB_BASE} style={{color:hbcp.inkLight, textDecoration:'none'}}>TOP</a>
              <span>/</span>
              <a href={archive_url} style={{color:hbcp.inkLight, textDecoration:'none'}}>{jp_label}</a>
              {cats[0] && (<>
                <span>/</span>
                <a href={cats[0].url||'#'} style={{color:hbcp.inkLight, textDecoration:'none'}}>{cats[0].name}</a>
              </>)}
            </nav>

            {/* Topic kicker（HBR 流：H1 上に小さく分野表示） */}
            {cats[0] && (
              <a href={cats[0].url || '#'} style={{display:'inline-block', fontFamily:fontENSans, fontSize:11, letterSpacing:'.32em', fontWeight:700, color:hbcp.blue, textDecoration:'none', marginBottom:18, textTransform:'uppercase'}}>
                {cats[0].name}
              </a>
            )}

            {/* Serif 大型 H1 */}
            <h1 className="hb-article-title" style={{fontFamily:fontSerif, fontWeight:700, fontSize:'clamp(28px, 3.4vw, 40px)', lineHeight:1.4, letterSpacing:'-.005em', margin:'0 0 24px', color:hbcp.ink}}>{title}</h1>

            {/* Byline (date + author) */}
            <div style={{display:'flex', alignItems:'center', gap:14, paddingBottom:18, borderBottom:`1px solid ${hbcp.line}`, flexWrap:'wrap'}}>
              {author && author.avatar && (
                <img src={author.avatar} alt="" style={{width:32, height:32, borderRadius:'50%', display:'block', flex:'0 0 auto'}}/>
              )}
              <div style={{display:'flex', alignItems:'center', gap:10, fontSize:13, color:hbcp.inkSoft, flexWrap:'wrap'}}>
                {author && <span style={{fontFamily:fontJP, fontWeight:600, color:hbcp.ink}}>{author.name}</span>}
                {author && <span style={{color:hbcp.inkLight}}>·</span>}
                <span style={{fontFamily:fontMono, color:hbcp.inkLight}}>{date}</span>
              </div>
            </div>
          </div>

          {/* Hero image — 本文カラムと同じ 720px 幅で控えめに */}
          {thumbnail && (
            <div style={{maxWidth:720, margin:'32px auto 0', aspectRatio:'16/9', overflow:'hidden', background:hbcp.paper}}>
              <img src={thumbnail} alt="" style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
            </div>
          )}
        </section>

        {/* ===== Article body (with right-rail TOC on PC) ===== */}
        <section style={{padding:'40px 32px 64px', background:hbcp.white}}>
          <div className="hb-article-row" style={{maxWidth:1024, margin:'0 auto', display:'grid', gridTemplateColumns:toc.length>0 ? 'minmax(0,720px) 220px' : 'minmax(0,720px)', gap:64, alignItems:'flex-start', justifyContent:'center'}}>
            <div style={{minWidth:0}}>
              {/* Summary box (この記事のポイント) — HBR 流の TL;DR 配置 */}
              {summary && summary.trim() && (
                <div className="hb-article-summary" style={{padding:'22px 26px', background:hbcp.blueGhost, borderLeft:`3px solid ${hbcp.blue}`, marginBottom:36}}>
                  <div style={{fontFamily:fontENSans, fontSize:10, letterSpacing:'.32em', color:hbcp.blue, fontWeight:700, marginBottom:10}}>● SUMMARY</div>
                  <div style={{fontFamily:fontJP, fontSize:14.5, lineHeight:1.95, color:hbcp.ink, fontWeight:500}} dangerouslySetInnerHTML={{__html: summary}}/>
                </div>
              )}

              <article ref={articleRef} className="hb-article" style={{fontSize:16, lineHeight:1.95, color:hbcp.ink}}
                       dangerouslySetInnerHTML={{ __html: content_html }} />

              {/* Author bio（記事末尾。HBR 流の "About the author" box） */}
              {author && author.bio && (
                <div style={{marginTop:64, padding:'28px 28px', background:hbcp.paper, border:`1px solid ${hbcp.line}`, display:'grid', gridTemplateColumns:'80px 1fr', gap:20, alignItems:'flex-start'}}>
                  {author.avatar && <img src={author.avatar} alt="" style={{width:80, height:80, borderRadius:'50%', display:'block'}}/>}
                  <div>
                    <div style={{fontFamily:fontENSans, fontSize:9.5, letterSpacing:'.32em', color:hbcp.blue, fontWeight:700, marginBottom:8}}>● ABOUT THE AUTHOR</div>
                    <h4 style={{fontFamily:fontJP, fontWeight:700, fontSize:18, margin:'0 0 8px'}}>{author.name}</h4>
                    <p style={{fontSize:13.5, lineHeight:1.85, color:hbcp.inkSoft, margin:0}}>{author.bio}</p>
                  </div>
                </div>
              )}
            </div>

            {toc.length > 0 && (
              <aside style={{position:'sticky', top:96, alignSelf:'flex-start', borderLeft:`1px solid ${hbcp.line}`, paddingLeft:18, fontSize:12.5, lineHeight:1.7}}>
                <div style={{fontFamily:fontENSans, fontSize:10, letterSpacing:'.32em', color:hbcp.blue, marginBottom:14, fontWeight:700}}>● CONTENTS</div>
                <ol style={{listStyle:'none', padding:0, margin:0}}>
                  {toc.map((it, i) => (
                    <li key={it.id} style={{padding:'4px 0', paddingLeft: it.level===3 ? 14 : 0}}>
                      <a href={`#${it.id}`} onClick={(e)=>{ e.preventDefault(); const el = document.getElementById(it.id); if (el) el.scrollIntoView({behavior:'smooth', block:'start'}); }} style={{color: it.level===2 ? hbcp.ink : hbcp.inkSoft, textDecoration:'none'}}>
                        {it.level===2 && <span style={{fontFamily:fontEN, fontStyle:'italic', color:hbcp.blue, marginRight:6}}>{String(i+1).padStart(2,'0')}</span>}
                        {it.text}
                      </a>
                    </li>
                  ))}
                </ol>
              </aside>
            )}
          </div>

          <style>{`
            /* HBR 風の「詰まった記事」読み心地 — 行間ゆったり、タイポ階層強め、画像は本文幅 */
            .hb-article p { margin: 0 0 1.4em; }
            .hb-article > p:first-of-type { font-size:18px; line-height:1.95; color:${hbcp.ink}; font-weight:500; }
            .hb-article h2 {
              font-family: ${fontSerif}; font-weight:700; font-size:26px; line-height:1.45;
              margin:56px 0 18px; padding-top:28px; border-top:1px solid ${hbcp.line};
              letter-spacing:-.005em; scroll-margin-top: 96px; color:${hbcp.ink};
            }
            .hb-article h3 {
              font-family: ${fontJP}; font-weight:700; font-size:18px; line-height:1.5;
              margin:32px 0 12px; scroll-margin-top: 96px; color:${hbcp.ink};
              padding-left:14px; border-left:3px solid ${hbcp.blue};
            }
            .hb-article h4 { font-family:${fontJP}; font-weight:700; font-size:16px; margin:24px 0 10px; }
            .hb-article a { color:${hbcp.blue}; text-decoration: underline; text-underline-offset: .2em; text-decoration-thickness: 1px; }
            .hb-article a:hover { text-decoration-thickness: 2px; }
            .hb-article ul, .hb-article ol { padding-left: 1.4em; margin: 0 0 1.4em; }
            .hb-article li { margin: .4em 0; }

            /* Pull-quote 大型引用（章中の呼吸点） */
            .hb-article blockquote {
              margin: 36px 0; padding: 20px 0 20px 28px;
              border-left: 4px solid ${hbcp.blue}; background: transparent;
              font-family: ${fontSerif}; font-style: italic;
              font-size: 22px; line-height: 1.7; color: ${hbcp.ink}; font-weight: 500;
            }
            .hb-article blockquote p:last-child { margin-bottom: 0; }
            .hb-article blockquote cite { display:block; margin-top:12px; font-family:${fontENSans}; font-style:normal; font-size:12px; letter-spacing:.16em; color:${hbcp.inkLight}; }

            /* 画像は本文と同じ幅 / 余白も控えめに（記事として詰まる） */
            .hb-article img { max-width: 100%; height: auto; margin: 28px 0; }
            .hb-article figure { margin: 28px 0; }
            .hb-article figure img { margin: 0; }
            .hb-article figcaption { font-family:${fontMono}; font-size:11px; color:${hbcp.inkLight}; margin-top:8px; line-height:1.6; }

            /* コードブロック */
            .hb-article pre { background: ${hbcp.ink}; color: #fff; padding: 18px 22px; overflow-x: auto; font-family: ${fontMono}; font-size: 13px; line-height: 1.6; margin: 24px 0; }
            .hb-article code { font-family: ${fontMono}; font-size: 13.5px; background: ${hbcp.paper}; padding: 2px 6px; border-radius: 2px; }
            .hb-article pre code { background: transparent; padding: 0; }

            /* 区切り線 */
            .hb-article hr { border: 0; border-top: 1px solid ${hbcp.line}; margin: 48px 0; }

            /* テーブル（数字の見せ方） */
            .hb-article table { border-collapse: collapse; width: 100%; margin: 28px 0; font-size: 14px; }
            .hb-article th, .hb-article td { border: 1px solid ${hbcp.line}; padding: 10px 14px; text-align: left; }
            .hb-article th { background: ${hbcp.paper}; font-weight: 700; }

            /* 既存ハテナ ブログCSS との互換 — highlight-box / case-study / section-content は触らないで活かす */
            .hb-article .highlight-box { background: ${hbcp.blueGhost}; border-left: 3px solid ${hbcp.blue}; padding: 18px 22px; margin: 24px 0; }
            .hb-article .highlight-title { font-family:${fontJP}; font-weight:700; font-size:14px; color:${hbcp.blue}; margin-bottom:8px; }
            .hb-article .case-study { background: ${hbcp.paper}; border-left: 3px solid ${hbcp.blue}; padding: 18px 22px; margin: 18px 0; border-radius: 2px; }
            .hb-article .case-study h4 { color: ${hbcp.blue}; margin-top:0; }
            .hb-article .section-content { margin: 0 0 1.4em; }
            .hb-article .section-title { font-family:${fontSerif}; font-weight:700; font-size:24px; }

            @media (max-width: 880px) { .hb-article-row { grid-template-columns: 1fr !important; } }

            /* ===== The Economist 風 モバイル組版（≤640px） =====
               日本語編集記事として読み心地を絞り込む。
               欧文 Economist の数値感（17px / 1.5）を CJK 換算で 15px / 1.85 に置換。
               左右ガターは variant-d-loader 側で一括 20px → 本文と画像が同じ視覚幅になる。 */
            @media (max-width: 640px) {
              /* 記事タイトル — clamp 最小 28px は CJK では大きいので 24px へ */
              .hb-article-title { font-size: 24px !important; line-height: 1.35 !important; letter-spacing: -.01em !important; margin: 0 0 18px !important; }

              /* Body — 16/1.95 → 15/1.85 にスケールダウン */
              .hb-article { font-size: 15px !important; line-height: 1.85 !important; }
              .hb-article p { margin: 0 0 1.15em !important; }
              .hb-article > p:first-of-type { font-size: 16px !important; line-height: 1.85 !important; font-weight: 500 !important; }

              /* H2/H3/H4 階層をモバイル比で圧縮 */
              .hb-article h2 {
                font-size: 21px !important; line-height: 1.4 !important;
                margin: 36px 0 12px !important; padding-top: 20px !important;
              }
              .hb-article h3 {
                font-size: 15.5px !important; line-height: 1.5 !important;
                margin: 24px 0 8px !important;
                padding-left: 10px !important; border-left-width: 2px !important;
              }
              .hb-article h4 { font-size: 14.5px !important; margin: 20px 0 8px !important; }

              /* Blockquote — 装飾を控えめに */
              .hb-article blockquote {
                margin: 24px 0 !important; padding: 12px 0 12px 16px !important;
                font-size: 17px !important; line-height: 1.7 !important;
                border-left-width: 3px !important;
              }

              /* リスト — インデントを CJK 向けに詰める */
              .hb-article ul, .hb-article ol { padding-left: 1.2em !important; margin: 0 0 1.15em !important; }
              .hb-article li { margin: .25em 0 !important; }

              /* 画像・キャプション — 縦余白を圧縮 */
              .hb-article img, .hb-article figure { margin: 20px 0 !important; }
              .hb-article figcaption { font-size: 10.5px !important; }

              /* Code blocks */
              .hb-article pre { font-size: 12px !important; padding: 12px 14px !important; margin: 18px 0 !important; }
              .hb-article code { font-size: 12.5px !important; }

              /* テーブル */
              .hb-article table { font-size: 13px !important; margin: 20px 0 !important; }
              .hb-article th, .hb-article td { padding: 7px 9px !important; }

              /* 装飾ブロック（ハテナ ブログ既存 CSS 互換） */
              .hb-article .highlight-box, .hb-article .case-study { padding: 14px 16px !important; margin: 18px 0 !important; }
              .hb-article .highlight-title { font-size: 13px !important; }
              .hb-article .section-title { font-size: 19px !important; }

              /* 区切り線 */
              .hb-article hr { margin: 32px 0 !important; }

              /* SUMMARY box（この記事のポイント） */
              .hb-article-summary { padding: 16px 18px !important; margin-bottom: 26px !important; }
              .hb-article-summary > div:last-child { font-size: 13.5px !important; line-height: 1.85 !important; }
            }
          `}</style>
        </section>

        {/* ===== Tags + Share ===== */}
        <section style={{padding:'24px 32px 56px', background:hbcp.white, borderBottom:`1px solid ${hbcp.line}`}}>
          <div style={{maxWidth:720, margin:'0 auto', display:'flex', flexWrap:'wrap', gap:24, alignItems:'flex-end', justifyContent:'space-between'}}>
            {tags.length > 0 ? (
              <div>
                <div style={{fontFamily:fontENSans, fontSize:10, letterSpacing:'.32em', color:hbcp.inkLight, marginBottom:10}}>TOPICS</div>
                <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
                  {tags.map(t => (
                    <a key={t.name} href={t.url || '#'} style={{padding:'6px 12px', background:hbcp.paper, color:hbcp.ink, fontFamily:fontJP, fontSize:12, fontWeight:500, textDecoration:'none', border:`1px solid ${hbcp.line}`}}>#{t.name}</a>
                  ))}
                </div>
              </div>
            ) : <div/>}

            <div>
              <div style={{fontFamily:fontENSans, fontSize:10, letterSpacing:'.32em', color:hbcp.inkLight, marginBottom:10, textAlign:'right'}}>SHARE</div>
              <div style={{display:'flex', gap:8}}>
                <a href={`https://x.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(title)}`} target="_blank" rel="noopener" aria-label="X" style={{width:36, height:36, border:`1px solid ${hbcp.line}`, display:'grid', placeItems:'center', textDecoration:'none', color:hbcp.ink}}>
                  <span style={{fontFamily:fontENSans, fontSize:13, fontWeight:700}}>𝕏</span>
                </a>
                <a href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`} target="_blank" rel="noopener" aria-label="Facebook" style={{width:36, height:36, border:`1px solid ${hbcp.line}`, display:'grid', placeItems:'center', textDecoration:'none', color:hbcp.ink}}>
                  <span style={{fontFamily:fontENSans, fontSize:13, fontWeight:700}}>f</span>
                </a>
                <button onClick={()=>{ navigator.clipboard?.writeText(shareUrl); }}
                  aria-label="Copy URL"
                  style={{width:36, height:36, border:`1px solid ${hbcp.line}`, background:'transparent', display:'grid', placeItems:'center', cursor:'pointer'}}>
                  <span style={{fontFamily:fontMono, fontSize:11, color:hbcp.ink}}>⧉</span>
                </button>
              </div>
            </div>
          </div>
        </section>

        {/* ===== End CTA ===== */}
        <section style={{padding:'72px 32px', background:hbcp.blue, color:'#fff'}}>
          <div style={{maxWidth:1080, margin:'0 auto', display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:48, alignItems:'flex-end'}}>
            <div>
              <div style={{fontFamily:fontENSans, fontSize:10, letterSpacing:'.32em', opacity:.8, marginBottom:14}}>● CONTACT</div>
              <h3 style={{fontFamily:fontJP, fontWeight:800, fontSize:'clamp(22px, 2.6vw, 30px)', lineHeight:1.45, margin:'0 0 14px'}}>
                記事の内容について、もっと詳しく聞いてみる。
              </h3>
              <p style={{fontSize:14, lineHeight:1.9, opacity:.9, margin:0, maxWidth:520}}>
                kintone・会計・AI・編集の現場の話を、30分・無料で具体的に伺います。
              </p>
            </div>
            <div style={{display:'grid', gap:12}}>
              <a href={`${HB_BASE}/contact`} style={{padding:'16px 24px', background:'#fff', color:hbcp.blue, textDecoration:'none', fontFamily:fontJP, fontSize:14, fontWeight:700, display:'flex', justifyContent:'space-between'}}>
                <span>無料相談を予約する</span><span style={{fontFamily:fontEN, fontStyle:'italic'}}>→</span>
              </a>
              <a href={`${HB_BASE}/document-request`} style={{padding:'16px 24px', background:'transparent', color:'#fff', border:'1px solid rgba(255,255,255,.6)', textDecoration:'none', fontFamily:fontJP, fontSize:14, fontWeight:600, display:'flex', justifyContent:'space-between'}}>
                <span>サービス資料を請求する</span><span style={{fontFamily:fontEN, fontStyle:'italic'}}>↗</span>
              </a>
            </div>
          </div>
        </section>

        {/* ===== Related ===== */}
        {related.length > 0 && (
          <section style={{padding:'72px 32px 96px', background:hbcp.paper}}>
            <div style={{maxWidth:1280, margin:'0 auto'}}>
              <div className="hb-section-head">
                <span className="hb-section-head-en">Related</span>
                <span className="hb-section-head-jp">関連記事</span>
              </div>
              <div style={{display:'grid', gridTemplateColumns:`repeat(${Math.min(related.length, 3)}, 1fr)`, gap:24}}>
                {related.map(r => (
                  <a key={r.id} href={r.permalink} style={{display:'flex', flexDirection:'column', gap:12, background:'#fff', textDecoration:'none', color:hbcp.ink, border:`1px solid ${hbcp.line}`}}>
                    {r.thumbnail && (
                      <div style={{aspectRatio:'16/9', overflow:'hidden', background:hbcp.paper}}>
                        <img src={r.thumbnail} alt="" style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
                      </div>
                    )}
                    <div style={{padding:r.thumbnail?'12px 18px 18px':'18px'}}>
                      <div style={{fontFamily:fontMono, fontSize:11, color:hbcp.inkLight, marginBottom:8}}>{r.date}</div>
                      <h3 style={{fontFamily:fontJP, fontWeight:700, fontSize:14.5, lineHeight:1.55, margin:0}}>{r.title}</h3>
                    </div>
                  </a>
                ))}
              </div>
            </div>
          </section>
        )}
      </HBLayout>
    );
  }

  Object.assign(window, { SinglePostPage });
})();
