/**
 * Antwort-Pfeil automatisch — einmal pro Profil nach kurzer Verzögerung.
 * einmal pro Profil/Chat nach Verzögerung, unabhängig vom Mic. Kein Klick nach Senden.
 */
(function (global) {
  'use strict';

  const SETTINGS_KEY = 'chillicollectivoVoiceSettings';
  const PROFILE_DELAY_MS = 2000;
  const MIN_ATTEMPT_GAP_MS = 120;

  function norm(text) {
    return String(text || '').replace(/\s+/g, ' ').trim();
  }

  function isTorchwoodConversation() {
    return /(^|\.)torchwood\.app$/i.test(location.hostname || '')
      && /\/conversation\//i.test(location.pathname || '');
  }

  function buildConversationKey() {
    const match = String(location.pathname || '').match(/\/conversation\/([a-f0-9-]+)/i);
    return match?.[1] || '';
  }

  function buildProfileKey() {
    const conv = buildConversationKey();
    if (!conv) return '';

    if (typeof global.chillicollectivoReadProfilInformationen === 'function') {
      const info = global.chillicollectivoReadProfilInformationen('customer');
      const extra = [info?.name, info?.ort, info?.alter, info?.geburtstag]
        .map((v) => norm(v))
        .filter(Boolean)
        .join('|');
      if (extra) return `${conv}|${extra}`;
    }

    const customerText = typeof global.chillicollectivoGetLastCustomerMessage === 'function'
      ? norm(global.chillicollectivoGetLastCustomerMessage()).slice(0, 80)
      : '';
    return customerText ? `${conv}|${customerText}` : conv;
  }

  function logSkip(reason, extra = {}) {
    global.ChillicollectivoDiagnosticLog?.info?.(
      'voice.customer-respond-skipped',
      'Antwort-Pfeil automatisch übersprungen',
      {
        reason,
        profileKey: buildProfileKey().slice(0, 160),
        conversationKey: buildConversationKey(),
        micIndependent: true,
        ...extra,
      },
    );
  }

  function logRespond(result) {
    const level = result?.ok ? 'info' : 'warn';
    const event = result?.ok ? 'voice.customer-respond-clicked' : 'voice.customer-respond-miss';
    const message = result?.ok
      ? 'Antwort-Pfeil an letzter Kundennachricht geklickt'
      : 'Antwort-Pfeil an letzter Kundennachricht nicht gefunden';
    global.ChillicollectivoDiagnosticLog?.[level]?.(event, message, {
      trigger: 'profile-open',
      reason: result?.reason || 'unknown',
      snippet: result?.snippet || '',
      profileKey: buildProfileKey().slice(0, 160),
      conversationKey: buildConversationKey(),
      micIndependent: true,
    });
  }

  const state = {
    enabled: false,
    started: false,
    profileKey: '',
    profileSeenAt: 0,
    lastRespondedProfile: '',
    lastAttemptAt: 0,
    timer: null,
    observer: null,
    urlInterval: null,
  };

  function loadSettings() {
    return new Promise((resolve) => {
      if (!chrome?.storage?.local) {
        resolve({ enabled: false });
        return;
      }
      chrome.storage.local.get([SETTINGS_KEY], (data) => {
        const settings = data?.[SETTINGS_KEY] || {};
        resolve({ enabled: settings.replyToLastCustomer !== false });
      });
    });
  }

  function tryRespond() {
    if (!state.enabled) return;
    if (!isTorchwoodConversation()) return;
    if (typeof global.chillicollectivoClickRespondOnLastCustomerMessage !== 'function') {
      logSkip('click-helper-missing');
      return;
    }

    const profileKey = buildProfileKey();
    if (!profileKey) {
      logSkip('no-profile-key');
      return;
    }

    if (state.profileKey !== profileKey) {
      state.profileKey = profileKey;
      state.profileSeenAt = Date.now();
      state.lastAttemptAt = 0;
    }

    const elapsed = Date.now() - state.profileSeenAt;
    if (elapsed < PROFILE_DELAY_MS) return;

    if (state.lastRespondedProfile === profileKey) return;

    if (Date.now() - state.lastAttemptAt < MIN_ATTEMPT_GAP_MS) return;

    const customerText = typeof global.chillicollectivoGetLastCustomerMessage === 'function'
      ? norm(global.chillicollectivoGetLastCustomerMessage())
      : '';
    if (!customerText) {
      logSkip('no-customer-message', { profileKey: profileKey.slice(0, 120) });
      return;
    }

    state.lastAttemptAt = Date.now();
    const result = global.chillicollectivoClickRespondOnLastCustomerMessage();
    logRespond(result);
    if (result?.ok) {
      state.lastRespondedProfile = profileKey;
    }
  }

  function scheduleRun(delay = 120) {
    if (!state.started) return;
    if (state.timer) clearTimeout(state.timer);
    state.timer = setTimeout(() => {
      state.timer = null;
      tryRespond();
    }, delay);
  }

  async function refreshSettings() {
    const cfg = await loadSettings();
    state.enabled = cfg.enabled;
    if (state.enabled && !state.started && isTorchwoodConversation()) start();
    if (!state.enabled && state.started) stop();
  }

  function start() {
    if (state.started || !isTorchwoodConversation()) return;
    state.started = true;
    state.profileKey = '';
    state.lastRespondedProfile = '';
    state.profileSeenAt = Date.now();

    state.observer = new MutationObserver(() => scheduleRun(120));
    const root = document.body;
    if (root) {
      state.observer.observe(root, { childList: true, subtree: true });
    }

    let lastHref = location.href;
    state.urlInterval = setInterval(() => {
      if (location.href !== lastHref) {
        lastHref = location.href;
        state.profileKey = '';
        state.lastRespondedProfile = '';
        state.profileSeenAt = Date.now();
        if (isTorchwoodConversation()) {
          scheduleRun(40);
        }
      }
    }, 1500);

    scheduleRun(0);
    global.ChillicollectivoDiagnosticLog?.info?.(
      'voice.customer-respond-armed',
      'Antwort-Pfeil-Auto aktiv (einmal pro Profil)',
      {
        profileKey: buildProfileKey().slice(0, 160),
        conversationKey: buildConversationKey(),
        profileDelayMs: PROFILE_DELAY_MS,
        micIndependent: true,
      },
    );
  }

  function stop() {
    const wasStarted = state.started;
    state.started = false;
    if (state.timer) {
      clearTimeout(state.timer);
      state.timer = null;
    }
    if (state.observer) {
      state.observer.disconnect();
      state.observer = null;
    }
    if (state.urlInterval) {
      clearInterval(state.urlInterval);
      state.urlInterval = null;
    }
    if (wasStarted) {
      global.ChillicollectivoDiagnosticLog?.info?.(
        'voice.customer-respond-stopped',
        'Antwort-Pfeil-Auto gestoppt',
        { conversationKey: buildConversationKey(), micIndependent: true },
      );
    }
  }

  function init() {
    if (!/(^|\.)torchwood\.app$/i.test(location.hostname || '')) return;
    refreshSettings().then(() => {
      if (state.enabled && isTorchwoodConversation()) start();
    });
    chrome.storage?.onChanged?.addListener((changes, area) => {
      if (area !== 'local' || !changes[SETTINGS_KEY]) return;
      const next = changes[SETTINGS_KEY].newValue || {};
      const enabled = next.replyToLastCustomer !== false;
      state.enabled = enabled;
      if (enabled && !state.started && isTorchwoodConversation()) start();
      if (!enabled && state.started) stop();
    });
  }

  global.ChillicollectivoTorchwoodAutoRespond = {
    start,
    stop,
    refreshSettings,
    tryRespond,
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }
})(typeof window !== 'undefined' ? window : globalThis);
