<template>
  <div class="overlay-body">
    <div class="sub-panel">
      <header class="sub-panel-header">
        <h3>脚本管理</h3>
        <button class="btn-ghost tiny" @click="loadScripts" :disabled="scriptLoading">刷新</button>
      </header>
      <p v-if="scriptError" class="form-error small">{{ scriptError }}</p>

      <div class="script-layout">
        <div class="script-list" v-if="scriptList.length">
          <button
            v-for="item in scriptList"
            :key="item.name"
            class="script-item"
            :class="{ active: item.name === scriptSelected }"
            type="button"
            @click="selectScript(item.name)"
          >
            {{ item.name }}
          </button>
        </div>
        <p v-else class="empty-hint">暂无脚本，可直接在右侧新建。</p>

        <div class="script-editor">
          <div class="form-grid">
            <label>
              名称
              <input
                v-model.trim="scriptForm.name"
                placeholder="例如 docker-info.sh"
                :disabled="!!scriptSelected"
              />
            </label>
          </div>
          <label class="script-content-label">
            内容
            <textarea v-model="scriptForm.content" rows="6" placeholder="#!/bin/bash"></textarea>
          </label>
          <div class="form-actions">
            <button class="btn-primary small" type="button" @click="saveScript" :disabled="scriptSaving">
              {{ scriptSaving ? "保存中..." : scriptSelected ? "更新" : "新建" }}
            </button>
            <button v-if="scriptSelected" class="btn-danger small" type="button" @click="deleteScript">删除</button>
            <button class="btn-secondary small" type="button" @click="resetScriptForm">重置</button>
            <button class="btn-secondary small" type="button" @click="applyScriptToTerminal" :disabled="!scriptForm.content">
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useScripts } from "../../composables/useScripts";

const {
  scriptList, scriptLoading, scriptSaving, scriptError, scriptSelected, scriptForm,
  loadScripts, selectScript, resetScriptForm, saveScript, deleteScript, applyScriptToTerminal,
} = useScripts();
</script>
