<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>データ印生成</title>
  <style>
    body {
      font-family: "BIZ UDPGothic", sans-serif, Arial;
      width: 100vw;
      height: 100vh;
      margin: 0;
      background-color: #f0f0f0;
      padding: 0;
      overflow: hidden;
    }

    main {
      width: 100vw;
      height: 100vh;
      margin: 0;
      background-color: #f0f0f0;
      padding: 0;

      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    input,
    button {
      margin: 10px 0;
      padding: 5px;
      width: 100%;
      border-radius: 0.5em;
      border-color: #eee;
      box-sizing: border-box;
    }

    button {
      border-radius: 3em;
      border: none;
      box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
    }

    #message {
      color: red;
    }

    #stampFrame {
      display: flex;
    }

    #btnClip {
      display: none;
      font-size: 0.8em;
      padding: 5px 10px;
    }

    button {
      height: 2em;
      font-size: 1.2em;
      font-weight: bold;
      ;
      padding: 5px 5px;
      background-color: #fff;
      color: black;
      border: none;
      border-radius: 50px;
      box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
      cursor: pointer;
      transition: all 0.3s ease;
    }

    button:hover {
      background-color: #e6e2ff;
      box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
    }

    button:active {
      background-color: #d1caff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transform: translateY(2px);
    }

    main {
      z-index: 1;
      position: relative;
    }


    input {
      font-size: 16px;
      width: 100%;
      border: none;
      outline: none;
      padding-bottom: 0px;
      /*横幅の解釈をpadding, borderまでとする*/
      box-sizing: border-box;
      margin-bottom: 5px
    }
    
    select {
    	margin-top: 16px;
    }

    .text_underline {
      position: relative;
      /*.text_underline::beforeの親要素*/
      border-top: 2px solid #c2c2c2;
      /*text3の下線*/
    }

    /*共通のstyle*/
    .text_underline::before,
    .text_underline::after {
      position: absolute;
      bottom: 0px;
      /*中央配置*/
      width: 0px;
      /*アニメーションで0pxから50%に*/
      height: 1px;
      /*高さ*/
      content: '';
      background-color: #2fff4e;
      /*アニメーションの色*/
      transition: all 0.5s;
      -webkit-transition: all 1.0s;
    }

    /*中央から右へのアニメーション*/
    .text_underline::before {
      left: 50%;
      /*中央配置*/
    }

    /*中央から左へのアニメーション*/
    .text_underline::after {
      right: 50%;
      /*中央配置*/
    }

    input:focus+.text_underline::before,
    input:focus+.text_underline::after {
      width: 50%;
    }

    .group {
      margin-bottom: 20px;
      display: grid;
    }

    .group>label {
      font-size: 0.8em;
      ;
    }

    h2 {
      text-align: center;
      background: #dfefff;
      box-shadow: 0px 0px 0px 5px #dfefff;
      border: dashed 2px white;
      padding: 0.2em 0.5em;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    #title-icon-left {
      margin-right: 10px;
      animation: rotate_anime 5s infinite; 
      animation-direction:reverse;
    }

    #title-icon-right {
      margin-left: 10px;
      animation: rotate_anime 10s infinite; 
    }
    
    @keyframes rotate_anime {
    0% {
        transform:rotate(0deg);
    }
    100% {
        transform:rotate(360deg);
    }
    }
    
    
    .right-box {
      min-width: 200px;
      margin-left: 20px;
      border: 2px solid #eee;
      border-radius: 10px;
      padding: 20px;
    }
    
    #stampContainer {
      margin-left: auto;
    }
    .btn-mini {
    	border: 1px solid gray;
    	border-radius: 5px;
    	font-size: 0.7em;
    	padding: 2px 5px;
    	width: auto;
    	margin: 0 10px;
    }
  </style>
</head>

