<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ノベルゲームスクリプト変換ツール</title>
  <!-- TailwindCSS (ブラウザ用) -->
  <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
  <!-- animate.css の読み込み -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', sans-serif;
    }
    .container {
      max-width: 800px;
      margin: 2rem auto;
      padding: 2rem;
      background-color: #f3f4f6;
      border-radius: 0.5rem;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .header {
      display: flex;
      gap: 1rem;
      align-items: center;
      margin-bottom: 1rem;
    }
    .editable-area {
      margin-bottom: 1rem;
    }
    /* 編集可能な入力エリア */
    #editable-input {
      width: 100%;
      min-height: 200px;
      padding: 1rem;
      border: 1px solid #d1d5db;
      border-radius: 0.375rem;
      font-family: monospace;
      background-color: #fff;
      white-space: pre-wrap;
      outline: none;
      transition: box-shadow 0.3s ease;
    }
    #editable-input:focus {
      box-shadow: 0 0 0 3px rgba(66,153,225,0.5);
    }
    .name-selection {
      display: flex;
      flex-wrap: wrap;
      gap: 0.75rem;
      margin-top: 0.5rem;
      align-items: center;
    }
    .name-button {
      padding: 0.5rem 1rem;
      background-color: #e5e7eb;
      color: #374151;
      border-radius: 0.375rem;
      cursor: pointer;
      transition: background-color 0.3s ease, transform 0.2s ease, box-shadow 0.2s ease;
      border: 1px solid #d1d5db;
      box-shadow: 0 1px 2px rgba(0,0,0,0.05);
      white-space: nowrap;
    }
    .name-button:hover {
      background-color: #d1d5db;
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    /* カスタム名入力エリア */
    #custom-name-container {
      display: none;
      gap: 0.5rem;
      align-items: center;
      animation: fadeIn 0.3s ease forwards;
    }
    #custom-name-input {
      padding: 0.5rem;
      border: 1px solid #d1d5db;
      border-radius: 0.375rem;
      outline: none;
      font-size: 1rem;
    }
    #register-name-button {
      padding: 0.5rem 1rem;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 0.375rem;
      cursor: pointer;
      font-size: 1rem;
      transition: background-color 0.3s ease;
    }
    #register-name-button:hover {
      background-color: #45a049;
    }
    .highlighted-bracket {
      color: #e67e22;
      font-weight: bold;
      background-color: #f5f5f5;
    }
    /* アニメーション用のキーフレーム */
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    /* .hidden クラス */
    .hidden { display: none; }
  </style>
