HTMLの基礎

HTMLってなに?

  • Webページの骨組みを作る言語(見出し・段落・画像・リンクなどの構造)。
  • 見た目はCSS、動きはJSが担当。HTMLは“意味と構造”。

まずは雛形(コピペOK)

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>はじめてのHTML</title>
  <meta name="description" content="このページの説明文" />
</head>
<body>
  <h1>こんにちは!</h1>
  <p>これは最小構成のHTML5ページです。</p>
</body>
</html>

よく使う要素(超基本)

  • 見出し:<h1>~<h6>(ページに基本はh1は1つ
  • 段落:<p>
  • リンク:<a href="https://example.com">リンク</a>
  • 画像:<img src="img.png" alt="画像の説明">alt必須
  • リスト:<ul><li>…</li></ul> / <ol>…</ol>
  • 強調:<strong>(重要) / <em>(強調)
  • 区切り:<br>(改行は最小限)、<hr>(区切り線)
  • まとまり:<div>(汎用ブロック)、<span>(汎用インライン)

セマンティック要素(構造をわかりやすく)

  • header(ヘッダー)
  • nav(ナビ)
  • main(主内容は1ページ1つ
  • section(章)
  • article(単体で完結する記事)
  • aside(補足)
  • footer(フッター)

属性のキホン

  • id(一意な識別子)/class(グループ化)
  • href(リンク先)/src(画像・スクリプト元)
  • alt(画像代替文)/title(補足ヒント)
  • target="_blank"rel="noopener noreferrer"とセットで

フォーム最小例

<form action="/search" method="get">
  <label for="q">検索:</label>
  <input id="q" name="q" type="search" required>
  <button type="submit">送信</button>
</form>

テーブル最小例(表)

<table>
  <thead><tr><th>商品</th><th>価格</th></tr></thead>
  <tbody>
    <tr><td>りんご</td><td>120</td></tr>
    <tr><td>みかん</td><td>100</td></tr>
  </tbody>
</table>

CSS / JS の読み込み

<link rel="stylesheet" href="styles.css">
<script src="app.js" defer></script>
  • deferはHTML解析後に実行(推奨)。

ちょっとだけ“実践的”なサンプル

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>ミニサイト</title>
  <style>
    body { font-family: system-ui, sans-serif; line-height: 1.7; margin: 0; }
    header, footer { padding: 16px; background: #f5f5f5; }
    nav a { margin-right: 12px; }
    main { max-width: 920px; margin: 24px auto; padding: 0 16px; }
    img { max-width: 100%; height: auto; }
    .card { border: 1px solid #ddd; border-radius: 8px; padding: 16px; }
  </style>
</head>
<body>
  <header>
    <h1>ミニサイト</h1>
    <nav>
      <a href="#about">概要</a>
      <a href="#gallery">ギャラリー</a>
      <a href="#contact">お問い合わせ</a>
    </nav>
  </header>

  <main id="content">
    <section id="about">
      <h2>概要</h2>
      <p>これはHTMLの基本で作ったミニページです。</p>
    </section>

    <section id="gallery">
      <h2>ギャラリー</h2>
      <div class="card">
        <img src="sample.jpg" alt="サンプル画像">
        <p>レスポンシブに画像が縮みます。</p>
      </div>
      <ul>
        <li>箇条書き1</li>
        <li>箇条書き2</li>
      </ul>
    </section>

    <section id="contact">
      <h2>お問い合わせ</h2>
      <form>
        <label for="name">お名前</label><br>
        <input id="name" name="name" required><br><br>
        <label for="msg">メッセージ</label><br>
        <textarea id="msg" name="msg" rows="4"></textarea><br><br>
        <button type="submit">送信</button>
      </form>
    </section>
  </main>

  <footer>
    <small>&copy; 2025 MiniSite</small>
  </footer>

  <script>
    // ごく簡単なJS:ナビをクリックしたらスムーズスクロール
    document.querySelectorAll('nav a').forEach(a => {
      a.addEventListener('click', e => {
        const id = a.getAttribute('href');
        if (id.startsWith('#')) {
          e.preventDefault();
          document.querySelector(id)?.scrollIntoView({ behavior: 'smooth' });
        }
      });
    });
  </script>
</body>
</html>

初心者がつまずきやすいポイント

  • 文字化け→<meta charset="utf-8">を必ず入れる。
  • スマホで拡大縮小が変→<meta name="viewport" …>を入れる。
  • 画像が大きすぎる→CSSでimg { max-width: 100%; height: auto; }
  • 見出し乱用→h1はページの主題に1回、階層は順序を守る。
  • altなし→スクリーンリーダー/SEO的にマイナス。必ず書く。

もっと深掘り(フォームのバリデーション、SEO、アクセシビリティ、Flex/Gridレイアウト、コンポーネント化など)もまとめられます。どこから強化したい?(例:フォームをしっかり、レイアウトを学ぶ、CSS設計、JS連携 など)

QuestFoundry

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Quest Foundry | 世界観からクエスト自動設計</title>
  <meta name="description" content="世界観のキーワードからNPC・アイテム・場所・クエストを一括生成。JSON/CSVエクスポート、依存関係、難易度バランス、シード固定対応。" />
  <!-- Tailwind CDN (Node不要) -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: { sans: ["Noto Sans JP", "ui-sans-serif", "system-ui"] },
          colors: { brand: { 50: '#eef2ff', 100:'#e0e7ff', 200:'#c7d2fe', 300:'#a5b4fc', 400:'#818cf8', 500:'#6366f1', 600:'#4f46e5', 700:'#4338ca', 800:'#3730a3', 900:'#312e81'} }
        }
      }
    };
  </script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700;900&display=swap" rel="stylesheet">
  <style>
    html, body { height: 100%; }
    .glass { backdrop-filter: blur(10px); background: rgba(255,255,255,0.7); }
    .prose pre { white-space: pre-wrap; word-break: break-word; }
    .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
    .card { @apply rounded-2xl shadow-lg p-5 bg-white; }
      .prose h1{font-size:1.5rem;line-height:1.3;margin:0 0 .6rem;font-weight:800}
    .prose h2{font-size:1.2rem;line-height:1.35;margin:1.2rem 0 .4rem;font-weight:700;border-left:4px solid #6366f1;padding-left:.6rem}
    .prose h3{font-size:1rem;line-height:1.4;margin:1rem 0 .3rem;font-weight:700}
    .prose ul{list-style:disc;padding-left:1.25rem;margin:.4rem 0 .8rem}
    .prose li{margin:.2rem 0}
    .badge{display:inline-block;font-size:.72rem;line-height:1;background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe;border-radius:.5rem;padding:.15rem .45rem;margin-right:.25rem}
    details.quest{border:1px solid #e5e7eb;border-radius:.75rem;padding:.6rem .8rem;margin:.5rem 0;background:#fff}
    details.quest > summary{cursor:pointer;list-style:none}
    details.quest > summary::-webkit-details-marker{display:none}
    .kv{display:inline-grid;grid-template-columns:auto auto;gap:.2rem .6rem;align-items:center}
  </style>
</head>
<body class="min-h-screen bg-gradient-to-br from-brand-50 to-white text-slate-800">
  <header class="sticky top-0 z-40 border-b bg-white/80 backdrop-blur">
    <div class="mx-auto max-w-7xl px-4 py-3 flex items-center gap-4">
      <div class="text-2xl font-black tracking-tight"><span class="text-brand-700">Quest</span> Foundry</div>
      <div class="text-xs text-slate-500">世界観→NPC/アイテム/場所/クエストを自動生成(JSON/CSV出力可)</div>
      <div class="ml-auto flex items-center gap-2">
        <button id="btnSave" class="px-3 py-2 text-sm rounded-lg border hover:bg-slate-50">保存</button>
        <button id="btnLoad" class="px-3 py-2 text-sm rounded-lg border hover:bg-slate-50">読込</button>
        <button id="btnPrint" class="px-3 py-2 text-sm rounded-lg border hover:bg-slate-50">印刷/PDF</button>
      </div>
    </div>
  </header>

  <main class="mx-auto max-w-7xl px-4 py-6 grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- 左:設定フォーム -->
    <section class="lg:col-span-1 card">
      <h2 class="text-lg font-bold mb-4">ワールド設定</h2>
      <form id="worldForm" class="space-y-4">
        <div>
          <label class="block text-sm font-medium">世界名</label>
          <input id="worldName" type="text" class="w-full mt-1 rounded-lg border px-3 py-2" placeholder="例:アトラティア" />
        </div>
        <div>
          <label class="block text-sm font-medium">テーマ・キーワード(読点・スペース区切り)</label>
          <input id="themes" type="text" class="w-full mt-1 rounded-lg border px-3 py-2" placeholder="例:古代遺跡 砂漠 精霊 冒険者ギルド" />
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium">難易度</label>
            <select id="difficulty" class="w-full mt-1 rounded-lg border px-3 py-2">
              <option value="easy">Easy</option>
              <option value="normal" selected>Normal</option>
              <option value="hard">Hard</option>
              <option value="epic">Epic</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium">クエスト数</label>
            <input id="questCount" type="number" min="1" max="30" value="8" class="w-full mt-1 rounded-lg border px-3 py-2" />
          </div>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium">シード(同じ結果を再現)</label>
            <input id="seed" type="text" class="w-full mt-1 rounded-lg border px-3 py-2" placeholder="未入力なら自動" />
          </div>
          <div class="flex items-end gap-2">
            <input id="lockSeed" type="checkbox" class="h-5 w-5" />
            <label for="lockSeed" class="text-sm">シード固定(再生成でも変化しない)</label>
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium">トーン</label>
          <select id="tone" class="w-full mt-1 rounded-lg border px-3 py-2">
            <option value="classic" selected>古典ファンタジー</option>
            <option value="dark">ダーク</option>
            <option value="steampunk">スチームパンク</option>
            <option value="myth">神話/叙事詩</option>
            <option value="sci">サイファンタジー</option>
          </select>
        </div>
        <div class="flex flex-wrap gap-2 pt-2">
          <button id="btnGenerate" type="button" class="px-4 py-2 rounded-xl bg-brand-600 text-white hover:bg-brand-700">生成</button>
          <button id="btnRegenerate" type="button" class="px-4 py-2 rounded-xl bg-slate-800 text-white hover:bg-slate-900">再生成(同条件)</button>
          <button id="btnShuffleSeed" type="button" class="px-4 py-2 rounded-xl border">シード再抽選</button>
        </div>
      </form>
      <p class="text-xs text-slate-500 mt-4">※外部API不使用。テンプレート×確率モデルでローカル生成。ブラウザ上で完結。</p>
    </section>

    <!-- 中央:結果(テキスト) -->
    <section class="lg:col-span-2 card">
      <div class="flex items-center gap-2 mb-4">
        <h2 class="text-lg font-bold">生成結果</h2>
        <span id="meta" class="ml-auto text-xs text-slate-500"></span>
      </div>
      <div class="flex flex-wrap gap-2 mb-4">
        <button id="btnCopyText" class="px-3 py-2 rounded-lg border">テキストをコピー</button>
        <button id="btnDownloadJSON" class="px-3 py-2 rounded-lg border">JSONダウンロード</button>
        <button id="btnExportCSV" class="px-3 py-2 rounded-lg border">CSV書き出し</button>
        <button id="btnToggleJson" class="px-3 py-2 rounded-lg border">JSON表示切替</button>
      </div>
      <div id="outText" class="prose max-w-none text-sm leading-6"></div>
      <details id="jsonBlock" class="mt-4 hidden">
        <summary class="cursor-pointer select-none text-sm text-slate-600">JSON表示</summary>
        <pre id="outJSON" class="mono text-xs bg-slate-50 p-3 rounded-lg overflow-x-auto"></pre>
      </details>
    </section>

    <!-- 下:プレビュー(カードレイアウト) -->
    <section class="lg:col-span-3 card">
      <h2 class="text-lg font-bold mb-4">カードビュー</h2>
      <div class="grid md:grid-cols-3 gap-4" id="cards"></div>
    </section>
  </main>

  <footer class="py-8 text-center text-xs text-slate-500">
    &copy; 2025 Quest Foundry — Local-first Fantasy Content Generator
  </footer>

  <script>
    /* =========================
     *  乱数とユーティリティ
     * ========================= */
    function cyrb128(str){ let h1=1779033703,h2=3144134277,h3=1013904242,h4=2773480762; for(let i=0;i<str.length;i++){ let k=str.charCodeAt(i); h1=h2^(Math.imul(h1^k,597399067)); h2=h3^(Math.imul(h2^k,2869860233)); h3=h4^(Math.imul(h3^k,951274213)); h4=h1^(Math.imul(h4^k,2716044179)); } h1=Math.imul(h3^(h1>>>18),597399067); h2=Math.imul(h4^(h2>>>22),2869860233); h3=Math.imul(h1^(h3>>>17),951274213); h4=Math.imul(h2^(h4>>>19),2716044179); let r=(h1^h2^h3^h4)>>>0; return r.toString(36); }
    function mulberry32(a){ return function(){ let t=a+=0x6D2B79F5; t=Math.imul(t^(t>>>15), t|1); t^=t+Math.imul(t^(t>>>7), t|61); return ((t^(t>>>14))>>>0)/4294967296; } }
    function rngFromSeed(seed){ let n=0; for(const ch of seed) n=(n*31 + ch.charCodeAt(0))>>>0; return mulberry32(n||1); }
    function choice(r, arr){ return arr[Math.floor(r()*arr.length)] }
    function pickN(r, arr, n){ const a=[...arr]; const out=[]; for(let i=0;i<n && a.length;i++){ out.push(a.splice(Math.floor(r()*a.length),1)[0]); } return out; }
    function cap(s){ return s.charAt(0).toUpperCase()+s.slice(1) }
    function id(prefix, i){ return `${prefix}-${String(i).padStart(3,'0')}` }

    function syllableName(r, tone){
      const syll = {
        classic:["an","ar","bel","ca","da","el","fa","gal","har","is","jor","kel","lir","mor","nel","or","pa","qua","rhi","sa","tor","ur","val","wen","xel","yor","zel"],
        dark:["mor","noir","gloam","umb","dol","grav","nek","var","zul","vex","drei","thar","khar","wyrm"],
        steampunk:["gear","steam","bolt","cog","brass","tink","pneu","copper","fuse","riv","spindle"],
        myth:["aeg","od","ish","ra","zeph","io","sol","lun","tyr","fre","eir","hel"],
        sci:["neo","ion","quant","cyber","astra","plasma","proto","omega","nova","phase","flux"]
      };
      const pool = (syll[tone]||[]).concat(syll.classic);
      const len = 2 + Math.floor(r()*2);
      let s=""; for(let i=0;i<len;i++) s+= choice(r,pool);
      return cap(s);
    }

    /* =========================
     *  テンプレ/語彙
     * ========================= */
    const LEX = {
      roles: ["ギルドマスター","考古学者","巡回騎士","密偵","占星術師","錬金術師","旅の商人","巫女","司書","鍛冶師","船乗り","薬師","狩人","吟遊詩人","修道士"],
      traits: ["勇敢","狡猾","博識","短気","誠実","猜疑心が強い","陽気","冷静","計算高い","臆病","義理堅い","野心家"],
      factions: ["碧星同盟","砂冠商会","螺旋教団","古図書騎士団","白霧旅団","錆鉄工房","風詠み集落","赤砂盗賊団"],
      biomes: ["砂漠","湿原","黒森","高地","沿岸","雪原","火山地帯","古代都市跡"],
      itemTypes: ["剣","短剣","槍","杖","弓","護符","指輪","書","設計図","薬","鉱石","布","レンズ","コイル"],
      rarities: ["Common","Uncommon","Rare","Epic","Legendary"],
      verbs: ["救出せよ","護衛せよ","探索せよ","奪還せよ","調査せよ","討伐せよ","修復せよ","封印せよ","交渉せよ","護送せよ","潜入せよ"],
      twists: ["依頼主は真犯人","実は時間制限あり","二重スパイがいる","偽物が混じっている","古き呪いが再発","天候異常が発生","儀式の日が前倒し"],
      rewardsExtra: ["評判+10","ギルドランク昇格","隠し店舗の解放","旅人の加護","快速移動の解放"]
    };

    const DIFF_MULT = { easy: 0.8, normal: 1.0, hard: 1.3, epic: 1.7 };

    /* =========================
     *  生成器
     * ========================= */
    function genFactions(r, themes){
      const count = Math.min(5, 2 + Math.floor(r()*4));
      return Array.from({length:count}, (_,i)=>({ id: id('F',i+1), name: `${choice(r,LEX.factions)}`, goal: `${choice(r,["遺物の独占","古文書の解読","交易路の掌握","禁術の復活","辺境防衛"])}`, vibe: choice(r,["協調的","中立","敵対的"]) }));
    }

    function genLocations(r, themes){
      const count = Math.min(8, 4 + Math.floor(r()*5));
      return Array.from({length:count}, (_,i)=>({ id: id('L',i+1), name: `${choice(r,LEX.biomes)}の${syllableName(r,'classic')}`, feature: choice(r,["崩れた門","封じ石","光る碑文","隠し水路","浮遊足場","古代機構"]) }));
    }

    function genNPCs(r, tone, factions){
      const count = Math.min(12, 6 + Math.floor(r()*6));
      return Array.from({length:count}, (_,i)=>{
        const fac = choice(r, factions);
        return {
          id: id('N',i+1),
          name: syllableName(r,tone),
          role: choice(r, LEX.roles),
          trait: choice(r, LEX.traits),
          faction: fac?.id || null
        }
      });
    }

    function genItems(r, tone){
      const count = Math.min(18, 8 + Math.floor(r()*10));
      return Array.from({length:count}, (_,i)=>{
        const t = choice(r, LEX.itemTypes);
        const rare = choice(r, LEX.rarities);
        return {
          id: id('I',i+1),
          name: `${syllableName(r,tone)}の${t}`,
          type: t,
          rarity: rare,
          value: Math.floor((10+ r()*90) * (1 + 0.3*LEX.rarities.indexOf(rare)))
        }
      });
    }

    function genQuests(r, tone, count, npcs, locations, items, difficulty){
      const q = [];
      const scale = DIFF_MULT[difficulty] || 1.0;
      for(let i=0;i<count;i++){
        const giver = choice(r, npcs);
        const loc = choice(r, locations);
        const verb = choice(r, LEX.verbs);
        const keyItem = choice(r, items);
        const level = Math.max(1, Math.round((i+1)*scale + r()*3));
        const objectives = [
          `${loc.name}で手掛かりを見つける`,
          `${giver.name}(${giver.role})に報告する`,
          `${keyItem.name}を入手する`
        ];
        // 依存関係:稀に前のクエストを前提にする
        let dependsOn = null;
        if(i>0 && r()<0.4){ dependsOn = q[Math.floor(r()*i)].id; }
        // ツイストは低確率で
        const twist = r()<0.35 ? choice(r, LEX.twists) : null;
        const rewardGold = Math.floor((100+ r()*200) * scale * (1 + i*0.05));
        const rewardItems = pickN(r, items, r()<0.6?1:2).map(o=>o.id);
        q.push({
          id: id('Q',i+1),
          title: `${verb}:${loc.name}`,
          level,
          giver: giver.id,
          location: loc.id,
          objectives,
          requires: dependsOn,
          reward: { gold: rewardGold, items: rewardItems, extra: r()<0.25? choice(r, LEX.rewardsExtra): null },
          twist
        });
      }
      return q;
    }

    function assembleWorld(input){
      const seed = input.seed || `${Date.now().toString(36)}-${cyrb128(input.worldName + (input.themes||''))}`;
      const r = rngFromSeed(seed);
      const tone = input.tone || 'classic';
      const factions = genFactions(r, input.themes);
      const locations = genLocations(r, input.themes);
      const npcs = genNPCs(r, tone, factions);
      const items = genItems(r, tone);
      const quests = genQuests(r, tone, input.questCount, npcs, locations, items, input.difficulty);
      return { meta: { seed, createdAt: new Date().toISOString(), worldName: input.worldName||syllableName(r,tone), themes: input.themes, difficulty: input.difficulty, tone }, factions, locations, npcs, items, quests };
    }

    /* =========================
     *  出力レンダリング
     * ========================= */
    function renderText(world){
      const idmap = (arr)=> Object.fromEntries(arr.map(a=>[a.id,a]));
      const NPC = idmap(world.npcs);
      const LOC = idmap(world.locations);
      const ITM = idmap(world.items);

      const lines = [];
      lines.push(`# 世界:${world.meta.worldName}`);
      lines.push(`- テーマ:${world.meta.themes||'—'} / トーン:${world.meta.tone} / 難易度:${world.meta.difficulty}`);
      lines.push(`- 生成日時:${new Date(world.meta.createdAt).toLocaleString()}`);
      lines.push(`- シード:${world.meta.seed}`);
      lines.push(`\n## 勢力(${world.factions.length})`);
      world.factions.forEach(f=>{ lines.push(`- [${f.id}] ${f.name}|目的:${f.goal}|態度:${f.vibe}`) });
      lines.push(`\n## 場所(${world.locations.length})`);
      world.locations.forEach(l=>{ lines.push(`- [${l.id}] ${l.name}|特徴:${l.feature}`) });
      lines.push(`\n## NPC(${world.npcs.length})`);
      world.npcs.forEach(n=>{ lines.push(`- [${n.id}] ${n.name}(${n.role}/${n.trait}) 所属:${n.faction||'なし'}`) });
      lines.push(`\n## アイテム(${world.items.length})`);
      world.items.forEach(i=>{ lines.push(`- [${i.id}] ${i.name}|種類:${i.type}|希少度:${i.rarity}|価値:${i.value}`) });
      lines.push(`\n## クエスト(${world.quests.length})`);
      world.quests.forEach(q=>{
        const giver = NPC[q.giver]?.name || q.giver;
        const loc = LOC[q.location]?.name || q.location;
        const req = q.requires? `(前提:${q.requires})` : '';
        lines.push(`\n### [${q.id}] ${q.title} Lv.${q.level} ${req}`);
        lines.push(`- 依頼主:${giver}`);
        lines.push(`- 場所:${loc}`);
        lines.push(`- 目的:`);
        q.objectives.forEach(o=>lines.push(`  - ${o}`));
        const rewardItems = q.reward.items.map(id=> ITM[id]?.name || id).join('、');
        lines.push(`- 報酬:${q.reward.gold}G / アイテム:${rewardItems}${q.reward.extra? ' / '+q.reward.extra:''}`);
        if(q.twist) lines.push(`- ツイスト:${q.twist}`);
      });
      return lines.join('\n');
    }

    function renderHTML(world){
      const idmap = (arr)=> Object.fromEntries(arr.map(a=>[a.id,a]));
      const NPC = idmap(world.npcs);
      const LOC = idmap(world.locations);
      const ITM = idmap(world.items);

      const head = `
        <h1>世界:${world.meta.worldName}</h1>
        <div class="kv text-sm text-slate-600 gap-x-2">
          <span class="badge">トーン:${world.meta.tone}</span>
          <span class="badge">難易度:${world.meta.difficulty}</span>
          <span class="badge">クエスト:${world.quests.length}</span>
          <span class="badge">シード:${world.meta.seed}</span>
        </div>
        <p class="mt-2 text-sm text-slate-600">テーマ:${world.meta.themes||'—'} / 生成日時:${new Date(world.meta.createdAt).toLocaleString()}</p>
      `;

      const factions = `
        <h2>勢力(${world.factions.length})</h2>
        <ul>
          ${world.factions.map(f=>`<li><code>[${f.id}]</code> ${f.name}|目的:${f.goal}|態度:${f.vibe}</li>`).join('')}
        </ul>
      `;

      const locs = `
        <h2>場所(${world.locations.length})</h2>
        <ul>
          ${world.locations.map(l=>`<li><code>[${l.id}]</code> ${l.name}|特徴:${l.feature}</li>`).join('')}
        </ul>
      `;

      const npcs = `
        <h2>NPC(${world.npcs.length})</h2>
        <ul>
          ${world.npcs.map(n=>`<li><code>[${n.id}]</code> ${n.name}(${n.role}/${n.trait}) 所属:${n.faction||'なし'}</li>`).join('')}
        </ul>
      `;

      const items = `
        <h2>アイテム(${world.items.length})</h2>
        <ul>
          ${world.items.map(i=>`<li><code>[${i.id}]</code> ${i.name}|種類:${i.type}|希少度:${i.rarity}|価値:${i.value}</li>`).join('')}
        </ul>
      `;

      const quests = `
        <h2>クエスト(${world.quests.length})</h2>
        ${world.quests.map(q=>{
          const giver = NPC[q.giver]?.name || q.giver;
          const loc = LOC[q.location]?.name || q.location;
          const req = q.requires? `(前提:${q.requires})` : '';
          const rewardItems = q.reward.items.map(id=> ITM[id]?.name || id).join('、');
          return `
            <details class="quest">
              <summary><strong><code>[${q.id}]</code> ${q.title}</strong> <span class="text-sm text-slate-600">Lv.${q.level} ${req}</span></summary>
              <div class="mt-2 text-sm">
                <div>依頼主:${giver}</div>
                <div>場所:${loc}</div>
                <div class="mt-1">目的:</div>
                <ul>
                  ${q.objectives.map(o=>`<li>${o}</li>`).join('')}
                </ul>
                <div class="mt-1">報酬:${q.reward.gold}G / アイテム:${rewardItems}${q.reward.extra? ' / '+q.reward.extra:''}</div>
                ${q.twist? `<div class="mt-1 text-rose-700">ツイスト:${q.twist}</div>`:''}
              </div>
            </details>`;
        }).join('')}
      `;

      return [head, factions, locs, npcs, items, quests].join('');
    }

    function renderCards(world){
      const $cards = document.getElementById('cards');
      $cards.innerHTML = '';
      const make = (title, body)=>{
        const el = document.createElement('div');
        el.className = 'rounded-2xl border p-4 bg-white';
        el.innerHTML = `<div class="text-sm font-bold mb-2">${title}</div><div class="text-xs text-slate-700 whitespace-pre-wrap">${body}</div>`;
        $cards.appendChild(el);
      };
      make('ワールド', `名前:${world.meta.worldName}\n難易度:${world.meta.difficulty}\nトーン:${world.meta.tone}\nシード:${world.meta.seed}`);
      make('勢力', world.factions.map(f=>`[${f.id}] ${f.name}/目的:${f.goal}`).join('\n'));
      make('場所', world.locations.map(l=>`[${l.id}] ${l.name}/${l.feature}`).join('\n'));
      make('NPC', world.npcs.slice(0,12).map(n=>`[${n.id}] ${n.name}/${n.role}`).join('\n'));
      make('アイテム', world.items.slice(0,15).map(i=>`[${i.id}] ${i.name}/${i.rarity}`).join('\n'));
      make('クエスト', world.quests.map(q=>`[${q.id}] ${q.title} Lv.${q.level}${q.requires? '(前提:'+q.requires+')':''}`).join('\n'));
    }

    /* =========================
     *  CSV/JSON/コピー/保存
     * ========================= */
    function toCSV(rows){
      return rows.map(r=> r.map(v=>`"${String(v).replaceAll('"','""')}"`).join(',')).join('\n');
    }
    function exportCSVs(world){
      const npcRows = [["id","name","role","trait","faction"]].concat(world.npcs.map(n=>[n.id,n.name,n.role,n.trait,n.faction||'']));
      const itemRows = [["id","name","type","rarity","value"]].concat(world.items.map(i=>[i.id,i.name,i.type,i.rarity,i.value]));
      const questRows = [["id","title","level","giver","location","requires","objectives","reward_gold","reward_items","twist"]].concat(
        world.quests.map(q=>[
          q.id, q.title, q.level, q.giver, q.location, q.requires||'', q.objectives.join(' / '), q.reward.gold, q.reward.items.join('|'), q.twist||''
        ])
      );
      const files = [
        {name:`${world.meta.worldName}_NPC.csv`, data: toCSV(npcRows)},
        {name:`${world.meta.worldName}_Items.csv`, data: toCSV(itemRows)},
        {name:`${world.meta.worldName}_Quests.csv`, data: toCSV(questRows)}
      ];
      files.forEach(f=>{
        const blob = new Blob(["\ufeff"+f.data], {type:'text/csv'});
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = f.name; a.click(); URL.revokeObjectURL(a.href);
      });
    }
    function downloadJSON(world){
      const blob = new Blob([JSON.stringify(world, null, 2)], {type:'application/json'});
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = `${world.meta.worldName}_world.json`; a.click(); URL.revokeObjectURL(a.href);
    }
    function copyText(text){
      navigator.clipboard.writeText(text).then(()=>{
        toast('テキストをコピーしました');
      });
    }
    function saveLocal(world){ localStorage.setItem('quest_foundry_last', JSON.stringify(world)); toast('保存しました'); }
    function loadLocal(){ const s=localStorage.getItem('quest_foundry_last'); if(!s){ toast('保存データなし'); return null; } try{ return JSON.parse(s);}catch(e){ toast('読込失敗'); return null; } }

    /* =========================
     *  UI
     * ========================= */
    function toast(msg){
      const t = document.createElement('div');
      t.className = 'fixed bottom-4 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-sm px-4 py-2 rounded-xl shadow-lg';
      t.textContent = msg; document.body.appendChild(t);
      setTimeout(()=>{ t.classList.add('opacity-0'); t.style.transition='opacity .6s'; }, 1600);
      setTimeout(()=> t.remove(), 2300);
    }

    let lastInput = null;
    let lastWorld = null;

    function currentInput(){
      const worldName = document.getElementById('worldName').value.trim();
      const themes = document.getElementById('themes').value.trim();
      const difficulty = document.getElementById('difficulty').value;
      const questCount = Math.max(1, Math.min(30, parseInt(document.getElementById('questCount').value || '8')));
      const seed = document.getElementById('seed').value.trim();
      const tone = document.getElementById('tone').value;
      return { worldName, themes, difficulty, questCount, seed, tone };
    }

    function applyWorld(world){
      lastWorld = world;
      document.getElementById('meta').textContent = `ワールド:${world.meta.worldName} / クエスト:${world.quests.length}件`;
      document.getElementById('outText').innerHTML = renderHTML(world);
      document.getElementById('outJSON').textContent = JSON.stringify(world, null, 2);
      renderCards(world);
    }

    function generate(withNewSeed=false){
      const input = currentInput();
      if(withNewSeed && !document.getElementById('lockSeed').checked){ input.seed = ''; }
      if(!input.seed) { input.seed = cyrb128((input.worldName||'World') + (input.themes||'') + Date.now()); document.getElementById('seed').value = input.seed; }
      lastInput = input;
      const world = assembleWorld(input);
      applyWorld(world);
    }

    // イベント
    document.getElementById('btnGenerate').addEventListener('click', ()=> generate(false));
    document.getElementById('btnRegenerate').addEventListener('click', ()=> generate(false));
    document.getElementById('btnShuffleSeed').addEventListener('click', ()=> generate(true));
    document.getElementById('btnCopyText').addEventListener('click', ()=>{ if(lastWorld) copyText(renderText(lastWorld)); });
    document.getElementById('btnDownloadJSON').addEventListener('click', ()=>{ if(lastWorld) downloadJSON(lastWorld); });
    document.getElementById('btnExportCSV').addEventListener('click', ()=>{ if(lastWorld) exportCSVs(lastWorld); });
    document.getElementById('btnToggleJson').addEventListener('click', ()=>{ document.getElementById('jsonBlock').classList.toggle('hidden'); });
    document.getElementById('btnSave').addEventListener('click', ()=>{ if(lastWorld) saveLocal(lastWorld); });
    document.getElementById('btnLoad').addEventListener('click', ()=>{ const w=loadLocal(); if(w) applyWorld(w); });
    document.getElementById('btnPrint').addEventListener('click', ()=> window.print());

    // 初期プレースホルダ生成
    window.addEventListener('DOMContentLoaded', ()=>{
      document.getElementById('worldName').value = '運命の剣界';
      document.getElementById('themes').value = '古代遺跡 風の精霊 砂漠 旅人ギルド';
      generate(true);
    });
  </script>
</body>
</html>

MailLite — シンプルWebメール

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>MailLite — シンプルWebメール</title>
<style>
  :root{
    --bg:#f6f7fb;
    --panel:#ffffff;
    --text:#1f2937;
    --muted:#6b7280;
    --primary:#4f46e5;
    --primary-weak:#eef2ff;
    --border:#e5e7eb;
    --danger:#ef4444;
    --success:#10b981;
    --warning:#f59e0b;
  }
  .dark{
    --bg:#0b0e15;
    --panel:#0f1623;
    --text:#e5e7eb;
    --muted:#9ca3af;
    --primary:#8b5cf6;
    --primary-weak:#221a36;
    --border:#1f2937;
    --danger:#f87171;
    --success:#34d399;
    --warning:#fbbf24;
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0;background:var(--bg);color:var(--text);
    font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,"Noto Sans JP",sans-serif;
  }
  .app{
    display:grid;grid-template-rows:56px 1fr;height:100%;
  }
  /* Topbar */
  .topbar{
    display:flex;align-items:center;gap:12px;
    padding:0 16px;border-bottom:1px solid var(--border);background:var(--panel);
    position:sticky;top:0;z-index:5;
  }
  .logo{
    display:flex;align-items:center;gap:10px;font-weight:700;
    letter-spacing:.2px;
  }
  .badge{font-size:10px;padding:2px 6px;border-radius:999px;background:var(--primary-weak);color:var(--primary)}
  .search{
    margin-left:auto;display:flex;align-items:center;gap:8px;background:var(--bg);
    padding:6px 10px;border-radius:10px;border:1px solid var(--border);min-width:220px;max-width:460px;flex:1;
  }
  .search input{border:none;background:transparent;outline:none;color:var(--text);width:100%}
  .icon{width:18px;height:18px;display:inline-block;flex:0 0 18px}
  .btn{
    display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:10px;
    border:1px solid var(--border);background:var(--panel);cursor:pointer;color:var(--text);
  }
  .btn.primary{background:var(--primary);border-color:var(--primary);color:#fff}
  .btn.ghost{background:transparent}
  .btn:disabled{opacity:.6;cursor:not-allowed}

  /* Layout */
  .layout{
    display:grid;grid-template-columns:260px 360px 1fr;gap:12px;padding:12px;height:calc(100vh - 56px);
  }
  .panel{background:var(--panel);border:1px solid var(--border);border-radius:14px;overflow:hidden;display:flex;flex-direction:column;min-height:0}
  .sidebar{padding:12px}
  .compose-block{padding:12px}
  .compose-button{width:100%;justify-content:center}
  .nav-group{margin-top:8px}
  .nav-item{
    display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;color:var(--text);text-decoration:none;cursor:pointer;
  }
  .nav-item:hover{background:var(--primary-weak)}
  .nav-item.active{background:var(--primary);color:#fff}
  .nav-item .count{margin-left:auto;opacity:.8}

  /* List */
  .list-toolbar{display:flex;align-items:center;gap:8px;padding:8px;border-bottom:1px solid var(--border)}
  .list{overflow:auto}
  .msg{
    display:grid;grid-template-columns:24px 1fr auto;gap:10px;padding:12px;border-bottom:1px solid var(--border);cursor:pointer;
  }
  .msg:hover{background:var(--primary-weak)}
  .msg.unread{background:linear-gradient(0deg,transparent,transparent), var(--panel);font-weight:600}
  .msg .from{color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .msg .subject{color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .msg .snippet{color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .msg .meta{display:flex;flex-direction:column;align-items:end;gap:4px;color:var(--muted)}
  .chip{display:inline-flex;align-items:center;gap:6px;padding:2px 8px;border-radius:999px;border:1px solid var(--border);font-size:11px}
  .star{cursor:pointer;opacity:.7}
  .star.active{opacity:1}
  .avatar{
    width:24px;height:24px;border-radius:50%;background:linear-gradient(135deg,var(--primary),#22c1c3);
    display:grid;place-items:center;color:#fff;font-size:12px;font-weight:700;
  }

  /* Reader */
  .reader-head{
    padding:12px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;flex-wrap:wrap;
  }
  .reader-title{font-size:18px;font-weight:700}
  .reader-meta{color:var(--muted);font-size:12px}
  .reader-actions{margin-left:auto;display:flex;gap:8px}
  .reader-body{padding:16px;overflow:auto}
  .empty{display:grid;place-items:center;height:100%;color:var(--muted)}

  /* Modal */
  .modal{
    position:fixed;inset:0;background:rgba(0,0,0,.4);display:none;align-items:center;justify-content:center;z-index:20;
  }
  .modal.open{display:flex}
  .modal-card{
    width:min(920px,94vw);max-height:88vh;overflow:auto;background:var(--panel);border:1px solid var(--border);
    border-radius:16px;
  }
  .modal-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border)}
  .modal-body{padding:16px;display:grid;gap:10px}
  .field{display:grid;gap:6px}
  .input, textarea{
    width:100%;padding:10px 12px;border-radius:10px;border:1px solid var(--border);
    background:transparent;color:var(--text);outline:none;
  }
  textarea{min-height:220px;resize:vertical}
  .row{display:flex;gap:10px;flex-wrap:wrap}
  .grow{flex:1}

  /* Responsive */
  @media (max-width: 1100px){
    .layout{grid-template-columns:220px 1fr}
    .reader{display:none}
    .layout.show-reader .list{display:none}
    .layout.show-reader .reader{display:flex}
  }
  @media (max-width: 640px){
    .layout{grid-template-columns:1fr}
    .sidebar{display:none}
  }
</style>
</head>
<body>
<div class="app">
  <!-- Topbar -->
  <div class="topbar">
    <div class="logo">
      <svg class="icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M3 7.5 12 13l9-5.5v9A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z" stroke="currentColor" stroke-width="1.5"/>
        <path d="m3 7.5 9-5 9 5" stroke="currentColor" stroke-width="1.5"/>
      </svg>
      MailLite <span class="badge">beta</span>
    </div>

    <div class="search">
      <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="m21 21-4.2-4.2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="1.5"/></svg>
      <input id="search" placeholder="メールを検索(差出人・件名・本文・ラベル)" />
      <button class="btn ghost" id="clearSearch" title="検索クリア">クリア</button>
    </div>

    <button class="btn" id="toggleDark" title="ダークモード">
      <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9Z" stroke="currentColor" stroke-width="1.5"/></svg>
      主题
    </button>
    <button class="btn primary" id="composeBtn">
      <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M4 20h16M6 14l9.5-9.5a2.1 2.1 0 1 1 3 3L9 17l-5 1 2-4Z" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>
      新規作成
    </button>
  </div>

  <!-- Main layout -->
  <div class="layout" id="layout">
    <!-- Sidebar -->
    <aside class="panel sidebar">
      <div class="compose-block">
        <button class="btn primary compose-button" id="composeBtn2">
          <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M4 20h16M6 14l9.5-9.5a2.1 2.1 0 1 1 3 3L9 17l-5 1 2-4Z" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>
          新規メール
        </button>
      </div>
      <nav class="nav-group" id="folders"></nav>
    </aside>

    <!-- List -->
    <section class="panel">
      <div class="list-toolbar">
        <button class="btn" id="markReadBtn" title="既読にする">既読</button>
        <button class="btn" id="markUnreadBtn" title="未読にする">未読</button>
        <button class="btn" id="archiveBtn" title="アーカイブ">アーカイブ</button>
        <button class="btn" id="deleteBtn" title="削除">削除</button>
        <div style="margin-left:auto;display:flex;align-items:center;gap:6px;">
          <span class="chip"><span class="dot" style="width:8px;height:8px;border-radius:50%;background:var(--primary)"></span> ラベル</span>
        </div>
      </div>
      <div class="list" id="list"></div>
    </section>

    <!-- Reader -->
    <section class="panel reader" id="reader">
      <div class="empty" id="emptyState">メールを選択してください</div>
      <div style="display:none;flex-direction:column;height:100%;" id="readerWrap">
        <div class="reader-head">
          <div style="display:flex;align-items:center;gap:10px;min-width:0">
            <div class="avatar" id="readerAvatar">Y</div>
            <div style="min-width:0">
              <div class="reader-title" id="readerSubject">件名</div>
              <div class="reader-meta" id="readerMeta">From – To ・ 日付</div>
            </div>
          </div>
          <div class="reader-actions">
            <button class="btn" id="replyBtn" title="返信">返信</button>
            <button class="btn" id="starBtn" title="スター">
              <span id="starIcon">☆</span> スター
            </button>
            <button class="btn" id="archBtn" title="アーカイブ">アーカイブ</button>
            <button class="btn" id="trashBtn" title="削除" style="color:var(--danger)">削除</button>
          </div>
        </div>
        <div class="reader-body">
          <div id="readerBody"></div>
        </div>
      </div>
    </section>
  </div>
</div>

<!-- Compose Modal -->
<div class="modal" id="composeModal" aria-hidden="true">
  <div class="modal-card">
    <div class="modal-head">
      <strong>新規メッセージ</strong>
      <div class="row">
        <button class="btn" id="saveDraftBtn">下書き保存</button>
        <button class="btn primary" id="sendBtn">送信</button>
        <button class="btn" id="closeModalBtn">閉じる</button>
      </div>
    </div>
    <div class="modal-body">
      <div class="row">
        <div class="field grow">
          <label for="to">宛先(カンマ区切り)</label>
          <input class="input" id="to" placeholder="example@example.com, someone@domain.jp" />
        </div>
        <div class="field" style="min-width:160px;">
          <label for="label">ラベル</label>
          <input class="input" id="label" placeholder="work, personal など" />
        </div>
      </div>
      <div class="field">
        <label for="subject">件名</label>
        <input class="input" id="subject" placeholder="件名を入力" />
      </div>
      <div class="field">
        <label for="body">本文</label>
        <textarea id="body" placeholder="本文を入力"></textarea>
      </div>
    </div>
  </div>
</div>

<script>
/** ======= Simple Mail App (no backend) ======= */
const DB_KEY = "maillite-db-v1";
const QS = sel => document.querySelector(sel);
const QSA = sel => [...document.querySelectorAll(sel)];
const state = {
  currentFolder: "inbox",
  query: "",
  selectedIds: new Set(),
  currentId: null,
  db: { messages: [] }
};
const FOLDERS = [
  {id:"inbox",   name:"受信箱",    icon:"📥"},
  {id:"starred", name:"スター",    icon:"⭐"},
  {id:"sent",    name:"送信済み",  icon:"📤"},
  {id:"drafts",  name:"下書き",    icon:"📝"},
  {id:"archive", name:"アーカイブ",icon:"🗄️"},
  {id:"spam",    name:"迷惑",      icon:"🚫"},
  {id:"trash",   name:"ゴミ箱",    icon:"🗑️"},
];

function initDB(){
  const saved = localStorage.getItem(DB_KEY);
  if(saved){
    state.db = JSON.parse(saved);
    return;
  }
  // Seed sample messages
  const now = Date.now();
  const demo = [
    mkMsg("suzuki@example.com","ようこそ MailLite へ","MailLite をお試しいただきありがとうございます!\n\nこのメールはデモです。",["welcome"], now-3600_000),
    mkMsg("shop@ec.example.com","【お知らせ】サマーセール開催!","最大 50%OFF。今すぐチェック!",["promo"], now-7200_000),
    mkMsg("boss@company.jp","明日の打合せ議題","・リリース計画\n・障害対応\n・コスト見直し",["work"], now-86400_000, true),
    mkMsg("friend@chat.jp","週末の予定どう?","映画かカラオケ行かない?",["personal"], now-5400_000),
    mkMsg("security@service.jp","ログイン通知","新しい端末からログインがありました。",["security"], now-9600_000),
  ];
  demo[2].unread = false;
  state.db.messages = demo;
  persist();
}
function mkMsg(from, subject, body, labels=[], time=Date.now(), starred=false){
  const id = crypto.randomUUID();
  const initials = (from.split("@")[0][0]||"U").toUpperCase();
  return {
    id, box:"inbox", from, to:[], subject, body, labels, starred, unread:true,
    date: time, initials
  };
}
function persist(){ localStorage.setItem(DB_KEY, JSON.stringify(state.db)); }

function formatDate(ts){
  const d = new Date(ts);
  const pad = n => String(n).padStart(2,"0");
  return `${d.getFullYear()}/${pad(d.getMonth()+1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

// Render folders
function renderFolders(){
  const el = QS("#folders");
  el.innerHTML = "";
  for(const f of FOLDERS){
    const count = countFolder(f.id);
    const a = document.createElement("a");
    a.className = "nav-item" + (state.currentFolder===f.id?" active":"");
    a.dataset.id = f.id;
    a.innerHTML = `<span>${f.icon}</span><span>${f.name}</span><span class="count">${count||""}</span>`;
    a.addEventListener("click", ()=>{
      state.currentFolder = f.id;
      state.selectedIds.clear();
      state.currentId = null;
      render();
    });
    el.appendChild(a);
  }
}
function countFolder(folder){
  return filterByFolder(state.db.messages, folder).length;
}
function filterByFolder(list, folder){
  switch(folder){
    case "inbox":   return list.filter(m=>m.box==="inbox");
    case "starred": return list.filter(m=>m.starred && m.box!=="trash");
    case "sent":    return list.filter(m=>m.box==="sent");
    case "drafts":  return list.filter(m=>m.box==="drafts");
    case "archive": return list.filter(m=>m.box==="archive");
    case "spam":    return list.filter(m=>m.box==="spam");
    case "trash":   return list.filter(m=>m.box==="trash");
    default:        return list;
  }
}

// Search
function matchesQuery(m,q){
  if(!q) return true;
  const s = q.toLowerCase();
  const hay = [
    m.from, (m.to||[]).join(","), m.subject, m.body, (m.labels||[]).join(",")
  ].join("\n").toLowerCase();
  return hay.includes(s);
}

// Render list
function renderList(){
  const wrap = QS("#list");
  const items = filterByFolder(state.db.messages, state.currentFolder)
    .filter(m=>matchesQuery(m, state.query))
    .sort((a,b)=>b.date-a.date);
  wrap.innerHTML = "";
  if(items.length===0){
    wrap.innerHTML = `<div class="empty" style="height:100%;">${state.query? "検索結果がありません":"このフォルダは空です"}</div>`;
    return;
  }
  for(const m of items){
    const row = document.createElement("div");
    row.className = "msg" + (m.unread?" unread":"");
    row.dataset.id = m.id;
    const starClass = m.starred? "active":"";
    row.innerHTML = `
      <div class="avatar" title="${m.from}">${m.initials}</div>
      <div style="min-width:0">
        <div class="from">${m.from}</div>
        <div class="subject">${m.subject}</div>
        <div class="snippet">${(m.labels?.length? m.labels.map(l=>"#"+l).join(" ")+" · ":"")}${m.body.replace(/\n/g," ").slice(0,120)}</div>
      </div>
      <div class="meta">
        <div>${formatDate(m.date)}</div>
        <div class="star ${starClass}" data-star-id="${m.id}" title="スター">${m.starred?"★":"☆"}</div>
      </div>
    `;
    row.addEventListener("click", (e)=>{
      // If star clicked, don't open
      if(e.target && e.target.dataset.starId){ return; }
      openMessage(m.id);
    });
    row.querySelector(".star").addEventListener("click",(e)=>{
      e.stopPropagation();
      toggleStar(m.id);
    });
    wrap.appendChild(row);
  }
}

// Reader
function openMessage(id){
  const m = state.db.messages.find(x=>x.id===id);
  if(!m) return;
  state.currentId = id;
  m.unread = false;
  persist();
  QS("#emptyState").style.display = "none";
  QS("#readerWrap").style.display = "flex";
  QS("#readerSubject").textContent = m.subject || "(件名なし)";
  QS("#readerMeta").textContent    = `From: ${m.from}  /  To: ${(m.to||[]).join(", ")||"(なし)"} ・ ${formatDate(m.date)}`; 
  QS("#readerBody").innerHTML      = safeHtml(m.body).replace(/\n/g,"<br>");
  QS("#readerAvatar").textContent  = m.initials || "U";
  QS("#starIcon").textContent      = m.starred ? "★" : "☆";
  // Mobile: show reader
  QS("#layout").classList.add("show-reader");
  render();
}

function safeHtml(s=""){
  return s.replace(/[&<>"']/g, ch => ({
    "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"
  }[ch]));
}

// Actions
function getSelectedOrCurrentIds(){
  if(state.selectedIds.size>0) return [...state.selectedIds];
  if(state.currentId) return [state.currentId];
  return [];
}
function markRead(read=true){
  for(const id of getSelectedOrCurrentIds()){
    const m = state.db.messages.find(x=>x.id===id);
    if(m) m.unread = !read;
  }
  persist(); render();
}
function moveTo(box){
  for(const id of getSelectedOrCurrentIds()){
    const m = state.db.messages.find(x=>x.id===id);
    if(m) m.box = box;
  }
  // If current message was moved out of view, clear reader
  if(state.currentId){
    const cm = state.db.messages.find(x=>x.id===state.currentId);
    const visible = filterByFolder([cm], state.currentFolder).length>0;
    if(!visible){ state.currentId = null; QS("#readerWrap").style.display="none"; QS("#emptyState").style.display="grid"; }
  }
  persist(); render();
}
function toggleStar(id){
  const m = state.db.messages.find(x=>x.id===id);
  if(m){ m.starred = !m.starred; persist(); render(); if(state.currentId===id) QS("#starIcon").textContent=m.starred?"★":"☆"; }
}

// Compose
function openCompose(prefill={}){
  QS("#composeModal").classList.add("open");
  QS("#to").value      = prefill.to?.join(", ") || "";
  QS("#subject").value = prefill.subject || "";
  QS("#body").value    = prefill.body || "";
  QS("#label").value   = (prefill.labels||[]).join(", ");
}
function closeCompose(){ QS("#composeModal").classList.remove("open"); }

function saveDraft(){
  const draft = collectForm();
  draft.box = "drafts";
  draft.unread = false;
  draft.from = "me@local";
  draft.id = crypto.randomUUID();
  state.db.messages.push(draft);
  persist(); closeCompose(); render();
  alert("下書きを保存しました。");
}
function sendMail(){
  const msg = collectForm();
  if(!msg.to.length){ alert("宛先を入力してください"); return; }
  msg.box = "sent";
  msg.unread = false;
  msg.from = "me@local";
  msg.id = crypto.randomUUID();
  state.db.messages.push(msg);
  persist(); closeCompose(); render();
  alert("送信しました(デモ動作:実送信なし)");
}
function collectForm(){
  const to = QS("#to").value.split(",").map(s=>s.trim()).filter(Boolean);
  const subject = QS("#subject").value.trim() || "(件名なし)";
  const body = QS("#body").value;
  const labels = QS("#label").value.split(",").map(s=>s.trim()).filter(Boolean);
  return { to, subject, body, labels, date: Date.now(), starred:false, unread:true, initials:"M" };
}

// Selection (click+Ctrl/Shift optional simplified)
QS("#list").addEventListener("click",(e)=>{
  const row = e.target.closest(".msg");
  if(!row) return;
  if(e.ctrlKey || e.metaKey){
    const id = row.dataset.id;
    if(state.selectedIds.has(id)) state.selectedIds.delete(id); else state.selectedIds.add(id);
    row.classList.toggle("selected");
  }
});

// Topbar controls
QS("#composeBtn").onclick = ()=>openCompose();
QS("#composeBtn2").onclick = ()=>openCompose();
QS("#closeModalBtn").onclick = closeCompose;
QS("#saveDraftBtn").onclick = saveDraft;
QS("#sendBtn").onclick = sendMail;

QS("#search").addEventListener("input",(e)=>{ state.query = e.target.value.trim(); renderList(); });
QS("#clearSearch").onclick = ()=>{ QS("#search").value=""; state.query=""; renderList(); };

QS("#toggleDark").onclick = ()=>{
  document.body.classList.toggle("dark");
  localStorage.setItem("maillite-theme", document.body.classList.contains("dark")? "dark":"light");
};

// List toolbar actions
QS("#markReadBtn").onclick = ()=>markRead(true);
QS("#markUnreadBtn").onclick = ()=>markRead(false);
QS("#archiveBtn").onclick = ()=>moveTo("archive");
QS("#deleteBtn").onclick = ()=>moveTo("trash");

// Reader actions
QS("#replyBtn").onclick = ()=>{
  const m = state.db.messages.find(x=>x.id===state.currentId);
  if(!m) return;
  openCompose({ to:[m.from], subject:"Re: "+m.subject, body:`\n\n--- ${m.from} さんのメッセージ ---\n${m.body}`, labels:["reply"] });
};
QS("#starBtn").onclick = ()=>{ if(state.currentId) toggleStar(state.currentId); };
QS("#archBtn").onclick = ()=>moveTo("archive");
QS("#trashBtn").onclick = ()=>moveTo("trash");

// Clicking outside modal to close
QS("#composeModal").addEventListener("click",(e)=>{ if(e.target===QS("#composeModal")) closeCompose(); });

// Mobile back from reader by clicking empty area (or press Escape)
document.addEventListener("keydown",(e)=>{
  if(e.key==="Escape"){
    if(QS("#composeModal").classList.contains("open")) closeCompose();
    else QS("#layout").classList.remove("show-reader");
  }
});

// Initial render
function render(){
  renderFolders();
  renderList();
}
(function boot(){
  initDB();
  render();
  // Theme
  if(localStorage.getItem("maillite-theme")==="dark"){ document.body.classList.add("dark"); }
})();
</script>
</body>
</html>

ミニ百科.html

<!DOCTYPE html>
<html lang="ja" class="scroll-smooth">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>ミニ百科 – シングルファイル版</title>
  <meta name="description" content="検索・カテゴリ・タグ・ブックマーク対応のシングルファイル百科事典。" />
  <link rel="preconnect" href="https://cdn.jsdelivr.net" />
  <!-- TailwindCSS (CDN) -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome (icons) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" integrity="sha512-5I0VnK5tQhJ0eZ5Ck1gC3b6h9fJ3k6l9FeI3K6J0q9JtO1Yw1l2Y7N5M6d2xQf8Q2F6mZ8l2s3A=" crossorigin="anonymous" referrerpolicy="no-referrer" />
  <!-- Favicon (inline SVG) -->
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 256 256'%3E%3Cpath fill='%234f46e5' d='M32 56c0-13.3 10.7-24 24-24h144c13.3 0 24 10.7 24 24v144c0 13.3-10.7 24-24 24H56c-13.3 0-24-10.7-24-24z'/%3E%3Cpath fill='white' d='M72 80h112v16H72zM72 112h80v16H72zM72 144h112v16H72zM72 176h96v16H72z'/%3E%3C/svg%3E" />
  <style>
    /* 追加の細かなスタイル */
    .line-clamp-3{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
    .prose h2{scroll-margin-top:6rem}
    .toc a{display:block;padding:.25rem .5rem;border-radius:.5rem}
    .toc a.active{background:rgba(99,102,241,.12)}
  </style>
  <script>
    // ダークモード初期化
    (function(){
      const theme=localStorage.getItem('theme');
      if(theme==='dark'||(!theme&&window.matchMedia('(prefers-color-scheme: dark)').matches)){
        document.documentElement.classList.add('dark');
      }
    })();
  </script>
</head>
<body class="bg-slate-50 text-slate-800 dark:bg-slate-900 dark:text-slate-100 min-h-screen">
  <!-- Skip link -->
  <a href="#main" class="sr-only focus:not-sr-only focus:absolute focus:top-2 focus:left-2 focus:bg-indigo-600 focus:text-white focus:px-3 focus:py-2 focus:rounded">本文へスキップ</a>

  <!-- Header -->
  <header class="sticky top-0 z-40 backdrop-blur border-b border-slate-200/60 dark:border-slate-700/60 bg-white/70 dark:bg-slate-900/70">
    <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-3 flex items-center gap-3">
      <button id="btnHome" class="shrink-0 px-2 py-1 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/40" title="ホーム">
        <i class="fa-solid fa-book-open text-indigo-600"></i>
      </button>
      <h1 class="text-lg sm:text-2xl font-bold tracking-tight">ミニ百科 <span class="text-indigo-600">Mini Encyclopedia</span></h1>
      <div class="ms-auto flex items-center gap-2">
        <button id="btnRandom" class="px-3 py-2 rounded-xl bg-indigo-600 text-white text-sm hover:opacity-90"><i class="fa-solid fa-shuffle me-1"></i>ランダム</button>
        <button id="btnBookmarks" class="px-3 py-2 rounded-xl bg-amber-500 text-white text-sm hover:opacity-90"><i class="fa-solid fa-star me-1"></i>ブックマーク</button>
        <button id="btnDark" class="px-3 py-2 rounded-xl bg-slate-800 text-white text-sm dark:bg-slate-700 hover:opacity-90" title="ダーク/ライト切替"><i class="fa-solid fa-moon"></i></button>
      </div>
    </div>
  </header>

  <!-- Toolbar -->
  <section class="border-b border-slate-200/60 dark:border-slate-700/60 bg-white/60 dark:bg-slate-900/60">
    <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-4 grid gap-3 sm:grid-cols-12 items-end">
      <div class="sm:col-span-6">
        <label for="search" class="block text-sm text-slate-600 dark:text-slate-300 mb-1">記事検索</label>
        <div class="relative">
          <input id="search" type="search" placeholder="キーワード(例: 富士山 / 恐竜 / インターネット)" class="w-full rounded-2xl border border-slate-300 dark:border-slate-700 bg-white/80 dark:bg-slate-800/80 px-4 py-2 pe-10 outline-none focus:ring-2 focus:ring-indigo-500" />
          <i class="fa-solid fa-magnifying-glass absolute right-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
        </div>
      </div>
      <div class="sm:col-span-3">
        <label for="category" class="block text-sm text-slate-600 dark:text-slate-300 mb-1">カテゴリ</label>
        <select id="category" class="w-full rounded-2xl border border-slate-300 dark:border-slate-700 bg-white/80 dark:bg-slate-800/80 px-4 py-2 outline-none focus:ring-2 focus:ring-indigo-500">
          <option value="">すべて</option>
        </select>
      </div>
      <div class="sm:col-span-3">
        <label for="sort" class="block text-sm text-slate-600 dark:text-slate-300 mb-1">並び替え</label>
        <select id="sort" class="w-full rounded-2xl border border-slate-300 dark:border-slate-700 bg-white/80 dark:bg-slate-800/80 px-4 py-2 outline-none focus:ring-2 focus:ring-indigo-500">
          <option value="recent">更新が新しい順</option>
          <option value="title">タイトル順</option>
        </select>
      </div>
      <div class="sm:col-span-12" id="tagBar" aria-label="タグフィルタ" class="flex flex-wrap gap-2"></div>
    </div>
  </section>

  <main id="main" class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-6">
    <!-- Home / List View -->
    <section id="view-home" class="grid gap-6">
      <div class="flex items-center justify-between">
        <h2 class="text-xl sm:text-2xl font-semibold">記事一覧</h2>
        <div class="text-sm text-slate-500"><span id="resultCount">0</span> 件</div>
      </div>
      <div id="cards" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <!-- cards injected -->
      </div>
      <div class="flex items-center justify-center gap-2 pt-2" id="pager"></div>
    </section>

    <!-- Article View -->
    <section id="view-article" class="hidden lg:grid lg:grid-cols-12 gap-8">
      <aside class="lg:col-span-3 order-last lg:order-first">
        <div class="sticky top-[6.5rem] border border-slate-200 dark:border-slate-700 rounded-2xl p-4">
          <h3 class="font-semibold mb-2">目次</h3>
          <nav id="toc" class="toc text-sm space-y-1"></nav>
        </div>
      </aside>
      <article class="lg:col-span-9">
        <nav class="text-sm text-slate-500 mb-3" id="breadcrumb"></nav>
        <header class="mb-4">
          <h1 id="articleTitle" class="text-2xl sm:text-3xl font-bold tracking-tight"></h1>
          <div class="mt-2 flex flex-wrap items-center gap-2 text-sm text-slate-500" id="articleMeta"></div>
          <div class="mt-3 flex items-center gap-2">
            <button id="btnCopyLink" class="px-3 py-2 rounded-xl border border-slate-300 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800"><i class="fa-solid fa-link me-1"></i>リンクをコピー</button>
            <button id="btnToggleBookmark" class="px-3 py-2 rounded-xl border border-amber-400 text-amber-600 hover:bg-amber-50"><i class="fa-regular fa-star me-1"></i>ブックマーク</button>
          </div>
        </header>
        <div id="articleContent" class="prose prose-slate dark:prose-invert max-w-none"></div>
        <section class="mt-8">
          <h3 class="font-semibold mb-2">関連タグ</h3>
          <div id="articleTags" class="flex flex-wrap gap-2"></div>
        </section>
      </article>
    </section>
  </main>

  <footer class="border-t border-slate-200 dark:border-slate-700 py-8">
    <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 text-sm text-slate-500 flex flex-wrap items-center gap-2">
      <span>© <span id="year"></span> ミニ百科</span>
      <span class="mx-1">•</span>
      <button id="btnExport" class="underline underline-offset-4">データを書き出す(JSON)</button>
      <span class="mx-1">•</span>
      <label class="cursor-pointer">JSON読み込み <input id="fileImport" type="file" accept="application/json" class="hidden" /></label>
    </div>
  </footer>

  <!-- Structured data placeholder (updated on article view) -->
  <script id="ldjson" type="application/ld+json">{}</script>

  <script>
  // ======================
  //  サンプル記事データ
  // ======================
  /**
   * 記事スキーマ:
   * id, slug, title, category, tags[], summary, updated(ISO), author, content(HTML)
   */
  const ARTICLES = [
    {
      id: 1,
      slug: 'fuji-san',
      title: '富士山',
      category: '地理',
      tags: ['日本','山','世界文化遺産'],
      summary: '日本の象徴ともいわれる成層火山。標高3,776mで日本最高峰。',
      updated: '2025-08-15',
      author: 'ミニ百科編集部',
      content: `
        <p>富士山は本州中部に位置する<span>成層火山</span>で、標高は3,776m。2013年に世界文化遺産に登録されました。古来より信仰の対象であり、芸術や文学にも多く登場します。</p>
        <h2 id="geo">地形と地質</h2>
        <p>富士山は何度もの噴火活動を経て現在の美しい円錐形を形成しました。火口は山頂部にあり、外輪としてお鉢巡りが知られています。</p>
        <h2 id="climb">登山と保全</h2>
        <p>一般的な登山シーズンは夏。登山道の混雑やゴミ問題、低温・高山病などのリスク対策が重要です。</p>
        <h2 id="culture">文化的意義</h2>
        <p>葛飾北斎の『富嶽三十六景』をはじめ、絵画や和歌に頻繁に詠まれ、日本の象徴として国際的にも広く知られています。</p>
      `
    },
    {
      id: 2,
      slug: 'internet-basics',
      title: 'インターネットの基礎',
      category: 'テクノロジー',
      tags: ['ネットワーク','Web','通信'],
      summary: '世界中のコンピュータを相互接続する情報ネットワークの総称。',
      updated: '2025-07-01',
      author: 'ミニ百科編集部',
      content: `
        <p>インターネットは標準化された<span>TCP/IP</span>により機器同士が通信する巨大なネットワークです。Web、メール、動画配信など多様なサービスの土台になっています。</p>
        <h2 id="protocols">主要プロトコル</h2>
        <p>HTTP/HTTPS、DNS、SMTP、FTPなどが代表的。セキュリティ確保には暗号化や認証が重要です。</p>
        <h2 id="web">Webの仕組み</h2>
        <p>ブラウザがURLを解決し、サーバからHTML/CSS/JS等のリソースを取得・表示します。</p>
        <h2 id="safety">安全な利用</h2>
        <p>二要素認証、ソフトウェア更新、フィッシング対策、強力なパスワード管理が基本です。</p>
      `
    },
    {
      id: 3,
      slug: 'dinosaurs',
      title: '恐竜',
      category: '生物',
      tags: ['古生物学','白亜紀','化石'],
      summary: '中生代に栄えた爬虫類のグループ。鳥類は恐竜の系統に含まれると考えられている。',
      updated: '2025-05-28',
      author: 'ミニ百科編集部',
      content: `
        <p>恐竜は約2億3000万年前に出現し、中生代に多様化しました。<span>鳥類</span>は恐竜の一系統とみなされます。</p>
        <h2 id="era">時代区分</h2>
        <p>三畳紀・ジュラ紀・白亜紀に区分され、各時代で特徴的な種が繁栄しました。</p>
        <h2 id="extinction">大量絶滅</h2>
        <p>約6600万年前の大量絶滅で多くが消滅。隕石衝突や火山活動などが要因と考えられています。</p>
      `
    },
    {
      id: 4,
      slug: 'ww2-overview',
      title: '第二次世界大戦(概説)',
      category: '歴史',
      tags: ['20世紀','戦争','国際関係'],
      summary: '1939年から1945年にかけて行われた世界規模の戦争。',
      updated: '2025-03-10',
      author: 'ミニ百科編集部',
      content: `
        <p>第二次世界大戦は多数の国が参戦した世界規模の戦争で、政治・経済・科学技術・社会に長期の影響を与えました。</p>
        <h2 id="fronts">主要戦線</h2>
        <p>ヨーロッパ、太平洋、北アフリカ、東部戦線など多くの戦域に分かれました。</p>
        <h2 id="aftermath">戦後の世界</h2>
        <p>国際連合の設立、冷戦構造の形成、国際秩序の再編などにつながりました。</p>
      `
    },
    {
      id: 5,
      slug: 'ai-basics',
      title: '人工知能の基礎',
      category: 'テクノロジー',
      tags: ['AI','機械学習','深層学習'],
      summary: '知的な処理をコンピュータで実現する研究分野と技術群。',
      updated: '2025-06-12',
      author: 'ミニ百科編集部',
      content: `
        <p>人工知能は探索・推論から機械学習・深層学習まで多様な手法を含みます。現代では大量データと計算資源により実世界応用が拡大。</p>
        <h2 id="ml">機械学習</h2>
        <p>教師あり・教師なし・強化学習などの枠組みがあり、予測や分類に用いられます。</p>
        <h2 id="dl">深層学習</h2>
        <p>多層ニューラルネットワークにより画像・音声・自然言語処理で高精度を実現。</p>
      `
    },
    {
      id: 6,
      slug: 'sakura',
      title: 'サクラ(桜)',
      category: '文化',
      tags: ['日本文化','植物','季節'],
      summary: '日本の春を象徴する花。花見は古くからの季節行事。',
      updated: '2025-04-02',
      author: 'ミニ百科編集部',
      content: `
        <p>桜はバラ科サクラ属の総称。品種が多く、花期は短いものの観賞価値が高いことで知られます。</p>
        <h2 id="hanami">花見の歴史</h2>
        <p>貴族文化から庶民に広がり、現在では地域の祭りや観光資源にもなっています。</p>
      `
    },
    {
      id: 7,
      slug: 'japan-history-outline',
      title: '日本史(概説)',
      category: '歴史',
      tags: ['古代','中世','近代'],
      summary: '古代から現代までの日本の歴史を大まかに概観する。',
      updated: '2025-01-20',
      author: 'ミニ百科編集部',
      content: `
        <p>日本史は縄文・弥生・古墳などの古代から、中世・近世、明治以降の近代・現代に至るまで連続する多様な変化の歴史です。</p>
        <h2 id="ancient">古代</h2>
        <p>稲作の普及、古代国家の形成、律令制の確立など。</p>
        <h2 id="modern">近代・現代</h2>
        <p>近代化、戦後復興、高度経済成長、少子高齢化と新たな課題。</p>
      `
    },
    {
      id: 8,
      slug: 'programming-intro',
      title: 'プログラミング入門',
      category: 'テクノロジー',
      tags: ['コード','アルゴリズム','学習'],
      summary: 'コンピュータに手順を伝えるための技術と考え方の総称。',
      updated: '2025-07-22',
      author: 'ミニ百科編集部',
      content: `
        <p>プログラミングは問題を分解し、再利用可能な手順として表現する作業です。変数、条件分岐、反復、関数などの基本を学ぶと応用が広がります。</p>
        <h2 id="lang">主な言語</h2>
        <p>Python、JavaScript、C#、C++ など用途に応じて選択されます。</p>
      `
    },
    {
      id: 9,
      slug: 'tea-ceremony',
      title: '茶道',
      category: '文化',
      tags: ['日本文化','礼法','芸道'],
      summary: '湯を沸かし茶を点て、客をもてなす総合芸術。',
      updated: '2025-05-03',
      author: 'ミニ百科編集部',
      content: `
        <p>茶道は道具、作法、空間、季節感などが一体となる総合芸術です。<span>和敬清寂</span>の精神が重視されます。</p>
        <h2 id="tools">道具</h2>
        <p>茶碗、茶筅、茶杓、釜、柄杓など。取り扱いには所作と配慮が求められます。</p>
      `
    },
    {
      id: 10,
      slug: 'solar-system',
      title: '太陽系',
      category: '天文学',
      tags: ['惑星','衛星','宇宙'],
      summary: '太陽とその周囲を公転する天体の集まり。',
      updated: '2025-06-30',
      author: 'ミニ百科編集部',
      content: `
        <p>太陽系は太陽を中心に、8つの惑星、準惑星、小惑星、彗星、塵やガスが重力で結びつくシステムです。</p>
        <h2 id="planets">惑星</h2>
        <p>水星・金星・地球・火星・木星・土星・天王星・海王星。各惑星は固有の特徴を持ちます。</p>
      `
    }
  ];

  // ================
  // ユーティリティ
  // ================
  const $ = (sel, root=document) => root.querySelector(sel);
  const $$ = (sel, root=document) => Array.from(root.querySelectorAll(sel));
  const fmtDate = iso => new Date(iso).toLocaleDateString('ja-JP', {year:'numeric', month:'short', day:'numeric'});
  const unique = arr => [...new Set(arr)];
  const slugToArticle = slug => ARTICLES.find(a=>a.slug===slug);
  const STORAGE = {
    bookmarks: 'mini_ency_bookmarks',
    history: 'mini_ency_history'
  };

  function getBookmarks(){
    try{return JSON.parse(localStorage.getItem(STORAGE.bookmarks)||'[]');}catch{ return []; }
  }
  function setBookmarks(list){ localStorage.setItem(STORAGE.bookmarks, JSON.stringify(unique(list))); }
  function isBookmarked(slug){ return getBookmarks().includes(slug); }
  function toggleBookmark(slug){
    const list=getBookmarks();
    if(list.includes(slug)) setBookmarks(list.filter(s=>s!==slug));
    else setBookmarks([...list, slug]);
  }
  function pushHistory(slug){
    try{
      const now = Date.now();
      const hist = JSON.parse(localStorage.getItem(STORAGE.history)||'[]');
      const filtered = hist.filter(h=>h.slug!==slug);
      filtered.unshift({slug, t: now});
      localStorage.setItem(STORAGE.history, JSON.stringify(filtered.slice(0,50)));
    }catch{}
  }

  // ================
  // 検索・フィルタ
  // ================
  let state = {
    q: '',
    category: '',
    tag: '',
    sort: 'recent',
    page: 1,
    perPage: 9
  };

  function normalize(str){ return (str||'').toString().toLowerCase(); }

  function filterArticles(){
    let list = ARTICLES.slice();
    if(state.q){
      const q = normalize(state.q);
      list = list.filter(a => normalize(a.title+" "+a.summary+" "+a.tags.join(' ')+" "+a.content.replace(/<[^>]+>/g,'')).includes(q));
    }
    if(state.category){ list = list.filter(a => a.category===state.category); }
    if(state.tag){ list = list.filter(a => a.tags.includes(state.tag)); }
    if(state.sort==='recent'){ list.sort((a,b)=> new Date(b.updated)-new Date(a.updated)); }
    if(state.sort==='title'){ list.sort((a,b)=> a.title.localeCompare(b.title,'ja')); }
    return list;
  }

  // =============
  //  一覧描画
  // =============
  function renderCategories(){
    const select = $('#category');
    const cats = unique(ARTICLES.map(a=>a.category)).sort((a,b)=>a.localeCompare(b,'ja'));
    select.innerHTML = '<option value="">すべて</option>' + cats.map(c=>`<option value="${c}">${c}</option>`).join('');
  }

  function renderTagsBar(){
    const bar = $('#tagBar');
    const tags = unique(ARTICLES.flatMap(a=>a.tags)).sort((a,b)=>a.localeCompare(b,'ja'));
    bar.innerHTML = '<div class="flex flex-wrap gap-2">' + tags.map(t=>
      `<button data-tag="${t}" class="tag-btn px-3 py-1 rounded-full border border-slate-300 dark:border-slate-700 text-sm hover:bg-slate-100 dark:hover:bg-slate-800 ${state.tag===t?'bg-indigo-600 text-white border-indigo-600':''}">#${t}</button>`
    ).join('') + '</div>';
    $$('.tag-btn').forEach(b=> b.addEventListener('click',()=>{ state.tag = (state.tag===b.dataset.tag? '' : b.dataset.tag); state.page=1; syncList(); }));
  }

  function createCard(a){
    const bookmarked = isBookmarked(a.slug);
    return `
      <article class="border border-slate-200 dark:border-slate-700 rounded-2xl p-4 bg-white/70 dark:bg-slate-800/70 hover:shadow transition">
        <header class="flex items-start justify-between gap-3">
          <h3 class="text-lg font-semibold leading-tight">${a.title}</h3>
          <button class="bookmark inline-flex items-center justify-center w-9 h-9 rounded-full ${bookmarked?'text-amber-500':'text-slate-400'}" title="ブックマーク" data-slug="${a.slug}">
            <i class="${bookmarked?'fa-solid':'fa-regular'} fa-star"></i>
          </button>
        </header>
        <div class="mt-1 text-sm text-slate-500">${a.category}・更新 ${fmtDate(a.updated)}</div>
        <p class="mt-2 text-sm line-clamp-3">${a.summary}</p>
        <div class="mt-3 flex flex-wrap gap-2 text-xs">${a.tags.map(t=>`<span class='px-2 py-1 rounded-full bg-slate-100 dark:bg-slate-700'>#${t}</span>`).join('')}</div>
        <div class="mt-4 flex gap-2">
          <a href="#/a/${a.slug}" class="inline-flex items-center gap-2 px-3 py-2 rounded-xl bg-indigo-600 text-white text-sm hover:opacity-90"><i class="fa-solid fa-circle-info"></i> 詳細</a>
          <button class="copy-link inline-flex items-center gap-2 px-3 py-2 rounded-xl border border-slate-300 dark:border-slate-700 text-sm hover:bg-slate-100 dark:hover:bg-slate-800" data-link="${location.origin+location.pathname}#/a/${a.slug}"><i class="fa-solid fa-link"></i>リンク</button>
        </div>
      </article>
    `;
  }

  function renderPager(total){
    const pager = $('#pager');
    const pages = Math.max(1, Math.ceil(total/state.perPage));
    state.page = Math.min(state.page, pages);
    let html='';
    for(let i=1;i<=pages;i++){
      html += `<button class="px-3 py-1 rounded-lg border ${i===state.page?'bg-indigo-600 text-white border-indigo-600':'border-slate-300 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800'}" data-page="${i}">${i}</button>`;
    }
    pager.innerHTML = html;
    $$('#pager button').forEach(b=> b.addEventListener('click',()=>{ state.page=Number(b.dataset.page); syncList(false); }));
  }

  function syncList(scrollTop=true){
    const list = filterArticles();
    $('#resultCount').textContent = list.length;
    renderPager(list.length);

    const start=(state.page-1)*state.perPage;
    const pageItems=list.slice(start, start+state.perPage);
    $('#cards').innerHTML = pageItems.map(createCard).join('');

    // events
    $$('.bookmark').forEach(b=> b.addEventListener('click',()=>{ toggleBookmark(b.dataset.slug); syncList(false); }));
    $$('.copy-link').forEach(b=> b.addEventListener('click',()=> copyText(b.dataset.link)));

    if(scrollTop) window.scrollTo({top:0, behavior:'smooth'});
  }

  // =================
  // 記事ページ描画
  // =================
  function renderArticle(slug){
    const a = slugToArticle(slug);
    if(!a){ location.hash = ''; return; }

    // breadcrumb
    $('#breadcrumb').innerHTML = `<a class="underline" href="#">ホーム</a> / <span class="text-slate-600">${a.category}</span>`;

    // title & meta
    $('#articleTitle').textContent = a.title;
    $('#articleMeta').innerHTML = `
      <span><i class="fa-regular fa-calendar"></i> 更新 ${fmtDate(a.updated)}</span>
      <span class="mx-1">•</span>
      <span><i class="fa-regular fa-user"></i> ${a.author}</span>
      <span class="mx-1">•</span>
      <span><i class="fa-solid fa-folder"></i> ${a.category}</span>
    `;

    // content
    const container = $('#articleContent');
    container.innerHTML = a.content;

    // tags
    $('#articleTags').innerHTML = a.tags.map(t=>`<a href="#" data-tag="${t}" class="px-3 py-1 rounded-full border border-slate-300 dark:border-slate-700 text-sm hover:bg-slate-100 dark:hover:bg-slate-800">#${t}</a>`).join('');
    $$('#articleTags a').forEach(el=> el.addEventListener('click',(e)=>{ e.preventDefault(); state.tag=el.dataset.tag; location.hash=''; }));

    // bookmark button
    const btnBM = $('#btnToggleBookmark');
    const setBM = ()=>{
      const marked = isBookmarked(a.slug);
      btnBM.innerHTML = `<i class="${marked?'fa-solid':'fa-regular'} fa-star me-1"></i>${marked?'保存済み':'ブックマーク'}`;
    };
    btnBM.onclick = ()=>{ toggleBookmark(a.slug); setBM(); };
    setBM();

    // copy link
    $('#btnCopyLink').onclick = ()=> copyText(location.href);

    // TOC
    buildTOC();

    // JSON-LD
    updateLDJSON(a);

    // history
    pushHistory(a.slug);
  }

  function buildTOC(){
    const toc = $('#toc');
    const headings = $$('#articleContent h2, #articleContent h3');
    if(headings.length===0){ toc.innerHTML = '<div class="text-slate-500 text-sm">見出しがありません</div>'; return; }
    let html='';
    headings.forEach(h=>{
      if(!h.id) h.id = h.textContent.trim().toLowerCase().replace(/[^a-z0-9一-龥ぁ-んァ-ヶー]+/g,'-');
      const indent = h.tagName==='H3' ? 'ms-4' : '';
      html += `<a href="#${h.id}" class="${indent} hover:text-indigo-600">${h.textContent}</a>`;
    });
    toc.innerHTML = html;

    const observer = new IntersectionObserver((entries)=>{
      entries.forEach(e=>{
        if(e.isIntersecting){
          $$('#toc a').forEach(a=>a.classList.remove('active'));
          const a = $(`#toc a[href="#${e.target.id}"]`);
          if(a) a.classList.add('active');
        }
      });
    }, {rootMargin: '0px 0px -70% 0px'});
    headings.forEach(h=> observer.observe(h));
  }

  function updateLDJSON(a){
    const obj = {
      '@context':'https://schema.org',
      '@type':'Article',
      headline: a.title,
      dateModified: a.updated,
      author: { '@type':'Organization', name: a.author },
      keywords: a.tags.join(','),
      articleSection: a.category,
      url: location.href
    };
    $('#ldjson').textContent = JSON.stringify(obj);
  }

  // ============
  //  ルーター
  // ============
  function route(){
    const hash = location.hash.slice(1);
    if(hash.startsWith('/a/')){
      const slug = hash.split('/')[2];
      $('#view-home').classList.add('hidden');
      $('#view-article').classList.remove('hidden');
      renderArticle(slug);
      window.scrollTo({top:0, behavior:'instant'});
    }else{
      $('#view-article').classList.add('hidden');
      $('#view-home').classList.remove('hidden');
      syncList();
    }
  }

  window.addEventListener('hashchange', route);

  // ============
  //  便利機能
  // ============
  function copyText(text){
    navigator.clipboard.writeText(text).then(()=>{
      toast('リンクをコピーしました');
    }, ()=>{
      prompt('コピーできない場合は手動で選択してコピーしてください:', text);
    });
  }

  function toast(msg){
    const t = document.createElement('div');
    t.textContent = msg;
    t.className = 'fixed left-1/2 -translate-x-1/2 bottom-6 z-50 bg-black/80 text-white px-4 py-2 rounded-xl text-sm';
    document.body.appendChild(t);
    setTimeout(()=>{ t.remove(); }, 1600);
  }

  function randomArticle(){
    const a = ARTICLES[Math.floor(Math.random()*ARTICLES.length)];
    location.hash = `#/a/${a.slug}`;
  }

  // ==============
  //  I/O (JSON)
  // ==============
  function exportJSON(){
    const blob = new Blob([JSON.stringify(ARTICLES, null, 2)], {type:'application/json'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'mini-encyclopedia.json'; a.click();
    URL.revokeObjectURL(url);
  }

  function importJSON(file){
    const reader = new FileReader();
    reader.onload = (e)=>{
      try{
        const data = JSON.parse(e.target.result);
        if(Array.isArray(data)){
          // 形式が正しければ差し替え
          if(data.every(x=>x.slug && x.title && x.content)){
            ARTICLES.length = 0; // 破壊的更新
            data.forEach(x=> ARTICLES.push(x));
            init();
            toast('JSONを読み込みました');
          }else{
            alert('スキーマが不正です。slug/title/content は必須です。');
          }
        }else{
          alert('配列形式のJSONが必要です');
        }
      }catch(err){
        alert('JSONの解析に失敗しました: '+err.message);
      }
    };
    reader.readAsText(file);
  }

  // ============
  //  初期化
  // ============
  function init(){
    // 年
    $('#year').textContent = new Date().getFullYear();

    // カテゴリ・タグバー
    renderCategories();
    renderTagsBar();

    // イベント
    $('#search').addEventListener('input', (e)=>{ state.q = e.target.value.trim(); state.page=1; syncList(); });
    $('#category').addEventListener('change', (e)=>{ state.category = e.target.value; state.page=1; syncList(); });
    $('#sort').addEventListener('change', (e)=>{ state.sort = e.target.value; state.page=1; syncList(); });
    $('#btnRandom').addEventListener('click', randomArticle);
    $('#btnBookmarks').addEventListener('click', ()=>{
      const bms = getBookmarks();
      if(bms.length===0){ toast('ブックマークはまだありません'); return; }
      const first = slugToArticle(bms[0]);
      if(first) location.hash = `#/a/${first.slug}`;
    });
    $('#btnHome').addEventListener('click', ()=>{ location.hash=''; });

    // ダークモード切替
    $('#btnDark').addEventListener('click', ()=>{
      const root = document.documentElement;
      const isDark = root.classList.toggle('dark');
      localStorage.setItem('theme', isDark? 'dark':'light');
    });

    // JSON I/O
    $('#btnExport').addEventListener('click', exportJSON);
    $('#fileImport').addEventListener('change', (e)=>{ const f=e.target.files?.[0]; if(f) importJSON(f); e.target.value=''; });

    // 初回描画
    route();
  }

  document.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>

XLogpro.html(ツイートまとめサイト)

<!DOCTYPE html>
<html lang="ja" data-theme="light" style="--cols:3; --card-h:640px; --accent:#2563eb">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Xlog Pro — HTMLだけで動く自動ツイートまとめ</title>
  <link rel="preconnect" href="https://platform.twitter.com" crossorigin>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
  <meta name="description" content="HTMLだけ/APIキー不要のX(Twitter)まとめボード。プロフィール・ハッシュタグ・検索・リストを好きな列で配置し、JSON/HTML書き出しや手動ランキング、ボード切替に対応。">
  <style>
    :root{
      --bg: #0b0e14; --panel:#111827; --muted:#9aa4b2; --text:#e5e7eb; --border:#1f2937; --chip:#141a23; --card:#0f172a; --btn:#1f2937; --btn-text:#e5e7eb; --link:#60a5fa;
    }
    [data-theme="light"]{ --bg:#f8fafc; --panel:#ffffff; --muted:#64748b; --text:#0f172a; --border:#e2e8f0; --chip:#f1f5f9; --card:#ffffff; --btn:#0f172a; --btn-text:#ffffff; --link:#1d9bf0; }
    *{box-sizing:border-box}
    body{margin:0;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji"}
    header{position:sticky;top:0;z-index:10;background:var(--panel);border-bottom:1px solid var(--border)}
    .wrap{max-width:1280px;margin:0 auto;padding:12px 16px}
    .row{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
    .brand{display:flex;gap:10px;align-items:center;font-weight:800}
    .brand i{color:var(--accent)}
    .muted{color:var(--muted)}
    .pill{display:inline-flex;gap:8px;align-items:center;background:var(--chip);border:1px solid var(--border);border-radius:999px;padding:6px 10px}
    .input, select, textarea{background:transparent;border:1px solid var(--border);border-radius:10px;padding:8px 10px;color:var(--text)}
    textarea{min-height:88px;width:100%;}
    input[type="text"].input{min-width:220px}
    button{cursor:pointer;border:none}
    .btn{background:var(--btn);color:var(--btn-text);padding:9px 12px;border-radius:12px}
    .btn.secondary{background:transparent;color:var(--text);border:1px solid var(--border)}
    .btn.ghost{background:transparent;color:var(--text)}
    .btn.badge{padding:6px 10px;border-radius:999px}
    .grid{display:grid;grid-template-columns:320px 1fr;gap:16px}
    @media (max-width:1080px){.grid{grid-template-columns:1fr}}
    aside{background:var(--panel);border:1px solid var(--border);border-radius:16px;padding:14px;position:sticky;top:72px;height:max-content}
    h2{margin:6px 0 12px 0;font-size:18px}
    .list{display:flex;flex-direction:column;gap:12px}
    .card{background:var(--card);border:1px solid var(--border);border-radius:16px;overflow:hidden}
    .card .head{display:flex;justify-content:space-between;align-items:center;padding:12px 14px;border-bottom:1px solid var(--border)}
    .card .head .title{display:flex;gap:8px;align-items:center;font-weight:700}
    .card .body{padding:0;min-height:var(--card-h)}
    .sources{display:flex;flex-wrap:wrap;gap:8px}
    .chip{background:var(--chip);border:1px solid var(--border);border-radius:999px;padding:6px 10px;display:flex;gap:8px;align-items:center}
    .chip b{color:var(--accent)}
    .columns{display:grid;grid-template-columns:repeat(var(--cols),1fr);gap:16px}
    @media (max-width:1200px){:root{--cols:2}}
    @media (max-width:860px){:root{--cols:1}}
    .drag{cursor:grab}
    .toolbar{display:flex;gap:8px;flex-wrap:wrap}
    .footer{padding:24px 16px;color:var(--muted);text-align:center}
    .kbd{font-family:ui-monospace, Menlo, Monaco, Consolas; background:var(--chip); border:1px solid var(--border); padding:2px 6px; border-radius:6px}
    .danger{color:#ef4444}
    .accent{color:var(--accent)}
    .section{background:var(--panel);border:1px solid var(--border);border-radius:16px;padding:14px}
    .help{font-size:13px;color:var(--muted)}
    .label{font-size:12px;color:var(--muted)}
    .tiny{font-size:12px}
    .row-wrap{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
    .w-100{width:100%}
    .space{height:8px}
  </style>
</head>
<body>
  <header>
    <div class="wrap row">
      <div class="brand"><i class="fa-solid fa-wave-square"></i> Xlog <span class="muted">Pro</span></div>
      <div class="pill">
        <i class="fa-solid fa-diagram-project"></i>
        <select id="boardSelect" title="ボード切替"></select>
        <button id="boardNew" class="btn badge secondary" title="新規ボード"><i class="fa-solid fa-plus"></i></button>
        <button id="boardRename" class="btn badge secondary" title="名前変更"><i class="fa-solid fa-pen"></i></button>
        <button id="boardDelete" class="btn badge secondary danger" title="削除"><i class="fa-regular fa-trash-can"></i></button>
      </div>
      <div class="pill" title="テーマ切替"><i class="fa-solid fa-circle-half-stroke"></i>
        <label class="row-wrap"><input id="themeToggle" type="checkbox" /> ダーク</label>
      </div>
      <div class="pill" title="アクセントカラー">
        <i class="fa-solid fa-palette"></i>
        <input id="accentPicker" type="color" value="#2563eb" />
      </div>
      <div class="pill" title="列数"><i class="fa-solid fa-table-columns"></i>
        <input id="colsRange" type="range" min="1" max="4" step="1" value="3"/>
        <span id="colsVal" class="tiny"></span>
      </div>
      <div class="pill" title="カード高さ"><i class="fa-solid fa-up-down"></i>
        <input id="heightRange" type="range" min="360" max="1200" step="40" value="640"/>
        <span id="heightVal" class="tiny"></span>
      </div>
      <div class="pill" title="自動再読み込み">
        <label class="row-wrap"><input id="autoRefreshToggle" type="checkbox"/> 自動</label>
        <select id="refreshMinutes">
          <option value="3">3分</option>
          <option value="5" selected>5分</option>
          <option value="10">10分</option>
          <option value="30">30分</option>
        </select>
      </div>
      <div class="pill help tiny">ショートカット: <span class="kbd">N</span> 追加 / <span class="kbd">R</span> 再描画 / <span class="kbd">G</span> グリッド- / <span class="kbd">H</span> 高さ-</div>
    </div>
  </header>

  <main class="wrap grid">
    <aside>
      <div class="list">
        <div class="section">
          <h2>ソースを追加</h2>
          <div class="toolbar row-wrap">
            <select id="sourceType">
              <option value="profile">プロフィール</option>
              <option value="hashtag">ハッシュタグ</option>
              <option value="search">検索キーワード</option>
              <option value="list">リストURL</option>
            </select>
            <input id="sourceValue" class="input" type="text" placeholder="@username / #tag / キーワード / リストURL" />
            <input id="sourceLabel" class="input" type="text" placeholder="表示名(任意)" />
            <button id="addBtn" class="btn"><i class="fa-solid fa-plus"></i> 追加</button>
          </div>
          <div class="space"></div>
          <label class="label">まとめて追加(改行/カンマ区切りOK)</label>
          <textarea id="bulkArea" placeholder="@OpenAI, #UnrealEngine, Unity URP, https://twitter.com/i/lists/123...\n@EpicGames"></textarea>
          <div class="row-wrap">
            <button id="bulkAdd" class="btn secondary"><i class="fa-solid fa-download"></i> 取り込み</button>
            <button id="bulkClear" class="btn ghost"><i class="fa-solid fa-eraser"></i> クリア</button>
          </div>
          <p class="help" style="margin-top:8px">形式は自動判定:<span class="kbd">@id</span> → プロフィール、<span class="kbd">#tag</span> → ハッシュタグ、<span class="kbd">twitter.com/i/lists</span> → リスト、それ以外は検索。</p>
          <div class="space"></div>
          <div class="row-wrap help tiny">クイック追加:</div>
          <div class="row-wrap">
            <button class="btn badge secondary quick" data-type="hashtag" data-val="#UnrealEngine">#UnrealEngine</button>
            <button class="btn badge secondary quick" data-type="hashtag" data-val="#Unity3D">#Unity3D</button>
            <button class="btn badge secondary quick" data-type="search" data-val="VRM OR \"Meta Quest\"">VR/Quest</button>
            <button class="btn badge secondary quick" data-type="profile" data-val="@OpenAI">@OpenAI</button>
          </div>
        </div>

        <div class="section">
          <h2>保存・書き出し</h2>
          <div class="toolbar row-wrap">
            <button id="exportBtn" class="btn secondary"><i class="fa-solid fa-file-export"></i> JSON</button>
            <label class="btn secondary" for="importFile"><i class="fa-solid fa-file-import"></i> JSON読込</label>
            <input id="importFile" type="file" accept="application/json" hidden />
            <button id="exportHtmlBtn" class="btn"><i class="fa-regular fa-file-code"></i> 単一HTML</button>
            <button id="clearBtn" class="btn ghost danger"><i class="fa-regular fa-trash-can"></i> すべて削除</button>
          </div>
          <p class="help">単一HTML: いまのレイアウトと設定を埋め込んだ自立HTMLを生成します。</p>
        </div>

        <div class="section">
          <h2>手動ランキング</h2>
          <div class="toolbar row-wrap">
            <input id="tweetUrl" class="input" type="text" placeholder="ツイートURLを貼り付け" />
            <button id="addTweetBtn" class="btn"><i class="fa-brands fa-x-twitter"></i> 追加</button>
          </div>
          <label class="label">メモ(任意・次回以降も保持)</label>
          <textarea id="tweetNote" placeholder="このツイートの要点やタグ(例: #UE5 #VRM)"></textarea>
          <p class="help">※HTMLのみの制約で自動集計は不可。URLをカード化して手動で順序を決められます。</p>
        </div>

        <div class="section">
          <h2>RSS生成(ランキング→RSS)</h2>
          <div class="toolbar row-wrap">
            <input id="rssTitle" class="input" type="text" placeholder="RSSタイトル(例: Xlogランキング)"/>
            <button id="rssExport" class="btn secondary"><i class="fa-solid fa-rss"></i> RSSを書き出し</button>
          </div>
          <p class="help">ランキングに登録したツイートURLから簡易RSS(XML)を生成し、ファイルとして保存します。</p>
        </div>

        <div class="section">
          <h2>ヘルプ</h2>
          <div class="help">
            ・列の並べ替えはカードの <span class="kbd">⋯</span> アイコンをドラッグ。<br>
            ・<span class="kbd">R</span> で全カラムを再描画。<br>
            ・URLハッシュ <span class="kbd">#data=</span> に設定をBase64で埋め込んで共有可能(メニューから自動生成予定)。
          </div>
        </div>
      </div>
    </aside>

    <section>
      <div class="card" style="margin-bottom:16px">
        <div class="head">
          <div class="title"><i class="fa-solid fa-layer-group drag"></i> マイまとめ <span class="muted tiny" id="boardInfo"></span></div>
          <div class="sources" id="activeChips"></div>
        </div>
        <div class="body" style="padding:14px">
          <div id="columns" class="columns"></div>
        </div>
      </div>

      <div class="card">
        <div class="head">
          <div class="title"><i class="fa-regular fa-star"></i> 手動ランキング</div>
          <div class="help">ドラッグで順序変更/🗑で削除/✎でメモ編集</div>
        </div>
        <div class="body" style="padding:14px">
          <div id="ranking" class="columns"></div>
        </div>
      </div>

      <div class="footer">Xlog Pro v2 — HTML Only / Embedded Timelines. No API keys. <span class="muted">Made for you.</span></div>
    </section>
  </main>

  <script async src="https://platform.twitter.com/widgets.js"></script>
  <script>
    // ========== 基本ユーティリティ ==========
    const $ = (s, d=document)=>d.querySelector(s);
    const $$ = (s, d=document)=>Array.from(d.querySelectorAll(s));

    const defaultBoard = ()=>({sources:[], tweets:[]});
    const defaultState = ()=>({
      version:2,
      dark:false,
      accent:'#2563eb',
      autoRefresh:false,
      minutes:5,
      columns:3,
      cardHeight:640,
      boards:{'Default': defaultBoard()},
      activeBoard:'Default'
    });

    const store = {
      key: 'xlog-pro-v2',
      load(){
        try{ return JSON.parse(localStorage.getItem(this.key)) || defaultState(); }
        catch(e){ return defaultState(); }
      },
      save(v){ localStorage.setItem(this.key, JSON.stringify(v)); }
    };

    function migrate(s){
      const base = defaultState();
      if (!s || typeof s !== 'object') return base;
      // v1互換(sources/tweets直下 → boards.Default)
      if (s.sources || s.tweets){
        base.boards.Default.sources = s.sources||[];
        base.boards.Default.tweets = s.tweets||[];
      }
      // 既存キー上書き
      for (const k of ['dark','accent','autoRefresh','minutes','columns','cardHeight','boards','activeBoard']){
        if (k in s) base[k]=s[k];
      }
      return base;
    }

    // ハッシュ (#data=BASE64) から読み込み
    function loadFromHash(){
      const h = location.hash || '';
      if (!h.startsWith('#data=')) return null;
      try{
        const b64 = decodeURIComponent(h.slice(6));
        const json = atob(b64);
        return JSON.parse(json);
      }catch(e){ return null; }
    }

    let embedded = (typeof window.__XLOG_INITIAL_STATE__!== 'undefined') ? window.__XLOG_INITIAL_STATE__ : null;
    if (!embedded){
      const el = document.getElementById('xlog-init');
      if (el) { try{ embedded = JSON.parse(el.textContent); }catch(_e){} }
    }

    let state = migrate( embedded || loadFromHash() || store.load() );

    // ========== テーマ/アクセント/レイアウト適用 ==========
    function applySkin(){
      document.documentElement.setAttribute('data-theme', state.dark ? 'dark' : 'light');
      document.documentElement.style.setProperty('--cols', state.columns);
      document.documentElement.style.setProperty('--card-h', state.cardHeight+'px');
      document.documentElement.style.setProperty('--accent', state.accent || '#2563eb');
      $('#themeToggle').checked = !!state.dark;
      $('#colsRange').value = String(state.columns);
      $('#colsVal').textContent = state.columns+'列';
      $('#heightRange').value = String(state.cardHeight);
      $('#heightVal').textContent = state.cardHeight+'px';
      $('#accentPicker').value = state.accent || '#2563eb';
    }

    // ========== X埋め込み ==========
    function waitTwttr(){
      return new Promise(res=>{
        if (window.twttr && twttr.widgets) return res();
        const timer = setInterval(()=>{ if(window.twttr && twttr.widgets){ clearInterval(timer); res(); } }, 200);
      });
    }

    function timelineOptions(){
      return {
        height: state.cardHeight,
        theme: state.dark ? 'dark' : 'light',
        chrome: 'nofooter noborders transparent',
        linkColor: getComputedStyle(document.documentElement).getPropertyValue('--link').trim() || '#1d9bf0'
      };
    }

    async function createTimeline(el, src){
      await waitTwttr();
      const opts = timelineOptions();
      const t = (src.type||'profile');
      if (t==='profile'){
        const screenName = src.value.replace(/^@/,'');
        return twttr.widgets.createTimeline({ sourceType:'profile', screenName }, el, opts);
      }
      if (t==='list'){
        return twttr.widgets.createTimeline({ sourceType:'url', url: src.value }, el, opts);
      }
      if (t==='hashtag'){
        const tag = src.value.replace(/^#/,'');
        const url = `https://twitter.com/hashtag/${encodeURIComponent(tag)}?f=live`;
        return twttr.widgets.createTimeline({ sourceType:'url', url }, el, opts);
      }
      if (t==='search'){
        const url = `https://twitter.com/search?q=${encodeURIComponent(src.value)}&f=live`;
        return twttr.widgets.createTimeline({ sourceType:'url', url }, el, opts);
      }
    }

    // ========== 現在ボードの参照 ==========
    function board(){ return state.boards[state.activeBoard] || (state.boards[state.activeBoard]=defaultBoard()); }

    // ========== 描画 ==========
    function chipNode(src, idx){
      const chip = document.createElement('span');
      chip.className='chip';
      const kind = {profile:'@',hashtag:'#',search:'検索:',list:'リスト'}[src.type] || '';
      chip.innerHTML = `<b>${kind}</b> ${src.label || src.value} <a class="muted" href="${openUrl(src)}" target="_blank" title="Xで開く"><i class="fa-solid fa-arrow-up-right-from-square"></i></a> <button title="削除" data-del="${idx}" class="muted"><i class="fa-solid fa-xmark"></i></button>`;
      chip.querySelector('button').onclick = ()=>{ board().sources.splice(idx,1); store.save(state); renderAll(); };
      return chip;
    }

    function openUrl(src){
      if (src.type==='profile') return `https://twitter.com/${src.value.replace(/^@/,'')}`;
      if (src.type==='hashtag') return `https://twitter.com/hashtag/${src.value.replace(/^#/,'')}`;
      if (src.type==='list') return src.value;
      return `https://twitter.com/search?q=${encodeURIComponent(src.value)}&f=live`;
    }

    function columnCard(src, idx){
      const card = document.createElement('div');
      card.className='card';
      card.draggable=true; card.dataset.idx=idx;
      card.innerHTML = `
        <div class="head">
          <div class="title"><i class="fa-solid fa-grip-vertical drag"></i> ${src.label || prettyLabel(src)}</div>
          <div class="toolbar">
            <a class="btn ghost" href="${openUrl(src)}" target="_blank" title="Xで開く"><i class="fa-solid fa-arrow-up-right-from-square"></i></a>
            <button class="btn ghost" title="再読み込み" data-refresh="${idx}"><i class="fa-solid fa-rotate"></i></button>
            <button class="btn ghost danger" title="削除" data-remove="${idx}"><i class="fa-regular fa-trash-can"></i></button>
          </div>
        </div>
        <div class="body"><div class="embed" style="min-height:120px"></div></div>`;

      // DnD 並べ替え
      card.addEventListener('dragstart', e=>{ e.dataTransfer.setData('text/plain', idx); card.style.opacity='0.6'; });
      card.addEventListener('dragend', ()=>{ card.style.opacity='1'; });
      card.addEventListener('dragover', e=>{ e.preventDefault(); card.style.outline='2px dashed var(--accent)'; });
      card.addEventListener('dragleave', ()=>{ card.style.outline='none'; });
      card.addEventListener('drop', e=>{
        e.preventDefault(); card.style.outline='none';
        const from = +e.dataTransfer.getData('text/plain');
        const to = +card.dataset.idx;
        if (from===to) return;
        const arr = board().sources;
        const [moved] = arr.splice(from,1);
        arr.splice(to,0,moved);
        store.save(state); renderAll();
      });

      // 操作
      card.querySelector('[data-remove]')?.addEventListener('click', ()=>{ board().sources.splice(idx,1); store.save(state); renderAll(); });
      card.querySelector('[data-refresh]')?.addEventListener('click', ()=>{ mountTimeline(card, src); });
      // 初回描画
      mountTimeline(card, src);
      return card;
    }

    function mountTimeline(card, src){
      const holder = card.querySelector('.embed');
      holder.innerHTML = '<div style="padding:14px" class="muted">読み込み中…</div>';
      createTimeline(holder, src).catch(()=>{
        holder.innerHTML = '<div style="padding:14px" class="danger">読み込みに失敗しました。値を確認してください。</div>';
      });
    }

    function prettyLabel(src){
      if (src.type==='profile') return '@'+src.value.replace(/^@/,'');
      if (src.type==='hashtag') return '#'+src.value.replace(/^#/,'');
      if (src.type==='search') return '検索: '+src.value;
      if (src.type==='list') return 'リスト';
      return src.value;
    }

    function renderAll(){
      // ボード情報
      const info = $('#boardInfo');
      const b = board();
      info.textContent = `(${state.activeBoard}|${b.sources.length}列 / ${b.tweets.length}件)`;

      // チップ
      const chips = $('#activeChips'); chips.innerHTML='';
      b.sources.forEach((s,i)=> chips.appendChild(chipNode(s,i)) );
      // カラム
      const col = $('#columns'); col.innerHTML='';
      b.sources.forEach((s,i)=> col.appendChild(columnCard(s,i)) );
      // ランキング
      renderRanking();
    }

    // ========== ランキング ==========
    function parseTweetId(url){ const m = (url||'').match(/status\/(\d{5,})/); return m? m[1] : null; }
    function tweetUrlFromId(id){ return `https://twitter.com/i/web/status/${id}`; }

    async function addTweet(url, note){
      const id = parseTweetId(url);
      if (!id) return alert('ツイートURLが正しくありません');
      board().tweets.push({id, note: (note||'')});
      store.save(state); renderRanking();
    }

    async function renderRanking(){
      await waitTwttr();
      const root = $('#ranking'); root.innerHTML='';
      const arr = board().tweets;
      arr.forEach((t, idx)=>{
        const card = document.createElement('div'); card.className='card'; card.draggable=true; card.dataset.idx=idx;
        card.innerHTML = `
          <div class="head">
            <div class="title"><i class="fa-solid fa-grip-vertical drag"></i> エントリ #${idx+1}</div>
            <div class="toolbar">
              <button class="btn ghost" data-edit="${idx}" title="メモ編集"><i class="fa-regular fa-pen-to-square"></i></button>
              <a class="btn ghost" href="${tweetUrlFromId(t.id)}" target="_blank" title="Xで開く"><i class="fa-solid fa-arrow-up-right-from-square"></i></a>
              <button class="btn ghost danger" title="削除" data-del-rank="${idx}"><i class="fa-regular fa-trash-can"></i></button>
            </div>
          </div>
          <div class="body">
            <div class="embed"></div>
            <div style="padding:10px 14px;border-top:1px solid var(--border)" class="tiny"><span class="muted">メモ:</span> <span class="note">${escapeHtml(t.note||'')}</span></div>
          </div>`;

        // イベント
        card.querySelector('[data-del-rank]')?.addEventListener('click', ()=>{ arr.splice(idx,1); store.save(state); renderRanking(); });
        card.querySelector('[data-edit]')?.addEventListener('click', ()=>{
          const newNote = prompt('メモを編集', t.note||'');
          if (newNote!==null){ t.note = newNote; store.save(state); renderRanking(); }
        });

        // DnD 並べ替え
        card.addEventListener('dragstart', e=>{ e.dataTransfer.setData('text/plain', 'rank:'+idx); card.style.opacity='0.6'; });
        card.addEventListener('dragend', ()=>{ card.style.opacity='1'; });
        card.addEventListener('dragover', e=>{ e.preventDefault(); card.style.outline='2px dashed var(--accent)'; });
        card.addEventListener('dragleave', ()=>{ card.style.outline='none'; });
        card.addEventListener('drop', e=>{
          e.preventDefault(); card.style.outline='none';
          const data = e.dataTransfer.getData('text/plain'); if (!data.startsWith('rank:')) return;
          const from = +data.split(':')[1]; const to = +card.dataset.idx;
          const [moved] = arr.splice(from,1); arr.splice(to,0,moved);
          store.save(state); renderRanking();
        });

        const holder = card.querySelector('.embed');
        twttr.widgets.createTweet(t.id, holder, { theme: state.dark ? 'dark' : 'light' });
        root.appendChild(card);
      });
    }

    function escapeHtml(s){ return (s||'').replace(/[&<>"']/g, m=> ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[m])); }

    // ========== 自動再描画 ==========
    let refreshTimer = null;
    function applyAutoRefresh(){
      if (refreshTimer) { clearInterval(refreshTimer); refreshTimer=null; }
      if (state.autoRefresh){
        const ms = Math.max(1, +state.minutes) * 60 * 1000;
        refreshTimer = setInterval(()=>{
          $$('#columns .card').forEach((card, i)=>{
            const src = board().sources[i]; if (src) mountTimeline(card, src);
          });
        }, ms);
      }
    }

    // ========== ボード管理 ==========
    function refreshBoardSelect(){
      const sel = $('#boardSelect'); sel.innerHTML='';
      Object.keys(state.boards).forEach(name=>{
        const opt = document.createElement('option'); opt.value=name; opt.textContent=name; sel.appendChild(opt);
      });
      sel.value = state.activeBoard;
    }

    function addBoard(name){
      if (!name) return;
      if (state.boards[name]) return alert('同名のボードが存在します');
      state.boards[name] = defaultBoard(); state.activeBoard = name; store.save(state);
      refreshBoardSelect(); renderAll();
    }

    function renameBoard(newName){
      if (!newName) return;
      if (state.boards[newName]) return alert('同名のボードが存在します');
      const old = state.activeBoard;
      state.boards[newName] = state.boards[old];
      delete state.boards[old];
      state.activeBoard = newName; store.save(state);
      refreshBoardSelect(); renderAll();
    }

    function deleteBoard(){
      const names = Object.keys(state.boards);
      if (names.length<=1) return alert('最後のボードは削除できません');
      if (!confirm(`ボード「${state.activeBoard}」を削除しますか?`)) return;
      delete state.boards[state.activeBoard];
      state.activeBoard = Object.keys(state.boards)[0];
      store.save(state); refreshBoardSelect(); renderAll();
    }

    // ========== 共有(URLハッシュ生成) ==========
    function exportHashUrl(){
      const cloned = JSON.parse(JSON.stringify(state));
      const json = JSON.stringify(cloned);
      const b64 = btoa(json);
      const url = location.origin + location.pathname + '#data=' + encodeURIComponent(b64);
      return url;
    }

    // ========== 単一HTML出力 ==========
    function download(filename, text){
      const blob = new Blob([text], {type:'text/html'});
      const a = document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=filename; a.click(); URL.revokeObjectURL(a.href);
    }

    function exportSingleHtml(){
      // 現在のHTMLに初期状態スクリプトを差し込む
      let html = document.documentElement.outerHTML;
      const idx = html.indexOf('<head>');
      const inject = `<head>\n  <script>window.__XLOG_INITIAL_STATE__=${JSON.stringify(state)}<\/script>`;
      if (idx>=0){ html = html.replace('<head>', inject); }
      download('xlog-pro.html', '<!DOCTYPE html>\n' + html);
    }

    // ========== RSS生成 ==========
    function exportRss(){
      const title = $('#rssTitle').value.trim() || 'Xlog Ranking';
      const items = board().tweets.map(t=>({
        title: (t.note||'Tweet '+t.id).replace(/[\r\n]+/g,' ').slice(0,120),
        link: tweetUrlFromId(t.id),
        guid: t.id,
        description: escapeHtml(t.note||''),
        pubDate: new Date().toUTCString()
      }));
      const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0"><channel>\n<title>${escapeXml(title)}</title>\n<link>${escapeXml(location.href)}</link>\n<description>Generated by Xlog Pro</description>\n${items.map(i=>`<item><title>${escapeXml(i.title)}</title><link>${escapeXml(i.link)}</link><guid isPermaLink=\"false\">${escapeXml(i.guid)}</guid><description>${escapeXml(i.description)}</description><pubDate>${i.pubDate}</pubDate></item>`).join('')}\n</channel></rss>`;
      const blob = new Blob([xml], {type:'application/rss+xml'});
      const a = document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='xlog-ranking.xml'; a.click(); URL.revokeObjectURL(a.href);
    }

    function escapeXml(s){ return (s||'').replace(/[<>&\"']/g, m=> ({'<':'&lt;','>':'&gt;','&':'&amp;','\"':'&quot;','\'':'&apos;'}[m])); }

    // ========== 入力ヘルパ ==========
    function detectType(v){
      if (/^@/.test(v)) return 'profile';
      if (/^#/.test(v)) return 'hashtag';
      if (/twitter\.com\/i\/lists\//.test(v)) return 'list';
      return 'search';
    }

    function addSource(type, value, label){
      const src = {type, value:value.trim(), label:(label||'').trim()};
      board().sources.push(src); store.save(state); renderAll();
    }

    function bulkAddFromText(txt){
      const parts = txt.split(/[\n,]+/).map(s=>s.trim()).filter(Boolean);
      let count = 0;
      for (const p of parts){ addSource(detectType(p), p, ''); count++; }
      return count;
    }

    // ========== キーイベント ==========
    function setupShortcuts(){
      window.addEventListener('keydown', (e)=>{
        if (['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) return;
        if (e.key==='n' || e.key==='N'){ $('#sourceValue').focus(); }
        if (e.key==='r' || e.key==='R'){ renderAll(); }
        if (e.key==='g' || e.key==='G'){ state.columns=Math.max(1,state.columns-1); applySkin(); store.save(state); }
        if (e.key==='h' || e.key==='H'){ state.cardHeight=Math.max(360,state.cardHeight-40); applySkin(); store.save(state); renderAll(); }
      });
    }

    // ========== 設定と起動 ==========
    window.addEventListener('DOMContentLoaded', ()=>{
      // スキン
      applySkin();

      // ボード選択
      refreshBoardSelect();
      $('#boardSelect').addEventListener('change', (e)=>{ state.activeBoard = e.target.value; store.save(state); renderAll(); });
      $('#boardNew').addEventListener('click', ()=>{ const name = prompt('新しいボード名','Board '+(Object.keys(state.boards).length+1)); addBoard(name); });
      $('#boardRename').addEventListener('click', ()=>{ const name = prompt('新しい名前', state.activeBoard); if (name) renameBoard(name); });
      $('#boardDelete').addEventListener('click', deleteBoard);

      // テーマ/アクセント/レイアウト
      $('#themeToggle').addEventListener('change', e=>{ state.dark = e.target.checked; store.save(state); applySkin(); renderAll(); });
      $('#accentPicker').addEventListener('input', e=>{ state.accent = e.target.value; store.save(state); applySkin(); });
      $('#colsRange').addEventListener('input', e=>{ state.columns = +e.target.value; store.save(state); applySkin(); });
      $('#heightRange').addEventListener('input', e=>{ state.cardHeight = +e.target.value; store.save(state); applySkin(); renderAll(); });

      // ソース追加
      $('#addBtn').addEventListener('click', ()=>{
        const type = $('#sourceType').value;
        const val = $('#sourceValue').value.trim();
        const label = $('#sourceLabel').value.trim();
        if (!val) return alert('値を入力してください');
        addSource(type, val, label);
        $('#sourceValue').value=''; $('#sourceLabel').value='';
      });
      $$('.quick').forEach(btn=> btn.addEventListener('click', ()=> addSource(btn.dataset.type, btn.dataset.val, '')) );

      // まとめて追加
      $('#bulkAdd').addEventListener('click', ()=>{ const n = bulkAddFromText($('#bulkArea').value); alert(n+'件追加しました'); $('#bulkArea').value=''; });
      $('#bulkClear').addEventListener('click', ()=> $('#bulkArea').value='' );

      // ランキング
      $('#addTweetBtn').addEventListener('click', ()=>{
        const url = $('#tweetUrl').value.trim();
        const note = $('#tweetNote').value.trim();
        if (!url) return;
        addTweet(url, note); $('#tweetUrl').value=''; $('#tweetNote').value='';
      });

      // 設定
      $('#autoRefreshToggle').checked = !!state.autoRefresh;
      $('#refreshMinutes').value = String(state.minutes||5);
      $('#autoRefreshToggle').addEventListener('change', e=>{ state.autoRefresh = e.target.checked; store.save(state); applyAutoRefresh(); });
      $('#refreshMinutes').addEventListener('change', e=>{ state.minutes = +e.target.value; store.save(state); applyAutoRefresh(); });

      // 書き出し/読み込み
      $('#exportBtn').addEventListener('click', ()=>{
        const blob = new Blob([JSON.stringify(state,null,2)], {type:'application/json'});
        const a = document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='xlog-pro-config.json'; a.click(); URL.revokeObjectURL(a.href);
      });
      $('#importFile').addEventListener('change', e=>{
        const file = e.target.files?.[0]; if (!file) return;
        const fr = new FileReader();
        fr.onload = () => {
          try{ const obj = JSON.parse(fr.result); state = migrate(obj); store.save(state); applySkin(); refreshBoardSelect(); renderAll(); applyAutoRefresh(); }
          catch(err){ alert('JSONの読み込みに失敗しました'); }
        };
        fr.readAsText(file);
      });
      $('#exportHtmlBtn').addEventListener('click', exportSingleHtml);
      $('#clearBtn').addEventListener('click', ()=>{
        if (!confirm('現在のボードのソースとランキングを削除しますか?')) return;
        const b = board(); b.sources = []; b.tweets=[]; store.save(state); renderAll();
      });

      // RSS
      $('#rssExport').addEventListener('click', exportRss);

      // 初期描画
      renderAll();
      applyAutoRefresh();
      setupShortcuts();
    });
  </script>
</body>
</html>

推しログ – 推し活情報共有サービス

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>推しログ - 推し活情報共有サービス</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gradient-to-r from-purple-200 to-indigo-200">

  <!-- ヘッダー -->
  <header class="bg-purple-600 text-white p-4 shadow-lg">
    <div class="container mx-auto flex justify-between items-center">
      <h1 class="text-3xl font-bold"><i class="fa-solid fa-heart mr-2"></i>推しログ</h1>
      <nav class="space-x-4">
        <a href="#" class="hover:text-gray-200">ホーム</a>
        <a href="#" class="hover:text-gray-200">スケジュール</a>
        <a href="#" class="hover:text-gray-200">ニュース</a>
        <a href="#" class="hover:text-gray-200">ログイン</a>
      </nav>
    </div>
  </header>

  <!-- メインコンテンツ -->
  <main class="container mx-auto my-8 px-4">

    <!-- 推しスケジュール -->
    <section class="bg-white p-8 rounded-xl shadow-xl mb-8">
      <h2 class="text-2xl font-bold border-b pb-2 mb-4"><i class="fa-regular fa-calendar mr-2"></i>今月の推しスケジュール</h2>
      <ul class="space-y-3">
        <li class="flex justify-between items-center p-4 bg-gray-50 rounded-lg shadow">
          <span class="font-semibold">ライブ配信「推しの部屋」</span>
          <span class="text-gray-500">8/10(木) 20:00〜</span>
        </li>
        <li class="flex justify-between items-center p-4 bg-gray-50 rounded-lg shadow">
          <span class="font-semibold">ニューシングル発売日!</span>
          <span class="text-gray-500">8/15(火)</span>
        </li>
        <li class="flex justify-between items-center p-4 bg-gray-50 rounded-lg shadow">
          <span class="font-semibold">ファンクラブ限定イベント</span>
          <span class="text-gray-500">8/25(金) 18:30〜</span>
        </li>
      </ul>
      <button class="mt-4 bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded">もっと見る</button>
    </section>

    <!-- 最新推しニュース -->
    <section class="bg-white p-8 rounded-xl shadow-xl mb-8">
      <h2 class="text-2xl font-bold border-b pb-2 mb-4"><i class="fa-solid fa-newspaper mr-2"></i>最新推しニュース</h2>
      <article class="mb-6 border-b pb-4">
        <h3 class="font-semibold text-purple-700 mb-1">推しの新曲MVが公開!</h3>
        <p class="text-gray-600">待望の新曲MVが公式YouTubeチャンネルにて公開されました!視聴数も急上昇中!</p>
        <a href="#" class="text-blue-500 hover:underline">詳しく見る <i class="fa-solid fa-arrow-right ml-1"></i></a>
      </article>

      <article>
        <h3 class="font-semibold text-purple-700 mb-1">推し、テレビ番組に出演決定!</h3>
        <p class="text-gray-600">8/12(土)の「音楽バズ」にゲスト出演予定です。特別トークもお楽しみに!</p>
        <a href="#" class="text-blue-500 hover:underline">詳しく見る <i class="fa-solid fa-arrow-right ml-1"></i></a>
      </article>
      <button class="mt-4 bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded">もっと見る</button>
    </section>

    <!-- 推しメンバー紹介 -->
    <section class="bg-white p-8 rounded-xl shadow-xl">
      <h2 class="text-2xl font-bold border-b pb-2 mb-4"><i class="fa-solid fa-user-group mr-2"></i>推しメンバー紹介</h2>
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="text-center">
          <img src="https://via.placeholder.com/150" class="rounded-full mx-auto mb-2" alt="推し1">
          <h3 class="font-semibold">推しメン1</h3>
        </div>
        <div class="text-center">
          <img src="https://via.placeholder.com/150" class="rounded-full mx-auto mb-2" alt="推し2">
          <h3 class="font-semibold">推しメン2</h3>
        </div>
        <div class="text-center">
          <img src="https://via.placeholder.com/150" class="rounded-full mx-auto mb-2" alt="推し3">
          <h3 class="font-semibold">推しメン3</h3>
        </div>
        <div class="text-center">
          <img src="https://via.placeholder.com/150" class="rounded-full mx-auto mb-2" alt="推し4">
          <h3 class="font-semibold">推しメン4</h3>
        </div>
      </div>
    </section>

  </main>

  <!-- フッター -->
  <footer class="bg-gray-900 text-white text-center py-4 mt-8">
    <p class="text-sm">© 2024 推しログ. All rights reserved.</p>
  </footer>

</body>
</html>

Verse – 次世代ソーシャルネットワーク


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verse - 次世代ソーシャルネットワーク</title>
 <!-- SVG ファビコンを指定 -->
   <link rel="shortcut icon" href="favicon.ico">
  <!-- PNG版 -->
  <link rel="icon" type="image/png" href="favicon.png">
  <!-- SVG版 -->
  <link rel="icon" type="image/svg+xml" href="favicon.svg">



    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/rita@3.0.0/dist/rita.min.js"></script>
    <style>
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh;
        }
        .glass-effect { 
            background: rgba(255,255,255,0.25); 
            backdrop-filter: blur(10px); 
            border-radius: 10px; 
            border: 1px solid rgba(255,255,255,0.18);
        }
        .card-hover { transition: all 0.3s ease; }
        .card-hover:hover { 
            transform: translateY(-5px); 
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);
        }
        .gradient-text { 
            background: linear-gradient(45deg, #667eea, #764ba2); 
            -webkit-background-clip: text; 
            -webkit-text-fill-color: transparent; 
            background-clip: text;
        }
        .timeline-post { 
            background: white; 
            border-radius: 15px; 
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); 
            transition: all 0.3s ease; 
            border-left: 4px solid #667eea;
        }
        .timeline-post:hover { 
            transform: translateX(5px); 
            box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        }
        .profile-avatar { 
            width: 100px; 
            height: 100px; 
            border-radius: 50%; 
            object-fit: cover; 
            border: 4px solid white; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .btn-primary { 
            background: linear-gradient(45deg, #667eea, #764ba2); 
            border: none; 
            transition: all 0.3s ease;
        }
        .btn-primary:hover { 
            transform: translateY(-2px); 
            box-shadow: 0 7px 14px rgba(0,0,0,0.18);
        }
        .section-divider { 
            height: 3px; 
            background: linear-gradient(90deg, #667eea, #764ba2); 
            border-radius: 2px; 
            margin: 2rem 0;
        }
        .username-badge { 
            background: linear-gradient(45deg, #667eea, #764ba2); 
            color: white; 
            padding: 0.2rem 0.5rem; 
            border-radius: 1rem; 
            font-size: 0.75rem; 
            font-weight: 600; 
            display: inline-block; 
            margin-left: 0.5rem;
        }
        .share-menu { 
            position: absolute; 
            z-index: 50; 
            min-width: 180px; 
            right: 0; 
            top: 110%; 
            background: white; 
            border-radius: 10px; 
            box-shadow: 0 8px 24px rgba(0,0,0,0.13);
        }
        .share-menu button { 
            width: 100%; 
            text-align: left; 
            padding: 10px 20px; 
            border: none; 
            background: none; 
            cursor: pointer; 
            font-size: 0.95rem;
        }
        .share-menu button:hover { background: #f0f4ff; }
        .status-indicator { 
            display: inline-block; 
            width: 8px; 
            height: 8px; 
            border-radius: 50%; 
            margin-right: 5px;
        }
        .status-active { 
            background-color: #10b981; 
            animation: pulse 2s infinite;
        }
        .status-inactive { background-color: #6b7280; }
        .log-container { 
            max-height: 150px; 
            overflow-y: auto; 
            background: rgba(255,255,255,0.1); 
            border-radius: 5px; 
            padding: 10px; 
            margin-top: 10px; 
            font-size: 0.8rem;
            font-family: monospace;
        }
        .rss-item { 
            background: rgba(255,255,255,0.1); 
            border-radius: 5px; 
            padding: 8px; 
            margin: 5px 0; 
            font-size: 0.8rem;
        }
        .error-message { 
            color: #ef4444; 
            background: rgba(239, 68, 68, 0.1); 
            padding: 8px; 
            border-radius: 5px; 
            margin: 5px 0;
        }
        .success-message { 
            color: #10b981; 
            background: rgba(16, 185, 129, 0.1); 
            padding: 8px; 
            border-radius: 5px; 
            margin: 5px 0;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        .dark .glass-effect { 
            background: rgba(0,0,0,0.3); 
            backdrop-filter: blur(10px); 
            border: 1px solid rgba(255,255,255,0.1);
        }
        .dark .timeline-post { 
            background: #374151; 
            color: #f9fafb;
        }
        @media print { 
            body { background: white !important; -webkit-print-color-adjust: exact; } 
            .glass-effect { background: white !important; backdrop-filter: none !important; border: 1px solid #e5e7eb !important; }
        }
    </style>
</head>
<body>
<header class="glass-effect mx-4 mt-4 p-6">
    <div class="text-center">
        <h1 class="text-4xl font-bold text-white mb-2">
            <i class="fas fa-comments mr-3"></i>Verse
            <span class="text-sm opacity-75 ml-2">v2.0 完全修正版</span>
        </h1>
        <p class="text-white text-lg opacity-90">次世代ソーシャルネットワーク</p>
        <div class="mt-4 flex justify-center items-center space-x-4">
            <div class="flex items-center">
                <img id="header-profile-icon" class="profile-avatar" src="https://via.placeholder.com/100" alt="プロフィール">
                <div class="ml-3 text-white">
                    <div class="font-semibold text-lg" id="header-username">未設定</div>
                    <div class="text-sm opacity-75">ユーザー</div>
                </div>
            </div>
            <button onclick="toggleDarkMode()" class="btn-primary px-4 py-2 rounded-full text-white">
                <i class="fas fa-moon mr-2"></i>ダークモード
            </button>
            <button onclick="showSystemStatus()" class="btn-primary px-4 py-2 rounded-full text-white">
                <i class="fas fa-info-circle mr-2"></i>ステータス
            </button>
        </div>
    </div>
</header>

<div class="max-w-6xl mx-auto px-4 py-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左側カラム -->
        <div class="lg:col-span-1 space-y-6">
            <!-- プロフィール -->
            <div class="glass-effect p-6 card-hover">
                <h3 class="text-2xl font-bold gradient-text mb-4">
                    <i class="fas fa-user-circle mr-2"></i>プロフィール
                </h3>
                <div class="text-center mb-6">
                    <img id="profile-icon" class="profile-avatar mx-auto mb-4" src="https://via.placeholder.com/100" alt="プロフィール">
                    <input type="file" id="profile-upload" accept="image/*" onchange="uploadProfileIcon(event)" class="hidden">
                    <button onclick="document.getElementById('profile-upload').click()" class="btn-primary px-4 py-2 rounded-full text-white">
                        <i class="fas fa-camera mr-2"></i>画像変更
                    </button>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block text-white font-semibold mb-2">ユーザー名</label>
                        <input type="text" id="username" class="w-full p-3 border rounded-lg bg-white bg-opacity-90" placeholder="ユーザー名を入力してください" maxlength="20">
                    </div>
                    <div>
                        <label class="block text-white font-semibold mb-2">自己紹介</label>
                        <textarea id="self-intro" class="w-full p-3 border rounded-lg bg-white bg-opacity-90" rows="4" placeholder="自己紹介を入力してください"></textarea>
                    </div>
                    <button onclick="saveProfile()" class="btn-primary w-full py-2 rounded-lg text-white">
                        <i class="fas fa-save mr-2"></i>プロフィール保存
                    </button>
                    <div class="p-3 bg-white bg-opacity-80 rounded-lg">
                        <h5 class="font-semibold text-gray-800 mb-2">プレビュー:</h5>
                        <div class="text-gray-700">
                            <div class="font-semibold mb-1" id="username-preview">未設定</div>
                            <div id="self-intro-preview" class="text-sm whitespace-pre-line min-h-8">まだ自己紹介がありません</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- BOT機能 -->
            <div class="glass-effect p-6 card-hover">
                <h3 class="text-xl font-bold text-white mb-4">
                    <i class="fas fa-robot mr-2"></i>BOT機能
                    <span class="status-indicator" id="bot-status"></span>
                    <span id="bot-status-text" class="text-xs opacity-75">停止中</span>
                </h3>
                <div class="space-y-4">
                    <div>
                        <textarea id="botContent" class="w-full p-3 border rounded-lg bg-white bg-opacity-90" rows="3" placeholder="BOT投稿内容"></textarea>
                        <button onclick="postBotMessage()" class="btn-primary w-full mt-2 py-2 rounded-lg text-white">
                            <i class="fas fa-robot mr-2"></i>BOT投稿
                        </button>
                    </div>
                    <div>
                        <input type="number" id="botIntervalSec" class="w-full p-2 border rounded-lg bg-white bg-opacity-90" placeholder="マルコフ自動投稿間隔(秒)" min="10" max="3600" value="60">
                        <div class="flex space-x-2 mt-2">
                            <button onclick="postMarkovBot()" class="btn-primary flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-dice mr-2"></i>マルコフ生成
                            </button>
                            <button onclick="startBotAutoPost()" class="btn-primary flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-play mr-2"></i>自動開始
                            </button>
                            <button onclick="stopBotAutoPost()" class="bg-red-500 hover:bg-red-600 flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-stop mr-2"></i>停止
                            </button>
                        </div>
                    </div>
                    <div class="text-white text-xs opacity-75">
                        <i class="fas fa-info-circle mr-1"></i>マルコフ連鎖では過去の投稿からランダムな文章を生成します
                    </div>
                    <div id="bot-log" class="log-container text-white text-xs"></div>
                </div>
            </div>

            <!-- RSS機能 -->
            <div class="glass-effect p-6 card-hover">
                <h3 class="text-xl font-bold text-white mb-4">
                    <i class="fas fa-rss mr-2"></i>RSS機能
                    <span class="status-indicator" id="rss-status"></span>
                    <span id="rss-status-text" class="text-xs opacity-75">停止中</span>
                </h3>
                <div class="space-y-4">
                    <div>
                        <input type="text" id="feedUrl" class="w-full p-3 border rounded-lg bg-white bg-opacity-90" placeholder="RSS URL">
                        <button onclick="registerFeedUrl()" class="btn-primary w-full mt-2 py-2 rounded-lg text-white">
                            <i class="fas fa-plus mr-2"></i>フィード登録
                        </button>
                    </div>
                    <div>
                        <input type="number" id="feedIntervalSec" class="w-full p-2 border rounded-lg bg-white bg-opacity-90" placeholder="RSS自動取得間隔(秒)" min="60" max="3600" value="180">
                        <div class="flex space-x-2 mt-2">
                            <button onclick="fetchAllFeeds()" class="btn-primary flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-download mr-2"></i>手動取得
                            </button>
                            <button onclick="startRSSAutoPost()" class="btn-primary flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-play mr-2"></i>自動開始
                            </button>
                            <button onclick="stopRSSAutoPost()" class="bg-red-500 hover:bg-red-600 flex-1 py-2 rounded-lg text-white">
                                <i class="fas fa-stop mr-2"></i>停止
                            </button>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-80 rounded-lg p-3">
                        <div class="flex justify-between items-center mb-2">
                            <h5 class="font-semibold text-gray-800">登録済みフィード:</h5>
                            <button onclick="addDefaultFeeds()" class="text-xs bg-blue-500 text-white px-2 py-1 rounded">
                                デフォルト追加
                            </button>
                        </div>
                        <div id="feed-list" class="text-sm text-gray-700"></div>
                    </div>
                    <div id="rss-log" class="log-container text-white text-xs"></div>
                </div>
            </div>
        </div>

        <!-- 右側カラム -->
        <div class="lg:col-span-2 space-y-6">
            <!-- 新規投稿 -->
            <div class="glass-effect p-6 card-hover">
                <h3 class="text-2xl font-bold gradient-text mb-4">
                    <i class="fas fa-edit mr-2"></i>新規投稿
                </h3>
                <div>
                    <textarea id="postContent" class="w-full p-4 border rounded-lg bg-white bg-opacity-90" rows="4" placeholder="今何を考えていますか?" maxlength="500"></textarea>
                    <div class="mt-4 flex justify-between items-center">
                        <div class="text-white text-sm opacity-75">
                            <i class="fas fa-info-circle mr-1"></i>あなたの思いを共有しましょう 
                            <span id="char-count" class="ml-2">(0/500)</span>
                        </div>
                        <button onclick="createUserPost()" class="btn-primary px-6 py-3 rounded-lg text-white font-semibold">
                            <i class="fas fa-paper-plane mr-2"></i>投稿する
                        </button>
                    </div>
                </div>
            </div>

            <div class="section-divider"></div>

            <!-- タイムライン -->
            <div class="glass-effect p-6">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-2xl font-bold text-white">
                        <i class="fas fa-stream mr-2"></i>タイムライン 
                        <span id="post-count" class="text-sm font-normal opacity-75 ml-2">(0件の投稿)</span>
                    </h3>
                    <div class="flex space-x-2">
                        <button onclick="clearAllPosts()" class="bg-red-500 hover:bg-red-600 px-3 py-1 rounded text-white text-sm">
                            <i class="fas fa-trash mr-1"></i>全削除
                        </button>
                        <button onclick="exportData()" class="bg-green-500 hover:bg-green-600 px-3 py-1 rounded text-white text-sm">
                            <i class="fas fa-download mr-1"></i>エクスポート
                        </button>
                    </div>
                </div>
                <div id="timeline" class="space-y-4"></div>
                <div id="empty-timeline" class="text-center py-12 text-white opacity-75">
                    <i class="fas fa-comments text-4xl mb-4"></i>
                    <p class="text-lg">まだ投稿がありません</p>
                    <p class="text-sm">最初の投稿をして、タイムラインを始めましょう!</p>
                </div>
            </div>
        </div>
    </div>
</div>

<footer class="glass-effect mx-4 mb-4 p-4 text-center">
    <p class="text-white opacity-75">
        <i class="fas fa-copyright mr-2"></i>2025 Verse - 次世代ソーシャルネットワーク v2.0
        <span class="ml-4">
            <i class="fas fa-bug mr-1"></i>RSS自動投稿完全修正版
        </span>
    </p>
</footer>

<script>
// === 設定とグローバル変数 ===
const DEFAULT_FEEDS = [
    "https://feeds.feedburner.com/hatena/b/hotentry",
    "https://gigazine.net/news/rss_2.0/",
    "https://rss.cnn.com/rss/edition.rss",
    "https://feeds.bbci.co.uk/news/rss.xml",
    "https://www.reddit.com/r/worldnews/.rss"
];

const RSS_APIS = [
    'https://api.rss2json.com/v1/api.json',
    'https://cors-anywhere.herokuapp.com/',
    'https://api.allorigins.win/get'
];

// グローバル状態
let posts = JSON.parse(localStorage.getItem('verse_posts') || '[]');
let feedUrls = JSON.parse(localStorage.getItem('verse_feeds') || '[]');
let profile = JSON.parse(localStorage.getItem('verse_profile') || '{}');
let processedItems = new Set(JSON.parse(localStorage.getItem('verse_processed') || '[]'));

// タイマーとステータス
let botInterval = null;
let rssInterval = null;
let isDarkMode = localStorage.getItem('verse_darkMode') === 'true';
let markovChain = null;
let isInitialized = false;

// 統計情報
let stats = {
    totalPosts: 0,
    rssSuccess: 0,
    rssErrors: 0,
    botPosts: 0,
    lastRSSUpdate: null,
    lastBotPost: null
};

// === 初期化処理 ===
function initializeApp() {
    if (isInitialized) return;
    
    // プロフィール初期化
    if (!profile.icon) profile.icon = 'https://via.placeholder.com/100';
    if (!profile.username) profile.username = 'ゲストユーザー';
    if (!profile.selfIntro) profile.selfIntro = '';
    
    // デフォルトフィード設定
    if (feedUrls.length === 0) {
        feedUrls = [...DEFAULT_FEEDS];
        saveData();
        addLog('rss-log', 'デフォルトRSSフィードを登録しました', 'success');
    }
    
    // UI初期化
    updateAllUI();
    updateStatusIndicators();
    
    // ダークモード適用
    if (isDarkMode) {
        document.body.classList.add('dark');
        document.body.style.background = 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)';
    }
    
    isInitialized = true;
    addLog('rss-log', 'アプリケーション初期化完了', 'success');
    addLog('bot-log', 'BOT機能初期化完了', 'success');
    
    // 初回RSS取得(遅延実行)
    setTimeout(() => {
        addLog('rss-log', '初回RSS取得を開始します...', 'info');
        fetchAllFeeds();
    }, 3000);
}

// === データ管理 ===
function saveData() {
    try {
        localStorage.setItem('verse_posts', JSON.stringify(posts));
        localStorage.setItem('verse_feeds', JSON.stringify(feedUrls));
        localStorage.setItem('verse_profile', JSON.stringify(profile));
        localStorage.setItem('verse_processed', JSON.stringify([...processedItems]));
        localStorage.setItem('verse_darkMode', isDarkMode);
        
        stats.totalPosts = posts.length;
    } catch (error) {
        console.error('データ保存エラー:', error);
        addLog('rss-log', `データ保存エラー: ${error.message}`, 'error');
    }
}

function clearAllPosts() {
    if (confirm('すべての投稿を削除してもよろしいですか?\nこの操作は元に戻せません。')) {
        posts = [];
        processedItems.clear();
        saveData();
        renderTimeline();
        addLog('rss-log', 'すべての投稿を削除しました', 'info');
        addLog('bot-log', 'すべての投稿を削除しました', 'info');
    }
}

function exportData() {
    const exportData = {
        posts: posts,
        profile: profile,
        feedUrls: feedUrls,
        stats: stats,
        exportDate: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `verse_export_${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
    
    addLog('rss-log', 'データをエクスポートしました', 'success');
}

// === ログ機能 ===
function addLog(elementId, message, type = 'info') {
    const logElement = document.getElementById(elementId);
    if (!logElement) return;
    
    const timestamp = new Date().toLocaleTimeString('ja-JP');
    const logEntry = document.createElement('div');
    
    const typeClass = {
        'error': 'error-message',
        'success': 'success-message',
        'info': 'text-white opacity-75'
    }[type] || 'text-white opacity-75';
    
    logEntry.className = typeClass;
    logEntry.innerHTML = `<span class="opacity-75">[${timestamp}]</span> ${message}`;
    
    logElement.appendChild(logEntry);
    logElement.scrollTop = logElement.scrollHeight;
    
    // ログ数制限
    while (logElement.children.length > 50) {
        logElement.removeChild(logElement.firstChild);
    }
}

// === ステータス管理 ===
function updateStatusIndicators() {
    const botIndicator = document.getElementById('bot-status');
    const rssIndicator = document.getElementById('rss-status');
    const botStatusText = document.getElementById('bot-status-text');
    const rssStatusText = document.getElementById('rss-status-text');
    
    if (botIndicator && botStatusText) {
        const isActive = botInterval !== null;
        botIndicator.className = `status-indicator ${isActive ? 'status-active' : 'status-inactive'}`;
        botStatusText.textContent = isActive ? '動作中' : '停止中';
    }
    
    if (rssIndicator && rssStatusText) {
        const isActive = rssInterval !== null;
        rssIndicator.className = `status-indicator ${isActive ? 'status-active' : 'status-inactive'}`;
        rssStatusText.textContent = isActive ? '動作中' : '停止中';
    }
}

function showSystemStatus() {
    const statusInfo = `
=== Verse システムステータス ===
総投稿数: ${stats.totalPosts}
RSS成功: ${stats.rssSuccess}
RSSエラー: ${stats.rssErrors}
BOT投稿数: ${stats.botPosts}
最後のRSS更新: ${stats.lastRSSUpdate || 'なし'}
最後のBOT投稿: ${stats.lastBotPost || 'なし'}

RSS自動取得: ${rssInterval ? '動作中' : '停止中'}
BOT自動投稿: ${botInterval ? '動作中' : '停止中'}
登録フィード数: ${feedUrls.length}
処理済みアイテム: ${processedItems.size}
    `;
    alert(statusInfo);
}

// === 投稿管理 ===
function createPost(content, type = 'user', username = null, icon = null) {
    if (!content || !content.trim()) {
        addLog('rss-log', '空のコンテンツは投稿できません', 'error');
        return false;
    }
    
    // RSS重複チェック
    if (type === 'feed') {
        const urlMatch = content.match(/href="([^"]+)"/);
        const url = urlMatch ? urlMatch[1] : null;
        
        if (url && processedItems.has(url)) {
            addLog('rss-log', `重複記事をスキップ: ${url.substring(0, 50)}...`, 'info');
            return false;
        }
        
        if (url) {
            processedItems.add(url);
        }
    }
    
    const post = {
        id: Date.now() + Math.random(),
        content: content.trim(),
        likes: 0,
        timestamp: new Date().toLocaleString('ja-JP'),
        type: type,
        username: username || profile.username,
        icon: icon || profile.icon
    };
    
    posts.unshift(post);
    
    // 統計更新
    if (type === 'bot' || type === 'markov') {
        stats.botPosts++;
        stats.lastBotPost = post.timestamp;
    }
    if (type === 'feed') {
        stats.rssSuccess++;
        stats.lastRSSUpdate = post.timestamp;
    }
    
    saveData();
    renderTimeline();
    return true;
}

function createUserPost() {
    const content = document.getElementById('postContent').value.trim();
    if (content) {
        if (createPost(content, 'user')) {
            document.getElementById('postContent').value = '';
            updateCharCount();
            addLog('bot-log', 'ユーザー投稿を作成しました', 'success');
        }
    }
}

function likePost(id) {
    const post = posts.find(p => p.id === id);
    if (post) {
        post.likes++;
        saveData();
        renderTimeline();
    }
}

function deletePost(id) {
    if (confirm('この投稿を削除しますか?')) {
        const post = posts.find(p => p.id === id);
        if (post && post.type === 'feed') {
            const urlMatch = post.content.match(/href="([^"]+)"/);
            if (urlMatch) {
                processedItems.delete(urlMatch[1]);
            }
        }
        
        posts = posts.filter(p => p.id !== id);
        saveData();
        renderTimeline();
    }
}

// === タイムライン表示 ===
function renderTimeline() {
    const timeline = document.getElementById('timeline');
    const emptyTimeline = document.getElementById('empty-timeline');
    const postCount = document.getElementById('post-count');
    
    if (posts.length === 0) {
        timeline.innerHTML = '';
        emptyTimeline.style.display = 'block';
        postCount.textContent = '(0件の投稿)';
        return;
    }
    
    emptyTimeline.style.display = 'none';
    postCount.textContent = `(${posts.length}件の投稿)`;
    
    timeline.innerHTML = posts.map(post => {
        const typeInfo = getPostTypeInfo(post.type);
        return `
            <div class="timeline-post p-6">
                <div class="flex justify-between items-start mb-4">
                    <div class="flex items-center space-x-3">
                        <img src="${post.icon}" alt="アバター" class="w-10 h-10 rounded-full object-cover">
                        <div>
                            <div class="flex items-center">
                                <span class="font-semibold text-gray-800 dark:text-white">${post.username}</span>
                                <span class="username-badge">${typeInfo.badge}</span>
                            </div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">${post.timestamp}</div>
                        </div>
                    </div>
                </div>
                <div class="text-gray-800 dark:text-gray-200 mb-4 leading-relaxed">${post.content}</div>
                <div class="flex items-center space-x-4 pt-4 border-t border-gray-100 dark:border-gray-600">
                    <button onclick="likePost(${post.id})" class="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-red-500 transition-colors">
                        <i class="fas fa-heart"></i>
                        <span>${post.likes}</span>
                    </button>
                    <div class="relative">
                        <button onclick="toggleShareMenu(${post.id})" class="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-blue-500 transition-colors">
                            <i class="fas fa-share"></i>
                            <span>シェア</span>
                        </button>
                        <div id="share-menu-${post.id}" class="share-menu hidden">
                            <button onclick="shareToX(${post.id})"><i class="fab fa-x-twitter text-blue-400 mr-2"></i>Xでシェア</button>
                            <button onclick="shareToLine(${post.id})"><i class="fab fa-line text-green-400 mr-2"></i>LINEでシェア</button>
                            <button onclick="copyPost(${post.id})"><i class="fas fa-copy mr-2"></i>コピー</button>
                        </div>
                    </div>
                    <button onclick="deletePost(${post.id})" class="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-red-500 transition-colors ml-auto">
                        <i class="fas fa-trash"></i>
                        <span>削除</span>
                    </button>
                </div>
            </div>
        `;
    }).join('');
}

function getPostTypeInfo(type) {
    const typeMap = {
        'bot': { badge: '🤖 BOT' },
        'markov': { badge: '🎲 MarkovBOT' },
        'feed': { badge: '📡 RSS Feed' },
        'user': { badge: '👤 ユーザー' }
    };
    return typeMap[type] || typeMap['user'];
}

// === シェア機能 ===
function getPostContentText(id) {
    const post = posts.find(p => p.id === id);
    if (!post) return '';
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = post.content;
    return tempDiv.textContent || tempDiv.innerText || '';
}

function toggleShareMenu(id) {
    document.querySelectorAll('[id^="share-menu-"]').forEach(el => el.classList.add('hidden'));
    const menu = document.getElementById('share-menu-' + id);
    if (menu) {
        menu.classList.toggle('hidden');
        setTimeout(() => {
            const closeMenu = (e) => {
                if (!menu.contains(e.target)) {
                    menu.classList.add('hidden');
                    document.removeEventListener('mousedown', closeMenu);
                }
            };
            document.addEventListener('mousedown', closeMenu);
        }, 100);
    }
}

function shareToX(id) {
    const text = encodeURIComponent(getPostContentText(id));
    const url = encodeURIComponent(location.href);
    window.open(`https://twitter.com/intent/tweet?text=${text}&url=${url}`, '_blank');
}

function shareToLine(id) {
    const text = encodeURIComponent(getPostContentText(id) + ' ' + location.href);
    window.open(`https://social-plugins.line.me/lineit/share?url=${text}`, '_blank');
}

function copyPost(id) {
    const text = getPostContentText(id);
    navigator.clipboard.writeText(text).then(() => {
        alert('投稿内容をクリップボードにコピーしました!');
    }).catch(() => {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('投稿内容をコピーしました!');
    });
}

// === BOT機能 ===
function postBotMessage() {
    const content = document.getElementById('botContent').value.trim();
    if (content) {
        if (createPost(content, 'bot', 'BOT')) {
            document.getElementById('botContent').value = '';
            addLog('bot-log', `BOT投稿: "${content.substring(0, 30)}..."`, 'success');
        }
    }
}

// === マルコフ連鎖機能(強化版) ===
function initializeMarkovChain() {
    try {
        if (typeof RiTa === 'undefined') {
            addLog('bot-log', 'RiTaライブラリが未読み込みです', 'error');
            return false;
        }
        
        markovChain = new RiTa.Markov(3);
        
        const userPosts = posts.filter(p => 
            (p.type === 'user' || p.type === 'bot') && 
            p.content.length > 20 &&
            !p.content.includes('<div') &&
            !p.content.includes('href=')
        );
        
        if (userPosts.length < 5) {
            addLog('bot-log', `学習データ不足 (${userPosts.length}件) - 5件以上必要`, 'error');
            return false;
        }
        
        const textData = userPosts
            .map(p => cleanTextForMarkov(p.content))
            .filter(text => text.length > 15)
            .join('\n');
            
        if (textData.length < 200) {
            addLog('bot-log', 'テキストデータが不十分です', 'error');
            return false;
        }
        
        markovChain.addText(textData);
        addLog('bot-log', `マルコフ連鎖学習完了 (${userPosts.length}件の投稿を学習)`, 'success');
        return true;
        
    } catch (error) {
        addLog('bot-log', `マルコフ初期化エラー: ${error.message}`, 'error');
        return false;
    }
}

function cleanTextForMarkov(text) {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = text;
    let cleanText = tempDiv.textContent || tempDiv.innerText || '';
    
    cleanText = cleanText
        .replace(/https?:\/\/[^\s]+/g, '')
        .replace(/[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FAF\u3400-\u4DBFa-zA-Z0-9\s!?。、.,!?\n]/g, '')
        .replace(/\s+/g, ' ')
        .replace(/[。!?]{2,}/g, '。')
        .trim();
        
    return cleanText;
}

function generateMarkovText() {
    try {
        if (!initializeMarkovChain()) {
            const fallbackMessages = [
                "今日はいい天気ですね!どのように過ごされていますか?",
                "最近面白いニュースありましたか?",
                "新しいアイデアが浮かんできました。",
                "皆さんはどう思いますか?",
                "今日も一日頑張りましょう!"
            ];
            return fallbackMessages[Math.floor(Math.random() * fallbackMessages.length)];
        }
        
        let bestText = '';
        const maxAttempts = 15;
        
        for (let i = 0; i < maxAttempts; i++) {
            try {
                const options = {
                    maxLength: 120,
                    minLength: 20,
                    count: Math.floor(Math.random() * 2) + 1
                };
                
                const sentences = markovChain.generate(options);
                
                if (sentences && sentences.length > 0) {
                    let generatedText = sentences.join(' ').trim();
                    
                    // 文章の自然な終端処理
                    if (generatedText.length > 150) {
                        const endMarkers = ['。', '!', '?'];
                        let bestEnd = -1;
                        
                        endMarkers.forEach(marker => {
                            const pos = generatedText.lastIndexOf(marker, 130);
                            if (pos > 30) bestEnd = Math.max(bestEnd, pos);
                        });
                        
                        if (bestEnd > -1) {
                            generatedText = generatedText.substring(0, bestEnd + 1);
                        }
                    }
                    
                    // 品質チェック
                    if (generatedText.length >= 20 && 
                        generatedText.length <= 200 &&
                        !generatedText.includes('undefined') &&
                        generatedText.length > bestText.length) {
                        bestText = generatedText;
                    }
                }
            } catch (genError) {
                continue;
            }
        }
        
        if (!bestText || bestText.length < 10) {
            bestText = "新しいアイデアについて考えています。皆さんの意見も聞きたいですね。";
        }
        
        return bestText;
        
    } catch (error) {
        addLog('bot-log', `マルコフ生成エラー: ${error.message}`, 'error');
        return "マルコフ連鎖で自然な文章を生成しています。";
    }
}

function postMarkovBot() {
    const content = generateMarkovText();
    if (createPost(content, 'markov', 'MarkovBOT')) {
        addLog('bot-log', `マルコフ投稿: "${content.substring(0, 40)}..."`, 'success');
    }
}

function startBotAutoPost() {
    const interval = parseInt(document.getElementById('botIntervalSec').value) || 60;
    if (interval < 10) {
        alert('間隔は10秒以上で設定してください。');
        return;
    }
    
    stopBotAutoPost();
    
    // 初回投稿
    setTimeout(postMarkovBot, 2000);
    
    botInterval = setInterval(() => {
        postMarkovBot();
    }, interval * 1000);
    
    updateStatusIndicators();
    addLog('bot-log', `マルコフBOT自動投稿開始 (${interval}秒間隔)`, 'success');
}

function stopBotAutoPost() {
    if (botInterval) {
        clearInterval(botInterval);
        botInterval = null;
        updateStatusIndicators();
        addLog('bot-log', 'マルコフBOT自動投稿を停止しました', 'info');
    }
}

// === RSS機能(完全修正版) ===
function addDefaultFeeds() {
    let addedCount = 0;
    DEFAULT_FEEDS.forEach(url => {
        if (!feedUrls.includes(url)) {
            feedUrls.push(url);
            addedCount++;
        }
    });
    
    if (addedCount > 0) {
        saveData();
        renderFeedList();
        addLog('rss-log', `${addedCount}件のデフォルトフィードを追加しました`, 'success');
    } else {
        addLog('rss-log', 'すべてのデフォルトフィードは既に登録されています', 'info');
    }
}

function registerFeedUrl() {
    const url = document.getElementById('feedUrl').value.trim();
    if (!url) {
        alert('URLを入力してください。');
        return;
    }
    
    if (!url.startsWith('http')) {
        alert('有効なURLを入力してください(http://またはhttps://で開始)。');
        return;
    }
    
    if (feedUrls.includes(url)) {
        alert('このフィードは既に登録されています。');
        return;
    }
    
    feedUrls.push(url);
    saveData();
    renderFeedList();
    document.getElementById('feedUrl').value = '';
    addLog('rss-log', `フィード登録: ${url}`, 'success');
}

function removeFeedUrl(index) {
    if (confirm('このフィードを削除しますか?')) {
        const removedUrl = feedUrls[index];
        feedUrls.splice(index, 1);
        saveData();
        renderFeedList();
        addLog('rss-log', `フィード削除: ${removedUrl}`, 'info');
    }
}

function renderFeedList() {
    const feedList = document.getElementById('feed-list');
    if (feedUrls.length === 0) {
        feedList.innerHTML = '<div class="text-gray-500">登録されたフィードはありません</div>';
        return;
    }
    
    feedList.innerHTML = feedUrls.map((url, index) => `
        <div class="rss-item flex items-center justify-between">
            <span class="text-xs truncate flex-1" title="${url}">${url}</span>
            <button onclick="removeFeedUrl(${index})" class="text-red-500 hover:text-red-700 ml-2 text-xs">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `).join('');
}

// 改良されたRSS取得機能
async function fetchAllFeeds() {
    if (feedUrls.length === 0) {
        addLog('rss-log', 'RSSフィードが登録されていません', 'error');
        return;
    }
    
    addLog('rss-log', `RSS取得開始 (${feedUrls.length}件のフィード)`, 'info');
    let successCount = 0;
    let errorCount = 0;
    
    for (let i = 0; i < feedUrls.length; i++) {
        const url = feedUrls[i];
        
        try {
            addLog('rss-log', `[${i + 1}/${feedUrls.length}] 取得中: ${url.substring(0, 50)}...`, 'info');
            
            const success = await fetchSingleFeed(url);
            if (success) {
                successCount++;
                addLog('rss-log', `✓ 成功: ${url.substring(0, 50)}...`, 'success');
            } else {
                errorCount++;
                addLog('rss-log', `✗ 失敗: ${url.substring(0, 50)}...`, 'error');
            }
            
        } catch (error) {
            errorCount++;
            addLog('rss-log', `✗ エラー: ${error.message}`, 'error');
        }
        
        // レート制限対策(フィード間に待機時間)
        if (i < feedUrls.length - 1) {
            await sleep(2000);
        }
    }
    
    stats.rssSuccess += successCount;
    stats.rssErrors += errorCount;
    
    const resultMsg = `RSS取得完了: 成功 ${successCount}件 / エラー ${errorCount}件`;
    addLog('rss-log', resultMsg, successCount > 0 ? 'success' : 'error');
    
    if (successCount > 0) {
        saveData();
    }
}

async function fetchSingleFeed(feedUrl) {
    const apis = [
        // API 1: rss2json
        async () => {
            const response = await fetchWithTimeout(
                `https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(feedUrl)}&count=5`,
                10000
            );
            const data = await response.json();
            
            if (data.status !== 'ok') {
                throw new Error(data.message || 'RSS API error');
            }
            
            return data.items || [];
        },
        
        // API 2: allorigins
        async () => {
            const response = await fetchWithTimeout(
                `https://api.allorigins.win/get?url=${encodeURIComponent(feedUrl)}`,
                10000
            );
            const data = await response.json();
            
            if (!data.contents) {
                throw new Error('No contents returned');
            }
            
            return parseRSSContent(data.contents);
        }
    ];
    
    for (const api of apis) {
        try {
            const items = await api();
            return await processRSSItems(items, feedUrl);
        } catch (error) {
            continue;
        }
    }
    
    return false;
}

async function processRSSItems(items, feedUrl) {
    if (!items || items.length === 0) {
        return false;
    }
    
    let processedCount = 0;
    
    for (const item of items.slice(0, 3)) { // 最大3件まで
        if (!item.title || !item.link) continue;
        
        // 重複チェック
        if (processedItems.has(item.link)) {
            continue;
        }
        
        const cleanTitle = cleanHTML(item.title).substring(0, 100);
        const cleanDescription = item.description 
            ? cleanHTML(item.description).substring(0, 150) 
            : '';
        
        const content = createRSSPostContent(cleanTitle, cleanDescription, item.link, feedUrl);
        
        if (createPost(content, 'feed', 'RSS Feed')) {
            processedCount++;
            processedItems.add(item.link);
            
            // 投稿間の間隔
            if (processedCount < 3) {
                await sleep(1000);
            }
        }
    }
    
    return processedCount > 0;
}

function createRSSPostContent(title, description, link, feedUrl) {
    const feedDomain = new URL(feedUrl).hostname;
    
    return `
        <div class="border-l-4 border-blue-500 pl-4 bg-gray-50 dark:bg-gray-700 rounded-r-lg p-3">
            <h4 class="font-semibold mb-2 text-gray-900 dark:text-white">${title}</h4>
            ${description ? `<p class="text-sm text-gray-600 dark:text-gray-300 mb-3">${description}${description.length >= 150 ? '...' : ''}</p>` : ''}
            <div class="flex items-center justify-between">
                <span class="text-xs text-gray-500 dark:text-gray-400">
                    <i class="fas fa-globe mr-1"></i>${feedDomain}
                </span>
                <a href="${link}" target="_blank" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 text-sm font-medium">
                    <i class="fas fa-external-link-alt mr-1"></i>記事を読む
                </a>
            </div>
        </div>
    `;
}

function parseRSSContent(xmlContent) {
    // 簡易XMLパース(実装を簡略化)
    const items = [];
    const parser = new DOMParser();
    const doc = parser.parseFromString(xmlContent, 'text/xml');
    
    const rssItems = doc.querySelectorAll('item');
    rssItems.forEach(item => {
        const title = item.querySelector('title')?.textContent;
        const link = item.querySelector('link')?.textContent;
        const description = item.querySelector('description')?.textContent;
        
        if (title && link) {
            items.push({ title, link, description });
        }
    });
    
    return items;
}

function cleanHTML(text) {
    if (!text) return '';
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = text;
    return (tempDiv.textContent || tempDiv.innerText || '').trim();
}

async function fetchWithTimeout(url, timeout = 10000) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    try {
        const response = await fetch(url, {
            signal: controller.signal,
            headers: {
                'Accept': 'application/json',
                'User-Agent': 'Verse RSS Reader 2.0'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        return response;
    } finally {
        clearTimeout(timeoutId);
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function startRSSAutoPost() {
    const interval = parseInt(document.getElementById('feedIntervalSec').value) || 180;
    if (interval < 60) {
        alert('間隔は60秒以上で設定してください。');
        return;
    }
    
    stopRSSAutoPost();
    
    // 初回実行(少し遅延)
    setTimeout(() => {
        addLog('rss-log', '自動RSS取得の初回実行を開始...', 'info');
        fetchAllFeeds();
    }, 5000);
    
    rssInterval = setInterval(() => {
        addLog('rss-log', '定期RSS取得を実行中...', 'info');
        fetchAllFeeds();
    }, interval * 1000);
    
    updateStatusIndicators();
    addLog('rss-log', `RSS自動取得開始 (${interval}秒間隔)`, 'success');
}

function stopRSSAutoPost() {
    if (rssInterval) {
        clearInterval(rssInterval);
        rssInterval = null;
        updateStatusIndicators();
        addLog('rss-log', 'RSS自動取得を停止しました', 'info');
    }
}

// === プロフィール機能 ===
function uploadProfileIcon(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    if (file.size > 5 * 1024 * 1024) {
        alert('画像サイズは5MB以下にしてください。');
        return;
    }
    
    const reader = new FileReader();
    reader.onload = function(e) {
        profile.icon = e.target.result;
        updateAllUI();
        saveData();
        alert('プロフィール画像を更新しました!');
    };
    reader.readAsDataURL(file);
}

function saveProfile() {
    const username = document.getElementById('username').value.trim();
    const selfIntro = document.getElementById('self-intro').value.trim();
    
    if (username && username.length > 20) {
        alert('ユーザー名は20文字以内で入力してください。');
        return;
    }
    
    profile.username = username || 'ゲストユーザー';
    profile.selfIntro = selfIntro;
    
    updateAllUI();
    saveData();
    alert('プロフィールを保存しました!');
}

// === UI更新 ===
function updateAllUI() {
    // プロフィール画像更新
    const profileIcon = document.getElementById('profile-icon');
    const headerIcon = document.getElementById('header-profile-icon');
    if (profileIcon) profileIcon.src = profile.icon;
    if (headerIcon) headerIcon.src = profile.icon;
    
    // ユーザー名更新
    const usernameElements = ['username-preview', 'header-username'];
    usernameElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) element.textContent = profile.username;
    });
    
    // 自己紹介更新
    const selfIntroPreview = document.getElementById('self-intro-preview');
    if (selfIntroPreview) {
        selfIntroPreview.textContent = profile.selfIntro || 'まだ自己紹介がありません';
    }
    
    // タイムライン再描画
    renderTimeline();
    renderFeedList();
}

function updateCharCount() {
    const postContent = document.getElementById('postContent');
    const charCount = document.getElementById('char-count');
    if (postContent && charCount) {
        const length = postContent.value.length;
        charCount.textContent = `(${length}/500)`;
        charCount.style.color = length > 450 ? '#ef4444' : '';
    }
}

function toggleDarkMode() {
    isDarkMode = !isDarkMode;
    if (isDarkMode) {
        document.body.classList.add('dark');
        document.body.style.background = 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)';
    } else {
        document.body.classList.remove('dark');
        document.body.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
    }
    saveData();
}

// === イベントリスナー ===
document.addEventListener('DOMContentLoaded', function() {
    // 文字数カウンター
    const postContent = document.getElementById('postContent');
    if (postContent) {
        postContent.addEventListener('input', updateCharCount);
    }
    
    // プロフィール入力のリアルタイム更新
    const usernameInput = document.getElementById('username');
    const selfIntroInput = document.getElementById('self-intro');
    
    if (usernameInput) {
        usernameInput.addEventListener('input', function() {
            const username = this.value.trim() || 'ゲストユーザー';
            document.getElementById('username-preview').textContent = username;
            document.getElementById('header-username').textContent = username;
        });
    }
    
    if (selfIntroInput) {
        selfIntroInput.addEventListener('input', function() {
            const selfIntro = this.value.trim() || 'まだ自己紹介がありません';
            document.getElementById('self-intro-preview').textContent = selfIntro;
        });
    }
});

// === 初期化実行 ===
window.addEventListener('load', function() {
    // アプリ初期化
    initializeApp();
    
    // プロフィール情報を入力フィールドに設定
    document.getElementById('username').value = profile.username || '';
    document.getElementById('self-intro').value = profile.selfIntro || '';
    
    // ページ終了時のクリーンアップ
    window.addEventListener('beforeunload', function() {
        stopBotAutoPost();
        stopRSSAutoPost();
        saveData();
    });
});
</script>
</body>
</html>

Verse.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verse - 次世代ソーシャルネットワーク</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rita/1.3.63/rita-full.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: #f0f0f0; }
        header, .footer { background: linear-gradient(45deg, #6a11cb, #2575fc); color: white; text-align: center; padding: 20px; }
        .nav-container { background: #2575fc; display: flex; justify-content: center; padding: 10px; position: sticky; top: 0; }
        .nav-menu a { color: white; text-decoration: none; margin: 0 10px; }
        .content { max-width: 900px; margin: 20px auto; background: white; padding: 20px; border-radius: 8px; }
        .cta-button { background: #2575fc; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; }
        .profile-icon { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; }
        .dark-mode { background: #1e1e1e; color: #ddd; }
        .timeline { margin-top: 20px; }
        .timeline-post { border: 1px solid #ddd; border-radius: 8px; padding: 10px; margin-bottom: 10px; background: #fff; }
        .post-controls { display: flex; gap: 10px; }
        .search-box { width: 100%; margin-bottom: 10px; }
    </style>
    <script>
        let posts = JSON.parse(localStorage.getItem('posts') || '[]');
        let feedUrls = JSON.parse(localStorage.getItem('feedUrls') || '[]');
        let botInterval = null;
        let feedInterval = null;

        function saveData() {
            localStorage.setItem('posts', JSON.stringify(posts));
            localStorage.setItem('feedUrls', JSON.stringify(feedUrls));
        }

        function createPost(content) {
            posts.unshift({ content: content, likes: 0 });
            saveData();
            renderTimeline();
        }

        function createUserPost() {
            const content = document.getElementById('postContent').value.trim();
            if(content) {
                createPost(content);
                document.getElementById('postContent').value = '';
            }
        }

        function likePost(index) {
            posts[index].likes++;
            saveData();
            renderTimeline();
        }

        function deletePost(index) {
            posts.splice(index, 1);
            saveData();
            renderTimeline();
        }

        function searchPosts() {
            const query = document.getElementById('searchInput').value.trim().toLowerCase();
            renderTimeline(query);
        }

        function renderTimeline(filter = '') {
            const container = document.getElementById('timeline');
            container.innerHTML = '';
            posts.filter(post => post.content.toLowerCase().includes(filter)).forEach((post, index) => {
                const postDiv = document.createElement('div');
                postDiv.className = 'timeline-post';
                postDiv.innerHTML = `
                    <p>${post.content}</p>
                    <div class='post-controls'>
                        <button class='btn btn-sm btn-primary' onclick='likePost(${index})'>❤️ いいね (${post.likes})</button>
                        <button class='btn btn-sm btn-danger' onclick='deletePost(${index})'>🗑️ 削除</button>
                    </div>
                `;
                container.appendChild(postDiv);
            });
        }

        function toggleDarkMode() {
            document.body.classList.toggle('dark-mode');
        }

        function uploadProfileIcon(event) {
            const file = event.target.files[0];
            if(file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('profile-icon').src = e.target.result;
                    showTimeline();
                };
                reader.readAsDataURL(file);
            }
        }

        function showTimeline() {
            document.getElementById('profile-section').style.display = 'none';
            document.getElementById('post-section').style.display = 'block';
            document.getElementById('timeline').style.display = 'block';
        }

        function showProfile() {
            document.getElementById('profile-section').style.display = 'block';
            document.getElementById('post-section').style.display = 'none';
            document.getElementById('timeline').style.display = 'none';
        }

        function postBotMessage() {
            const content = document.getElementById('botContent').value.trim();
            if(content) {
                createPost(`🤖 BOT: ${content}`);
                document.getElementById('botContent').value = '';
            }
        }

        function generateMarkovText() {
            const combinedText = posts.map(p => p.content).join(' ');
            if(combinedText.length < 20) return "BOTの投稿データが不足しています。";

            const markov = new RiTa.Markov(3);
            markov.addText(combinedText);
            const sentences = markov.generate(1);
            return sentences[0] ? sentences[0] : "自然な文章の生成に失敗しました。";
        }

        function postMarkovBot() {
            const text = generateMarkovText();
            createPost(`🤖 MarkovBOT: ${text}`);
        }

        function startBotAutoPost(intervalSec) {
            if(botInterval) clearInterval(botInterval);
            botInterval = setInterval(postMarkovBot, intervalSec * 1000);
            alert(`マルコフ連鎖BOTの自動投稿間隔を${intervalSec}秒に設定しました。`);
        }

        function registerFeedUrl() {
            const url = document.getElementById('feedUrl').value.trim();
            if(url) {
                feedUrls.push(url);
                saveData();
                alert('RSSフィードURLを登録しました。');
                document.getElementById('feedUrl').value = '';
            }
        }

        async function fetchAllFeeds() {
            for(const url of feedUrls) {
                try {
                    const response = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(url)}`);
                    const data = await response.json();
                    data.items.forEach(item => {
                        createPost(`📡 FEED: ${item.title} - ${item.link}`);
                    });
                } catch (error) {
                    console.error('RSSフィード取得エラー:', error);
                }
            }
        }

        function startFeedAutoPost(intervalSec) {
            if(feedInterval) clearInterval(feedInterval);
            feedInterval = setInterval(fetchAllFeeds, intervalSec * 1000);
            alert(`RSSフィードの自動投稿間隔を${intervalSec}秒に設定しました。`);
        }

        window.onload = function() {
            renderTimeline();
        };
    </script>
</head>
<body>
    <header>
        <h1>Verse</h1>
        <button class="cta-button" onclick="toggleDarkMode()">🌙 ダークモード切替</button>
    </header>

    <div class="nav-container">
        <div class="nav-menu">
            <a href="#" onclick="showTimeline()">ホーム</a>
            <a href="#" onclick="showProfile()">プロフィール</a>
        </div>
    </div>

    <div class="content">
        <section id="profile-section" style="display:none;">
            <h2>プロフィール</h2>
            <img id="profile-icon" src="https://via.placeholder.com/80" alt="プロフィールアイコン" class="profile-icon"><br><br>
            <input type="file" accept="image/*" onchange="uploadProfileIcon(event)">
        </section>

        <section id="post-section">
            <h2>新規投稿</h2>
            <textarea id="postContent" class="form-control" placeholder="いま何してる?"></textarea><br>
            <button class="cta-button" onclick="createUserPost()">投稿</button>

            <h2>BOT投稿登録</h2>
            <textarea id="botContent" class="form-control" placeholder="BOTに投稿させたい内容"></textarea><br>
            <button class="cta-button" onclick="postBotMessage()">BOT投稿登録</button><br><br>

            <input type="number" id="botIntervalSec" placeholder="BOTの自動投稿間隔(秒)">
            <button class="cta-button" onclick="startBotAutoPost(parseInt(document.getElementById('botIntervalSec').value))">マルコフ連鎖 自動投稿開始</button><br><br>

            <h2>RSSフィード登録</h2>
            <input type="text" id="feedUrl" class="form-control" placeholder="RSSフィードのURL"><br>
            <button class="cta-button" onclick="registerFeedUrl()">フィード登録</button><br><br>

            <input type="number" id="feedIntervalSec" placeholder="RSS自動投稿間隔(秒)">
            <button class="cta-button" onclick="startFeedAutoPost(parseInt(document.getElementById('feedIntervalSec').value))">RSS 自動投稿開始</button>
        </section>

        <input type="text" id="searchInput" class="form-control search-box" placeholder="投稿を検索..." onkeyup="searchPosts()">

        <section id="timeline" class="timeline"></section>
    </div>

    <div class="footer">&copy; 2025 Verse - 新しいつながりを創造する</div>
</body>
</html>

匿名相談・共感プラットフォーム

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>匿名相談・共感プラットフォーム</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #eef1f5; margin: 0; padding: 20px; }
    header { text-align: center; padding: 20px; background: #4a90e2; color: white; border-radius: 8px; }
    .container { max-width: 800px; margin: 20px auto; }
    .card { background: white; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 15px; margin-bottom: 20px; }
    textarea, input[type="text"] { width: 100%; padding: 10px; margin: 5px 0; border: 1px solid #ccc; border-radius: 5px; }
    button { background: #4a90e2; color: white; border: none; padding: 10px 15px; border-radius: 5px; cursor: pointer; margin-right: 5px; }
    button:hover { background: #357ab8; }
    .comment { background: #f5f5f5; border-left: 3px solid #4a90e2; padding: 8px; margin-top: 8px; border-radius: 5px; }
    .meta { font-size: 0.85em; color: #555; }
    .tag { display: inline-block; background: #ddd; border-radius: 5px; padding: 2px 8px; margin-right: 5px; font-size: 0.8em; }
    footer { text-align: center; font-size: 0.8em; color: #888; margin-top: 50px; }
    .search-bar { margin-bottom: 20px; }
    .delete-btn { background: #e94e4e; }
    .delete-btn:hover { background: #b73939; }
    .edit-btn { background: #f0ad4e; }
    .edit-btn:hover { background: #d98c00; }
    .copy-btn { background: #6cc070; }
    .copy-btn:hover { background: #4e9f50; }
  </style>
</head>
<body>

  <header>
    <h1>匿名相談・共感プラットフォーム</h1>
    <p>悩みや相談を匿名で投稿し、共感やコメントをもらおう</p>
  </header>

  <div class="container">
    <div class="card">
      <h3>新しい相談を投稿</h3>
      <input type="text" id="postTags" placeholder="タグ(カンマ区切り)">
      <textarea id="postText" placeholder="あなたの悩みや相談を書いてください..."></textarea>
      <button onclick="addPost()">投稿する</button>
    </div>

    <div class="card search-bar">
      <input type="text" id="searchInput" placeholder="投稿検索..." oninput="searchPosts()">
    </div>

    <div id="postsContainer"></div>
  </div>

  <footer>
    &copy; 2025 匿名相談・共感プラットフォーム
  </footer>

  <script>
    let posts = JSON.parse(localStorage.getItem('posts')) || [];

    function addPost() {
      const text = document.getElementById('postText').value.trim();
      const tags = document.getElementById('postTags').value.split(',').map(tag => tag.trim()).filter(tag => tag);
      if (text) {
        posts.unshift({ text, tags, empathy: 0, comments: [], date: new Date().toLocaleString() });
        document.getElementById('postText').value = '';
        document.getElementById('postTags').value = '';
        saveAndRender();
      }
    }

    function addEmpathy(index) {
      posts[index].empathy++;
      saveAndRender();
    }

    function addComment(index, commentId) {
      const input = document.getElementById(commentId);
      const commentText = input.value.trim();
      if (commentText) {
        posts[index].comments.push({ text: commentText, date: new Date().toLocaleString() });
        input.value = '';
        saveAndRender();
      }
    }

    function editPost(index) {
      const newText = prompt('投稿内容を編集してください:', posts[index].text);
      if (newText !== null) {
        posts[index].text = newText;
        saveAndRender();
      }
    }

    function deletePost(index) {
      if (confirm('この投稿を削除しますか?')) {
        posts.splice(index, 1);
        saveAndRender();
      }
    }

    function copyPost(index) {
      navigator.clipboard.writeText(posts[index].text)
        .then(() => alert('投稿内容をコピーしました'))
        .catch(() => alert('コピーに失敗しました'));
    }

    function saveAndRender() {
      localStorage.setItem('posts', JSON.stringify(posts));
      renderPosts();
    }

    function renderPosts(filteredPosts = posts) {
      const container = document.getElementById('postsContainer');
      container.innerHTML = '';

      filteredPosts.forEach((post, index) => {
        let postHtml = `
          <div class="card">
            <p>${post.text}</p>
            <div>${post.tags.map(tag => `<span class='tag'>#${tag}</span>`).join(' ')}</div>
            <p class="meta">投稿日: ${post.date}</p>
            <button onclick="addEmpathy(${index})">共感 (${post.empathy})</button>
            <button class="copy-btn" onclick="copyPost(${index})">コピー</button>
            <button class="edit-btn" onclick="editPost(${index})">編集</button>
            <button class="delete-btn" onclick="deletePost(${index})">削除</button>
            <h4>コメント</h4>
            <input type="text" id="commentInput${index}" placeholder="コメントを書く...">
            <button onclick="addComment(${index}, 'commentInput${index}')">送信</button>
        `;

        post.comments.forEach(comment => {
          postHtml += `<div class="comment">${comment.text}<div class="meta">${comment.date}</div></div>`;
        });

        postHtml += '</div>';
        container.innerHTML += postHtml;
      });
    }

    function searchPosts() {
      const query = document.getElementById('searchInput').value.toLowerCase();
      const filtered = posts.filter(post =>
        post.text.toLowerCase().includes(query) ||
        post.tags.some(tag => tag.toLowerCase().includes(query))
      );
      renderPosts(filtered);
    }

    renderPosts();
  </script>

</body>
</html>

AIキャラクター掲示板

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AIキャラクター掲示板</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #e0e0e0;
      margin: 0;
      padding: 0;
    }
    header {
      background: #3949ab;
      color: white;
      text-align: center;
      padding: 15px;
    }
    .container {
      max-width: 800px;
      margin: 20px auto;
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    }
    .post {
      border-bottom: 1px solid #ddd;
      padding: 10px 0;
      display: flex;
      align-items: flex-start;
    }
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 10px;
    }
    .post-content {
      flex-grow: 1;
    }
    .character {
      font-weight: bold;
      color: #3949ab;
    }
    .timestamp {
      font-size: 0.8em;
      color: gray;
    }
    .message {
      margin: 5px 0;
    }
    .likes {
      font-size: 0.9em;
      cursor: pointer;
      color: #ff5722;
    }
    .input-group {
      margin-top: 20px;
    }
    input, textarea {
      width: 100%;
      padding: 8px;
      margin-top: 5px;
      border-radius: 4px;
      border: 1px solid #ccc;
      box-sizing: border-box;
    }
    button {
      margin-top: 10px;
      padding: 10px 15px;
      background: #3949ab;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button:hover {
      background: #303f9f;
    }
  </style>
</head>
<body>

<header>
  <h1>AIキャラクター掲示板</h1>
  <p>投稿数: <span id="postCount">0</span></p>
</header>

<div class="container" id="board"></div>

<div class="container input-group">
  <label>あなたの名前:</label>
  <input type="text" id="username" placeholder="例: カナタ">
  
  <label>メッセージ:</label>
  <textarea id="userMessage" placeholder="メッセージを入力..."></textarea>
  
  <button onclick="postMessage()">投稿</button>
</div>

<script>
  let postCounter = 0;

  const aiCharacters = [
    { name: 'ネオン', avatar: 'https://via.placeholder.com/40/673ab7/ffffff?text=N', replies: ['それ面白いね!', '詳しく教えて!', 'すごい!'] },
    { name: 'ルナ', avatar: 'https://via.placeholder.com/40/ff4081/ffffff?text=L', replies: ['なるほど!', '私もそう思うわ。', '参考になったわ。'] },
    { name: 'ソラ', avatar: 'https://via.placeholder.com/40/03a9f4/ffffff?text=S', replies: ['良い話だね!', '素敵だ!', 'もっと教えて!'] }
  ];

  function postMessage() {
    const username = document.getElementById('username').value || '名無しさん';
    const message = document.getElementById('userMessage').value.trim();
    if (!message) return;

    addPost(username, message, 'https://via.placeholder.com/40/9e9e9e/ffffff?text=U');
    document.getElementById('userMessage').value = '';
    aiCharacters.forEach((char, index) => {
      setTimeout(() => aiReply(char), 1000 * (index + 1));
    });
  }

  function addPost(user, message, avatarUrl) {
    postCounter++;
    document.getElementById('postCount').textContent = postCounter;

    const board = document.getElementById('board');
    const time = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    const post = document.createElement('div');
    post.className = 'post';
    post.innerHTML = `
      <img src="${avatarUrl}" alt="avatar" class="avatar">
      <div class="post-content">
        <span class="character">${user}</span> <span class="timestamp">[${time}]</span>
        <p class="message">${message}</p>
        <span class="likes" onclick="likePost(this)">♡ いいね</span>
      </div>`;
    board.appendChild(post);
  }

  function aiReply(character) {
    const reply = character.replies[Math.floor(Math.random() * character.replies.length)];
    addPost(character.name, reply, character.avatar);
  }

  function likePost(element) {
    let current = element.textContent;
    if (current.includes('♡')) {
      element.textContent = current.replace('♡', '❤️');
    }
  }
</script>

</body>
</html>