<body>
  <main>
    <div class="container">
      <h2>
        <svg id="title-icon-left" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 200 200">
          <!-- 円を描画 -->
          <circle cx="100" cy="100" r="90" stroke="red" fill="none" stroke-width="8" />
          <!-- 横線を描画 -->
          <line x1="15" y1="70" x2="185" y2="70" stroke="red" stroke-width="5" />
          <line x1="15" y1="130" x2="185" y2="130" stroke="red" stroke-width="5" />
        </svg>
        データ印生成
        <svg id="title-icon-right" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 200 200">
          <!-- 円を描画 -->
          <circle cx="100" cy="100" r="90" stroke="red" fill="none" stroke-width="8" />
          <!-- 横線を描画 -->
          <line x1="15" y1="70" x2="185" y2="70" stroke="red" stroke-width="5" />
          <line x1="15" y1="130" x2="185" y2="130" stroke="red" stroke-width="5" />
        </svg>
      </h2>
      <div style="display: flex;">
        <div class="left-box">
          <form>
          
          <div class="group">
            <label for="topText">上段テキスト</label>
            <input type="text" id="topText" placeholder="上段テキスト">
            <div class="text_underline"></div>
          </div>
          <div style="display: flex; align-items: baseline">
              <div class="group">
                <label for="dateInput">中段日付<button type="button" class="btn-mini" onclick="setNow()">今日</button></label>
                <input type="date" id="dateInput">
                <div class="text_underline"></div>
              </div>
              <div class="group" style="margin-left: 10px;">
                <label for="dateFormatInput">日付書式</label>
	            <input type="text" id="dateFormatInput" style="margin-top: 14px" placeholder="日付書式 (ex. yyyy/MM/dd)" value="yyyy/MM/dd" list="dateFormatList">
                <div class="text_underline"></div>
              </div>
          </div>
          <datalist id="dateFormatList">
            <option value="yyyy/MM/dd"></option>
            <option value="yyyy.MM.dd"></option>
            <option value="yyyy-MM-dd"></option>
            <option value="yy/MM/dd"></option>
          </datalist>
          
          <div class="group">
            <label for="bottomText">下段テキスト</label>
            <input type="text" id="bottomText" placeholder="下段テキスト">
            <div class="text_underline"></div>
          </div>
          
          <div style="display: flex">
	          <div class="group">
	            <label for="sizeInput">画像サイズ</label>
	            <div style="display:flex; align-items: baseline"><input type="number" id="sizeInput" min="100" max="500" placeholder="サイズ（ピクセル）" value="200"><div>px</div></div>
	            <div class="text_underline"></div>
	          </div>
	          <div class="group" style="margin-left: 10px">
	            <label for="sizeInput">文字サイズ調整 (上段/中段/下段)</label>
	            <div style="display:flex; align-items: baseline">
	            <input type="number" id="fontSizeAdujstTopInput" style="width: 3.5em" required min="10" max="200" placeholder="文字サイズに対しての拡大・縮小率" value="100"><div>%</div>
	            <input type="number" id="fontSizeAdujstMiddleInput" style="width: 3.5em" required min="10" max="200" placeholder="文字サイズに対しての拡大・縮小率" value="100"><div>%</div>
	            <input type="number" id="fontSizeAdujstBottomInput" style="width: 3.5em" required min="10" max="200" placeholder="文字サイズに対しての拡大・縮小率" value="100"><div>%</div>
	            </div>
	            <div class="text_underline"></div>
	          </div>
          </div>
          <div class="group">
            <label for="colorInput">色</label>
            <input type="color" id="colorInput" value="#ff0000">
            <div class="text_underline"></div>
          </div>

          <button onclick="generateStamp()">データ印作成</button>
          </form>
        </div>

        <div class="right-box">
            <div id="stampContainer"></div>
            <button id="btnClip" onclick="copyImageToClipboard(stampImage)">クリップボードにコピー</button>
            <div id="message"></div>
        </div>
      </div>
  </main>
  <script>
    function createDateStamp(size, color, topText, middleText, bottomText, fontSizeAdujstTop, fontSizeAdujstMiddle, fontSizeAdujstBottom) {
      const circleLineWidth = size / 60;
      
      const canvas = document.createElement('canvas');
      canvas.width = size;
      canvas.height = size;
      const ctx = canvas.getContext('2d');

      const centerX = size / 2;
      const centerY = size / 2;
      const radius = size / 2 - circleLineWidth;

      // 円を描画
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      ctx.strokeStyle = color;
      ctx.lineWidth = circleLineWidth;
      ctx.stroke();

      // 横線を描画
      const lineY1 = size / 3;
      const lineY2 = size * 2 / 3;

      function drawIntersectingLine(y) {
        const x = Math.sqrt(radius * radius - Math.pow(y - centerY, 2));
        ctx.beginPath();
        ctx.moveTo(centerX - x, y);
        ctx.lineTo(centerX + x, y);
        ctx.strokeStyle = color;
        ctx.lineWidth = size / 120;
        ctx.stroke();
      }

      drawIntersectingLine(lineY1);
      drawIntersectingLine(lineY2);

      // テキスト設定
      ctx.fillStyle = color;
      ctx.textAlign = 'center';

      // 上段テキスト
      const topFontSize = size / 8 * (fontSizeAdujstTop / 100);
      ctx.font = `${topFontSize}px "BIZ UDPGothic", sans-serif`;
      ctx.fillText(topText, centerX, size / 4);

      // 中段テキスト
      const middleFontSize = size / 7.8 * (fontSizeAdujstMiddle / 100);
      ctx.font = `${middleFontSize}px "BIZ UDPGothic", sans-serif`;
      ctx.fillText(middleText, centerX, size / 2 + size / 18);

      // 下段テキスト
      const bottomFontSize = size / 6 * (fontSizeAdujstBottom / 100);
      ctx.font = `${bottomFontSize}px "BIZ UDPGothic", sans-serif`;
      ctx.fillText(bottomText, centerX, size * 2 / 3 + size / 5);

      // copyImageToClipboard(canvas);
      return canvas.toDataURL();
    }

    async function copyImageToClipboard(canvas) {
      const iframe = document.createElement('iframe');
      iframe.allow = "clipboard-write";
      iframe.appendChild(canvas);

      canvas.toBlob(async (blob) => {
        try {
          await navigator.clipboard.write([
            new ClipboardItem({ 'image/png': blob })
          ]);
          console.log('画像をクリップボードにコピーしました');
        } catch (err) {
          console.error('コピーに失敗しました', err);
        }
      }, 'image/png');
    }

    async function copyImageToClipboard(imgElement) {
      // Canvas要素を作成し、img要素の内容を描画
      const canvas = document.createElement('canvas');
      canvas.width = imgElement.width;
      canvas.height = imgElement.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(imgElement, 0, 0);
      showMessage('クリップボード処理開始');

      // CanvasからBlobオブジェクトを生成
      const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));

      // ClipboardItemを作成し、クリップボードにコピー
      try {
        await navigator.clipboard.write([
          new ClipboardItem({ 'image/png': blob })
        ]);
        console.log('画像をクリップボードにコピーしました');
        showMessage('画像をコピーしました');
      } catch (err) {
        console.error('コピーに失敗しました', err);
        alert('コピーに失敗しました');
        showMessage('コピーに失敗しました');
      }
    }

    function saveDataToLocalStorage() {
      const data = {
        topText: document.getElementById('topText').value,
        bottomText: document.getElementById('bottomText').value,
        dateInput: document.getElementById('dateInput').value,
        sizeInput: document.getElementById('sizeInput').value,
        colorInput: document.getElementById('colorInput').value,
        fontSizeAdujstTopInput: document.getElementById('fontSizeAdujstTopInput').value,
        fontSizeAdujstMiddleInput: document.getElementById('fontSizeAdujstMiddleInput').value,
        fontSizeAdujstBottomInput: document.getElementById('fontSizeAdujstBottomInput').value,
        dateFormatInput: document.getElementById('dateFormatInput').value
      };
      localStorage.setItem('stampData', JSON.stringify(data));
    }

    function loadDataFromLocalStorage() {
      const savedData = localStorage.getItem('stampData');
      if (savedData) {
        const data = JSON.parse(savedData);
        document.getElementById('topText').value = data.topText;
        document.getElementById('bottomText').value = data.bottomText;
        document.getElementById('dateInput').value = data.dateInput;
        document.getElementById('sizeInput').value = data.sizeInput;
        document.getElementById('colorInput').value = data.colorInput;
        document.getElementById('fontSizeAdujstTopInput').value = data.fontSizeAdujstTopInput ?? 100;
        document.getElementById('fontSizeAdujstMiddleInput').value = data.fontSizeAdujstMiddleInput ?? 100;
        document.getElementById('fontSizeAdujstBottomInput').value = data.fontSizeAdujstBottomInput ?? 100;
        document.getElementById('dateFormatInput').value = data.dateFormatInput ?? "yyyy/MM/dd";
      } else {
        document.getElementById('topText').value = "上段";
        document.getElementById('bottomText').value = "下段";
        document.getElementById('dateInput').value = formatDate(new Date(Date.now()), "yyyy-MM-dd");
        document.getElementById('sizeInput').value = 200;
        document.getElementById('colorInput').value = '#ff0000';
        document.getElementById('fontSizeAdujstTopInput').value = 100;
        document.getElementById('fontSizeAdujstMiddleInput').value = 100;
        document.getElementById('fontSizeAdujstBottomInput').value = 100;
        document.getElementById('dateFormatInput').value = "yyyy/MM/dd";
      }
    }

	function showMessage(message) {
	    const messageBox = document.getElementById('message');
	    messageBox.style.display = 'block'; // メッセージを表示
	    messageBox.innerHTML = message;
	    console.log(messageBox);
	    setTimeout(function() {
	        messageBox.style.display = 'none'; // 3秒後にメッセージを非表示
	    }, 3000);
    }
    
    function formatDate(date, format) {
      const pad = (num) => ('00' + num).slice(-2);
      
      const replacements = {
        yyyy: date.getFullYear(),
        yy: date.getFullYear().toString().slice(-2),
        MM: pad(date.getMonth() + 1),
        dd: pad(date.getDate()),
        HH: pad(date.getHours()),
        mm: pad(date.getMinutes()),
        ss: pad(date.getSeconds()),
        M: date.getMonth() + 1,
        d: date.getDate(),
        H: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds()
      };

      return format.replace(/yyyy|yy|MM|M|dd|d|HH|H|mm|m|ss|s/g, (match) => replacements[match]);
    }
    
    function setNow() {
    	document.getElementById('dateInput').value = formatDate(new Date(Date.now()), "yyyy-MM-dd");
    }
    
    function generateStamp() {
      const topText = document.getElementById('topText').value;
      const bottomText = document.getElementById('bottomText').value;
      const date = document.getElementById('dateInput').value;
      const size = parseInt(document.getElementById('sizeInput').value);
      const color = document.getElementById('colorInput').value;
      const fontSizeAdujstTop = document.getElementById('fontSizeAdujstTopInput').value;
      const fontSizeAdujstMiddle = document.getElementById('fontSizeAdujstMiddleInput').value;
      const fontSizeAdujstBottom = document.getElementById('fontSizeAdujstBottomInput').value;
      const dateFormatInput = document.getElementById('dateFormatInput').value;
      if (size > 500) {
        alert('画像サイズは500以下を指定してください。');
        return;
      }
      
      //let separator = "";
      //const formattedDate = new Date(date).toLocaleDateString('ja-JP', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, separator);
      console.log(new Date(date));
      const formattedDate = formatDate(new Date(date), dateFormatInput);
      
      const stampDataUrl = createDateStamp(size, color, topText, formattedDate, bottomText, fontSizeAdujstTop, fontSizeAdujstMiddle, fontSizeAdujstBottom);

      const stampContainer = document.getElementById('stampContainer');
      stampContainer.innerHTML = '';
      const img = document.createElement('img');
      img.src = stampDataUrl;
      stampContainer.appendChild(img);
      
      saveDataToLocalStorage();

      stampImage = img;

      document.getElementById('btnClip').style.display = 'block';
    }

    let stampImage;

    loadDataFromLocalStorage();
    generateStamp();
  </script>
</body>

</html>