import './index.css';
import {
  type ArtStyle,
  type BackgroundMode,
  type TransformParams,
  transformArtwork,
} from './artEngine';
import {renderSampleStudy, SAMPLE_STUDIES, type StudyId} from './sampleStudies';

interface StudioState extends TransformParams {
  hasImage: boolean;
  fileName: string;
  hasGenerated: boolean;
  viewMode: 'side-by-side' | 'split';
  splitPercent: number;
}

const DEFAULT_PARAMS: TransformParams = {
  style: 'madhubani',
  detailIntensity: 62,
  colourComplexity: 6,
  patternDensity: 28,
  background: 'original',
  seed: 42,
};

const state: StudioState = {
  ...DEFAULT_PARAMS,
  hasImage: false,
  fileName: '',
  hasGenerated: false,
  viewMode: 'side-by-side',
  splitPercent: 50,
};

const sourceCanvas = document.createElement('canvas');

// DOM references
const fileInput = document.getElementById('imageFileInput') as HTMLInputElement;
const exploreStudioBtn = document.getElementById('exploreStudioBtn') as HTMLButtonElement | null;
const emptyUploadBtn = document.getElementById('emptyUploadBtn') as HTMLButtonElement;
const replaceImageBtn = document.getElementById('replaceImageBtn') as HTMLButtonElement;
const dropZone = document.getElementById('dropZone') as HTMLDivElement;
const dropZoneTitle = document.getElementById('dropZoneTitle') as HTMLParagraphElement;
const dropZoneMeta = document.getElementById('dropZoneMeta') as HTMLParagraphElement;
const statusMessage = document.getElementById('statusMessage') as HTMLDivElement;

const styleCards = Array.from(document.querySelectorAll<HTMLButtonElement>('.style-card'));
const styleButtons = Array.from(document.querySelectorAll<HTMLButtonElement>('.style-btn'));
const bgButtons = Array.from(document.querySelectorAll<HTMLButtonElement>('.bg-btn'));
const studyButtons = Array.from(document.querySelectorAll<HTMLButtonElement>('.study-btn'));
const archiveTryButtons = Array.from(
  document.querySelectorAll<HTMLButtonElement>('.archive-try-btn')
);

const panelStyleReadout = document.getElementById('panelStyleReadout') as HTMLSpanElement;

const detailSlider = document.getElementById('detailSlider') as HTMLInputElement;
const colourSlider = document.getElementById('colourSlider') as HTMLInputElement;
const patternSlider = document.getElementById('patternSlider') as HTMLInputElement;
const detailValue = document.getElementById('detailValue') as HTMLSpanElement;
const colourValue = document.getElementById('colourValue') as HTMLSpanElement;
const patternValue = document.getElementById('patternValue') as HTMLSpanElement;

const generateBtn = document.getElementById('generateBtn') as HTMLButtonElement;
const randomiseBtn = document.getElementById('randomiseBtn') as HTMLButtonElement;
const resetBtn = document.getElementById('resetBtn') as HTMLButtonElement;
const downloadBtn = document.getElementById('downloadBtn') as HTMLButtonElement;

const emptyStage = document.getElementById('emptyStage') as HTMLDivElement;
const sideBySideView = document.getElementById('sideBySideView') as HTMLDivElement;
const splitCompareView = document.getElementById('splitCompareView') as HTMLDivElement;
const loadingOverlay = document.getElementById('loadingOverlay') as HTMLDivElement;

const viewSideBySideBtn = document.getElementById('viewSideBySideBtn') as HTMLButtonElement;
const viewSplitBtn = document.getElementById('viewSplitBtn') as HTMLButtonElement;

const originalCanvas = document.getElementById('originalCanvas') as HTMLCanvasElement;
const outputCanvas = document.getElementById('outputCanvas') as HTMLCanvasElement;
const splitBeforeCanvas = document.getElementById('splitBeforeCanvas') as HTMLCanvasElement;
const splitAfterCanvas = document.getElementById('splitAfterCanvas') as HTMLCanvasElement;

const originalFileLabel = document.getElementById('originalFileLabel') as HTMLSpanElement;
const outputPlateCaption = document.getElementById('outputPlateCaption') as HTMLElement;
const renderTimeLabel = document.getElementById('renderTimeLabel') as HTMLSpanElement;

