import { GLYPH_FILL_FROM_TAB } from '../glyphs';

export interface FillFromTabOpts {
  sendMessage: (msg: { type: 'get_active_tab_url' }) => Promise<{ ok: boolean; data: { url: string; title: string } | null }>;
}

export function wireFillFromTab(form: HTMLElement, opts: FillFromTabOpts): void {
  const btn = form.querySelector<HTMLButtonElement>('#fill-from-tab-btn');
  if (!btn) return;
  btn.addEventListener('click', async () => {
    const resp = await opts.sendMessage({ type: 'get_active_tab_url' });
    if (!resp.ok || !resp.data) {
      btn.disabled = true;
      btn.title = 'no active tab';
      return;
    }
    const urlEl = form.querySelector<HTMLInputElement>('#f-url');
    const titleEl = form.querySelector<HTMLInputElement>('#f-title');
    if (urlEl) urlEl.value = resp.data.url;
    if (titleEl && !titleEl.value.trim()) titleEl.value = resp.data.title;
  });
}

export const FILL_FROM_TAB_BTN_HTML = `<button id="fill-from-tab-btn" class="glyph-btn" type="button" title="fill from active tab">${GLYPH_FILL_FROM_TAB}</button>`;

const CHIP_HUES = [
  '#5ea0c4', '#c47e5e', '#5ec47a', '#c45e9c',
  '#a3c45e', '#7e5ec4', '#c4b75e', '#5ec4c4',
];

function hostnameHue(host: string): string {
  let h = 0;
  for (let i = 0; i < host.length; i++) h = (h * 31 + host.charCodeAt(i)) | 0;
  return CHIP_HUES[Math.abs(h) % CHIP_HUES.length];
}

function tryParseHost(raw: string): string | null {
  const trimmed = raw.trim();
  if (!trimmed) return null;
  const candidate = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
  try {
    const u = new URL(candidate);
    const host = u.host || null;
    if (!host) return null;
    // Validate hostname contains only valid characters
    if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/.test(host)) {
      return null;
    }
    return host;
  } catch {
    return null;
  }
}

export function wireHostnameChip(form: HTMLElement): void {
  const input = form.querySelector<HTMLInputElement>('#f-url');
  const row = form.querySelector<HTMLElement>('#hostname-chip-row');
  if (!input || !row) return;
  let timer: ReturnType<typeof setTimeout> | null = null;

  const update = () => {
    const host = tryParseHost(input.value);
    if (!host) {
      row.hidden = true;
      row.innerHTML = '';
      return;
    }
    const initial = host[0]?.toUpperCase() ?? '?';
    const hue = hostnameHue(host);
    row.hidden = false;
    row.innerHTML = `<span class="hostname-chip" style="background:${hue};">${initial}</span><span class="hostname-text">${host}</span>`;
  };

  input.addEventListener('input', () => {
    if (timer !== null) clearTimeout(timer);
    timer = setTimeout(() => { timer = null; update(); }, 200);
  });
  update(); // initial render for prefilled values
}
