<template>
  <div class="code-editor-wrapper">
    <div class="editor-header">
      <div class="tabs">
        <button :class="{ active: tab === 'html' }" @click="tab = 'html'">HTML</button>
        <button :class="{ active: tab === 'css' }" @click="tab = 'css'">CSS</button>
        <button :class="{ active: tab === 'js' }" @click="tab = 'js'">JavaScript</button>
      </div>
      <div class="actions">
        <button @click="formatCode">Prettier</button>
        <button @click="saveCode">💾 Save</button>
        <button @click="loadCode">🔄 Load</button>
        <button @click="runCode">▶ Run</button>
      </div>
    </div>

    <div class="editor-body">
      <textarea v-if="tab === 'html'" v-model="html" placeholder="HTML 코드 입력" ></textarea>
      <textarea v-if="tab === 'css'" v-model="css" placeholder="CSS 코드 입력" ></textarea>
      <textarea v-if="tab === 'js'" v-model="js" placeholder="JavaScript 코드 입력" ></textarea>
    </div>

    <iframe ref="preview" class="preview-frame" sandbox="allow-scripts allow-modals allow-popups"></iframe>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import prettier from 'prettier/standalone';
import parserHtml from 'prettier/parser-html';
import parserCss from 'prettier/parser-postcss';
import parserJs from 'prettier/parser-babel';

const props = defineProps({
  html: {
    type: String,
    default: `<div id="box">Hello!</div>`,
  },
  css: {
    type: String,
    default: `#box { background: lightblue; padding: 1em; }`,
  },
  js: {
    type: String,
    default: `document.getElementById('box').onclick = () => alert('Clicked!');`,
  }
});

const html = ref(props.html);
const css = ref(props.css);
const js = ref(props.js);

// 부모 컴포넌트에서 prop이 바뀌면 내부 상태도 동기화
watch(() => props.html, val => { html.value = val; });
watch(() => props.css, val => { css.value = val; });
watch(() => props.js, val => { js.value = val; });

const tab = ref('html');
const preview = ref(null);
const LOCAL_KEY = 'code-editor-content';

const runCode = () => {
  const fullDoc = `
    <html><head><meta charset="UTF-8" /><style>${css.value}body {
            background-color: white; 
            color: black;
            margin: 0;
            padding: 1em;
            box-sizing: border-box;
          }</style></head><body>
    ${html.value}
    <script>${js.value.replace(/<\/script>/g, '<\\/script>')}<\/script>
    </body></html>
  `;
  const blob = new Blob([fullDoc], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  preview.value.src = url;

  if (preview.value._oldUrl) URL.revokeObjectURL(preview.value._oldUrl);
  preview.value._oldUrl = url;
};

const formatCode = () => {
  html.value = prettier.format(html.value, { parser: 'html', plugins: [parserHtml] });
  css.value = prettier.format(css.value, { parser: 'css', plugins: [parserCss] });
  js.value = prettier.format(js.value, { parser: 'babel', plugins: [parserJs] });
  runCode(); // 포맷팅 후 미리보기 갱신
};

const saveCode = () => {
  localStorage.setItem(LOCAL_KEY, JSON.stringify({ html: html.value, css: css.value, js: js.value }));
  alert('💾 코드가 저장되었습니다!');
};

const loadCode = () => {
  const saved = localStorage.getItem(LOCAL_KEY);
  if (saved) {
    const parsed = JSON.parse(saved);
    html.value = parsed.html || '';
    css.value = parsed.css || '';
    js.value = parsed.js || '';
    alert('✅ 저장된 코드를 불러왔습니다.');
  } else {
    alert('⚠ 저장된 코드가 없습니다.');
  }
};

onMounted(runCode);
</script>

<style scoped>
.code-editor-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  font-family: 'Fira Code', monospace;
  color: #eee;
}

/* 상단 탭 및 액션 버튼 */
.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #2d2d2d;
  border-bottom: 1px solid #444;
}

/* 탭 버튼 스타일 */
.tabs button {
  margin-right: 6px;
  padding: 6px 16px;
  background: transparent;
  border: none;
  color: #bbb;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 2px solid transparent;
}

.tabs .active {
  background: #444;         /* 진한 회색 */
  color: #fff;              /* 흰색 글자 */
  border-bottom: 2px solid #00c6ff; /* 강조선 */
}

.actions button {
  margin-left: 6px;
  padding: 6px 10px;
  cursor: pointer;
}

.editor-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 4px 8px;
}

textarea {
  width: 100%;
  height: 300px;
  font-family: monospace;
  font-size: 14px;
  padding: 8px;
  border: 1px solid #ccc;
  resize: vertical;
  box-sizing: border-box;
}

.preview-frame {
  height: 60vh;
  width: 100%;
  margin-top: 8px;
  border: 2px solid #aaa; /* 여기에 원하는 border 스타일 */
  border-radius: 4px; /* 둥근 모서리 옵션 */
}
</style>