const stageSummaryStyle = document.getElementById('stageSummaryStyle') as HTMLSpanElement;
const stageSummaryColours = document.getElementById('stageSummaryColours') as HTMLSpanElement;
const stageSummaryBg = document.getElementById('stageSummaryBg') as HTMLSpanElement;
const stageDimensions = document.getElementById('stageDimensions') as HTMLSpanElement;

const splitStage = document.getElementById('splitStage') as HTMLDivElement;
const splitBeforeClip = document.getElementById('splitBeforeClip') as HTMLDivElement;
const splitDivider = document.getElementById('splitDivider') as HTMLDivElement;
const splitRightBadge = document.getElementById('splitRightBadge') as HTMLDivElement;
const splitPercentLabel = document.getElementById('splitPercentLabel') as HTMLSpanElement;

const STYLE_LABELS: Record<ArtStyle, string> = {
  madhubani: 'Madhubani',
  gond: 'Gond',
  warli: 'Warli',
};

const BG_LABELS: Record<BackgroundMode, string> = {
  original: 'Original Ground',
  cream: 'Cream Ground',
  terracotta: 'Terracotta Ground',
  mustard: 'Mustard Ground',
};

const VALID_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
const VALID_EXT_RE = /\.(jpe?g|png|webp)$/i;

let debounceTimer: number | null = null;
let downloadFeedbackTimer: number | null = null;
let isProcessing = false;

function showStatus(message: string, tone: 'error' | 'info' = 'error'): void {
  statusMessage.textContent = message;
  statusMessage.classList.remove('hidden');
  if (tone === 'error') {
    statusMessage.className =
      'mt-3 border border-[#9D352C]/45 bg-[#9D352C]/10 px-3.5 py-2.5 text-xs leading-relaxed text-[#7A231B]';
  } else {
    statusMessage.className =
      'mt-3 border border-[#C69A43]/55 bg-[#C69A43]/15 px-3.5 py-2.5 text-xs leading-relaxed text-[#5A4212]';
  }
}

function clearStatus(): void {
  statusMessage.classList.add('hidden');
  statusMessage.textContent = '';
}

function setLoading(loading: boolean): void {
  isProcessing = loading;
  if (loading) {
    loadingOverlay.classList.remove('hidden');
    loadingOverlay.classList.add('flex');
    generateBtn.disabled = true;
    generateBtn.textContent = 'Composing Artwork…';
  } else {
    loadingOverlay.classList.add('hidden');
    loadingOverlay.classList.remove('flex');
    generateBtn.disabled = false;
    generateBtn.textContent = 'Generate Artwork';
  }
}

function updateSplitPosition(percent: number): void {
  const clamped = Math.max(2, Math.min(98, Math.round(percent)));
  state.splitPercent = clamped;
  splitBeforeClip.style.clipPath = `inset(0 ${100 - clamped}% 0 0)`;
  splitDivider.style.left = `${clamped}%`;
  splitDivider.setAttribute('aria-valuenow', String(clamped));
  splitPercentLabel.textContent = `${clamped}%`;
}