</head>
<body class="bg-gray-100">
  <div class="container animate__animated animate__fadeIn">
    <!-- ヘッダー：アップロードとダウンロード -->
    <div class="header">
      <!-- アップロードボタン：ラベルによりファイル入力をトリガー -->
      <label for="file-input" class="name-button cursor-pointer">アップロード</label>
      <input id="file-input" type="file" accept=".txt" class="hidden">
      <button id="download-button" class="name-button">ダウンロード</button>
    </div>
    <!-- 編集エリア -->
    <div class="editable-area">
      <label for="editable-input" class="block text-sm font-medium text-gray-700">編集エリア（直接入力）</label>
      <div id="editable-input" contenteditable="true" placeholder="ここにテキストを入力してください"></div>
    </div>
    <!-- 名前選択エリア -->
    <div class="name-selection">
      <!-- 名前ボタン群 -->
      <div id="name-buttons-container" class="flex gap-3 flex-wrap"></div>
      <!-- 名前追加ボタン -->
      <button id="add-name-button" class="name-button">名前追加</button>
      <!-- カスタム名入力欄 -->
      <div id="custom-name-container" class="animate__animated">
        <input id="custom-name-input" type="text" placeholder="カスタム名を入力" class="px-3 py-2 border rounded">
        <button id="register-name-button" class="name-button">登録</button>
      </div>
    </div>
  </div>

  <script>
    const editableInput = document.getElementById('editable-input');
    const fileInput = document.getElementById('file-input');
    const downloadButton = document.getElementById('download-button');
    const nameButtonsContainer = document.getElementById('name-buttons-container');
    const addNameButton = document.getElementById('add-name-button');
    const customNameContainer = document.getElementById('custom-name-container');
    const customNameInput = document.getElementById('custom-name-input');
    const registerNameButton = document.getElementById('register-name-button');

    let brackets = [];
    let currentBracketIndex = 0;
    let uploadedFileName = "output"; // アップロード前の初期値

    // セリフ開始・終了の記号（「、『 と 」、』）
    const startMarkers = ['「', '『'];
    const endMarkers = ['」', '』'];

    // 初期の名前ボタン（例）
    const initialNames = ["ぼく", "きみ", "かれ"];
    initialNames.forEach(name => {
      const btn = document.createElement('button');
      btn.className = 'name-button';
      btn.dataset.name = name;
      btn.textContent = name;
      attachNameButtonEvents(btn);
      nameButtonsContainer.appendChild(btn);
    });

    // 編集エリアの内容から対象となるセリフ開始位置を検出し、ハイライト用HTMLを生成
    function updateHighlight() {
      const text = editableInput.innerText;
      let highlightedHTML = '';
      brackets = [];
      for (let i = 0; i < text.length; i++) {
        if (startMarkers.includes(text[i])) {
          // 対象：先頭、改行直後、または直前が ']' の場合
          if (i === 0 || text[i - 1] === '\n' || text[i - 1] === ']') {
            brackets.push(i);
          }
          highlightedHTML += `<span class="highlighted-bracket">${text[i]}</span>`;
        } else if (endMarkers.includes(text[i])) {
          highlightedHTML += `<span class="highlighted-bracket">${text[i]}</span>`;
        } else {
          highlightedHTML += text[i];
        }
      }
      // 編集エリアの内容を更新（※カーソル位置は維持されません）
      editableInput.innerHTML = highlightedHTML;
    }

    // 名前挿入処理：現在の対象セリフの開始位置に [名前]\n を挿入
    function insertName(name) {
      let text = editableInput.innerText;
      if (brackets.length > 0 && currentBracketIndex < brackets.length) {
        const insertIndex = brackets[currentBracketIndex];
        const before = text.slice(0, insertIndex);
        const after = text.slice(insertIndex);
        const insertion = `[${name}]\n`;
        text = before + insertion + after;
        editableInput.innerText = text;
        currentBracketIndex++;
        updateHighlight();
      }
    }

    // 既存の名前ボタン押下時の処理を付与
    function attachNameButtonEvents(button) {
      button.addEventListener('click', () => {
        const name = button.dataset.name;
        insertName(name);
      });
    }

    // 名前追加ボタン押下でカスタム名入力欄の表示切替
    addNameButton.addEventListener('click', () => {
      if (customNameContainer.style.display === 'none' || customNameContainer.style.display === '') {
        customNameContainer.style.display = 'flex';
        customNameContainer.classList.add('animate__fadeInUp');
        customNameInput.focus();
      } else {
        customNameContainer.style.display = 'none';
      }
    });

    // カスタム名登録ボタン押下時の処理
    registerNameButton.addEventListener('click', () => {
      const customName = customNameInput.value.trim();
      if (customName) {
        const newButton = document.createElement('button');
        newButton.className = 'name-button';
        newButton.dataset.name = customName;
        newButton.textContent = customName;
        attachNameButtonEvents(newButton);
        nameButtonsContainer.appendChild(newButton);
        customNameInput.value = '';
        customNameContainer.style.display = 'none';
      }
    });

    // ファイル入力（TXTファイル）の読み込み
    fileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (!file) return;
      // 拡張子を除いた元のファイル名を取得
      uploadedFileName = file.name.replace(/\.[^/.]+$/, "");
      const reader = new FileReader();
      reader.onload = (event) => {
        editableInput.innerText = event.target.result;
        currentBracketIndex = 0;
        updateHighlight();
      };
      reader.readAsText(file, 'UTF-8');
    });

    // 現在の編集内容をTXTファイルとしてダウンロード
    downloadButton.addEventListener('click', () => {
      const text = editableInput.innerText;
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      // ダウンロードファイル名を「元のファイル名_script.txt」に設定
      a.download = `${uploadedFileName}_script.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    });

    // 編集エリア入力時のハイライト更新
    editableInput.addEventListener('input', () => {
      updateHighlight();
    });

    // 初期ハイライト更新
    updateHighlight();
  </script>
</body>
</html>
