/**
 * Admin SDK — typed client + UI helpers for the /admin panel.
 *
 * Centralises every client-side interaction so the page markup stays declarative:
 *  - uploadImage: posts a file to /api/admin/upload and returns stored paths
 *    (no page reload, so an in-progress post draft is preserved).
 *  - runTassAgent: invokes the TASS feed agent.
 *  - initTabs / initEditor / initConfirm / initUpload / initTass: wire the DOM.
 */
type UploadResult = { image: string; thumbnail: string };

const UPLOAD_FIELDS = {
  file: '#new-image-file',
  image: '#new-image-field',
  thumb: '#new-thumb-field',
  preview: '#new-image-preview',
  status: '#upload-status',
  button: '#new-upload-btn',
} as const;

const setUploadStatus = (tone: 'idle' | 'busy' | 'ok' | 'err', text: string) => {
  const el = document.querySelector<HTMLElement>(UPLOAD_FIELDS.status);
  if (!el) return;
  el.textContent = text;
  el.className = 'text-xs rounded-lg px-2.5 py-1 ' + (
    tone === 'busy' ? 'bg-gray-100 text-gray-600' :
    tone === 'ok' ? 'bg-green-50 text-green-700' :
    tone === 'err' ? 'bg-red-50 text-brand' : 'text-gray-400'
  );
};

const renderPreview = (src: string) => {
  const el = document.querySelector<HTMLElement>(UPLOAD_FIELDS.preview);
  if (!el) return;
  el.innerHTML = src
    ? `<img src="${src}" alt="" class="w-full h-full object-cover" />`
    : '<span class="text-gray-400 text-sm">تصویری انتخاب نشده</span>';
};

