/**
 * renderer.js - Builds the editor DOM structure
 * Inspired by Summernote's renderer.js
 */

import { createElement } from './core/dom.js';
import { sanitiseHTML } from './core/sanitise.js';

/**
 * Renders the editor layout around the original element.
 *
 * Structure:
 *   <div class="an-container">
 *     <div class="an-toolbar">...</div>
 *     <div class="an-editable" contenteditable="true">...</div>
 *     <div class="an-statusbar">...</div>
 *   </div>
 *
 * @param {HTMLElement} targetEl - the original element to replace/wrap
 * @param {import('./settings.js').AsnOptions} options
 * @returns {{ container: HTMLElement, editable: HTMLElement }}
 */
export function renderLayout(targetEl, options) {
  const container = createElement('div', { class: 'an-container' });

  // Editable area
  const editable = createElement('div', {
    class: 'an-editable',
    contenteditable: options.readOnly ? 'false' : 'true',
    spellcheck: String(options.spellcheck !== false),
    'aria-multiline': 'true',
    'aria-label': 'Rich text editor',
    role: 'textbox',
  });

  // Restore auto-saved content when available; fall back to element content
  let initialContent = '';
  if (options.autoSave && options.autoSaveKey) {
    try { initialContent = localStorage.getItem(options.autoSaveKey) || ''; } catch (_) {}
  }
  if (!initialContent) {
    initialContent = targetEl.tagName === 'TEXTAREA'
      ? (targetEl.value || '').trim()
      : (targetEl.innerHTML || '').trim();
  }
  editable.innerHTML = sanitiseHTML(initialContent, { allowIframes: true });

  // Apply default font family so the editable renders in the configured font
  const defaultFont = options.defaultFontFamily || (options.fontFamilies && options.fontFamilies[0]);
  if (defaultFont) {
    editable.style.fontFamily = defaultFont;
  }

  // Apply default font size so the size dropdown shows the correct value on startup
  if (options.defaultFontSize) {
    editable.style.fontSize = options.defaultFontSize;
  }

  // Apply height options.
  // `height` sets the initial visible height (takes priority).
  // `minHeight` is the drag-resize floor — only applied when no explicit `height` is given.
  if (options.height) {
    editable.style.minHeight = `${options.height}px`;
  } else if (options.minHeight) {
    editable.style.minHeight = `${options.minHeight}px`;
  }
  if (options.maxHeight) {
    editable.style.maxHeight = `${options.maxHeight}px`;
  }

  container.appendChild(editable);

  // Apply dark theme
  if (options.theme === 'dark') {
    container.classList.add('an-theme-dark');
  }

  // Read-only mode
  if (options.readOnly) {
    container.classList.add('an-disabled');
    editable.querySelectorAll('ul.an-checklist input[type="checkbox"]').forEach((cb) => {
      cb.setAttribute('disabled', '');
    });
  }

  // Text direction
  if (options.direction === 'rtl') {
    editable.setAttribute('dir', 'rtl');
    container.classList.add('an-dir-rtl');
  }

  // Toolbar overflow
  if (options.toolbarOverflow === 'scroll') {
    container.classList.add('an-toolbar-overflow-scroll');
  }

  // Configure sticky toolbar
  if (options.stickyToolbar) {
    container.classList.add('an-sticky-toolbar');
    if (options.stickyToolbarOffset) {
      container.style.setProperty('--an-sticky-top', `${options.stickyToolbarOffset}px`);
    }
  }

  // Custom focus ring colour
  if (options.focusColor) {
    container.style.setProperty('--an-focus-color', options.focusColor);
  }

  // Hide the original element; keep it in DOM for form submission
  targetEl.style.display = 'none';
  targetEl.insertAdjacentElement('afterend', container);

  return { container, editable };
}
