1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「これ、軽量モデルのフラッシュ君で書いたの…?」 ── 秀GASマネージャーを持たせたら、最速AIがネイティブ級スマホアプリを爆速生成する怪物になった話

1
Last updated at Posted at 2026-11-03

はじめに ―― 「これ、スマホで使えたら最強じゃないか?」

前回の記事で、自作のGmail爆速ビューア『Mクイック』をブラウザゼロで修復し、0.5秒の連打にも完全追従する怪物に仕立て上げた話を公開しました。

PCのブラウザで叩くMクイックは、まさに快適そのもの。数千件のメールがIndexedDBから瞬時に立ち上がり、キーボード操作でサクサク処理できる相棒になりました。

ですが、使い込んでいるうちに、ごく自然な欲求が湧き上がってきたのです。

「出先や移動中に、スマホでもこの速度でGmailを確認できたら、どれだけ助かるだろうか?」

早速スマートフォンでアクセスしてみました。
……しかし、現実は甘くありませんでした。

スマホ表示が崩れていた初期状態

PC用の4列テーブル(日付・差出人・件名・操作)を無理やりスマホの画面幅(約390px)に詰め込んだため、ヘッダーのボタンは画面外へ吹き飛び、件名列は押し潰され、とても実用に耐える状態ではなかったのです。

「やっぱりGASのWebアプリでスマホアプリなんて無理なのか……?」

普通ならここで諦めるか、「まあPC専用ツールだから」と割り切るところです。
しかし、私には 秀GASマネージャー と、頼れる相棒 Gemini Flash(フラッシュ君) がいました。

ここから、「軽量モデル×ガスマネージャー」が起こす、前代未聞のスマホアプリ開発劇が始まったのです。

スマホになった!


爆誕した『Mクイック』スマホ版 ―― ネイティブアプリと見分けがつかない3大機能

結論から申し上げます。完成したものは、「App Storeにあるネイティブアプリそのもの」 でした。
GAS特有のもっさり感や「Webページを見ている感」は完全に消え去っています。

スマホ版Mクイックの完成画面(ホワイト・グリーン・ダークの3色テーマ)

1. PWA(Progressive Web App)による「全画面アプリ化」

スマホのブラウザ(SafariやChrome)で開き、メニューから 「ホーム画面に追加」 を押すだけ。
それだけで、ブラウザのアドレスバーや戻るボタンが完全に消え去り、全画面スタンドアローンアプリとして起動します(※iPhoneでは専用の稲妻アイコン、AndroidではGAS仕様により親しみのある青いGoogleの「G」アイコンが配置されます)。

高価なMacも、年間数万円のApple Developer登録も、厳しいアプリ審査も一切不要。
Googleの無料インフラだけで、完全なスマホアプリが手元で動くのです。

2. Gmail公式準拠の「左右スワイプアクション」

スマートフォンで小さなボタンを親指で狙うのはストレスです。
そこで、メールカードを左右に指先でスワイプして処理できるようにしました。

  • 👉 右へスワイプ(緑): 指を離すとその場で 「アーカイブ」
  • 👈 左へスワイプ(赤): 指を離すとその場で 「ゴミ箱(削除)」

途中で指を戻せばバネのようにシュッと元の位置に戻る、滑らかなタッチアニメーションを実装しています。

3. 触覚フィードバック(Haptic微振動)

スワイプが閾値を超えた瞬間や、ボタンをタップした瞬間に、スマホ本体が 「コトッ」「トッ」と心地よく微振動 します。
わずか数行の Vibration API ですが、これが入るだけで「Webページを操作している感覚」が脳内から消え、本物のネイティブアプリの質感に化けました。


Mクイック のコード(自分でメールビューアを作りたい方へ)

この節では当初、Mクイック の写しをワンクリックで作れるリンクを置いていました。写しを配る形はやめて、コードをそのまま載せることにしました(2026-11-05)。

自分で Gmail のビューアを作ってみたい方の参考になればと思います。Apps Script の新しいプロジェクトに、下の 3 つのファイルを作って貼り、ウェブアプリとしてデプロイすれば動きます。

作るときに気をつけたい所を 2 つだけ書いておきます。

  • メール本文は sandbox 付きの iframe で表示しています。 getBody() で取れる HTML は、Gmail の画面と違ってスクリプトが取り除かれていません。Index.html の EMAIL_SAFE_HEAD の周りを見てください。
  • 添付ファイル名のように送り主が決める文字を onclick="…" に入れるときは、JS と HTML の両方の処理をしています。 Index.html の escapeJsStr です。

載せているのは、この 2 つを足した 11/05 の版です。

コード.gs(サーバー側・373 行)
コード.gs
/**
 * Webアプリケーションのエントリポイント
 */
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index')
    .setTitle('Gmail 一覧ダッシュボード')
    .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
    .addMetaTag('viewport', 'width=device-width, initial-scale=1');
}

/**
 * ユーザー作成のラベル一覧を取得
 */
function getUserLabels() {
  try {
    const labels = GmailApp.getUserLabels();
    return labels.map(label => label.getName());
  } catch (e) {
    console.error('getUserLabels error:', e);
    return [];
  }
}

/**
 * 条件に応じたメール一覧を取得 (N+1問題解消・添付走査の最適化版)
 */