function syncControlsUI(): void {
  // Section C large exhibition style cards
  for (const card of styleCards) {
    const active = card.dataset.style === state.style;
    card.setAttribute('aria-checked', String(active));
    const badge = card.querySelector('.style-card-badge');
    if (active) {
      card.className =
        'style-card group relative flex flex-col justify-between bg-[#FAF7F0] p-5 text-left transition-all duration-150 cursor-pointer border-2 border-[#9D352C] shadow-[inset_0_0_0_4px_#FAF7F0,inset_0_0_0_5px_#C69A43] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#9D352C]';
      if (badge) {
        badge.textContent = 'Active Style';
        badge.className = 'style-card-badge font-semibold text-[#9D352C]';
      }
    } else {
      card.className =
        'style-card group relative flex flex-col justify-between bg-[#FAF7F0] p-5 text-left transition-all duration-150 cursor-pointer border border-[#382820]/25 hover:border-[#9D352C]/70 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#9D352C]';
      if (badge) {
        badge.textContent = 'Select';
        badge.className = 'style-card-badge font-normal text-[#7D6655]';
      }
    }
  }

  // Section E quick switcher buttons
  for (const btn of styleButtons) {
    const active = btn.dataset.style === state.style;
    btn.setAttribute('aria-checked', String(active));
    btn.className = active
      ? 'style-btn border border-[#9D352C] bg-[#9D352C] px-2.5 py-2 text-xs font-medium text-[#FAF7F0] transition-colors duration-150 cursor-pointer whitespace-nowrap'
      : 'style-btn border border-[#382820]/25 bg-[#F3EBDD]/60 px-2.5 py-2 text-xs font-medium text-[#382820] hover:border-[#9D352C] transition-colors duration-150 cursor-pointer whitespace-nowrap';
  }

  panelStyleReadout.textContent = STYLE_LABELS[state.style];

  // Background pigment buttons
  for (const btn of bgButtons) {
    const active = btn.dataset.bg === state.background;
    btn.setAttribute('aria-checked', String(active));
    btn.className = active
      ? 'bg-btn flex items-center gap-2.5 border border-[#9D352C] bg-[#F3EBDD] px-3 py-2 text-xs font-semibold text-[#382820] cursor-pointer transition-colors duration-150 ring-1 ring-[#9D352C]/25'
      : 'bg-btn flex items-center gap-2.5 border border-[#382820]/20 bg-[#FAF7F0] px-3 py-2 text-xs font-medium text-[#382820] hover:border-[#9D352C] cursor-pointer transition-colors duration-150';
  }

  // Sliders
  detailSlider.value = String(state.detailIntensity);
  colourSlider.value = String(state.colourComplexity);
  patternSlider.value = String(state.patternDensity);

  detailValue.textContent = String(state.detailIntensity);
  colourValue.textContent = String(state.colourComplexity);
  patternValue.textContent = String(state.patternDensity);

  // Stage metadata summary
  stageSummaryStyle.textContent = STYLE_LABELS[state.style];
  stageSummaryColours.textContent = `${state.colourComplexity} Pigments`;
  stageSummaryBg.textContent = BG_LABELS[state.background];
  outputPlateCaption.textContent = `${STYLE_LABELS[state.style]} folk-art reconstruction`;
  splitRightBadge.textContent = `Plate II · ${STYLE_LABELS[state.style]}`;

  // View mode toggle
  if (state.viewMode === 'side-by-side') {
    viewSideBySideBtn.className =
      'px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] bg-[#382820] text-[#FAF7F0] transition-colors duration-150 cursor-pointer whitespace-nowrap shrink-0';
    viewSplitBtn.className =
      'px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] text-[#5B4538] hover:text-[#382820] transition-colors duration-150 cursor-pointer whitespace-nowrap shrink-0';
    viewSideBySideBtn.setAttribute('aria-selected', 'true');
    viewSplitBtn.setAttribute('aria-selected', 'false');
  } else {
    viewSplitBtn.className =
      'px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] bg-[#382820] text-[#FAF7F0] transition-colors duration-150 cursor-pointer whitespace-nowrap shrink-0';
    viewSideBySideBtn.className =
      'px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] text-[#5B4538] hover:text-[#382820] transition-colors duration-150 cursor-pointer whitespace-nowrap shrink-0';
    viewSplitBtn.setAttribute('aria-selected', 'true');
    viewSideBySideBtn.setAttribute('aria-selected', 'false');
  }

  updateStageVisibility();
  downloadBtn.disabled = !state.hasImage || !state.hasGenerated;
}

function updateStageVisibility(): void {
  if (!state.hasImage) {
    emptyStage.classList.remove('hidden');
    sideBySideView.classList.add('hidden');
    sideBySideView.classList.remove('grid');
    splitCompareView.classList.add('hidden');
    replaceImageBtn.classList.add('hidden');
    return;
  }

  emptyStage.classList.add('hidden');
  replaceImageBtn.classList.remove('hidden');

  if (state.viewMode === 'side-by-side') {
    sideBySideView.classList.remove('hidden');
    sideBySideView.classList.add('grid');
    splitCompareView.classList.add('hidden');
  } else {
    sideBySideView.classList.add('hidden');
    sideBySideView.classList.remove('grid');
    splitCompareView.classList.remove('hidden');
  }
}

function syncOriginalCanvases(): void {
  if (!state.hasImage) return;

  originalCanvas.width = sourceCanvas.width;
  originalCanvas.height = sourceCanvas.height;
  const oCtx = originalCanvas.getContext('2d');
  if (oCtx) {
    oCtx.drawImage(sourceCanvas, 0, 0);
  }

  originalFileLabel.textContent = state.fileName || 'Uploaded photograph';
  stageDimensions.textContent = `· ${sourceCanvas.width}×${sourceCanvas.height} px`;
}

