import './style.css';

import { icon, refreshIcons } from './icons.js';

import { bytes, escapeHTML as esc, loadFiles, release } from './io.js';

import { attachDownloadFeedback, saveHint } from './result-feedback.js';

import { lockForm } from './operation-focus.js';

import { rasterAccept } from '../catalog.mjs';



export function mount(tool, implementation, standalone = false) {

  document.title = `${tool.name} · 蓝色精英`;

  const state = { images: [], results: [], busy: false };

  document.querySelector('#app').innerHTML = `

    <header class="topbar"><a class="brand" href="https://lansejingying.com/" target="_blank" rel="noopener">${icon('Image')}<span>蓝色精英<span class="brand-sub">本地工具</span></span></a><a class="quiet-link" href="${standalone ? 'https://lansejingying.com/' : '../'}">${icon('ArrowLeft')}<span>${standalone ? '蓝色精英' : '全部工具'}</span></a></header>

    <main class="workbench"><div class="title-row"><div class="title-icon">${icon(tool.icon)}</div><h1>${tool.name}</h1><span class="local-badge">${icon('ShieldCheck')}本地处理</span></div>

      <div class="workspace"><section class="work-area"><div class="stage" id="stage"><div class="empty">${icon(tool.icon)}<span>${tool.count ? '尚未选择图片' : tool.name}</span></div></div><div class="file-list" id="files"></div></section>

      <aside class="settings"><form id="controls"><div class="settings-heading">${icon('Scaling')}<h2>参数</h2></div>

        ${tool.count ? `<input type="file" id="file-input" accept="${tool.accept || rasterAccept}" ${tool.count > 1 ? 'multiple' : ''} hidden><button class="upload" type="button" id="choose">${icon('Upload')}选择图片</button>` : ''}

        <div id="options">${implementation.controls}</div><button class="primary" type="submit" id="process">${icon('Check')}<span>${tool.count ? '开始处理' : '生成'}</span></button>

        <button class="reset quiet-link" type="button" id="reset">${icon('RotateCcw')}重置</button></form>

        <div id="status" aria-live="polite" aria-atomic="true"></div></aside></div>

      <section class="results" id="results" hidden><div class="section-heading"><h2>处理结果</h2><span id="summary"></span></div><p class="result-save-hint" id="save-hint"></p><div class="result-grid" id="result-list"></div><div id="details"></div></section>

      <footer><span>蓝色精英</span><span>${tool.core} · MIT / ISC</span><a href="./README.md" target="_blank">使用说明</a><a href="./THIRD-PARTY-NOTICES.txt" target="_blank">开源许可</a></footer>

    </main>`;

  const $ = (s) => document.querySelector(s);

  const form = $('#controls'); const stage = $('#stage'); const details = $('#details');

  const status = (text, error = false) => { $('#status').textContent = text; $('#status').className = error ? 'error' : ''; };

  const context = { state, form, stage, details, status, refreshIcons, invalidate: invalidateResults };

  function clearResults() { release(state.results); state.results = []; $('#results').hidden = true; $('#result-list').replaceChildren(); details.replaceChildren(); }

  function invalidateResults() {

    const hadResults = state.results.length > 0 || $('#status').classList.contains('error');

    clearResults();

    if (hadResults) status('输入或参数已更改,请重新生成结果。');

  }

  function defaultPreview() {

    stage.replaceChildren();

    if (state.images.length) { const img = document.createElement('img'); img.src = state.images[0].url; img.alt = state.images[0].file.name; stage.append(img); }

    else stage.innerHTML = `<div class="empty">${icon(tool.icon)}<span>${tool.count ? '尚未选择图片' : tool.name}</span></div>`;

  }

  function fileList() {

    $('#files').innerHTML = state.images.map((item, i) => `<div class="file-row"><img src="${item.url}" alt=""><div class="file-meta"><strong>${esc(item.file.name)}</strong><span>${item.width} × ${item.height} · ${bytes(item.file.size)}</span></div>${tool.id === 'gif-maker' ? `<label class="delay-label">毫秒<input type="number" min="20" max="5000" step="10" value="${item.delay}" data-delay="${i}" aria-label="第 ${i + 1} 帧时长"></label><button type="button" class="icon-button" data-move="${i}" data-direction="-1" title="上移" ${i === 0 ? 'disabled' : ''}>${icon('ArrowUp')}</button><button type="button" class="icon-button" data-move="${i}" data-direction="1" title="下移" ${i === state.images.length - 1 ? 'disabled' : ''}>${icon('ArrowDown')}</button>` : ''}<button type="button" class="icon-button" data-remove="${i}" title="移除 ${esc(item.file.name)}">${icon('X')}</button></div>`).join('');

    refreshIcons();

  }

  async function filesChanged() { invalidateResults(); defaultPreview(); fileList(); await implementation.loaded?.(context); refreshIcons(); }

  async function choose(files) {

    if (state.busy || !files.length) return;

    state.busy = true; const unlockForm = lockForm(form); status('正在读取图片…');

    let accepted = false; let message = ''; let failed = false;

    try {

      const images = await loadFiles(files, tool.count, tool.accept || rasterAccept);

      accepted = true; implementation.dispose?.(context); release(state.images); state.images = images;

      await filesChanged(); message = `${images.length} 张图片 · ${bytes(images.reduce((n, i) => n + i.file.size, 0))}`;

    } catch (error) { message = error.message + (!accepted && state.images.length ? (state.results.length ? ' 原文件和结果已保留。' : ' 原文件已保留。') : ''); failed = true; }

    finally { state.busy = false; unlockForm(); if ($('#file-input')) $('#file-input').value = ''; status(message, failed); }

  }

  $('#choose')?.addEventListener('click', () => $('#file-input').click());

  $('#file-input')?.addEventListener('change', (event) => choose(Array.from(event.target.files)));

  if (tool.count) {

    stage.addEventListener('dragover', (event) => { event.preventDefault(); stage.classList.add('dragover'); });

    stage.addEventListener('dragleave', () => stage.classList.remove('dragover'));

    stage.addEventListener('drop', (event) => { event.preventDefault(); stage.classList.remove('dragover'); choose(Array.from(event.dataTransfer.files)); });

  }

  $('#files').addEventListener('click', async (event) => {

    if (state.busy) return;

    const remove = event.target.closest('[data-remove]'); const move = event.target.closest('[data-move]');

    if (remove) { implementation.dispose?.(context); release(state.images.splice(Number(remove.dataset.remove), 1)); await filesChanged(); }

    if (move) { const i = Number(move.dataset.move); const j = i + Number(move.dataset.direction); [state.images[i], state.images[j]] = [state.images[j], state.images[i]]; await filesChanged(); }

  });

  $('#files').addEventListener('change', (event) => {

    if (event.target.matches('[data-delay]') && !state.busy) { state.images[Number(event.target.dataset.delay)].delay = Number(event.target.value); invalidateResults(); }

  });

  form.addEventListener('input', (event) => {

    if (event.target.type === 'file' || state.busy) return;

    if (event.target.type === 'range') { const output = event.target.parentElement.querySelector('output'); if (output) output.value = `${Math.round(Number(event.target.value) * 100)}%`; }

    invalidateResults(); implementation.changed?.(context, event);

  });

  $('#reset').addEventListener('click', () => {

    if (state.busy) return;

    implementation.dispose?.(context); release(state.images); state.images = []; clearResults(); HTMLFormElement.prototype.reset.call(form);

    for (const range of form.querySelectorAll('input[type=range]')) { const out = range.parentElement.querySelector('output'); if (out) out.value = `${Math.round(range.value * 100)}%`; }

    defaultPreview(); fileList(); implementation.reset?.(context); status(tool.count ? '已重置,请重新选择图片。' : '已恢复默认设置,结果已清空。'); refreshIcons();

  });

  form.addEventListener('submit', async (event) => {

    event.preventDefault(); if (state.busy) return;

    clearResults(); status('正在处理…'); state.busy = true; const unlockForm = lockForm(form); $('#files').inert = true; stage.setAttribute('aria-busy', 'true');

    try {

      if (tool.count && !state.images.length) throw new Error('请先选择图片。');

      await new Promise((r) => requestAnimationFrame(() => setTimeout(r, 0)));

      const output = await implementation.run(context);

      if (!Array.isArray(output) || !output.length) throw new Error('未生成有效结果。');

      state.results = output.map((item) => ({ ...item, url: URL.createObjectURL(item.blob) }));

      $('#result-list').innerHTML = state.results.map((item, i) => `<article class="result"><div class="result-preview">${item.blob.type.startsWith('image/') ? `<img src="${item.url}" alt="${esc(item.name)}">` : icon('FileSearch')}</div><div class="result-info"><strong>${esc(item.name)}</strong><span>${bytes(item.blob.size)}${item.note ? ` · ${esc(item.note)}` : ''}</span><button class="download" type="button" data-download="${i}" aria-label="下载 ${esc(item.name)}">${icon('Download')}下载${item.blob.type === 'application/json' ? ' JSON' : ''}</button><p class="download-status" role="status" aria-live="polite" aria-atomic="true"></p></div></article>`).join('');

      if (!tool.count && output[0].blob.type.startsWith('image/')) { stage.innerHTML = `<img src="${state.results[0].url}" alt="${esc(tool.name)}">`; }

      $('#save-hint').textContent = saveHint(output.length); $('#results').hidden = false; $('#summary').textContent = `${output.length} 个文件`; status('处理完成'); refreshIcons();

    } catch (error) { clearResults(); status(error.message || '处理失败,请缩小图片后重试。', true); }

    finally { state.busy = false; unlockForm(); $('#files').inert = false; stage.removeAttribute('aria-busy'); }

  });

  attachDownloadFeedback($('#result-list'), () => state.results);

  implementation.init?.(context); refreshIcons();

  window.addEventListener('pagehide', () => { implementation.dispose?.(context); release(state.images); release(state.results); });

}