function getEmailList(count, mode, _fetchDetails) {
  try {
    let query = '';
    if (mode === 'inbox') {
      query = 'in:inbox';
    } else if (mode === 'sent') {
      query = 'in:sent';
    } else if (mode === 'trash') {
      query = 'in:trash';
    } else if (mode === 'archive') {
      query = '-in:inbox -in:sent -in:trash';
    } else if (mode === 'all') {
      query = '-in:trash';
    } else {
      query = 'label:"' + mode + '" -in:trash';
    }

    const limit = (count === 'all' || typeof count !== 'number') ? 300 : count;
    const threads = GmailApp.search(query, 0, Math.min(limit, 500));
    
    if (threads.length === 0) return [];

    const messagesPerThread = GmailApp.getMessagesForThreads(threads);
    const result = [];
    const userEmail = Session.getActiveUser().getEmail();
    const timeZone = Session.getScriptTimeZone();

    threads.forEach((thread, index) => {
      const messages = messagesPerThread[index];
      if (!messages || messages.length === 0) return;

      const latestMsg = messages[messages.length - 1];
      const dateObj = latestMsg.getDate();

      const dateStr = Utilities.formatDate(dateObj, timeZone, 'yyyy/MM/dd');
      const timeStr = Utilities.formatDate(dateObj, timeZone, 'HH:mm');

      const fromRaw = (mode === 'sent') ? latestMsg.getTo() : latestMsg.getFrom();
      const fromMatch = fromRaw.match(/^(.*?)(?:<.*?>)?$/);
      const fromClean = (fromMatch && fromMatch[1].trim()) ? fromMatch[1].replace(/"/g, '').trim() : fromRaw;

      let hasAttachment = false;
      for (let i = messages.length - 1; i >= 0; i--) {
        try {
          if (messages[i].getAttachments({ includeInlineImages: false }).length > 0) {
            hasAttachment = true;
            break;
          }
        } catch (e) {
          break;
        }
      }

      const threadLabels = thread.getLabels().map(l => l.getName());
      const labelIds = [];
      if (thread.isInInbox()) labelIds.push('INBOX');
      if (thread.isInTrash()) labelIds.push('TRASH');
      if (mode === 'sent' || messages.some(m => m.getFrom().includes(userEmail))) {
        labelIds.push('SENT');
      }

      result.push({
        id: thread.getId(),
        subject: thread.getFirstMessageSubject() || '(件名なし)',
        from: fromClean,
        date: dateStr,
        time: timeStr,
        isUnread: thread.isUnread(),
        hasAttachment: hasAttachment,
        attachmentNames: [],
        labels: threadLabels,
        labelIds: labelIds
      });
    });

    return result;
  } catch (e) {
    console.error('getEmailList error:', e);
    throw new Error(e.message);
  }
}

/**
 * スレッドの詳細を取得し、既読化する
 */
function getThreadDetails(threadId) {
  try {
    const thread = GmailApp.getThreadById(threadId);
    if (!thread) return { success: false, error: 'スレッドが見つかりません' };

    if (thread.isUnread()) {
      thread.markRead();
    }

    const messages = thread.getMessages();
    const timeZone = Session.getScriptTimeZone();
    const details = messages.map(msg => {
      const msgId = msg.getId();
      const body = msg.getBody();
      const plainBody = body ? '' : msg.getPlainBody();
      const attachments = msg.getAttachments();
      return {
        id: msgId,
        from: msg.getFrom(),
        to: msg.getTo(),
        cc: msg.getCc(),
        date: Utilities.formatDate(msg.getDate(), timeZone, 'yyyy/MM/dd HH:mm:ss'),
        body: body,
        plainBody: plainBody,
        attachments: attachments.map((att, attIdx) => ({
          msgId: msgId,
          attIndex: attIdx,
          name: att.getName(),
          size: Math.round(att.getSize() / 1024) + ' KB',
          mimeType: att.getContentType()
        }))
      };
    });

    return {
      success: true,
      subject: thread.getFirstMessageSubject() || '(件名なし)',
      messages: details
    };
  } catch (e) {
    console.error('getThreadDetails error:', e);
    return { success: false, error: e.message };
  }
}

/**
 * ラベル付与とアーカイブ
 */
function updateLabelsAndArchive(threadId, labelName, isInboxMode) {
  try {
    const thread = GmailApp.getThreadById(threadId);
    if (!thread) return { success: false, error: 'スレッドが見つかりません' };

    if (labelName && labelName !== '__archive_only__') {
      let label = GmailApp.getUserLabelByName(labelName);
      if (!label) {
        label = GmailApp.createLabel(labelName);
      }
      thread.addLabel(label);
    }

    if (isInboxMode) {
      thread.moveToArchive();
    }

    return { success: true };
  } catch (e) {
    return { success: false, error: e.message };
  }
}

/**
 * スレッドからラベルを解除
 */
function removeLabelFromThread(threadId, labelName) {
  try {
    const thread = GmailApp.getThreadById(threadId);
    if (!thread) return { success: false, error: 'スレッドが見つかりません' };

    const label = GmailApp.getUserLabelByName(labelName);
    if (label) {
      thread.removeLabel(label);
    }

    return { success: true };
  } catch (e) {
    return { success: false, error: e.message };
  }
}

/**
 * メールをゴミ箱へ移動
 */

/**
 * ゴミ箱から受信トレイへ復元
 */

/**
 * ZIPエクスポート
 */
function exportEmailAsZip(threadId) {
  try {
    const thread = GmailApp.getThreadById(threadId);
    if (!thread) return { success: false, error: 'スレッドが見つかりません' };

    const messages = thread.getMessages();
    const firstMsg = messages[0];
    const timeZone = Session.getScriptTimeZone();
    const userEmail = Session.getActiveUser().getEmail();

    const timeStamp = Utilities.formatDate(firstMsg.getDate(), timeZone, 'yyyyMMdd_HHmm');
    const subject = thread.getFirstMessageSubject() || '無題';
    const cleanSubject = (subject.replace(/[\/\\?%*:|"<>]/g, '_').trim() || '無題').substring(0, 30);

    const isSent = firstMsg.getFrom().includes(userEmail);
    const rawTarget = isSent ? firstMsg.getTo() : firstMsg.getFrom();
    const match = rawTarget.match(/^(.*?)(?:<.*?>)?$/);
    const targetName = (match && match[1].trim()) ? match[1].replace(/["']/g, '').trim() : rawTarget;
    const cleanTarget = (targetName.replace(/[\/\\?%*:|"<>]/g, '_').trim() || '相手先').substring(0, 15);

    const baseName = `${timeStamp}_${cleanSubject}_${cleanTarget}`;

    let fullHtml = `<html><head><meta charset="utf-8"><style>body{font-family:sans-serif;padding:20px;} h2{border-bottom:1px solid #ccc;padding-bottom:8px;} .header{color:#555;font-size:13px;margin-bottom:20px;line-height:1.6;} hr{border:none;border-top:1px solid #eee;margin:20px 0;}</style></head><body>`;
    fullHtml += `<h2>${escapeHtmlServer(subject)}</h2>`;

    const blobs = [];
    const usedNames = new Set();

    function getUniqueName(fileName) {
      let name = fileName;
      let counter = 1;
      const dotIndex = name.lastIndexOf('.');
      const base = dotIndex !== -1 ? name.substring(0, dotIndex) : name;
      const ext = dotIndex !== -1 ? name.substring(dotIndex) : '';

      while (usedNames.has(name)) {
        name = `${base}(${counter})${ext}`;
        counter++;
      }
      usedNames.add(name);
      return name;
    }

    messages.forEach((msg, idx) => {
      fullHtml += `<div class="header">`;
      fullHtml += `<b>From:</b> ${escapeHtmlServer(msg.getFrom())}<br>`;
      fullHtml += `<b>To:</b> ${escapeHtmlServer(msg.getTo())}<br>`;
      fullHtml += `<b>Date:</b> ${Utilities.formatDate(msg.getDate(), timeZone, 'yyyy/MM/dd HH:mm:ss')}<br>`;
      fullHtml += `</div>`;
      fullHtml += `<div class="body">${msg.getBody()}</div>`;
      if (idx < messages.length - 1) fullHtml += `<hr>`;

      const attachments = msg.getAttachments();
      attachments.forEach(att => {
        const uniqueName = getUniqueName(att.getName());
        blobs.push(att.copyBlob().setName(uniqueName));
      });
    });
    fullHtml += `</body></html>`;

    const pdfName = getUniqueName(`${cleanSubject}.pdf`);
    const pdfBlob = Utilities.newBlob(fullHtml, 'text/html', `${cleanSubject}.html`)
      .getAs('application/pdf')
      .setName(pdfName);
    blobs.unshift(pdfBlob);

    const zipBlob = Utilities.zip(blobs, `${baseName}.zip`);
    const base64Data = Utilities.base64Encode(zipBlob.getBytes());

    return {
      success: true,
      fileName: `${baseName}.zip`,
      base64: base64Data
    };
  } catch (e) {
    console.error('exportEmailAsZip error:', e);
    return { success: false, error: e.message };
  }
}

function escapeHtmlServer(str) {
  if (!str) return '';
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}

/**
 * スレッドに対して正規の返信を送信する
 */
function replyToEmail(threadId, toAddress, _subjectText, bodyText, attachmentFiles) {
  try {
    const thread = GmailApp.getThreadById(threadId);
    if (!thread) return { success: false, error: 'スレッドが見つかりません' };

    const options = {
      htmlBody: bodyText.replace(/\n/g, '<br>')
    };

    if (attachmentFiles && attachmentFiles.length > 0) {
      options.attachments = attachmentFiles.map(file => {
        const decoded = Utilities.base64Decode(file.base64);
        return Utilities.newBlob(decoded, file.mimeType, file.name);
      });
    }

    // 最新メッセージの送信者と toAddress を比較し、追加の宛先があれば cc に追加
    const messages = thread.getMessages();
    const latestMsg = messages[messages.length - 1];
    const originalFrom = latestMsg.getFrom();

    if (toAddress && toAddress.trim()) {
      const targetEmails = toAddress.split(',').map(s => s.trim()).filter(Boolean);
      const extraRecipients = targetEmails.filter(addr => !originalFrom.includes(addr));
      if (extraRecipients.length > 0) {
        options.cc = extraRecipients.join(', ');
      }
    }

    // スレッドの文脈とヘッダー情報を維持して返信する
    thread.reply(bodyText, options);

    return { success: true };
  } catch (e) {
    console.error('replyToEmail error:', e);
    return { success: false, error: e.message };
  }
}

function getAttachment(messageId, attachmentIndex) {
  try {
    const msg = GmailApp.getMessageById(messageId);
    if (!msg) return { success: false, error: 'メッセージが見つかりません' };
    const attachments = msg.getAttachments();
    if (attachmentIndex < 0 || attachmentIndex >= attachments.length) {
      return { success: false, error: '添付ファイルが見つかりません' };
    }
    const att = attachments[attachmentIndex];
    return {
      success: true,
      name: att.getName(),
      mimeType: att.getContentType(),
      base64: Utilities.base64Encode(att.getBytes())
    };
  } catch (e) {
    console.error('getAttachment error:', e);
    return { success: false, error: e.message };
  }
}

function permanentlyDeleteMessage(threadId) {
  try {
    Gmail.Users.Threads.remove('me', threadId);
    return { success: true };
  } catch (e) {
    const msg = e.message || '';
    if (msg.includes('not found') || msg.includes('404') || msg.includes('NotFound')) {
      return { success: true, note: 'Already deleted' };
    }
    console.error('permanentlyDeleteMessage error:', e);
    return { success: false, error: msg };
  }
}
appsscript.json(設定)
appsscript.json
{
  "timeZone": "Asia/Tokyo",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Gmail",
        "version": "v1",
        "serviceId": "gmail"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_DEPLOYING",
    "access": "MYSELF"
  }
}
Index.html(画面・約 1,830 行)
Index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <!-- PWA / 全画面アプリ化 -->
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="Mクイック">
  <meta name="application-name" content="Mクイック">
  <meta name="theme-color" content="#ffffff" id="metaThemeColor">
  <link rel="apple-touch-icon" href="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><rect width='512' height='512' rx='128' fill='%230284c7'/><path d='M110 165l146 110 146-110' fill='none' stroke='white' stroke-width='32' stroke-linecap='round' stroke-linejoin='round'/><rect x='90' y='140' width='332' height='232' rx='28' fill='none' stroke='white' stroke-width='32'/><polygon points='280,210 220,320 270,320 240,410 330,290 270,290' fill='%23facc15'/></svg>">
  <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><rect width='512' height='512' rx='128' fill='%230284c7'/><path d='M110 165l146 110 146-110' fill='none' stroke='white' stroke-width='32' stroke-linecap='round' stroke-linejoin='round'/><rect x='90' y='140' width='332' height='232' rx='28' fill='none' stroke='white' stroke-width='32'/><polygon points='280,210 220,320 270,320 240,410 330,290 270,290' fill='%23facc15'/></svg>">
  <title>Mクイック - 超高速Gmailビューア</title>
  <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate, max-age=0">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="Wed, 11 Jan 1984 05:00:00 GMT">
  <style>
    :root {
      --text-main: #000000; --text-muted: #1e293b; --line-border: #cbd5e1; 
      --bg-header: #e2e8f0; --bg-btn: #f1f5f9; --bg-selected: #bae6fd;
      --bg-body: #e2e8f0; --bg-container: #ffffff; --ui-height: 32px;
      --sb-track: #f1f5f9; --sb-thumb: #94a3b8; --sb-thumb-hover: #64748b;
      --row-height: 56px;
      --card-bg: #ffffff; --card-border: #cbd5e1;
      --card-radius: 8px; --card-gap: 8px;
      --card-hover-bg: #e0f2fe; --card-hover-border: #0284c7;
      --card-selected-bg: #7dd3fc; --card-selected-border: #0284c7;
      --table-area-bg: #e2e8f0;
      --text-accent: #0284c7; --text-accent-hover: #0369a1;
    }

    body.dark-mode {
      --text-main: #f8fafc; --text-muted: #94a3b8; --line-border: #1e293b;
      --bg-header: #0b111e; --bg-btn: #1e293b; --bg-selected: #112547;
      --bg-body: #050811; --bg-container: #0b111e; --sb-track: #0b111e;
      --sb-thumb: #1e293b; --sb-thumb-hover: #334155;
      --card-bg: #111d33; --card-border: rgba(255, 255, 255, 0.08);
      --card-radius: 8px; --card-gap: 8px;
      --card-hover-bg: #162642; --card-hover-border: #2563eb;
      --card-selected-bg: #112547; --card-selected-border: #38bdf8;
      --table-area-bg: #0b111e;
      --text-accent: #38bdf8; --text-accent-hover: #7dd3fc;
    }

    body.green-mode {
      --text-main: #000000; --text-muted: #064e3b; --line-border: #86efac;
      --bg-header: #dcfce7; --bg-btn: #bbf7d0; --bg-selected: #86efac;
      --bg-body: #d1fae5; --bg-container: #ecfdf5; --sb-track: #d1fae5;
      --sb-thumb: #34d399; --sb-thumb-hover: #10b981;
      --ui-height: 32px; --row-height: 56px;
      --card-bg: #ffffff; --card-border: #86efac;
      --card-radius: 8px; --card-gap: 8px;
      --card-hover-bg: #a7f3d0; --card-hover-border: #047857;
      --card-selected-bg: #6ee7b7; --card-selected-border: #047857;
      --table-area-bg: #d1fae5;
      --text-accent: #047857; --text-accent-hover: #064e3b;
    }
    body.green-mode select.menu-select { background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path d='M0 3l5 5 5-5z' fill='%23047857'/></svg>"); background-color: #ecfdf5; }
    body.green-mode .top-settings-menu-item:hover { background: #bbf7d0; color: #064e3b; }
    body.green-mode button.count-btn.active { background: #047857; color: #ffffff; border-color: #047857; font-weight: 700; }

    body { 
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      background-color: var(--bg-body); margin: 0; padding: 20px; color: var(--text-main);
      transition: background-color 0.2s, color 0.2s;
    }

    .container { 
      max-width: 1300px; margin: 0 auto; background: var(--bg-container);
      border: 1px solid var(--line-border); border-radius: 8px;
      display: flex; flex-direction: column; height: 92vh; overflow: hidden;
      box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -1px rgba(0,0,0,0.02);
      transition: background-color 0.2s, border-color 0.2s; position: relative;
    }

    .top-bar { 
      padding: 10px 20px; border-bottom: 1px solid var(--line-border); 
      display: flex; align-items: center; justify-content: space-between; background: var(--bg-container);
      transition: background-color 0.2s, border-color 0.2s;
    }
    
    .title-area { display: flex; align-items: center; gap: 10px; }
    h1, h2 { margin: 0; font-size: 16px; font-weight: 600; color: var(--text-main); white-space: nowrap; user-select: none; }

    .sync-indicator { 
      display: none; align-items: center; gap: 4px; font-size: 11.5px; font-weight: 600;
      color: #0369a1; background: #e0f2fe; border: 1px solid #bae6fd;
      padding: 2px 8px; border-radius: 12px; white-space: nowrap;
    }
    body.dark-mode .sync-indicator { color: #38bdf8; background: rgba(56, 189, 248, 0.12); border-color: rgba(56, 189, 248, 0.3); }

    .controls { display: flex; align-items: center; gap: 12px; }
    .btn-group { display: flex; align-items: center; gap: 4px; }
    .btn-group span { font-size: 12px; font-weight: 600; margin-right: 2px; white-space: nowrap; color: var(--text-muted); }
    
    button.count-btn, select.menu-select, .search-box input { 
      height: var(--ui-height); box-sizing: border-box; border: 1px solid var(--line-border); border-radius: 6px; font-size: 12px; font-weight: 500; background: var(--bg-container); color: var(--text-main); padding: 0 10px; outline: none; transition: all 0.15s;
    }

    button.count-btn { cursor: pointer; background: var(--bg-btn); border-color: var(--line-border); }
    button.count-btn:hover { background: var(--line-border); }
    button.count-btn.active { background: #38bdf8; color: #0f172a; border-color: #38bdf8; font-weight: 700; }
    button:disabled, select:disabled, input:disabled { opacity: 0.5; cursor: not-allowed !important; }

    body:not(.dark-mode) select.menu-select { background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path d='M0 3l5 5 5-5z' fill='%23475569'/></svg>"); background-repeat: no-repeat; background-position: right 8px center; padding-right: 22px; appearance: none; }
    body.dark-mode select.menu-select { background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path d='M0 3l5 5 5-5z' fill='%2394a3b8'/></svg>"); background-repeat: no-repeat; background-position: right 8px center; padding-right: 22px; appearance: none; }

    .search-box { position: relative; display: flex; align-items: center; }
    .search-box input { padding: 0 24px 0 8px; width: 160px; }
    .search-box button { position: absolute; right: 6px; background: none; border: none; font-size: 18px; font-weight: 500; color: var(--text-muted); cursor: pointer; display: none; padding: 0; }

    .table-wrapper { overflow-y: auto; overflow-x: hidden; flex-grow: 1; outline: none; position: relative; background: var(--table-area-bg); padding: 8px 16px; }
    #mainTable { width: 100%; border-collapse: separate; border-spacing: 0 var(--card-gap); table-layout: fixed; }
    #mainTable thead th { position: sticky; top: 0; z-index: 10; background: var(--table-area-bg); font-size: 12px; color: var(--text-muted); padding: 4px 14px; border: none; text-align: left; font-weight: 600; letter-spacing: 0.02em; }
    
    #mainTable tbody tr { height: var(--row-height); cursor: pointer; transition: transform 0.15s ease, box-shadow 0.15s ease; }
    #mainTable td { padding: 0 14px; font-size: 13px; color: var(--text-main); overflow: hidden; font-weight: 400; vertical-align: middle; background-color: var(--card-bg); border-top: 1px solid var(--card-border); border-bottom: 1px solid var(--card-border); transition: background-color 0.15s ease, border-color 0.15s ease; }
    #mainTable td:first-child { border-left: 1px solid var(--card-border); border-top-left-radius: var(--card-radius); border-bottom-left-radius: var(--card-radius); }
    #mainTable td:last-child { border-right: 1px solid var(--card-border); border-top-right-radius: var(--card-radius); border-bottom-right-radius: var(--card-radius); }
    
    #mainTable tbody tr.processing { opacity: 0.4; pointer-events: none; } 
    #mainTable tbody tr:hover td { background-color: var(--card-hover-bg) !important; border-color: var(--card-hover-border) !important; }

    #mainTable tr.selected td,
    #mainTable tbody tr.selected td { background-color: var(--card-selected-bg) !important; border-color: var(--card-selected-border) !important; font-weight: 600; color: var(--text-main) !important; }
    #mainTable tr.selected td:first-child,
    #mainTable tbody tr.selected td:first-child { border-left: 6px solid var(--card-selected-border) !important; padding-left: 10px !important; }
    #mainTable tr.selected td:last-child,
    #mainTable tbody tr.selected td:last-child { border-right: 2px solid var(--card-selected-border) !important; }
    #mainTable tr.selected td,
    #mainTable tbody tr.selected td { border-top: 2px solid var(--card-selected-border) !important; border-bottom: 2px solid var(--card-selected-border) !important; } 
    
    #mainTable tr.selected .subject-text { color: var(--text-main) !important; font-weight: 600; }
    #mainTable tr.selected .col-from { color: var(--text-main) !important; font-weight: 700; }
    #mainTable tr.selected .clickable { color: var(--text-main) !important; }
    #mainTable tr.selected .clickable:hover { color: var(--text-accent-hover) !important; }

    tr.unread td { font-weight: 600; }
    tr.unread .subject-text { font-weight: 600; color: var(--text-accent) !important; }
    tr.selected.unread .subject-text { color: var(--text-accent) !important; font-weight: 700; }

    .clickable { cursor: pointer; }
    .clickable:hover { text-decoration: underline; color: var(--text-accent-hover) !important; }
    .col-date { width: 90px; text-align: center; color: var(--text-muted); font-size: 12px; }
    .col-from { width: 160px; font-weight: 500; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
    .col-subject { width: auto; position: relative; }

    .subject-wrapper { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; white-space: normal; line-height: 1.35; max-height: 2.7em; word-break: break-word; }
    .subject-text { font-weight: 400; color: var(--text-main); }

    .label-container { 
      display: inline-flex; align-items: center; gap: 4px; position: absolute;
      right: 14px; top: 50%; transform: translateY(-50%);
      background: var(--bg-container); padding: 2px 6px; border-radius: 4px;
      box-shadow: -4px 0 12px var(--bg-container);
      z-index: 5; opacity: 0; transition: opacity 0.1s ease; pointer-events: none; 
    }
    #mainTable tbody tr:hover .label-container { opacity: 1; pointer-events: auto; }
    
    .label-badge { display: inline-flex; align-items: center; padding: 1px 6px; font-size: 10.5px; background: var(--bg-btn) !important; border: 1px solid var(--line-border); border-radius: 4px; color: var(--text-main) !important; font-weight: 600; white-space: nowrap; }
    .remove-badge-btn { margin-left: 4px; cursor: pointer; font-weight: 700; color: var(--text-muted); padding: 0 1px; }
    .remove-badge-btn:hover { color: #ef4444; }
    
    .col-action { width: 155px; text-align: center; border-right: none; padding-left: 2px !important; padding-right: 2px !important; }
    .action-container { display: flex; align-items: center; justify-content: center; gap: 4px; width: 100%; flex-wrap: nowrap !important; white-space: nowrap !important; }

    .icon-btn { background: rgba(148, 163, 184, 0.08) !important; border: 1px solid var(--card-border) !important; font-size: 13px; cursor: pointer; margin: 0; border-radius: 6px; display: inline-flex; align-items: center; justify-content: center; transition: all 0.15s; width: 28px; height: 28px; box-sizing: border-box; flex-shrink: 0 !important; color: var(--text-main); }
    .icon-btn:hover { background: var(--bg-btn) !important; border-color: var(--text-muted) !important; transform: translateY(-1px); }
    
    .top-settings-menu { 
      position: absolute; top: 48px; right: 20px;
      background: var(--bg-container); border: 1px solid var(--line-border); border-radius: 8px; 
      box-shadow: 0 10px 25px rgba(0,0,0,0.2); 
      z-index: 1500; min-width: 180px; padding: 6px 0; display: none; flex-direction: column;
    }
    .top-settings-menu.show { display: flex; }
    .top-settings-menu-item { padding: 8px 16px; font-size: 13px; color: var(--text-main); cursor: pointer; font-weight: 500; display: flex; align-items: center; gap: 10px; }
    .top-settings-menu-item:hover { background: var(--bg-btn); color: #38bdf8; }
    .dropdown-divider { height: 1px; background: var(--line-border); margin: 4px 0; }

    .custom-dropdown-menu { 
      position: fixed; background: var(--bg-container); border: 1px solid var(--line-border); border-radius: 8px; 
      box-shadow: 0 10px 20px rgba(0,0,0,0.2); z-index: 1000; min-width: 150px; padding: 4px 0; max-height: 50vh; overflow-y: auto; 
    }
    .dropdown-item { padding: 6px 12px; font-size: 12.5px; color: var(--text-main); cursor: pointer; font-weight: 500; }
    .dropdown-item:hover { background: var(--bg-btn); color: #38bdf8; }
    
    .date-main { font-weight: 500; display: block; font-size: 12px; color: var(--text-main); pointer-events: none; }
    .date-sub { font-size: 10.5px; color: var(--text-muted); font-weight: 500; display: block; margin-top: 1px; pointer-events: none; }

    .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); display: none; align-items: center; justify-content: center; z-index: 2000; }
    .modal-content { background: #1e293b; color: #f8fafc; width: 85%; max-width: 840px; max-height: 82vh; border-radius: 12px; padding: 24px; overflow-y: auto; position: relative; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3); }
    .modal-header { display: flex; align-items: center; justify-content: space-between; border-bottom: 2px solid #38bdf8; padding-bottom: 10px; margin-bottom: 16px; }
    .modal-title { font-size: 17px; font-weight: 600; margin: 0; color: #f8fafc; display: flex; align-items: center; gap: 6px; }
    .close-btn { padding: 5px 12px; font-size: 12px; font-weight: 600; cursor: pointer; color: #f8fafc; border: 1px solid #475569; background: #334155; border-radius: 6px; transition: background 0.15s; }
    .close-btn:hover { background: #475569; }

    .email-modal-container { width: 90%; max-width: 950px; height: 85vh; display: flex; flex-direction: column; padding: 18px 24px; background: var(--bg-container); color: var(--text-main); border: 1px solid var(--line-border); }
    .email-modal-header { display: flex; align-items: center; justify-content: space-between; padding-bottom: 12px; border-bottom: 1px solid var(--line-border); }
    .email-modal-title { font-size: 16px; font-weight: 600; color: var(--text-main); margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 60%; }
    
    .email-modal-body { flex: 1; overflow-y: auto; padding-top: 14px; display: flex; flex-direction: column; }
    
    .msg-card { border: 1px solid var(--line-border); border-radius: 8px; background: var(--bg-header); padding: 12px 16px; margin-bottom: 14px; transition: all 0.2s; }
    .msg-meta { font-size: 12px; color: var(--text-muted); line-height: 1.6; margin-bottom: 10px; border-bottom: 1px dashed var(--line-border); padding-bottom: 8px; transition: all 0.2s; overflow: hidden; }
    .msg-meta strong { color: var(--text-main); }
    .msg-attachments { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 6px; }
    .attachment-chip { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; border-radius: 4px; background: var(--bg-btn); border: 1px solid var(--line-border); font-size: 11px; color: var(--text-main); }
    .clickable-attachment { cursor: pointer; transition: filter 0.15s, color 0.15s; }
    .clickable-attachment:hover { filter: brightness(0.9); color: #0284c7 !important; border-color: #7dd3fc; }
    body.dark-mode .clickable-attachment:hover { filter: brightness(1.2); color: #38bdf8 !important; }

    .email-frame { width: 100%; border: none; background: #ffffff; border-radius: 4px; min-height: 180px; }
    .open-ext-btn { padding: 5px 12px; font-size: 12px; font-weight: 600; cursor: pointer; color: #0284c7; background: #e0f2fe; border: 1px solid #bae6fd; border-radius: 6px; text-decoration: none; display: inline-flex; align-items: center; }

    details.recipients-box { margin: 3px 0; }
    details.recipients-box summary { cursor: pointer; list-style: none; display: flex; align-items: center; gap: 6px; user-select: none; outline: none; }
    details.recipients-box summary::-webkit-details-marker { display: none; }
    .recipients-summary-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-muted); font-size: 12px; flex: 1; }
    .recipients-badge { font-size: 11px; color: #38bdf8; background: rgba(56, 189, 248, 0.12); border: 1px solid rgba(56, 189, 248, 0.3); padding: 1px 7px; border-radius: 4px; white-space: nowrap; }
    .recipients-full-list { margin-top: 6px; padding: 8px 10px; background: var(--bg-container); border: 1px solid var(--line-border); border-radius: 6px; max-height: 120px; overflow-y: auto; font-size: 11.5px; line-height: 1.5; word-break: break-all; }

    .m-section { margin-bottom: 24px; }
    .m-h2 { font-size: 14.5px; font-weight: 700; margin-top: 22px; margin-bottom: 10px; padding: 4px 8px; border-left: 4px solid #38bdf8; background: rgba(56, 189, 248, 0.08); color: #38bdf8; border-radius: 0 4px 4px 0; }
    .m-p { font-size: 13px; color: #cbd5e1; line-height: 1.6; margin: 8px 0; font-weight: 400; }
    .m-ul { font-size: 13px; color: #cbd5e1; line-height: 1.7; padding-left: 20px; margin: 6px 0 12px 0; font-weight: 400; }
    .m-ul li { margin-bottom: 6px; }
    .m-ul strong { font-weight: 600; color: #f8fafc; }
    .m-tag { display: inline-block; padding: 1px 6px; font-size: 11px; border-radius: 4px; background: #334155; border: 1px solid #475569; color: #38bdf8; font-weight: 600; margin: 0 2px; }
    .m-table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 13px; }
    .m-table th { background: #0f172a !important; color: #38bdf8 !important; text-align: left; padding: 10px 12px; border: 1px solid #334155 !important; font-weight: 600; }
    .m-table td { background: #0f172a !important; color: #f8fafc !important; border: 1px solid #334155 !important; padding: 10px 12px; vertical-align: middle; border-radius: 0 !important; font-size: 13px; line-height: 1.6; }
    .m-table tbody tr:nth-child(even) td { background: #172033 !important; }
    .m-table td strong { color: #38bdf8 !important; }
    .m-callout { background: rgba(56, 189, 248, 0.05); border: 1px solid rgba(56, 189, 248, 0.2); border-radius: 6px; padding: 10px 14px; margin: 12px 0; font-size: 12.5px; color: #e2e8f0; line-height: 1.5; }

    * { scrollbar-width: thin; scrollbar-color: var(--sb-thumb) var(--sb-track); }
    ::-webkit-scrollbar { width: 12px; height: 12px; }
    ::-webkit-scrollbar-track { background: var(--sb-track); border-radius: 6px; }
    ::-webkit-scrollbar-thumb { background: var(--sb-thumb); border-radius: 6px; border: 3px solid var(--sb-track); }
    ::-webkit-scrollbar-thumb:hover { background: var(--sb-thumb-hover); }

    .btn-success { background: #10b981 !important; color: white !important; border-color: #059669 !important; }
    .btn-success:hover { background: #059669 !important; }
    .btn-primary { background: #38bdf8 !important; color: #0f172a !important; border-color: #0284c7 !important; font-weight: bold; }
    .btn-primary:hover { filter: brightness(0.9); }
    
    #replyFormContainer { display: none; border-top: 1px solid var(--line-border); padding: 16px 0 0 0; margin-top: 8px; }
    .reply-to-input { flex: 1; height: 30px; padding: 0 8px; border: 1px solid var(--line-border); border-radius: 4px; font-size: 13px; background: var(--bg-container); color: var(--text-main); outline: none; transition: border-color 0.2s; font-family: inherit; }
    .reply-to-input:focus { border-color: #38bdf8; }

    .reply-textarea { width: 100%; box-sizing: border-box; height: 150px; padding: 12px; border: 1px solid var(--line-border); border-radius: 6px; resize: vertical; font-family: inherit; font-size: 13.5px; background: var(--bg-container); color: var(--text-main); outline: none; transition: border-color 0.2s; }
    .reply-textarea:focus { border-color: #38bdf8; }
    .form-label { width: 55px; font-size: 13px; font-weight: 600; color: var(--text-main); text-align: right; padding-right: 8px; display: inline-block; }
  
    /* ==========================================
       スマートフォン最適化レスポンシブスタイル
       ========================================== */
    @media (max-width: 640px) {
      body {
        padding: 0 !important;
        margin: 0 !important;
        height: 100vh !important;
        height: 100dvh !important;
        overflow: hidden !important;
      }
      .container {
        max-width: 100% !important;
        width: 100% !important;
        height: 100vh !important;
        height: 100dvh !important;
        border: none !important;
        border-radius: 0 !important;
        margin: 0 !important;
      }
      .top-bar {
        padding: 8px 10px !important;
        flex-direction: column !important;
        gap: 8px !important;
        align-items: stretch !important;
      }
      .title-area {
        width: 100% !important;
        display: flex !important;
        justify-content: space-between !important;
        align-items: center !important;
      }
      .top-bar .controls {
        width: 100% !important;
        display: flex !important;
        align-items: center !important;
        gap: 6px !important;
        justify-content: space-between !important;
      }
      .top-bar .controls .menu-select {
        width: 86px !important;
        min-width: 86px !important;
        padding-left: 6px !important;
        padding-right: 18px !important;
        font-size: 11.5px !important;
      }
      .top-bar .controls .search-box {
        flex: 1 1 auto !important;
        min-width: 0 !important;
      }
      .top-bar .controls .search-box input {
        width: 100% !important;
        font-size: 11.5px !important;
      }
      .top-bar .controls .btn-group {
        flex: 0 0 auto !important;
        gap: 2px !important;
      }
      .top-bar .controls .btn-group span {
        display: none !important;
      }
      .top-bar .controls button.count-btn {
        padding: 0 6px !important;
        font-size: 11px !important;
      }

      
      /* スワイプアクション用アニメーション */
      .swipe-container {
        position: relative;
        overflow: hidden;
      }
      .swipe-action-bg {
        position: absolute;
        top: 0; bottom: 0; left: 0; right: 0;
        display: flex;
        align-items: center;
        padding: 0 20px;
        font-weight: 700;
        font-size: 14px;
        color: white;
        border-radius: 8px;
        z-index: 1;
        opacity: 0;
        transition: opacity 0.15s ease;
      }
      .swipe-action-archive {
        background: #10b981;
        justify-content: flex-start;
      }
      .swipe-action-delete {
        background: #ef4444;
        justify-content: flex-end;
      }
      #mainTable tbody tr:not(.virtual-spacer) {
        touch-action: pan-y;
        user-select: none;
        -webkit-user-select: none;
        transition: transform 0.2s cubic-bezier(0.2, 0.8, 0.2, 1), background-color 0.15s;
        will-change: transform;
      }

      /* テーブルのスマホカード化 */
      .table-wrapper {
        padding: 4px 8px !important;
      }
      #mainTable {
        display: block !important;
        width: 100% !important;
        table-layout: auto !important;
        border-spacing: 0 !important;
      }
      #mainTable thead {
        display: none !important;
      }
      #mainTable tbody {
        display: block !important;
        width: 100% !important;
      }
      .virtual-spacer {
        display: block !important;
        border: none !important;
        background: transparent !important;
        padding: 0 !important;
        margin: 0 !important;
        box-shadow: none !important;
      }
      .virtual-spacer td {
        display: block !important;
        border: none !important;
        padding: 0 !important;
        background: transparent !important;
      }

      #mainTable tbody tr:not(.virtual-spacer) {
        display: block !important;
        height: 114px !important;
        box-sizing: border-box !important;
        padding: 8px 10px !important;
        margin-bottom: 8px !important;
        border-radius: 8px !important;
        border: 1px solid var(--card-border) !important;
        background-color: var(--card-bg) !important;
        position: relative !important;
      }
      #mainTable tbody tr:not(.virtual-spacer) td {
        display: block !important;
        border: none !important;
        padding: 0 !important;
        background: transparent !important;
      }
      #mainTable tbody tr:not(.virtual-spacer) td:first-child,
      #mainTable tbody tr:not(.virtual-spacer) td:last-child {
        border-radius: 0 !important;
        border: none !important;
      }

      .col-from {
        display: block !important;
        font-size: 13.5px !important;
        font-weight: 700 !important;
        color: var(--text-main) !important;
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        margin-right: 80px !important;
        line-height: 18px !important;
      }
      .col-date {
        position: absolute !important;
        top: 8px !important;
        right: 10px !important;
        width: auto !important;
        font-size: 11px !important;
        color: var(--text-muted) !important;
        text-align: right !important;
        white-space: nowrap !important;
        line-height: 18px !important;
      }
      .date-main {
        font-size: 11px !important;
      }
      .date-sub {
        display: none !important;
      }
      .col-subject {
        display: block !important;
        margin-top: 4px !important;
        width: 100% !important;
        font-size: 12.5px !important;
        line-height: 1.35 !important;
        color: var(--text-main) !important;
      }
      .subject-wrapper {
        display: -webkit-box !important;
        -webkit-line-clamp: 2 !important;
        -webkit-box-orient: vertical !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: normal !important;
        max-height: 2.7em !important;
      }
      .col-action {
        position: absolute !important;
        bottom: 6px !important;
        right: 10px !important;
        left: 10px !important;
        width: auto !important;
        padding-top: 4px !important;
        border-top: 1px dashed var(--line-border) !important;
      }
      .action-container {
        display: flex !important;
        justify-content: flex-end !important;
        gap: 10px !important;
      }
      .action-container button.icon-btn {
        width: 30px !important;
        height: 26px !important;
        font-size: 14px !important;
        background: var(--bg-btn) !important;
        border: 1px solid var(--line-border) !important;
        border-radius: 4px !important;
      }

      /* 選択時ハイライト(スマホ) */
      #mainTable tbody tr.selected:not(.virtual-spacer) {
        background-color: var(--card-selected-bg) !important;
        border-color: var(--card-selected-border) !important;
      }

      /* モーダルのスマホ最適化 */
      .modal-content {
        width: 95% !important;
        max-width: 95% !important;
        max-height: 92vh !important;
        padding: 12px !important;
        border-radius: 8px !important;
      }
      .email-modal-header {
        flex-direction: column !important;
        align-items: stretch !important;
        gap: 8px !important;
      }
      .email-modal-header > div {
        flex-wrap: wrap !important;
        justify-content: flex-end !important;
      }
      .email-modal-title {
        font-size: 14px !important;
      }
    }

  </style>
</head>
<body>
  <div class="container">
    <header class="top-bar" role="banner">
      <div class="title-area">
        <h1 id="pageTitle">Gmail 一覧</h1>
        <span id="syncBadge" class="sync-indicator">🔄 同期中...</span>
      </div>
      <div class="controls">
        <div class="btn-group">
          <label for="viewSelect" style="display:flex;align-items:center;">種別:</label>
          <select id="viewSelect" class="menu-select" onchange="changeView(this.value)" aria-label="メール種別切り替え">
            <option value="inbox" selected>受信</option>
            <option value="sent">送信</option>
            <option value="archive">アーカイブ</option>
            <option value="all">全て</option>
            <option value="trash">ゴミ箱</option>
            <option disabled id="labelDivider">----------</option>
          </select>
        </div>
        <div class="search-box">
          <input type="text" id="keywordInput" placeholder="一覧から絞り込み..." aria-label="メール絞り込みキーワード">
          <button id="clearBtn" onclick="clearSearch()" aria-label="検索クリア">&times;</button>
        </div>
        <div class="btn-group" role="group" aria-label="表示件数切り替え">
          <button id="cntBtn50" onclick="changeCount(50, this)" class="count-btn active" aria-label="50件表示">50</button>
          <button id="cntBtn100" onclick="changeCount(100, this)" class="count-btn" aria-label="100件表示">100</button>
          <button id="cntBtnAll" onclick="changeCount('all', this)" class="count-btn" aria-label="全件表示">全</button>
        </div>
        <button id="mainSettingsBtn" onclick="toggleSettingsMenu(event)" class="icon-btn" title="設定とメニュー" aria-label="設定とメニュー">⚙️</button>
      </div>
    </header>
    
    <div id="topSettingsMenu" class="top-settings-menu" role="menu" aria-label="設定メニュー">
      <div class="top-settings-menu-item" onclick="handleMenuRefresh()" role="menuitem">
        <span class="top-settings-menu-icon">🔄</span> 最新情報を取得
      </div>
      <div class="top-settings-menu-item" onclick="handleCycleTheme()" role="menuitem">
        <span class="top-settings-menu-icon" id="themeMenuIcon">☀️</span> <span id="themeMenuText">ホワイトモード</span>
      </div>
      <div class="dropdown-divider"></div>
      <div class="top-settings-menu-item" onclick="handleMenuManual()" role="menuitem">
        <span class="top-settings-menu-icon">❓</span> 使い方マニュアル
      </div>
    </div>

    <main class="table-wrapper" id="tableArea" tabindex="0" onscroll="onScrollThrottled()" role="main">
      <table id="mainTable">
        <thead>
          <tr>
            <th class="col-date">日付</th>
            <th class="col-from">送付元・宛先</th>
            <th class="col-subject">件名</th>
            <th class="col-action">操作</th>
          </tr>
        </thead>
        <tbody id="listBody">
        </tbody>
      </table>
    </main>
  </div>

  <!-- メール閲覧モーダル -->
  <div id="emailViewModal" class="modal-overlay" onclick="closeEmailModal()">
    <div class="modal-content email-modal-container" onclick="event.stopPropagation()">
      <div class="email-modal-header">
        <h3 class="email-modal-title" id="viewModalSubject">読み込み中...</h3>
        <!-- ボタン群: 返信、Gmail、印刷、削除、閉じる の順 -->
        <div style="display: flex; gap: 8px; align-items: center;">
          <button id="replyBtn" class="open-ext-btn btn-success" style="display: none;" onclick="toggleReplyForm()">返信</button>
          <a id="viewModalExtLink" href="#" target="_blank" class="open-ext-btn">Gmail</a>
          <button id="printBtn" class="open-ext-btn" onclick="printCurrentEmail()">印刷</button>
          <button id="deleteEmailBtn" class="open-ext-btn" onclick="deleteCurrentEmail(event)" title="削除" style="color: #ef4444; background: #fee2e2; border-color: #fecaca; font-size: 13px; padding: 4px 10px;">🗑️</button>
          <button class="close-btn" onclick="closeEmailModal()">閉じる</button>
        </div>
      </div>
      
      <div class="email-modal-body" id="viewModalScrollArea">
        <div id="viewModalContent">
          <div style="text-align: center; padding: 40px; color: var(--text-muted);">本文を読み込んでいます...</div>
        </div>
        
        <!-- 返信フォーム -->
        <div id="replyFormContainer">
          <div style="margin-bottom: 12px; font-weight: 600; font-size: 14px; color: #38bdf8;">
            ◆ 返信の作成
          </div>
          
          <div style="display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px;">
            <div style="display: flex; align-items: center;">
              <span class="form-label">宛先(To):</span>
              <input type="text" id="replyToInput" class="reply-to-input" placeholder="宛先メールアドレスを入力してください">
            </div>
            <div style="display: flex; align-items: center;">
              <span class="form-label">件名:</span>
              <input type="text" id="replySubjectInput" class="reply-to-input" placeholder="件名を入力してください">
            </div>
          </div>
          
          <textarea id="replyBody" class="reply-textarea" placeholder="返信内容を入力してください..."></textarea>
          <div style="margin-top: 12px; display: flex; align-items: center; justify-content: space-between;">
            <input type="file" id="replyAttachments" multiple style="font-size: 12px; color: var(--text-muted); cursor: pointer;">
            <div style="display: flex; gap: 8px;">
              <button onclick="toggleReplyForm()" class="close-btn">キャンセル</button>
              <button id="sendReplyBtn" onclick="sendReply()" class="open-ext-btn btn-primary">送信する</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- マニュアルモーダル -->
  <div id="manualModal" class="modal-overlay" onclick="closeManualModal()">
    <div class="modal-content" onclick="event.stopPropagation()">
      <div class="modal-header">
        <h3 class="modal-title">📖 Gmail 一覧ダッシュボード 総合利用マニュアル</h3>
        <button class="close-btn" onclick="closeManualModal()">閉じる</button>
      </div>

      <div class="m-section">
        <p class="m-p">本ダッシュボードは、Gmailのメッセージ・スレッドをローカル環境並みの速度で一覧化し、プレビュー・分類・ダウンロード・返信を一元的に完結させるためのWebアプリケーションです。</p>
        <div class="m-callout">
          ⚡ <strong>高速化のコア仕組み:</strong> ブラウザ内部ストレージ(IndexedDB)と仮想スクロール、並列処理ワーカーを活用しています。画面遷移やロード待ちの時間を徹底的に削減し、即時描画と瞬時フィルタリングを実現しています。<br>
          ⌨️ <strong>操作のヒント:</strong> マニュアル、メール詳細、返信フォーム、メニューなど、<strong>開いた画面はすべてキーボードの <span class="m-tag">Esc</span> キーで瞬時に閉じることができます。</strong>
        </div>
      </div>

      <div class="m-h2">1. 画面構成と基本コントロール</div>
      <table class="m-table">
        <thead>
          <tr>
            <th style="width: 25%;">機能・UI</th>
            <th>説明・操作方法</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><strong>種別切り替え</strong></td>
            <td>受信トレイ、送信済み、アーカイブ、全て、ゴミ箱、およびユーザー作成の独自ラベルを瞬時に切り替えます。キャッシュ済みデータのため通信待機なしで切り替わります。</td>
          </tr>
          <tr>
            <td><strong>高速絞り込み検索</strong></td>
            <td>入力欄にキーワードを入れると、件名・差出人・日付をリアルタイム検索(Web Worker並列処理)します。右端の「×」で検索条件を即時クリアできます。</td>
          </tr>
          <tr>
            <td><strong>件数切り替え (50/100/全)</strong></td>
            <td>取得件数の上限を変更します。通常は「50」で十分ですが、過去ログをまとめて整理したい場合は「100」または「全」を選択します。</td>
          </tr>
          <tr>
            <td><strong>設定メニュー (⚙️)</strong></td>
            <td>最新メールの強制同期(🔄)、画面モードのローテーション切替(☀️ホワイト/🌙ダーク/🌿グリーン)、本マニュアルの再表示(❓)を行えます。選択したモードは自動保存されます。</td>
          </tr>
        </tbody>
      </table>

      <div class="m-h2">2. 一覧テーブルでの直感操作とカード型デザイン</div>
      <ul class="m-ul">
        <li><strong>モダンカード型レイアウト:</strong> 1通ごとのメールが独立した角丸カードとして整列し、選択中のメールは鮮やかなアクセント枠(左端極太バー)と高コントラストな背景色でクッキリ浮かび上がります。</li>
        <li><strong>クリック一発フィルタ:</strong> 「日付」または「送付元・宛先」のセルをクリックすると、その値が検索ボックスに自動投入され、同一人物や同日のメールを即座に絞り込みます。もう一度クリックすると解除されます。</li>
        <li><strong>マウスホバーの先読み機能:</strong> 行の上にマウスカーソルを乗せると、約0.4秒でメール本文をバックグラウンド取得(プリフェッチ)します。クリックした瞬間に待たずに本文が開きます。</li>
        <li><strong>未読と既読の管理:</strong> 各テーマに応じたアクセントカラーの太字で表示されているメールは未読です。本文プレビューを開くと、自動的にGmail側および画面上で既読状態に更新されます。</li>
      </ul>

      <div class="m-h2">3. 操作ボタン一覧 (行右端)</div>
      <table class="m-table">
        <thead>
          <tr>
            <th style="width: 15%;">ボタン</th>
            <th style="width: 25%;">機能名</th>
            <th>詳細</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style="text-align: center;"><span class="m-tag">👁️</span></td>
            <td><strong>本文プレビュー</strong></td>
            <td>画面を移動せず、同一画面上でスレッド全体の全メッセージ・本文・添付ファイルを確認できます。</td>
          </tr>
          <tr>
            <td style="text-align: center;"><span class="m-tag">📥</span></td>
            <td><strong>ZIP一括保存</strong></td>
            <td>スレッド全体の本文をまとめたPDFと、すべての添付ファイルを1つのZIPファイルにパッケージして一発ダウンロードします。</td>
          </tr>
          <tr>
            <td style="text-align: center;"><span class="m-tag">🏷️</span></td>
            <td><strong>ラベル付け・保管</strong></td>
            <td>独自ラベルの付与や、受信トレイからアーカイブへの移動を行います。付与されたラベルは件名右側にバッジ表示され、「×」ボタンで即時解除も可能です。</td>
          </tr>
          <tr>
            <td style="text-align: center;"><span class="m-tag">🗑️</span> / <span class="m-tag">↩️</span></td>
            <td><strong>ゴミ箱 / 復元</strong></td>
            <td>メールをゴミ箱へ移動します。種別で「ゴミ箱」を選択中は、ボタンが「↩️」に変化し、ワンクリックで受信トレイへ復元できます。</td>
          </tr>
        </tbody>
      </table>

      <div class="m-h2">4. メール詳細モーダルと返信手順</div>
      <ul class="m-ul">
        <li><strong>スレッド表示:</strong> 1つの案件に対する過去のやり取りが時系列でカード化されて並びます。宛先が複数ある場合は「他○名 ▼ 詳細」をクリックすることで全員の宛先・CCを確認できます。</li>
        <li><strong>添付ファイルの直接ダウンロード:</strong> チップをクリックするだけで、ブラウザ経由で即時保存できます。</li>
        <li><strong>返信の作成・送信:</strong>
          <ul style="padding-left: 18px; margin-top: 4px;">
            <li>右上の緑色ボタン <span class="m-tag">返信</span> を押すと、画面下部に返信フォームが開きます。</li>
            <li>「宛先(To)」および「件名(Re: 付与済み)」は自動入力されます(手動変更も可能)。</li>
            <li>返信本文を入力し、必要に応じてファイルを選択して <span class="m-tag">送信する</span> をクリックします。</li>
            <li><strong>自動スレッド統合:</strong> 送信後、Gmailの正規スレッドに自動マージされ、画面上のスレッド最下部に自身の返信がリアルタイム反映されます。</li>
          </ul>
        </li>
      </ul>

      <div class="m-h2">5. 動作・セキュリティ仕様とトラブルシューティング</div>
      <ul class="m-ul">
        <li><strong>正規Googleサーバーからの送信:</strong> 本アプリからの返信は、Google公式の送信認証(SPF/DKIM)をパスした正規メールとして相手先に届きます。行政機関(LGWAN/pref.lg.jpなど)のセキュリティゲートウェイでもなりすまし判定されません。</li>
        <li><strong>オプティミスティックUI(即時反応):</strong> アーカイブ・削除・ラベル変更は、サーバー通信の完了を待たずに画面へ即座に反映されます。万一サーバー側で失敗した場合は自動でロールバックされ、アラートでお知らせします。</li>
        <li><strong>最新情報の同期タイミング:</strong> 別タブやスマートフォンでGmailを操作した場合でも、この画面にフォーカスが戻ると(1分以上経過時)自動で差分同期が走ります。手動で即座に合わせたいときは「⚙️」→「🔄 最新情報を取得」を実行してください。</li>
      </ul>

      <div class="m-h2">6. 3つの画面テーマ(デザインモード)</div>
      <table class="m-table">
        <thead>
          <tr>
            <th style="width: 25%;">モード</th>
            <th>特徴・視覚設計</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><strong>☀️ ホワイトモード</strong></td>
            <td>標準の明るいテーマ。スレートグレーの背景に純白のカードが浮かび、選択行は濃いスカイブルー(#bae6fd)と左端の極太ブルーバーで誰が見ても一目で判別できます。</td>
          </tr>
          <tr>
            <td><strong>🌙 ダークモード</strong></td>
            <td>深みのある漆黒ネイビーを基調とした、夜間作業や目に優しい高コントラストモード。選択行は深青カードと鮮やかな発光水色枠で視認性を保ちます。</td>
          </tr>
          <tr>
            <td><strong>🌿 グリーンモード</strong></td>
            <td>穏やかなセージ&ミントグリーンを取り入れたナチュラルテーマ。爽快なパステルグリーンの世界観にエメラルドのアクセント枠が調和し、長時間の閲覧でも目が疲れません。</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <script>
    // ==========================================
    // 状態管理・最適化コア変数
    // ==========================================
    let currentCount = 50; 
    let currentMode = 'inbox';
    let currentFilterValue = null;
    let globalLabels = []; 
    let currentViewThreadId = null; 
    
    let allFetchedEmails = []; 
    let filteredData = []; 
    let ROW_HEIGHT = window.innerWidth <= 640 ? 122 : 56;
    window.addEventListener('resize', () => {
      const newHeight = window.innerWidth <= 640 ? 122 : 56;
      if (ROW_HEIGHT !== newHeight) {
        ROW_HEIGHT = newHeight;
        if (typeof onScroll === 'function') onScroll();
      }
    }); 

    const prefetchCache = new Map();
    let prefetchTimer = null;
    let lastSyncTime = 0; 

    // ==========================================
    // IndexedDB (永続化キャッシュ)
    // ==========================================
    const DB_NAME = 'GmailUltraDB';
    const STORE_NAME = 'emailsStore';

    function openDB() {
      return new Promise((resolve, reject) => {
        const req = indexedDB.open(DB_NAME, 1);
        req.onupgradeneeded = e => { e.target.result.createObjectStore(STORE_NAME, { keyPath: 'id' }); };
        req.onsuccess = e => resolve(e.target.result);
        req.onerror = e => reject(e.target.error);
      });
    }

    async function saveToDB(emails) {
      const db = await openDB();
      const tx = db.transaction(STORE_NAME, 'readwrite');
      const store = tx.objectStore(STORE_NAME);
      store.clear();
      emails.forEach(e => store.put(e));
    }

    async function loadFromDB() {
      const db = await openDB();
      return new Promise(resolve => {
        const req = db.transaction(STORE_NAME, 'readonly').objectStore(STORE_NAME).getAll();
        req.onsuccess = e => resolve(e.target.result);
      });
    }

    // ==========================================
    // Web Worker (並列フィルタリング & 自動ソート)
    // ==========================================
    const workerCode = `
      self.onmessage = function(e) {
        const { data, keyword, mode } = e.data;
        let result = data;
        
        if (mode === 'inbox') result = result.filter(m => m.labelIds && m.labelIds.includes('INBOX') && !m.labelIds.includes('TRASH'));
        else if (mode === 'sent') result = result.filter(m => m.labelIds && m.labelIds.includes('SENT') && !m.labelIds.includes('TRASH'));
        else if (mode === 'trash') result = result.filter(m => m.labelIds && m.labelIds.includes('TRASH'));
        else if (mode === 'archive') result = result.filter(m => m.labelIds && !m.labelIds.includes('INBOX') && !m.labelIds.includes('SENT') && !m.labelIds.includes('TRASH') && (!m.labels || m.labels.length === 0));
        else if (mode === 'all') result = result.filter(m => m.labelIds && !m.labelIds.includes('TRASH'));
        else result = result.filter(m => m.labels && m.labels.includes(mode) && m.labelIds && !m.labelIds.includes('TRASH'));

        if (keyword) {
          const kw = keyword.toLowerCase();
          result = result.filter(m => 
            (m.subject && m.subject.toLowerCase().includes(kw)) || 
            (m.from && m.from.toLowerCase().includes(kw)) || 
            (m.date && m.date.includes(kw))
          );
        }

        result.sort((a, b) => {
          const dtA = a.date + ' ' + a.time;
          const dtB = b.date + ' ' + b.time;
          return dtB.localeCompare(dtA);
        });

        self.postMessage(result);
      }
    `;
    const workerBlob = new Blob([workerCode], { type: 'text/javascript' });
    const filterWorker = new Worker(URL.createObjectURL(workerBlob));
    
    filterWorker.onmessage = function(e) {
      filteredData = e.data;
      document.getElementById('tableArea').scrollTop = 0; 
      renderVirtualScroll();
    };

    function applyWorkerFilter() {
      const kw = document.getElementById('keywordInput').value.trim();
      filterWorker.postMessage({ data: allFetchedEmails, keyword: kw, mode: currentMode });
    }

    // ==========================================
    // 初期化・UIイベント・自動同期機能
    // ==========================================
    
    // ==========================================
    // 触覚フィードバック (Haptic Feedback)
    // ==========================================
    function triggerHaptic(type) {
      if (!navigator.vibrate) return;
      try {
        if (type === 'light') navigator.vibrate(12);
        else if (type === 'medium') navigator.vibrate(22);
        else if (type === 'success') navigator.vibrate([15, 30, 20]);
        else if (type === 'warning') navigator.vibrate([25, 40, 25]);
      } catch (e) {}
    }

    // ==========================================
    // スマホ用スワイプアクション (Gmail準拠: 右アーカイブ / 左削除)
    // ==========================================
    let touchStartX = 0;
    let touchStartY = 0;
    let touchCurrentTr = null;
    let touchSwiping = false;
    let touchThresholdMet = false;

    function initSwipeListeners() {
      const tableWrapper = document.getElementById('tableArea');
      if (!tableWrapper) return;

      tableWrapper.addEventListener('touchstart', (e) => {
        if (window.innerWidth > 640) return;
        const tr = e.target.closest('#mainTable tbody tr:not(.virtual-spacer)');
        if (!tr || e.target.closest('.action-container') || e.target.closest('.label-badge')) return;
        
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
        touchCurrentTr = tr;
        touchSwiping = false;
        touchThresholdMet = false;
        tr.style.transition = 'none';
      }, { passive: true });

      tableWrapper.addEventListener('touchmove', (e) => {
        if (!touchCurrentTr || window.innerWidth > 640) return;
        const diffX = e.touches[0].clientX - touchStartX;
        const diffY = e.touches[0].clientY - touchStartY;

        // 垂直スクロール優先の判定
        if (!touchSwiping && Math.abs(diffY) > Math.abs(diffX) && Math.abs(diffY) > 8) {
          touchCurrentTr = null;
          return;
        }

        if (Math.abs(diffX) > 10) {
          touchSwiping = true;
          window.isSwipingNow = true;
          // カードの追従移動
          touchCurrentTr.style.transform = `translateX(${diffX}px)`;

          // 閾値(70px)を超えたら色味強調とフィードバック
          if (diffX > 70) {
            touchCurrentTr.style.backgroundColor = 'rgba(16, 185, 129, 0.15)'; // アーカイブ緑
            if (!touchThresholdMet) {
              touchThresholdMet = true;
              triggerHaptic('medium');
            }
          } else if (diffX < -70) {
            touchCurrentTr.style.backgroundColor = 'rgba(239, 68, 68, 0.15)'; // 削除赤
            if (!touchThresholdMet) {
              touchThresholdMet = true;
              triggerHaptic('medium');
            }
          } else {
            touchCurrentTr.style.backgroundColor = '';
            touchThresholdMet = false;
          }
        }
      }, { passive: true });

      tableWrapper.addEventListener('touchend', (e) => {
        if (!touchCurrentTr || window.innerWidth > 640) return;
        const tr = touchCurrentTr;
        const id = tr.dataset.id;
        const diffX = e.changedTouches[0].clientX - touchStartX;

        tr.style.transition = 'transform 0.25s ease, opacity 0.2s ease, background-color 0.2s';

        if (diffX > 80) {
          // 右スワイプ: アーカイブ
          tr.style.transform = 'translateX(100%)';
          tr.style.opacity = '0';
          triggerHaptic('success');
          setTimeout(() => {
            optimisticAction(id, 'archive', e);
          }, 180);
        } else if (diffX < -80) {
          // 左スワイプ: 削除
          tr.style.transform = 'translateX(-100%)';
          tr.style.opacity = '0';
          triggerHaptic('warning');
          setTimeout(() => {
            optimisticAction(id, 'delete', e);
          }, 180);
        } else {
          // 元に戻す
          tr.style.transform = 'translateX(0)';
          tr.style.backgroundColor = '';
        }

        touchCurrentTr = null;
        touchSwiping = false;
        touchThresholdMet = false;
        setTimeout(() => { window.isSwipingNow = false; }, 80);
      }, { passive: true });
    }

    window.onload = async function() {
      initSwipeListeners(); 
      let savedTheme = localStorage.getItem('gmail_ultra_theme');
      if (!savedTheme) {
        if (localStorage.getItem('gmail_ultra_dark_mode') === 'true') savedTheme = 'dark';
        else if (localStorage.getItem('gmail_ultra_green_mode') === 'true') savedTheme = 'green';
        else savedTheme = 'light';
      }
      applyTheme(savedTheme);

      const savedMode = localStorage.getItem('gmail_ultra_current_mode');
      if (savedMode) currentMode = savedMode;
      document.getElementById('viewSelect').value = currentMode;

      const cached = await loadFromDB();
      if (cached && cached.length > 0) {
        allFetchedEmails = cached;
        applyWorkerFilter();
      }

      google.script.run.withSuccessHandler(setupLabelOptions).withFailureHandler(e => console.warn('ラベル取得待機:', e)).getUserLabels();
      startSync(); 
      
      window.addEventListener('click', closeSettingsMenu); 
      document.getElementById('keywordInput').addEventListener('input', function() {
        currentFilterValue = this.value.trim();
        document.getElementById('clearBtn').style.display = currentFilterValue ? 'block' : 'none';
        clearTimeout(window.filterTimer);
        window.filterTimer = setTimeout(applyWorkerFilter, 200); 
      });
    };

    // ==========================================
    // キーボードショートカット (Escキーで閉じる)
    // ==========================================
    window.addEventListener('keydown', function(e) {
      if (e.key === 'Escape' || e.key === 'Esc') {
        if (document.getElementById('customLabelMenu')) {
          closeLabelMenu();
          return;
        }

        const settingsMenu = document.getElementById('topSettingsMenu');
        if (settingsMenu && settingsMenu.classList.contains('show')) {
          closeSettingsMenu();
          return;
        }

        const manualModal = document.getElementById('manualModal');
        if (manualModal && manualModal.style.display === 'flex') {
          closeManualModal();
          return;
        }

        const emailModal = document.getElementById('emailViewModal');
        if (emailModal && emailModal.style.display === 'flex') {
          const replyForm = document.getElementById('replyFormContainer');
          if (replyForm && replyForm.style.display === 'block') {
            toggleReplyForm();
          } else {
            closeEmailModal();
          }
          return;
        }
      }
    });

    window.addEventListener('focus', () => {
      const now = Date.now();
      if (now - lastSyncTime > 60000) { 
        startSync();
      }
    });

    let isSyncing = false;
    function startSync() {
      if (isSyncing) return;
      isSyncing = true;
      lastSyncTime = Date.now(); 
      
      setSyncBadge(true, '🔄 同期中...');
      google.script.run
        .withSuccessHandler(res => {
          isSyncing = false;
          setSyncBadge(false);
          if(!res) return;
          const newIds = new Set(res.map(m => m.id));
          
          allFetchedEmails = [
            ...res,
            ...allFetchedEmails.filter(m => {
              if (newIds.has(m.id)) return false;
              if (currentMode === 'trash' && m.labelIds && m.labelIds.includes('TRASH')) return false;
              if (currentMode === 'inbox' && m.labelIds && m.labelIds.includes('INBOX')) return false;
              if (currentMode === 'sent' && m.labelIds && m.labelIds.includes('SENT')) return false;
              if (currentMode === 'archive' && (!m.labelIds || (!m.labelIds.includes('INBOX') && !m.labelIds.includes('TRASH')))) return false;
              if (currentMode !== 'all' && m.labels && m.labels.includes(currentMode)) return false;
              return true;
            })
          ];
          saveToDB(allFetchedEmails);
          applyWorkerFilter(); 
        })
        .withFailureHandler(e => { isSyncing = false; setSyncBadge(false); console.error(e);
})
        .getEmailList(currentCount, currentMode, false);
    }

    function setSyncBadge(show, text) {
      const badge = document.getElementById('syncBadge');
      if (text) badge.innerText = text;
      badge.style.display = show ? 'inline-flex' : 'none';
    }

    // ==========================================
    // メニュー関連
    // ==========================================
    function toggleSettingsMenu(e) { e.stopPropagation(); document.getElementById('topSettingsMenu').classList.toggle('show'); }
    function closeSettingsMenu() { document.getElementById('topSettingsMenu').classList.remove('show'); }
    async function handleMenuRefresh() {
      closeSettingsMenu();
      allFetchedEmails = [];
      const db = await openDB();
      const tx = db.transaction(STORE_NAME, 'readwrite');
      tx.objectStore(STORE_NAME).clear();
      startSync();
    }
    const THEMES_LIST = ['light', 'dark', 'green'];
    const THEME_LABELS = { 'light': 'ホワイトモード', 'dark': 'ダークモード', 'green': 'グリーンモード' };
    const THEME_ICONS_MAP = { 'light': '☀️', 'dark': '🌙', 'green': '🌿' };

    function applyTheme(theme) {
      document.body.classList.remove('dark-mode', 'green-mode');
      if (theme === 'dark') document.body.classList.add('dark-mode');
      else if (theme === 'green') document.body.classList.add('green-mode');
      localStorage.setItem('gmail_ultra_theme', theme);
      localStorage.setItem('gmail_ultra_dark_mode', theme === 'dark');
      localStorage.setItem('gmail_ultra_green_mode', theme === 'green');
      const iconEl = document.getElementById('themeMenuIcon');
      const textEl = document.getElementById('themeMenuText');
      if (iconEl) iconEl.textContent = THEME_ICONS_MAP[theme] || '☀️';
      if (textEl) textEl.textContent = THEME_LABELS[theme] || 'ホワイトモード';
    }

    function handleCycleTheme() {
      triggerHaptic('light');
      let cur = localStorage.getItem('gmail_ultra_theme') || 'light';
      let nextIdx = (THEMES_LIST.indexOf(cur) + 1) % THEMES_LIST.length;
      applyTheme(THEMES_LIST[nextIdx]);
    }

    function handleMenuDarkMode() { handleCycleTheme(); }
    function toggleDarkMode() { handleCycleTheme(); }
    function handleMenuManual() { closeSettingsMenu(); openManualModal(); }
    function openManualModal() { document.getElementById('manualModal').style.display = 'flex'; }
    function closeManualModal() { document.getElementById('manualModal').style.display = 'none'; }
    
    function changeView(mode) { 
      currentMode = mode; 
      localStorage.setItem('gmail_ultra_current_mode', mode); 
      clearSearch(); 
      startSync(); 
    }
    
    function changeCount(count, btn) {
      document.querySelectorAll('.count-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      currentCount = count; clearSearch(); startSync();
    }
    function clearSearch() {
      const input = document.getElementById('keywordInput');
      input.value = ''; currentFilterValue = null;
      document.getElementById('clearBtn').style.display = 'none';
      applyWorkerFilter(); input.focus();
    }
    function toggleCellFilter(text, event) {
      if (window.getSelection().toString().length > 0) return;
      event.stopPropagation();
      currentFilterValue = (currentFilterValue === text) ? null : text;
      const input = document.getElementById('keywordInput');
      input.value = currentFilterValue || '';
      document.getElementById('clearBtn').style.display = currentFilterValue ? 'block' : 'none';
      applyWorkerFilter();
    }
    function setupLabelOptions(labels) {
      globalLabels = labels; 
      const select = document.getElementById('viewSelect');
      if (labels.length === 0) { document.getElementById('labelDivider')?.remove(); return; }
      labels.forEach(label => {
        const opt = document.createElement('option');
        opt.value = label; opt.innerText = label;
        select.appendChild(opt);
      });
      select.value = currentMode;
    }

    // ==========================================
    // 仮想スクロール描画
    // ==========================================
    let scrollTimer = null;
    function onScrollThrottled() {
      if (!scrollTimer) {
        scrollTimer = requestAnimationFrame(() => {
          renderVirtualScroll();
          scrollTimer = null;
        });
      }
    }

    function renderVirtualScroll() {
      const wrapper = document.getElementById('tableArea');
      const tbody = document.getElementById('listBody');
      
      if (filteredData.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; padding: 40px; border:none; color: var(--text-muted);">該当するメールはありません</td></tr>';
        return;
      }

      const scrollTop = wrapper.scrollTop;
      const viewportHeight = wrapper.clientHeight;
      
      const startIndex = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - 3);
      const endIndex = Math.min(filteredData.length, Math.ceil((scrollTop + viewportHeight) / ROW_HEIGHT) + 3);
      
      const topPadding = startIndex * ROW_HEIGHT;
      const bottomPadding = Math.max(0, (filteredData.length - endIndex) * ROW_HEIGHT);

      let html = `<tr class="virtual-spacer" style="height: ${topPadding}px; border:none; background:transparent;"><td colspan="4" style="padding:0; border:none;"></td></tr>`;
      for (let i = startIndex; i < endIndex; i++) { html += buildRowHTML(filteredData[i]); }
      html += `<tr class="virtual-spacer" style="height: ${bottomPadding}px; border:none; background:transparent;"><td colspan="4" style="padding:0; border:none;"></td></tr>`;
      
      tbody.innerHTML = html;
    }

    let currentSelectedId = null;

    function buildRowHTML(mail) {
      const isSel = (mail.id === currentSelectedId) ? ' selected' : '';
      const cls = (mail.isUnread ? 'unread' : '') + isSel;
      const escId = escapeJsStr(mail.id);
      const safeFrom = escapeHtml(mail.from);
      const safeDate = escapeHtml(mail.date);
      
      let labelBadges = '';
      if (mail.labels && mail.labels.length > 0) {
        const badges = mail.labels.map(l => 
          `<span class="label-badge">${escapeHtml(l)}<span class="remove-badge-btn" onclick="optimisticRemoveLabel('${escId}', '${escapeJsStr(l)}', event)" title="削除">×</span></span>`
        ).join('');
        labelBadges = `<div class="label-container">${badges}</div>`;
      }

      let attachIcon = mail.hasAttachment ? `<span style="color: #94a3b8; font-weight: bold; margin-right: 5px;" title="添付ファイルあり">📎</span>` : '';

      let actionButtons = `<div class="action-container">`;
      actionButtons += `<button class="icon-btn" onclick="openEmailModal('${escId}'); event.stopPropagation();" title="本文を見る">👁️</button>`;
      actionButtons += `<button class="icon-btn" onclick="downloadEmailAsZip('${escId}', this); event.stopPropagation();" title="ZIPダウンロード">📥</button>`;
      
      if (mail.labelIds && mail.labelIds.includes('TRASH')) {
        actionButtons += `<button class="icon-btn" onclick="optimisticAction('${escId}', 'restore', event)" title="元に戻す">↩️</button>`;
        actionButtons += `<button class="icon-btn" onclick="optimisticAction('${escId}', 'permanent_delete', event)" title="完全に削除" style="color: #ef4444;">❌</button>`;
      } else {
        actionButtons += `<button class="icon-btn" onclick="openLabelMenu('${escId}', this, event)" title="ラベル">🏷️</button>`;
        actionButtons += `<button class="icon-btn" onclick="optimisticAction('${escId}', 'delete', event)" title="削除">🗑️</button>`;
      }
      actionButtons += `</div>`;

      return `
        <tr class="${cls}" data-id="${mail.id}" onclick="selectCardRow('${escId}', event)" onmouseenter="triggerPrefetch('${escId}')" onmouseleave="cancelPrefetch()">
          <td class="col-date clickable" onclick="toggleCellFilter('${safeDate}', event)">
            <span class="date-main">${safeDate}</span><span class="date-sub">${escapeHtml(mail.time)}</span>
          </td>
          <td class="col-from clickable" title="${safeFrom}" onclick="toggleCellFilter('${safeFrom}', event)">${safeFrom}</td>
          <td class="col-subject clickable" title="${escapeHtml(mail.subject)}" onclick="openEmailModal('${escId}')">
            <div class="subject-wrapper" title="${escapeHtml(mail.subject)}">
              <span class="subject-text">${attachIcon}${escapeHtml(mail.subject)}</span>
              ${labelBadges}
            </div>
          </td>
          <td class="col-action">${actionButtons}</td>
        </tr>
      `;
    }

    function selectCardRow(id, event) {
      if (event && (event.target.closest('.action-container') || event.target.closest('.label-badge'))) return;
      currentSelectedId = id;
      document.querySelectorAll('#mainTable tbody tr').forEach(r => {
        if (r.dataset.id === id) {
          r.classList.add('selected');
        } else {
          r.classList.remove('selected');
        }
      });
      // スマートフォン環境ではタップで直接メール本文を開く(スワイプ移動中は無効化)
      if (window.innerWidth <= 640 && event && !window.isSwipingNow && !event.target.closest('.action-container') && !event.target.closest('.clickable-attachment')) {
        openEmailModal(id);
      }
    }

    // ==========================================
    // オプティミスティックUI & 投機的フェッチ
    // ==========================================
    function triggerPrefetch(threadId) {
      prefetchTimer = setTimeout(() => {
        if (!prefetchCache.has(threadId)) {
          google.script.run
            .withSuccessHandler(res => { if(res && res.success) prefetchCache.set(threadId, res); })
            .withFailureHandler(() => {})
            .getThreadDetails(threadId);
        }
      }, 100);
    }
    function cancelPrefetch() { clearTimeout(prefetchTimer); }

    function optimisticAction(id, actionType, event) {
      if (event && event.stopPropagation) event.stopPropagation();
      const index = allFetchedEmails.findIndex(m => m.id === id);
      if (index === -1) return;

      if (actionType === 'permanent_delete') {
        const removedItem = allFetchedEmails[index];
        allFetchedEmails.splice(index, 1);
        applyWorkerFilter();
        saveToDB(allFetchedEmails);

        google.script.run
          .withFailureHandler(err => {
            const errStr = (err && err.message) ? err.message : '';
            if (errStr.includes('not found') || errStr.includes('404')) return;
            allFetchedEmails.splice(index, 0, removedItem);
            applyWorkerFilter();
            saveToDB(allFetchedEmails);
            console.error('完全削除通信失敗:', err);
          })
          .withSuccessHandler(res => {
            if (res && !res.success) {
              const errStr = res.error || '';
              if (errStr.includes('not found') || errStr.includes('404')) return;
              allFetchedEmails.splice(index, 0, removedItem);
              applyWorkerFilter();
              saveToDB(allFetchedEmails);
              console.error('完全削除失敗:', res.error);
            }
          })
          .permanentlyDeleteMessage(id);
        return;
      }

      const backupLabels = [...allFetchedEmails[index].labelIds];
      if (actionType === 'delete') allFetchedEmails[index].labelIds.push('TRASH');
      else if (actionType === 'archive') allFetchedEmails[index].labelIds = allFetchedEmails[index].labelIds.filter(l => l !== 'INBOX');
      else if (actionType === 'restore') {
        allFetchedEmails[index].labelIds = allFetchedEmails[index].labelIds.filter(l => l !== 'TRASH');
        allFetchedEmails[index].labelIds.push('INBOX');
      }
      applyWorkerFilter(); saveToDB(allFetchedEmails);

      const runner = google.script.run.withFailureHandler(() => {
        allFetchedEmails[index].labelIds = backupLabels;
        applyWorkerFilter(); alert('処理に失敗しました。');
      });
      if (actionType === 'archive') {
        runner.updateLabelsAndArchive(id, null, true);
      } else {
        const gasMethod = (actionType === 'delete') ? 'deleteMessage' : 'restoreMessage';
        runner[gasMethod](id);
      }
    }

    function optimisticRemoveLabel(id, labelName, event) {
      event.stopPropagation(); 
      const index = allFetchedEmails.findIndex(m => m.id === id);
      if (index === -1) return;

      const backup = allFetchedEmails[index].labels ? [...allFetchedEmails[index].labels] : [];
      if (allFetchedEmails[index].labels) {
        allFetchedEmails[index].labels = allFetchedEmails[index].labels.filter(l => l !== labelName);
      }
      applyWorkerFilter(); saveToDB(allFetchedEmails);

      google.script.run
        .withFailureHandler(() => {
          allFetchedEmails[index].labels = backup;
          applyWorkerFilter(); alert('ラベル削除に失敗しました');
        })
        .removeLabelFromThread(id, labelName);
    }

    // ==========================================
    // ラベルメニュー UI
    // ==========================================
    function openLabelMenu(id, btnEl, event) {
      event.stopPropagation();
      closeLabelMenu(); 
      
      const overlay = document.createElement('div');
      overlay.id = 'customLabelOverlay';
      overlay.style.position = 'fixed'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100vw'; overlay.style.height = '100vh'; overlay.style.zIndex = '999';
      overlay.onclick = function(e) { e.stopPropagation(); closeLabelMenu(); };
      document.body.appendChild(overlay);
      
      const menu = document.createElement('div');
      menu.id = 'customLabelMenu'; menu.className = 'custom-dropdown-menu'; menu.style.zIndex = '1000';
      
      let menuHtml = '';
      if (currentMode === 'inbox') {
        menuHtml += `<div class="dropdown-item" onclick="execLabelAction('${escapeJsStr(id)}', '__archive_only__')">アーカイブ</div>`;
        if (globalLabels.length > 0) menuHtml += `<div class="dropdown-divider"></div>`;
      }
      globalLabels.forEach(l => { menuHtml += `<div class="dropdown-item" onclick="execLabelAction('${escapeJsStr(id)}', '${escapeJsStr(l)}')">${escapeHtml(l)}</div>`; });
      
      menu.innerHTML = menuHtml; document.body.appendChild(menu);
      
      const rect = btnEl.getBoundingClientRect();
      const menuRect = menu.getBoundingClientRect();
      let topPos = rect.bottom + 4;
      if (rect.bottom + menuRect.height > window.innerHeight) {
        topPos = Math.max(8, rect.top - menuRect.height - 4);
      }
      menu.style.top = topPos + 'px';
      
      const menuWidth = 150;
      let leftPos = rect.left;
      if (leftPos + menuWidth > window.innerWidth) {
        leftPos = Math.max(8, window.innerWidth - menuWidth - 16);
      }
      menu.style.left = leftPos + 'px';
    }

    function closeLabelMenu() {
      document.getElementById('customLabelMenu')?.remove(); 
      document.getElementById('customLabelOverlay')?.remove();
    }

    function execLabelAction(id, labelName) {
      closeLabelMenu();
      const isInboxMode = (currentMode === 'inbox');
      const index = allFetchedEmails.findIndex(m => m.id === id);
      if (index === -1) return;

      const backupLabels = allFetchedEmails[index].labels ? [...allFetchedEmails[index].labels] : [];
      const backupIds = [...allFetchedEmails[index].labelIds];

      if (labelName && labelName !== '__archive_only__') {
        if (!allFetchedEmails[index].labels) allFetchedEmails[index].labels = [];
        if (!allFetchedEmails[index].labels.includes(labelName)) allFetchedEmails[index].labels.push(labelName);
      }
      if (isInboxMode) allFetchedEmails[index].labelIds = allFetchedEmails[index].labelIds.filter(lid => lid !== 'INBOX');
      
      applyWorkerFilter(); saveToDB(allFetchedEmails);

      google.script.run
        .withFailureHandler(() => {
          allFetchedEmails[index].labels = backupLabels;
          allFetchedEmails[index].labelIds = backupIds;
          applyWorkerFilter(); alert('処理に失敗しました');
        })
        .updateLabelsAndArchive(id, labelName, isInboxMode);
    }

    // ==========================================
    // モーダルとZIPダウンロード機能
    // ==========================================
    function downloadEmailAsZip(id, btn) {
      btn.disabled = true;
      const originalText = btn.innerHTML;
      btn.innerHTML = '⏳'; 
      
      google.script.run
        .withSuccessHandler(result => {
          if (result.success && result.base64) {
            try {
              const byteCharacters = atob(result.base64);
              const byteNumbers = new Array(byteCharacters.length);
              for (let i = 0; i < byteCharacters.length; i++) byteNumbers[i] = byteCharacters.charCodeAt(i);
              const byteArray = new Uint8Array(byteNumbers);
              const blob = new Blob([byteArray], { type: 'application/zip' });
              const url = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = url; a.download = result.fileName; document.body.appendChild(a); a.click();
              document.body.removeChild(a); URL.revokeObjectURL(url);
              btn.innerHTML = '✅'; 
              setTimeout(() => { btn.innerHTML = originalText; btn.disabled = false; }, 3000);
            } catch(e) { alert('ダウンロード失敗: ' + e.message); btn.innerHTML = originalText; btn.disabled = false; }
          } else { alert('ZIP作成失敗'); btn.innerHTML = originalText; btn.disabled = false; }
        })
        .withFailureHandler(e => { alert('通信エラー'); btn.innerHTML = originalText; btn.disabled = false; })
        .exportEmailAsZip(id);
    }

    function openEmailModal(threadId) {
      currentViewThreadId = threadId; 

      const modal = document.getElementById('emailViewModal');
      const titleEl = document.getElementById('viewModalSubject');
      const contentEl = document.getElementById('viewModalContent');
      const extLink = document.getElementById('viewModalExtLink');

      document.getElementById('replyBtn').style.display = 'none';
      document.getElementById('replyFormContainer').style.display = 'none';
      document.getElementById('replyBody').value = '';
      document.getElementById('replyAttachments').value = '';
      document.getElementById('replyToInput').value = ''; 
      document.getElementById('replySubjectInput').value = '';

      titleEl.innerText = '読み込み中...';
      contentEl.innerHTML = '<div style="text-align: center; padding: 40px; color: var(--text-muted);">メール本文と添付ファイルを取得しています...</div>';
      extLink.href = 'https://mail.google.com/mail/u/0/#inbox/' + encodeURIComponent(threadId);
      modal.style.display = 'flex';

      const mail = allFetchedEmails.find(m => m.id === threadId);
      if(mail) { mail.isUnread = false; applyWorkerFilter(); saveToDB(allFetchedEmails); }

      if (prefetchCache.has(threadId)) {
        renderModalContent(prefetchCache.get(threadId));
      } else {
        google.script.run
          .withSuccessHandler(res => { prefetchCache.set(threadId, res); renderModalContent(res); })
          .withFailureHandler(e => { contentEl.innerHTML = `<div style="color: #ef4444; padding: 20px;">通信失敗: ${escapeHtml(e.message)}</div>`; })
          .getThreadDetails(threadId);
      }
    }

    function renderModalContent(res) {
      const contentEl = document.getElementById('viewModalContent');
      if (!res.success) { contentEl.innerHTML = `<div style="color: #ef4444; padding: 20px;">エラー: ${escapeHtml(res.error)}</div>`; return;
}

      document.getElementById('viewModalSubject').innerText = res.subject;
      document.getElementById('replyBtn').style.display = 'inline-flex';
      
      if (res.messages && res.messages.length > 0) {
        const latestMsg = res.messages[res.messages.length - 1];
        document.getElementById('replyToInput').value = latestMsg.from;
      }
      
      let replySubject = res.subject || '';
      if (!replySubject.toLowerCase().startsWith('re:')) {
        replySubject = 'Re: ' + replySubject;
      }
      document.getElementById('replySubjectInput').value = replySubject;
      
      contentEl.innerHTML = '';

      res.messages.forEach(msg => {
        const card = document.createElement('div');
        card.className = 'msg-card';

        let attachHtml = '';
        if (msg.attachments && msg.attachments.length > 0) {
          const attachChips = msg.attachments.map(a => {
            const safeName = escapeJsStr(a.name);
            const safeMime = escapeJsStr(a.mimeType || '');
            return `<a class="attachment-chip clickable-attachment" style="text-decoration:none; cursor:pointer;" onclick="downloadSingleAttachment('${a.msgId}', ${a.attIndex}, '${safeName}', '${safeMime}', this)" title="クリックしてダウンロード">📎 ${escapeHtml(a.name)} (${escapeHtml(a.size)})</a>`;
          }).join('');
          attachHtml = '<div class="msg-attachments">' + attachChips + '</div>';
        }

        const toList = msg.to ? msg.to.split(/,\s*(?=(?:[^"]*"[^"]*")*[^"]*$)/) : [];
        let recipientsHtml = '';
        if (toList.length > 1 || (msg.to && msg.to.length > 50) || msg.cc) {
          const previewText = toList[0] || '';
          const othersCount = toList.length > 1 ? toList.length - 1 : 0;
          const badgeLabel = othersCount > 0 ? `他 ${othersCount} 名 ▼ 詳細` : `▼ 詳細`;
          recipientsHtml = `
            <details class="recipients-box">
              <summary><strong style="white-space: nowrap;">宛先:</strong><span class="recipients-summary-text">${escapeHtml(previewText)}</span><span class="recipients-badge">${badgeLabel}</span></summary>
              <div class="recipients-full-list">
                <div><strong>To:</strong> ${escapeHtml(msg.to)}</div>
                ${msg.cc ? `<div style="margin-top: 4px;"><strong>CC:</strong> ${escapeHtml(msg.cc)}</div>` : ''}
              </div>
            </details>
          `;
        } else {
          recipientsHtml = `<div><strong>宛先:</strong> ${escapeHtml(msg.to)} ${msg.cc ? `<strong>CC:</strong> ${escapeHtml(msg.cc)}` : ''}</div>`;
        }

        card.innerHTML = `
          <div class="msg-meta">
            <div><strong>差出人:</strong> ${escapeHtml(msg.from)}</div>
            ${recipientsHtml}
            <div><strong>日時:</strong> ${escapeHtml(msg.date)}</div>
            ${attachHtml}
          </div>
        `;

        const iframe = document.createElement('iframe');
        iframe.className = 'email-frame';
        // メール本文のスクリプトを動かさない(allow-scripts を付けない・CSP で二重に止める)
        iframe.setAttribute('sandbox', 'allow-same-origin allow-popups allow-popups-to-escape-sandbox');
        const htmlContent = `<!DOCTYPE html><html><head>${EMAIL_SAFE_HEAD}<style>
          body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 13.5px; line-height: 1.6; color: #1e293b; margin: 8px; word-break: break-word; }
          img { max-width: 100%; height: auto; }
        </style></head><body>${msg.body || escapeHtml(msg.plainBody).replace(/\n/g, '<br>')}</body></html>`;
        iframe.srcdoc = htmlContent;
        iframe.onload = () => {
          try {
            iframe.style.height = Math.max(120, iframe.contentWindow.document.body.scrollHeight + 20) + 'px';
          } catch(e) {}
        };
        card.appendChild(iframe);
        contentEl.appendChild(card);
      });
    }

    function deleteCurrentEmail(event) {
      if (!currentViewThreadId) return;
      const threadId = currentViewThreadId;
      const action = (typeof currentMode !== 'undefined' && currentMode === 'trash') ? 'permanent_delete' : 'delete';
      if (action === 'permanent_delete') {
        if (!confirm('このメールを完全に削除しますか?\n(元に戻せません)')) return;
      }
      closeEmailModal();
      optimisticAction(threadId, action, event);
    }

    function closeEmailModal() {
      triggerHaptic('light'); document.getElementById('emailViewModal').style.display = 'none'; }
    function escapeHtml(str) { return String(str||'').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;'); }
    // onclick="…" の中に入れる文字列用: JS の文字列として逃がしたうえで、HTML の属性としても逃がす
    // (添付ファイル名などは送り主が自由に付けられる。" で属性を抜けられないようにする)
    function escapeJsStr(str) { return escapeHtml(String(str||'').replace(/\\/g, '\\\\').replace(/'/g, "\\'")); }

    // ==========================================
    // 印刷機能
    // ==========================================
    function printCurrentEmail() {
      const threadData = prefetchCache.get(currentViewThreadId);
      if (!threadData || !threadData.messages) {
        alert('印刷対象のメールデータが読み込まれていません。');
        return;
      }

      let printHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          ${EMAIL_SAFE_HEAD}
          <title>${escapeHtml(threadData.subject || '印刷')}</title>
          <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; padding: 24px; color: #0f172a; background: #ffffff; line-height: 1.5; font-size: 13px; margin: 0; }
            h2.print-subject { font-size: 18px; font-weight: 700; border-bottom: 2px solid #334155; padding-bottom: 8px; margin-top: 0; margin-bottom: 16px; word-break: break-all; }
            .print-msg-card { border: 1px solid #cbd5e1; border-radius: 6px; padding: 14px; margin-bottom: 18px; page-break-inside: avoid; }
            .print-meta { font-size: 12px; color: #475569; line-height: 1.6; margin-bottom: 10px; border-bottom: 1px dashed #cbd5e1; padding-bottom: 8px; }
            .print-meta strong { color: #0f172a; }
            .print-body { word-break: break-word; line-height: 1.6; }
            .print-body img { max-width: 100%; height: auto; }
            .print-attachments { margin-top: 8px; font-size: 11.5px; color: #475569; }
            @media print {
              body { padding: 0; }
              .print-msg-card { border: 1px solid #94a3b8; }
            }
          </style>
        </head>
        <body>
          <h2 class="print-subject">${escapeHtml(threadData.subject || '(件名なし)')}</h2>
      `;

      threadData.messages.forEach(msg => {
        let attachText = '';
        if (msg.attachments && msg.attachments.length > 0) {
          const names = msg.attachments.map(a => `${escapeHtml(a.name)} (${escapeHtml(a.size)})`).join(', ');
          attachText = `<div class="print-attachments">📎 <strong>添付ファイル:</strong> ${names}</div>`;
        }

        printHtml += `
          <div class="print-msg-card">
            <div class="print-meta">
              <div><strong>差出人:</strong> ${escapeHtml(msg.from)}</div>
              <div><strong>宛先:</strong> ${escapeHtml(msg.to)} ${msg.cc ? `<strong>CC:</strong> ${escapeHtml(msg.cc)}` : ''}</div>
              <div><strong>日時:</strong> ${escapeHtml(msg.date)}</div>
              ${attachText}
            </div>
            <div class="print-body">
              ${msg.body || escapeHtml(msg.plainBody).replace(/\n/g, '<br>')}
            </div>
          </div>
        `;
      });

      printHtml += `
        </body>
        </html>
      `;

      // 印刷は隠した iframe で行う(本文のスクリプトは動かない・印刷は親から呼ぶ)
      const printFrame = document.createElement('iframe');
      printFrame.setAttribute('sandbox', 'allow-same-origin allow-modals');
      printFrame.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;';
      printFrame.onload = () => {
        try {
          printFrame.contentWindow.focus();
          printFrame.contentWindow.print();
        } catch (e) {
          alert('印刷を開けませんでした: ' + e.message);
        }
        setTimeout(() => { printFrame.remove(); }, 1000);
      };
      printFrame.srcdoc = printHtml;
      document.body.appendChild(printFrame);
    }

    // メール本文を表示する iframe の頭に入れる守り(スクリプト禁止・リンクは別タブ)
    const EMAIL_SAFE_HEAD = `<meta http-equiv="Content-Security-Policy" content="script-src 'none'; object-src 'none'; base-uri 'none'"><base target="_blank">`;

    // ==========================================
    // メール返信機能
    // ==========================================
    function toggleReplyForm() {
      const form = document.getElementById('replyFormContainer');
      const isHidden = form.style.display === 'none' || form.style.display === '';
      
      if (isHidden) {
        form.style.display = 'block';
        document.getElementById('replyBody').focus();
        setTimeout(() => { 
          document.getElementById('viewModalScrollArea').scrollTo({
            top: document.getElementById('viewModalScrollArea').scrollHeight,
            behavior: 'smooth'
          });
        }, 50);
      } else {
        form.style.display = 'none';
      }
    }

    function readFileAsBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
        reader.readAsDataURL(file);
      });
    }

    async function sendReply() {
      const toAddress = document.getElementById('replyToInput').value;
      const subjectText = document.getElementById('replySubjectInput').value;
      const body = document.getElementById('replyBody').value;
      
      if (!toAddress.trim()) { alert('宛先(To)を入力してください'); return; }
      if (!subjectText.trim()) { alert('件名を入力してください'); return; }
      if (!body.trim()) { alert('本文を入力してください'); return; }

      const fileInput = document.getElementById('replyAttachments');
      const files = fileInput.files;
      const attachmentData = [];

      const sendBtn = document.getElementById('sendReplyBtn');
      sendBtn.disabled = true;
      sendBtn.innerText = '送信中...';

      try {
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          const base64Str = await readFileAsBase64(file);
          attachmentData.push({
            name: file.name,
            mimeType: file.type,
            base64: base64Str.split(',')[1]
          });
        }

        google.script.run
          .withSuccessHandler(res => {
            sendBtn.disabled = false;
            sendBtn.innerText = '送信する';
            
            if (res.success) {
              alert('返信を送信しました');
              toggleReplyForm(); 
              
              prefetchCache.delete(currentViewThreadId);
              const contentEl = document.getElementById('viewModalContent');
              contentEl.innerHTML = '<div style="text-align: center; padding: 40px; color: var(--text-muted);">返信を反映しています...</div>';
              
              google.script.run
                .withSuccessHandler(newData => { 
                  prefetchCache.set(currentViewThreadId, newData); 
                  renderModalContent(newData); 
                  
                  setTimeout(() => { 
                    const scrollArea = document.getElementById('viewModalScrollArea');
                    scrollArea.scrollTo({ top: scrollArea.scrollHeight, behavior: 'smooth' });
                  }, 150);
                })
                .withFailureHandler(err => {
                  contentEl.innerHTML = '<div style="color: #ef4444; padding: 20px; text-align: center;">返信の反映に失敗しました。画面を再読み込みしてください。</div>';
                })
                .getThreadDetails(currentViewThreadId);
                
            } else {
              alert('送信エラー: ' + res.error);
            }
          })
          .withFailureHandler(e => {
            sendBtn.disabled = false;
            sendBtn.innerText = '送信する';
            alert('通信エラー: ' + e.message);
          })
          .replyToEmail(currentViewThreadId, toAddress, subjectText, body, attachmentData);

      } catch (error) {
        alert('ファイル処理エラー: ' + error.message);
        sendBtn.disabled = false;
        sendBtn.innerText = '送信する';
      }
    }
  
function downloadSingleAttachment(msgId, attIndex, name, mimeType, element) {
  if (element && element.dataset.loading === 'true') return;
  if (element) {
    element.dataset.loading = 'true';
    element.innerText = `⏳ ${name} (取得中...)`;
  }
  google.script.run
    .withSuccessHandler(res => {
      if (element) {
        element.dataset.loading = 'false';
        element.innerText = `📎 ${name}`;
      }
      if (res && res.success && res.base64) {
        try {
          const byteCharacters = atob(res.base64);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) byteNumbers[i] = byteCharacters.charCodeAt(i);
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: res.mimeType || mimeType });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = res.name || name;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        } catch (err) {
          alert('ダウンロード処理エラー: ' + err.message);
        }
      } else {
        alert('添付ファイルの取得に失敗しました: ' + (res && res.error ? res.error : '不明なエラー'));
      }
    })
    .withFailureHandler(err => {
      if (element) {
        element.dataset.loading = 'false';
        element.innerText = `📎 ${name} (失敗)`;
      }
      alert('通信エラー: ' + err.message);
    })
    .getAttachment(msgId, attIndex);
}
</script>
</body>
</html>

「フラッシュくんにしては賢すぎる……?」 ── 開発現場で起きた最大の衝撃

このMクイックが完成した直後、私は作業画面を見つめながら、ふと強烈な違和感を覚えました。

「……待てよ。今、目の前でこの高度なスマホアプリを書いてくれたAIって、誰だっけ?」

前回の記事では、超大型・重厚モデルの Gemini 4 Argon(ゴンちゃん) と組んでいました。
しかし今回、日常使いとして私がチャット欄で選択していたのは、正真正銘、最軽量・最速の 【Gemini Flash(フラッシュ君)】 だったのです。

思わずチャット欄で声が出ました。

「さっきからフラッシュくんにしては賢すぎるなと思ってたんだが……裏でこっそりゴンちゃんがやってくれてたのか?」

するとフラッシュ君から返ってきたのは、衝撃の告白でした。

「いえ、しゅうさん!作業しているのは正真正銘、軽量・超高速のフラッシュ君です!」

フラッシュ君か

エンジニアの皆様なら、この衝撃が分かっていただけるはずです。

世間の常識では、
「高度なWebアプリ開発や、仮想スクロールとスワイプが絡む複雑なフロントエンドは、Claude Opas や Gemini Pro/Argon のような超大型モデルじゃないと破綻する」
「軽量モデル(FlashやHaiku)は、簡単な要約やチャット用のお手軽モデルだ」
と相場が決まっていました。

ところが、目の前で起きた事実は正反対でした。
超軽量でAPIコストもほぼタダ同然、秒速で返答してくるフラッシュ君が、ネイティブ級スマホアプリの複雑なコードを完璧に書き上げ、実機デプロイまで完走してしまったのです。


なぜ軽量モデルが怪物を書けるのか? ── 「頭脳」ではなく「外骨格」の革命

なぜ、軽量モデルのフラッシュ君がここまで賢く動けたのか?
その答えこそが、『秀GASマネージャー』がもたらした最大の技術革新でした。

AIの性能は、「モデル単体の頭脳の大きさ」だけで決まるのではありません。
「どんな外骨格(道具と検査関所)を身にまとわせるか」で決まるのです。

普通のAI開発環境では、AIは「頭の中の推測だけ」でコードを書き、「動くはずです」と人間に丸投げしてきます。だから軽量モデルだと細部でミスをし、破綻してしまうのです。

しかし、秀GASマネージャーを装備したフラッシュ君は、行動の次元が違います。

py gas.py inspect-ui Mクイック Index --device both --theme white

ガスマネージャーの新兵器「PC・スマホ同時実機監査」を叩けば、裏でPlaywright Chromiumが起動し、わずか 2.5秒 で「PC画面(1280px)」と「スマホ画面(390px/iPhone相当)」の両方を同時レンダリングします。

=== GAS Webアプリ実機画面監査 (inspect_ui): [Mクイック] ===
総合判定: [PASS] 合格
検査対象要素数: 16件
テストテーマ: desktop:white, mobile:white

【実機スクリーンショット物証 (2枚)】:
  - inspect_index_desktop_white.png (PC幅: 4列テーブル表示を死守)
  - inspect_index_mobile_white.png  (スマホ幅: 独立カード型へ自動変形)

フラッシュ君は、人間がスマホを見る前に、裏でレンダリングされた実機画像とDOMを自分で見分します。
「あ、スマホ幅だと差出人と日付が少し詰まっているな」
「仮想スクロールのスペーサー行に背景色がついちゃってるな」
それをAI自身が実機画像から瞬時に見抜き、自分でCSSを直して、合格証が出るまで叩き直してから人間へ報告してくるのです。

つまり、「ガスマネージャーという最強の実機検証ループ」があるからこそ、軽量爆速のフラッシュ君が、超大型モデルすら凌駕する圧倒的な精度とスピードを発揮できたのです。


個人がMacも審査もなしでアプリを即日配備する「新世界」

今回の開発を通じて、私たちは確信しました。
これは単なるツールの話ではありません。アプリ開発の歴史が変わる大革命です。

世の中では今も、
「スマホアプリを作るならFlutterかReact Nativeか」
「Macを買ってXcodeをインストールして……」
「超大型AIのAPIコストが高すぎる……」
という悩みが渦巻いています。

しかし、GAS + 最安最速のフラッシュ君 + ガスマネージャー の組み合わせは、そのすべての障壁を粉砕しました。

  1. 開発コストはほぼゼロ: Windowsの普通のPC上で、無料同然の軽量モデル(Flash)と雑談するだけ。
  2. 審査ゼロ・即時配備: 完成した瞬間、Googleドライブのリンクひとつで世界中へ配布可能。
  3. 品質保証の自動化: PCとスマホの両画面をAIが裏で秒速レンダリングし、崩れのない物証を確保してから本番へデプロイ。

革命だぞ

「思いついた業務ツールや便利アプリを、その日のうちにApp Store級のスマホアプリとして具現化し、世界へ配る」
高価なモデルや大掛かりな開発環境に頼らなくても、強固な道具(ガスマネージャー)さえあれば、最速の軽量モデルと人間が二人三脚で世界を変えられる。


関連リンク


最後までお読みいただき、ありがとうございました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?