function syncSplitCanvases(): void {
  if (!state.hasImage || !state.hasGenerated) return;
  const w = outputCanvas.width;
  const h = outputCanvas.height;

  splitBeforeCanvas.width = w;
  splitBeforeCanvas.height = h;
  const sbCtx = splitBeforeCanvas.getContext('2d');
  if (sbCtx) {
    sbCtx.drawImage(sourceCanvas, 0, 0, w, h);
  }

  splitAfterCanvas.width = w;
  splitAfterCanvas.height = h;
  const saCtx = splitAfterCanvas.getContext('2d');
  if (saCtx) {
    saCtx.drawImage(outputCanvas, 0, 0, w, h);
  }

  updateSplitPosition(state.splitPercent);
}

function runTransformation(): void {
  if (!state.hasImage) {
    showStatus(
      'Please upload a JPG, JPEG, PNG, or WebP photograph or select a studio study to begin.',
      'error'
    );
    return;
  }
  if (isProcessing) return;

  clearStatus();
  setLoading(true);

  requestAnimationFrame(() => {
    window.setTimeout(() => {
      try {
        const result = transformArtwork(sourceCanvas, outputCanvas, {
          style: state.style,
          detailIntensity: state.detailIntensity,
          colourComplexity: state.colourComplexity,
          patternDensity: state.patternDensity,
          background: state.background,
          seed: state.seed,
        });

        state.hasGenerated = true;
        renderTimeLabel.textContent = `${result.elapsedMs} ms`;
        syncSplitCanvases();
        syncControlsUI();
      } catch (err) {
        showStatus(
          err instanceof Error
            ? `Processing failed: ${err.message}`
            : 'Unable to process this image in the browser.',
          'error'
        );
      } finally {
        setLoading(false);
      }
    }, 24);
  });
}

function scheduleTransform(): void {
  if (!state.hasImage) return;
  if (debounceTimer !== null) {
    window.clearTimeout(debounceTimer);
  }
  debounceTimer = window.setTimeout(() => {
    debounceTimer = null;
    runTransformation();
  }, 160);
}

function loadCanvasAsSource(canvas: HTMLCanvasElement, label: string): void {
  sourceCanvas.width = canvas.width;
  sourceCanvas.height = canvas.height;
  const ctx = sourceCanvas.getContext('2d');
  if (!ctx) return;
  ctx.drawImage(canvas, 0, 0);

  state.hasImage = true;
  state.fileName = label;
  state.hasGenerated = false;

  dropZoneTitle.textContent = label;
  dropZoneMeta.textContent = `${canvas.width} × ${canvas.height} px · Click or drop to replace`;

  clearStatus();
  syncOriginalCanvases();
  syncControlsUI();
  runTransformation();
}

function handleFileUpload(file: File | undefined): void {
  if (!file) return;

  const validMime = VALID_MIME_TYPES.has(file.type.toLowerCase());
  const validExt = VALID_EXT_RE.test(file.name);
  if (!validMime && !validExt) {
    showStatus(
      `Unsupported file format "${file.name}". Please upload a JPG, JPEG, PNG, or WebP photograph.`,
      'error'
    );
    return;
  }

  const reader = new FileReader();
  reader.onerror = () => {
    showStatus('Could not read the selected file. Please try another photograph.', 'error');
  };
  reader.onload = () => {
    const img = new Image();
    img.onload = () => {
      const temp = document.createElement('canvas');
      temp.width = img.naturalWidth || img.width;
      temp.height = img.naturalHeight || img.height;
      const tCtx = temp.getContext('2d');
      if (!tCtx) return;
      tCtx.drawImage(img, 0, 0);
      loadCanvasAsSource(temp, file.name);
    };
    img.onerror = () => {
      showStatus(
        'The uploaded file appears damaged or is not a valid JPG, PNG, or WebP image.',
        'error'
      );
    };
    img.src = String(reader.result);
  };
  reader.readAsDataURL(file);
}

function triggerFileDialog(): void {
  fileInput.value = '';
  fileInput.click();
}

function selectArtStyle(next: ArtStyle): void {
  if (next === state.style) return;
  state.style = next;
  syncControlsUI();
  if (state.hasImage) runTransformation();
}

// Smooth Hero Explore button
exploreStudioBtn?.addEventListener('click', () => {
  document.getElementById('workspace')?.scrollIntoView({behavior: 'smooth'});
});

// Upload & Drag-and-Drop bindings
emptyUploadBtn.addEventListener('click', triggerFileDialog);
replaceImageBtn.addEventListener('click', triggerFileDialog);
dropZone.addEventListener('click', triggerFileDialog);
dropZone.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' || e.key === ' ') {
    e.preventDefault();
    triggerFileDialog();
  }
});