export const adminSdk = {
  async uploadImage(file: File): Promise<UploadResult> {
    const formData = new FormData();
    formData.append('image', file);
    const response = await fetch('/api/admin/upload', { method: 'POST', body: formData });
    const data = await response.json().catch(() => ({ error: 'پاسخ نامعتبر سرور' }));
    if (!response.ok || data.error) {
      throw new Error(data.error ?? 'آپلود ناموفق بود');
    }
    return data as UploadResult;
  },

  async runTassAgent(limit = 3): Promise<unknown> {
    const response = await fetch('/api/agents/tass', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ limit }),
    });
    if (!response.ok) {
      throw new Error('خطا در اجرای agent');
    }
    return response.json();
  },

  initUpload() {
    const fileInput = document.querySelector<HTMLInputElement>(UPLOAD_FIELDS.file);
    if (!fileInput) return;
    const imageField = document.querySelector<HTMLInputElement>(UPLOAD_FIELDS.image);
    const thumbField = document.querySelector<HTMLInputElement>(UPLOAD_FIELDS.thumb);
    const button = document.querySelector<HTMLButtonElement>(UPLOAD_FIELDS.button);

    const syncInsertButtons = () => {
      const value = imageField?.value ?? '';
      document.querySelectorAll<HTMLButtonElement>('[data-insert-image]').forEach((btn) => {
        btn.dataset.insertImage = value;
        btn.disabled = !value;
      });
    };

    const applyImage = (image: string, thumbnail: string) => {
      if (imageField) imageField.value = image;
      if (thumbField) thumbField.value = thumbnail;
      renderPreview(thumbnail || image);
      syncInsertButtons();
    };

    const handleFile = async (file: File) => {
      setUploadStatus('busy', 'در حال آپلود و پردازش...');
      if (button) button.disabled = true;
      try {
        const result = await adminSdk.uploadImage(file);
        applyImage(result.image, result.thumbnail);
        setUploadStatus('ok', 'تصویر آپلود شد و آماده استفاده است.');
      } catch (error) {
        setUploadStatus('err', error instanceof Error ? error.message : 'آپلود ناموفق بود.');
      } finally {
        if (button) button.disabled = false;
      }
    };

    fileInput.addEventListener('change', () => {
      const file = fileInput.files?.[0];
      if (file) handleFile(file);
    });
    button?.addEventListener('click', () => {
      const file = fileInput.files?.[0];
      if (file) handleFile(file);
      else setUploadStatus('err', 'ابتدا یک فایل انتخاب کنید.');
    });

    syncInsertButtons();
  },

  initEditor() {
    const editor = document.querySelector<HTMLTextAreaElement>('#post-body-editor');
    if (!editor) return;

    const insertAtCursor = (value: string) => {
      const start = editor.selectionStart;
      const end = editor.selectionEnd;
      const before = editor.value.slice(0, start);
      const after = editor.value.slice(end);
      const prefix = before.endsWith('\n') || before.length === 0 ? '' : '\n\n';
      const suffix = after.startsWith('\n') || after.length === 0 ? '' : '\n\n';
      editor.value = `${before}${prefix}${value}${suffix}${after}`;
      editor.focus();
      const cursor = before.length + prefix.length + value.length;
      editor.setSelectionRange(cursor, cursor);
    };

    document.querySelectorAll<HTMLButtonElement>('[data-insert-image]').forEach((button) => {
      button.addEventListener('click', () => {
        const image = button.dataset.insertImage;
        if (image) insertAtCursor(`[image:${image}|توضیح تصویر]`);
      });
    });

    document.querySelectorAll<HTMLButtonElement>('[data-editor-command]').forEach((button) => {
      button.addEventListener('click', () => {
        const command = button.dataset.editorCommand;
        if (command === 'heading') insertAtCursor('## تیتر میانی');
        if (command === 'quote') insertAtCursor('> متن نقل‌قول');
        if (command === 'separator') insertAtCursor('---');
      });
    });
  },

  initConfirm() {
    document.querySelectorAll<HTMLFormElement>('[data-confirm-form]').forEach((form) => {
      form.addEventListener('submit', (event) => {
        const message = form.dataset.confirmMessage || 'برای تایید حذف عبارت confirm را تایپ کنید.';
        const value = window.prompt(message);
        if (value !== 'confirm') {
          event.preventDefault();
          window.alert('حذف لغو شد. عبارت واردشده باید دقیقاً confirm باشد.');
          return;
        }
        const input = form.querySelector<HTMLInputElement>('[data-confirm-input]');
        if (input) input.value = value;
      });
    });
  },

  initTass() {
    const button = document.querySelector<HTMLButtonElement>('#run-tass-agent');
    const result = document.querySelector<HTMLPreElement>('#tass-agent-result');
    if (!button || !result) return;

    button.addEventListener('click', async () => {
      button.disabled = true;
      button.textContent = 'در حال اجرا...';
      result.classList.remove('hidden');
      result.textContent = 'در حال دریافت و ترجمه خبرها...';
      try {
        const data = await adminSdk.runTassAgent(3);
        result.textContent = JSON.stringify(data, null, 2);
      } catch (error) {
        result.textContent = error instanceof Error ? error.message : 'خطا در اجرای agent';
      } finally {
        button.disabled = false;
        button.textContent = 'اجرای agent و ساخت پست';
      }
    });
  },

  initTabs() {
    const nav = document.querySelector<HTMLElement>('[data-active-tab]');
    const defaultTab = nav?.dataset.activeTab ?? 'pending';
    const tabs = Array.from(document.querySelectorAll<HTMLAnchorElement>('[data-tab]'));
    const panels = Array.from(document.querySelectorAll<HTMLElement>('[data-panel]'));

    const activate = (id: string) => {
      tabs.forEach((tab) => {
        const active = tab.dataset.tab === id;
        tab.classList.toggle('bg-brand', active);
        tab.classList.toggle('text-white', active);
        tab.classList.toggle('border-brand', active);
        tab.classList.toggle('bg-white', !active);
        tab.classList.toggle('text-gray-700', !active);
        tab.classList.toggle('border-gray-200', !active);
        if (active) tab.setAttribute('aria-current', 'page');
        else tab.removeAttribute('aria-current');
      });
      panels.forEach((panel) => {
        panel.classList.toggle('hidden', panel.dataset.panel !== id);
      });
    };

    activate(defaultTab);

    tabs.forEach((tab) => {
      tab.addEventListener('click', (event) => {
        const id = tab.dataset.tab;
        if (!id) return;
        event.preventDefault();
        activate(id);
        const url = new URL(window.location.href);
        url.searchParams.set('tab', id);
        url.searchParams.delete('pendingPage');
        url.searchParams.delete('approvedPage');
        url.searchParams.delete('edit');
        window.history.pushState({}, '', url);
      });
    });

    window.addEventListener('popstate', () => {
      const params = new URLSearchParams(window.location.search);
      activate(params.get('tab') || defaultTab);
    });
  },
};
