/// Typed-item detail view dispatcher. Each type's renderDetail lives in
/// its own module under ./types/. Document stays "coming soon" until γ.

import { navigate, getState } from '../../shared/state';
import type { Item } from '../../shared/types';
import * as login from './types/login';
import * as secureNote from './types/secure-note';
import * as identity from './types/identity';
import * as card from './types/card';
import * as key from './types/key';
import * as totp from './types/totp';
import * as documentType from './types/document';

export async function renderItemDetail(app: HTMLElement): Promise<void> {
  // Tear down any tickers/handlers from a previous detail render before
  // the next one boots up. Each type module owns its own teardown; we
  // call all of them since the dispatcher doesn't know which was active.
  login.teardown();
  secureNote.teardown();
  identity.teardown();
  card.teardown();
  key.teardown();
  totp.teardown();
  documentType.teardown();

  const item = getState().selectedItem;
  if (!item) { navigate('list'); return; }

  switch (item.type) {
    case 'login':       return login.renderDetail(app, item);
    case 'secure_note': return secureNote.renderDetail(app, item);
    case 'identity':    return identity.renderDetail(app, item);
    case 'card':        return card.renderDetail(app, item);
    case 'key':         return key.renderDetail(app, item);
    case 'totp':        return totp.renderDetail(app, item);
    case 'document':    return documentType.renderDetail(app, item);
  }
}

function renderComingSoon(app: HTMLElement, item: Item): void {
  app.innerHTML = `
    <div class="pad">
      <div class="detail-title" style="margin-bottom:16px;">${item.title}</div>
      <p class="muted">The <strong>${item.type}</strong> item type is not editable in the extension yet.</p>
      <div class="form-actions"><button class="btn" id="back-btn">back</button></div>
    </div>
  `;
  document.getElementById('back-btn')?.addEventListener('click', () => navigate('list'));
}