fileInput.addEventListener('change', () => {
  const file = fileInput.files?.[0];
  handleFileUpload(file);
});

dropZone.addEventListener('dragover', (e) => {
  e.preventDefault();
  dropZone.classList.add('border-[#9D352C]', 'bg-[#F3EBDD]');
});

dropZone.addEventListener('dragleave', () => {
  dropZone.classList.remove('border-[#9D352C]', 'bg-[#F3EBDD]');
});

dropZone.addEventListener('drop', (e) => {
  e.preventDefault();
  dropZone.classList.remove('border-[#9D352C]', 'bg-[#F3EBDD]');
  const file = e.dataTransfer?.files?.[0];
  handleFileUpload(file);
});

// Sample archival study buttons
for (const btn of studyButtons) {
  btn.addEventListener('click', () => {
    const id = btn.dataset.study as StudyId | undefined;
    if (!id || !(id in SAMPLE_STUDIES)) return;
    const canvas = renderSampleStudy(id);
    loadCanvasAsSource(canvas, SAMPLE_STUDIES[id].title);
  });
}

// Section C large style cards
for (const card of styleCards) {
  card.addEventListener('click', () => {
    const next = card.dataset.style as ArtStyle | undefined;
    if (!next) return;
    selectArtStyle(next);
  });
}

// Section E control panel style buttons
for (const btn of styleButtons) {
  btn.addEventListener('click', () => {
    const next = btn.dataset.style as ArtStyle | undefined;
    if (!next) return;
    selectArtStyle(next);
  });
}

// Section F Archive gallery "Open in Studio" buttons
for (const btn of archiveTryButtons) {
  btn.addEventListener('click', () => {
    const style = btn.dataset.archiveStyle as ArtStyle | undefined;
    const studyId = btn.dataset.archiveStudy as StudyId | undefined;
    if (style) state.style = style;
    syncControlsUI();
    document.getElementById('workspace')?.scrollIntoView({behavior: 'smooth'});
    if (studyId && studyId in SAMPLE_STUDIES) {
      const canvas = renderSampleStudy(studyId);
      loadCanvasAsSource(canvas, SAMPLE_STUDIES[studyId].title);
    } else if (state.hasImage) {
      runTransformation();
    }
  });
}

// Background selector buttons
for (const btn of bgButtons) {
  btn.addEventListener('click', () => {
    const next = btn.dataset.bg as BackgroundMode | undefined;
    if (!next || next === state.background) return;
    state.background = next;
    syncControlsUI();
    if (state.hasImage) runTransformation();
  });
}

// Slider handlers
detailSlider.addEventListener('input', () => {
  state.detailIntensity = Number(detailSlider.value);
  detailValue.textContent = String(state.detailIntensity);
  scheduleTransform();
});

colourSlider.addEventListener('input', () => {
  state.colourComplexity = Number(colourSlider.value);
  colourValue.textContent = String(state.colourComplexity);
  syncControlsUI();
  scheduleTransform();
});

patternSlider.addEventListener('input', () => {
  state.patternDensity = Number(patternSlider.value);
  patternValue.textContent = String(state.patternDensity);
  scheduleTransform();
});

// Generate, Randomise, Reset, Download
generateBtn.addEventListener('click', () => {
  runTransformation();
});

randomiseBtn.addEventListener('click', () => {
  const bgs: BackgroundMode[] = ['original', 'cream', 'terracotta', 'mustard'];
  state.seed = Math.floor(Math.random() * 900000) + 100;
  state.detailIntensity = Math.floor(Math.random() * 52) + 40;
  state.colourComplexity = Math.floor(Math.random() * 8) + 4;
  state.patternDensity = Math.floor(Math.random() * 52) + 15;
  state.background = bgs[Math.floor(Math.random() * bgs.length)];
  syncControlsUI();

  if (state.hasImage) {
    runTransformation();
  } else {
    showStatus(
      'Parameters randomised. Upload a photograph or load a studio study to render this variation.',
      'info'
    );
  }
});

