// Comparison wording from section 3 of docs/20261119_sns_api_research_sol.md.
const comparisonRows = [
  ["見たいこと", "Instagram", "TikTok", "YouTube", "X"],
  ["現在のフォロワー・登録者", "取れる（`followers_count`）", "取れる（`followers_count` / `follower_count`）", "条件つき（`subscriberCount`、丸めあり）", "取れる（`followers_count`）"],
  ["日次・期間の増減", "条件つき（`follows_and_unfollows`、100人）", "条件つき（`daily_new_followers` 等）", "取れる（`subscribersGained/Lost`）", "条件つき（Enterprise で投稿別 `follows/unfollows`）。アカウント日次純増は未確認"],
  ["投稿の表示・再生", "取れる（`views`）", "取れる（動画 `video_views`）", "取れる（`viewCount`、`views`、`engagedViews`）", "取れる（`impression_count`、動画 `view_count`）"],
  ["投稿のユニーク到達", "取れる（`reach`、推定）", "条件つき（`reach`）", "取れない（Studio の `Unique viewers` 相当）", "取れない"],
  ["投稿のいいね・コメント・返信", "条件つき（`likes`、`comments`、ストーリー `replies`）", "取れる（`likes`、`comments`）", "取れる（`likeCount`、`commentCount`、コメント API）", "取れる（`like_count`、`reply_count`）"],
  ["投稿の保存", "条件つき（`saved`、フィード・リール）", "取れる（`favorites`）", "条件つき（`videosAddedToPlaylists`）", "取れる（`bookmark_count`）"],
  ["投稿→プロフィール", "条件つき（`profile_visits`、フィード・ストーリー）", "条件つき（`profile_views`）", "取れない", "条件つき（`user_profile_clicks`）"],
  ["投稿→フォロー", "条件つき（`follows`、フィード・ストーリー、帰属詳細未確認）", "条件つき（`new_followers`）", "条件つき（`subscribersGained`、視聴ページ経由）", "条件つき（Enterprise `follows`）"],
  ["投稿・プロフィール経由クリック", "条件つき（`link_clicks`、`profile_activity` の `BIO_LINK_CLICKED`、アカウント `profile_links_taps`）", "条件つき（`website_clicks`、アカウント `bio_link_clicks` 等）", "条件つき（`cardClicks`、`end_screen_element_clicks`。任意の説明欄URLは未確認）", "条件つき（`url_link_clicks`、Enterprise `url_clicks`）"],
  ["総・平均視聴時間", "条件つき（リールの2指標）", "条件つき（`total_time_watched`、`average_time_watched`）", "取れる（`estimatedMinutesWatched`、`averageViewDuration`）", "条件つき（メディア organic／Enterprise `watch_time_ms`。平均の直接フィールドは未確認）"],
  ["維持率・完視聴", "条件つき（リール `reels_skip_rate`）", "条件つき（`video_view_retention`、`full_video_watched_rate`）", "条件つき（`audienceWatchRatio` 等。完視聴率とは定義が異なる）", "条件つき（動画 `playback_*_count`）"],
  ["投稿への流入元", "取れない（投稿 Insights に流入元軸なし）", "条件つき（`impression_sources`）", "条件つき（`insightTrafficSourceType/Detail`）", "取れない（投稿 v2 指標に流入元軸なし）"],
  ["年齢・性別・国・市", "条件つき（アカウント属性）", "条件つき（フォロワー属性、動画は性別・国・市）", "条件つき（年齢・性別割合、国・市別実績）", "取れない（対象 API のオーディエンス集計）"],
  ["フォロワー・視聴者の活動時間", "未確認（`online_followers` の現行仕様）", "条件つき（`audience_activity`）", "取れない（Studio の活動時間ヒートマップ）", "取れない"],
  ["サムネイル表示・CTR", "取れない", "取れない", "条件つき（Reporting `video_thumbnail_impressions`、`video_thumbnail_impressions_ctr`）", "取れない"]
];

const catalogStatuses = {
  available:'取れる', conditional:'条件つき', ui_only:'管理画面だけ',
  unavailable:'取れない', deprecated:'廃止', unverified:'未確認'
};
const catalogLevels = {account:'アカウント', post:'投稿', audience:'視聴者の属性'};

function PlatformComparison() {
  const [headers, ...rows] = comparisonRows;
  return <section className="card catalog-section">
    <SectionTitle icon="grid">4媒体の比較</SectionTitle>
    <table className="catalog-table catalog-comparison">
      <thead><tr>{headers.map(label=><th scope="col" key={label}>{label}</th>)}</tr></thead>
      <tbody>{rows.map(([topic,...cells])=><tr key={topic}>
        <th scope="row">{topic}</th>
        {cells.map((cell,i)=><td key={headers[i+1]} data-label={headers[i+1]}>
          {cell.split('`').map((part,j)=>j%2?<code key={j}>{part}</code>:part)}
        </td>)}
      </tr>)}</tbody>
    </table>
  </section>;
}

