<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS タイポグラフィ・アートジェネレーター</title>
  <style>
    body { font-family: sans-serif; margin: 20px; }
    textarea { width: 100%; height: 150px; margin-bottom: 10px; }
    button { margin-right: 10px; padding: 8px 15px; cursor: pointer; }
    #typography-container { border: 1px solid #ccc; padding: 20px; 
                            white-space: pre-wrap; word-break: break-word; }
    .typography-part { display: inline-block; margin-right: 0.3em; 
                       margin-bottom: 0.3em; }
    #saved-settings-list { list-style-type: none; padding: 0; }
    #saved-settings-list li { margin-bottom: 5px; cursor: pointer; }
    #saved-settings-list li:hover { background-color: #f0f0f0; }
    .hidden { display: none; }
  </style>
</head>
<body>
  <h1>CSS タイポグラフィ・アートジェネレーター</h1>

  <textarea id="text-input" 
    placeholder="ここにテキストを入力してください"></textarea>

  <div>
    <button id="generate-button">ランダム生成 (CSS)</button>
    <button id="save-button" class="hidden">設定を保存</button>
    <input type="text" id="setting-name-input" placeholder="設定名" 
      class="hidden">
    <button id="load-random-button">ランダムな設定で再描画</button>
  </div>

  <div id="typography-container">
    </div>

  <h2>保存された設定</h2>
  <ul id="saved-settings-list">
    </ul>

  <script>
    const textInput = document.getElementById('text-input');
    const generateButton = document.getElementById('generate-button');
    const saveButton = document.getElementById('save-button');
    const settingNameInput = document.getElementById('setting-name-input');
    const typographyContainer = 
      document.getElementById('typography-container');
    const savedSettingsList = document.getElementById('saved-settings-list');
    const loadRandomButton = document.getElementById('load-random-button');

    let currentText = '';
    let currentStyles = [];

    function renderTypography(parts, styles) {
      typographyContainer.innerHTML = '';
      parts.forEach((part, index) => {
        const partElement = document.createElement('div');
        partElement.classList.add('typography-part');
        Object.assign(partElement.style, styles[index % styles.length]);
        partElement.textContent = part;
        typographyContainer.appendChild(partElement);
      });
    }

    generateButton.addEventListener('click', () => {
      currentText = textInput.value;
      fetch('/generate_css', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `text=${encodeURIComponent(currentText)}`,
      })
      .then(response => response.json())
      .then(data => {
        currentStyles = data.styles;
        renderTypography(data.parts, data.styles);
        saveButton.classList.remove('hidden');
        settingNameInput.classList.remove('hidden');
      })
      .catch(error => console.error('Error:', error));
    });

    saveButton.addEventListener('click', () => {
      const settingName = settingNameInput.value;
      if (!settingName) {
        alert('設定名を入力してください。');
        return;
      }
      fetch('/save_setting_css', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `setting_name=${encodeURIComponent(settingName)
               }&text=${encodeURIComponent(currentText)}&styles=${
               encodeURIComponent(JSON.stringify(currentStyles))}`,
      })
      .then(response => response.json())
      .then(data => {
        alert(data.message);
        if (data.success) {
          loadSavedSettings();
          settingNameInput.value = '';
          saveButton.classList.add('hidden');
          settingNameInput.classList.add('hidden');
        }
      })
      .catch(error => console.error('Error:', error));
    });

    function loadSavedSettings() {
      fetch('/api/settings')
      .then(response => response.json())
      .then(settings => {
        savedSettingsList.innerHTML = '';
        settings.forEach(setting => {
          const listItem = document.createElement('li');
          listItem.textContent = setting.name;
          listItem.setAttribute('data-id', setting.id);
          savedSettingsList.appendChild(listItem);
        });
        addLoadSettingListeners();
      })
      .catch(error => console.error('Error:', error));
    }

    function addLoadSettingListeners() {
      const listItems = savedSettingsList.querySelectorAll('li');
      listItems.forEach(item => {
        item.addEventListener('click', () => {
          const settingId = item.getAttribute('data-id');
          fetch(`/load_setting_css/${settingId}`)
          .then(response => response.json())
          .then(data => {
            if (!data.error) {
              const parts = data.text.split(/([。\n、,.?!！?…・]|[\s])/)
                                     .filter(part => part !== '');
              const styles = JSON.parse(data.styles);
              currentText = data.text;
              currentStyles = styles;
              renderTypography(parts, styles);
            } else {
              alert(data.error);
            }
          })
          .catch(error => console.error('Error:', error));
        });
      });
    }

    loadRandomButton.addEventListener('click', () => {
      fetch('/load_random_setting_css')
      .then(response => response.json())
      .then(data => {
        if (!data.error) {
          const parts = data.text.split(/([。\n、,.?!！?…・]|[\s])/)
                                 .filter(part => part !== '');
          const styles = JSON.parse(data.styles);
          currentText = data.text;
          currentStyles = styles;
          renderTypography(parts, styles);
        } else {
          alert(data.error);
        }
      })
      .catch(error => console.error('Error:', error));
    });

    // ページロード時に保存された設定を読み込む
    loadSavedSettings();
  </script>
</body>
</html>