resetBtn.addEventListener('click', () => {
  state.style = DEFAULT_PARAMS.style;
  state.detailIntensity = DEFAULT_PARAMS.detailIntensity;
  state.colourComplexity = DEFAULT_PARAMS.colourComplexity;
  state.patternDensity = DEFAULT_PARAMS.patternDensity;
  state.background = DEFAULT_PARAMS.background;
  state.seed = DEFAULT_PARAMS.seed;
  state.viewMode = 'side-by-side';
  state.splitPercent = 50;
  clearStatus();
  syncControlsUI();

  if (state.hasImage) {
    syncOriginalCanvases();
    runTransformation();
  }
});

downloadBtn.addEventListener('click', () => {
  if (!state.hasImage || !state.hasGenerated) {
    showStatus('Generate an artwork first before downloading as PNG.', 'error');
    return;
  }

  outputCanvas.toBlob((blob) => {
    if (!blob) {
      const dataUrl = outputCanvas.toDataURL('image/png');
      const link = document.createElement('a');
      link.download = `roop-${state.style}-${Date.now()}.png`;
      link.href = dataUrl;
      link.click();
    } else {
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.download = `roop-${state.style}-${Date.now()}.png`;
      link.href = url;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.setTimeout(() => URL.revokeObjectURL(url), 1000);
    }

    downloadBtn.textContent = 'Exported PNG ✓';
    if (downloadFeedbackTimer !== null) window.clearTimeout(downloadFeedbackTimer);
    downloadFeedbackTimer = window.setTimeout(() => {
      downloadBtn.textContent = 'Download PNG';
    }, 2000);
  }, 'image/png');
});

// Comparison mode toggle
viewSideBySideBtn.addEventListener('click', () => {
  state.viewMode = 'side-by-side';
  syncControlsUI();
});

viewSplitBtn.addEventListener('click', () => {
  state.viewMode = 'split';
  syncControlsUI();
  syncSplitCanvases();
});

// Interactive Before/After Split Divider
let isDraggingSplit = false;

function updateSplitFromClientX(clientX: number): void {
  const rect = splitStage.getBoundingClientRect();
  if (rect.width <= 0) return;
  const pct = ((clientX - rect.left) / rect.width) * 100;
  updateSplitPosition(pct);
}

splitDivider.addEventListener('pointerdown', (e) => {
  isDraggingSplit = true;
  splitDivider.setPointerCapture(e.pointerId);
  updateSplitFromClientX(e.clientX);
});

splitStage.addEventListener('pointerdown', (e) => {
  if (e.target === splitDivider || splitDivider.contains(e.target as Node)) return;
  isDraggingSplit = true;
  updateSplitFromClientX(e.clientX);
});

window.addEventListener('pointermove', (e) => {
  if (!isDraggingSplit) return;
  updateSplitFromClientX(e.clientX);
});

window.addEventListener('pointerup', () => {
  isDraggingSplit = false;
});

splitDivider.addEventListener('keydown', (e) => {
  if (e.key === 'ArrowLeft') {
    e.preventDefault();
    updateSplitPosition(state.splitPercent - 4);
  } else if (e.key === 'ArrowRight') {
    e.preventDefault();
    updateSplitPosition(state.splitPercent + 4);
  }
});

// Populate Section F Living Archive gallery plates asynchronously using the real artEngine
function populateArchivePreviews(): void {
  const items: Array<{canvasId: string; study: StudyId; style: ArtStyle; density: number}> = [
    {canvasId: 'archiveMadhubaniCanvas', study: 'courtyard', style: 'madhubani', density: 32},
    {canvasId: 'archiveGondCanvas', study: 'lotus', style: 'gond', density: 42},
    {canvasId: 'archiveWarliCanvas', study: 'vessels', style: 'warli', density: 34},
  ];

  let idx = 0;
  const renderNext = () => {
    if (idx >= items.length) return;
    const item = items[idx++];
    const target = document.getElementById(item.canvasId) as HTMLCanvasElement | null;
    if (target) {
      const fullStudy = renderSampleStudy(item.study);
      const scaled = document.createElement('canvas');
      scaled.width = 420;
      scaled.height = 310;
      const sCtx = scaled.getContext('2d');
      if (sCtx) {
        sCtx.drawImage(fullStudy, 0, 0, 420, 310);
        transformArtwork(scaled, target, {
          style: item.style,
          detailIntensity: 62,
          colourComplexity: 6,
          patternDensity: item.density,
          background: 'original',
          seed: 42,
        });
      }
    }
    requestAnimationFrame(renderNext);
  };

  requestAnimationFrame(renderNext);
}

// Initialize default UI state & render archive samples
syncControlsUI();
updateSplitPosition(50);
populateArchivePreviews();
