/**
 * ═══════════════════════════════════════════════════════════════════
 *  DWG/DXF viewer sample — 모듈 조합 레시피
 *  (docs/modules-dwg-dxf.html 에 정리된 모듈을 그대로 조립)
 *
 *  이 프로젝트는 hmwebviewer 와 형제 폴더로 분리된 독립 샘플입니다.
 *  ═══════════════════════════════════════════════════════════════════
 *
 *  ┌─ 모듈 지도 카드 ──────────────┬─ 이 파일에서의 역할 ──────────┐
 *  │ acadrust-dwg (WASM)           │ DWG 바이트 → parseResult      │
 *  │ dxf-parser + dxfHatchHandler  │ DXF 텍스트 → parseResult      │
 *  │ dxfAdapter                    │ dxf-parser 출력을 공통 스키마로 │
 *  │ Viewer2D                      │ parseResult → three 씬 렌더   │
 *  │ three (peer)                  │ WebGLRenderer / OrbitControls │
 *  │ slugText + NanumGothic.ttf    │ TEXT/MTEXT 한글·라틴 표시     │
 *  │ ext2d                         │ .dwg / .dxf 확장자 판별       │
 *  └───────────────────────────────┴───────────────────────────────┘
 *
 *  흐름:  File/URL → (확장자 분기) → 파서 → CadParseResult → Viewer2D.load()
 */

// ── ① 모듈 지도의 각 카드 (src/viewer2d/*) ────────────────────────
import {
  createViewer2D,
  isCad2DFile,
  loadCad,
  type CadLoadSummary,
} from '@hmwebviewer/viewer2d';
import {
  assertCadByteLength,
  fetchCadBuffer,
  resolveCadUrl,
} from './cadInputPolicy';

// parseDxfBuffer 내부:
//   dxf-parser → HatchHandler → dxfAdapter
// parseDwgBuffer 내부:
//   acadrustParser → acadrust-dwg WASM

// ── ② 호스트 정적 자산 ──────────────────────────────────────────
const appBase = new URL(import.meta.env.BASE_URL, window.location.origin);
const publicUrl = (path: string) => new URL(path, appBase).href;

// ── ③ Viewer2D 마운트 ───────────────────────────────────────────
const app = document.getElementById('app')!;
const statusEl = document.getElementById('status')!;
const layerList = document.getElementById('layerList')!;
const layersPanel = document.getElementById('layers')!;

function setStatus(msg: string, err = false) {
  statusEl.textContent = msg;
  statusEl.classList.toggle('err', err);
}

const viewer = createViewer2D(app, {
  fontUrl: publicUrl('fonts/NanumGothic-Regular.ttf'),
});
declare global {
  interface Window {
    __viewer2d?: typeof viewer;
  }
}
window.__viewer2d = viewer;
viewer.onSelect((entity: unknown) => {
  if (!entity) {
    setStatus('deselected');
    return;
  }
  const e = entity as { type?: string; layer?: string; handle?: { value?: string } };
  setStatus(`select ${e.type ?? '?'} · layer=${e.layer ?? '-'} · h=${e.handle?.value ?? '-'}`);
});

// ── ④ 파서 조합 ─────────────────────────────────────────────────
async function loadAndRender(buf: ArrayBuffer, name: string): Promise<CadLoadSummary> {
  return loadCad(viewer, { data: buf, name });
}

async function loadUrl(url: string, nameHint?: string) {
  const resolved = resolveCadUrl(url, new URL(window.location.href));
  const name = nameHint ?? resolved.pathname.split('/').pop() ?? resolved.href;
  return loadAndRender(await fetchCadBuffer(resolved), name);
}

async function loadFile(file: File) {
  if (!isCad2DFile(file.name)) throw new Error(`not .dwg/.dxf: ${file.name}`);
  assertCadByteLength(file.size);
  return loadAndRender(await file.arrayBuffer(), file.name);
}

// ── ⑤ 호스트 UI 글루 ────────────────────────────────────────────
function fillLayers() {
  layerList.innerHTML = '';
  for (const L of viewer.getLayerInfo()) {
    const label = document.createElement('label');
    label.dataset.name = L.name;
    const sw = document.createElement('span');
    sw.className = 'swatch';
    sw.style.background = L.colorHex || '#888';
    const cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.checked = L.visible;
    cb.addEventListener('change', () => {
      const next = new Set<string>();
      layerList.querySelectorAll('label').forEach((row) => {
        const input = row.querySelector('input') as HTMLInputElement;
        if (!input.checked) next.add(row.dataset.name!);
      });
      viewer.setHiddenLayers(next);
    });
    const text = document.createElement('span');
    text.textContent = `${L.name} (${L.count})`;
    label.append(sw, cb, text);
    layerList.append(label);
  }
}

async function afterLoad(name: string, result: CadLoadSummary) {
  setStatus(`✓ ${name} · ${result.entityCount} entities`);
  fillLayers();
  viewer.fit();
}

async function run(label: string, job: () => Promise<CadLoadSummary>) {
  setStatus(`loading ${label}…`);
  try {
    await afterLoad(label, await job());
  } catch (err) {
    setStatus(`${label}: ${(err as Error).message}`, true);
    console.error(err);
  }
}

document.getElementById('sample')!.addEventListener('click', () => {
  void run('BasicSample.dwg', () =>
    loadUrl(publicUrl('samples/BasicSample.dwg'), 'BasicSample.dwg'),
  );
});
document.getElementById('sampleDxf')!.addEventListener('click', () => {
  void run('simple.dxf', () => loadUrl(publicUrl('samples/simple.dxf'), 'simple.dxf'));
});
document.getElementById('file')!.addEventListener('change', (ev) => {
  const file = (ev.target as HTMLInputElement).files?.[0];
  if (!file) return;
  void run(file.name, () => loadFile(file));
  (ev.target as HTMLInputElement).value = '';
});
document.getElementById('fit')!.addEventListener('click', () => viewer.fit());
let dark = true;
document.getElementById('theme')!.addEventListener('click', () => {
  dark = !dark;
  viewer.setTheme(dark);
});
document.getElementById('layersBtn')!.addEventListener('click', () => {
  layersPanel.style.display = layersPanel.style.display === 'block' ? 'none' : 'block';
});

window.addEventListener('dragover', (e) => e.preventDefault());
window.addEventListener('drop', (e) => {
  e.preventDefault();
  const file = e.dataTransfer?.files?.[0];
  if (file) void run(file.name, () => loadFile(file));
});

const model = new URLSearchParams(location.search).get('model');
if (model) {
  try {
    const resolved = resolveCadUrl(model, new URL(window.location.href));
    void run(model, () => loadUrl(resolved.href));
  } catch (error) {
    setStatus((error as Error).message, true);
  }
} else {
  setStatus('ready · Sample DWG / DXF 또는 파일 드롭');
}

window.addEventListener(
  'pagehide',
  () => {
    viewer.dispose();
    delete window.__viewer2d;
  },
  { once: true },
);