function CatalogFilters({label,value,onChange,options}) {
  return <label className="catalog-control"><span>{label}</span>
    <SelectBox label={label} value={value} onChange={onChange}>
      <option value="">すべて</option>
      {Object.entries(options).map(([id,name])=><option key={id} value={id}>{name}</option>)}
    </SelectBox>
  </label>;
}

function MetricTable({title,rows,typeNames}) {
  return <section className="card catalog-section">
    <h2 className="section-title">{title}<small>{rows.length} 項目</small></h2>
    <table className="catalog-table catalog-metrics">
      <thead><tr>{['項目・フィールド名','状態・出典','投稿の種類','内訳に使える軸','取れる期間','条件'].map(label=><th scope="col" key={label}>{label}</th>)}</tr></thead>
      <tbody>{rows.map((m,i)=><tr key={m.field+i}>
        <th scope="row">{m.label_ja}<code>{m.field}</code></th>
        <td data-label="状態・出典"><span className={'catalog-badge catalog-'+m.status}>{catalogStatuses[m.status]}</span>
          <a href={m.source_url} target="_blank" rel="noopener noreferrer" aria-label={m.label_ja+'の公式ドキュメント（新しいタブ）'}>公式ドキュメント ↗</a></td>
        <td data-label="投稿の種類">{m.post_types.map(id=>typeNames[id]).join('・') || '指定なし'}</td>
        <td data-label="内訳に使える軸">{m.breakdowns.join('、') || '指定なし'}</td>
        <td data-label="取れる期間">{m.window}</td>
        <td data-label="条件">{m.conditions}{m.disagreement && <details className="catalog-disagreement">
          <summary>調査で見解が分かれた</summary>{m.disagreement}
        </details>}</td>
      </tr>)}</tbody>
    </table>
  </section>;
}

function PlatformCatalog({platform}) {
  const [status,setStatus]=useState('');
  const [level,setLevel]=useState('');
  const [type,setType]=useState('');
  const [query,setQuery]=useState('');
  const {metrics,post_types}=platform;
  const typeNames=Object.fromEntries(post_types.map(t=>[t.id,t.label_ja]));
  // Some researched metrics reference IDs outside the platform's post_types list.
  for(const m of metrics) for(const id of m.post_types) if(!typeNames[id]) typeNames[id]=id;
  const needle=query.trim().toLowerCase();
  const shown=metrics.filter(m=>(!status || m.status===status) && (!level || m.level===level)
    && (!type || m.post_types.includes(type)) && (m.label_ja.toLowerCase().includes(needle) || m.field.toLowerCase().includes(needle)));
  const medium=media.find(m=>m.id===platform.id);
  return <>
    <section className="card catalog-overview">
      <div className="catalog-summary-title"><Mark m={medium}/><h2>{medium.name}</h2><strong>{metrics.length} 項目</strong></div>
      <dl className="catalog-counts">{Object.entries(catalogStatuses).map(([id,name])=><div key={id}>
        <dt>{name}</dt><dd>{metrics.filter(m=>m.status===id).length}</dd>
      </div>)}</dl>
      <p className="catalog-types"><b>投稿の種類</b> {post_types.map(t=>t.label_ja).join('・')}</p>
    </section>
    <div className="catalog-controls">
      <CatalogFilters label="状態" value={status} onChange={setStatus} options={catalogStatuses}/>
      <CatalogFilters label="区分" value={level} onChange={setLevel} options={catalogLevels}/>
      <CatalogFilters label="投稿の種類" value={type} onChange={setType} options={typeNames}/>
      <label className="catalog-control catalog-search"><span>項目を検索</span>
        <input type="search" value={query} placeholder="日本語名・フィールド名" onChange={e=>setQuery(e.target.value)}/>
      </label>
    </div>
    <p className="catalog-result" role="status">{metrics.length} 項目中 {shown.length} 項目を表示</p>
    {Object.entries(catalogLevels).map(([id,name])=>{
      const rows=shown.filter(m=>m.level===id);
      return rows.length>0 && <MetricTable key={id} title={name} rows={rows} typeNames={typeNames}/>;
    })}
    {!shown.length && <p className="empty-note">条件に合う項目がありません。</p>}
  </>;
}

function Catalog({platforms}) {
  const [selection,setSelection]=useState(platforms[0].id);
  const platform=platforms.find(p=>p.id===selection);
  return <>
    <div className="catalog-switch" role="group" aria-label="媒体別の一覧と比較">
      {platforms.map(p=><button className="btn" key={p.id} aria-pressed={selection===p.id} onClick={()=>setSelection(p.id)}>
        {media.find(m=>m.id===p.id).name} <small>{p.metrics.length}</small>
      </button>)}
      <button className="btn" aria-pressed={selection==='comparison'} onClick={()=>setSelection('comparison')}>4媒体の比較</button>
    </div>
    {platform?<PlatformCatalog key={platform.id} platform={platform}/>:<PlatformComparison/>}
  </>;
}
