(function () {
  'use strict';

  const ORIGIN = `web:${location.origin}`;
  const STYLE_ID = 'dudou-autofill-style';

  function injectStyles() {
    if (document.getElementById(STYLE_ID)) return;
    const css = document.createElement('style');
    css.id = STYLE_ID;
    css.textContent = `
      .dudou-fill-dropdown {
        position: fixed; z-index: 2147483647;
        background: #fff; border: 1px solid #d1d5db;
        border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        padding: 4px; min-width: 160px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        font-size: 13px; color: #111827;
      }
      .dudou-fill-dropdown button {
        display: block; width: 100%;
        padding: 8px 12px; border: none; border-radius: 6px;
        background: none; cursor: pointer; text-align: left;
        font-size: 13px; color: #111827;
      }
      .dudou-fill-dropdown button:hover { background: #f3f4f6; }
      .dudou-fill-dropdown .dudou-dropdown-header {
        padding: 6px 12px 4px; font-size: 11px; color: #6b7280;
        text-transform: uppercase; letter-spacing: 0.05em;
      }
      .dudou-save-toast {
        position: fixed; top: 16px; right: 16px; z-index: 2147483647;
        background: #fff; border: 1px solid #d1d5db;
        border-radius: 10px; box-shadow: 0 4px 16px rgba(0,0,0,0.18);
        padding: 12px 16px; min-width: 200px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        font-size: 13px; color: #111827;
        animation: dudou-slide-in 0.2s ease-out;
      }
      @keyframes dudou-slide-in {
        from { transform: translateY(-8px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
      }
      .dudou-save-toast .dudou-toast-title {
        font-weight: 600; margin-bottom: 8px;
      }
      .dudou-save-toast .dudou-toast-actions {
        display: flex; gap: 8px; justify-content: flex-end;
      }
      .dudou-save-toast .dudou-toast-actions button {
        padding: 4px 12px; border: none; border-radius: 6px;
        cursor: pointer; font-size: 12px; font-weight: 500;
      }
      .dudou-save-toast .dudou-btn-primary {
        background: #4f46e5; color: #fff;
      }
      .dudou-save-toast .dudou-btn-primary:hover { background: #4338ca; }
      .dudou-save-toast .dudou-btn-secondary {
        background: #f3f4f6; color: #374151;
      }
      .dudou-save-toast .dudou-btn-secondary:hover { background: #e5e7eb; }
      .dudou-badge {
        position: fixed; z-index: 2147483647;
        width: 20px; height: 20px; border-radius: 50%;
        background: #4f46e5; color: #fff;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        font-size: 11px; font-weight: 700; line-height: 20px;
        text-align: center; cursor: pointer;
        box-shadow: 0 1px 4px rgba(0,0,0,0.15);
        transition: opacity 0.15s;
      }
      .dudou-badge:hover { opacity: 0.85; }
      .dudou-badge-tip {
        position: fixed; z-index: 2147483646;
        background: #1f2937; color: #f9fafb;
        padding: 6px 10px; border-radius: 6px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        font-size: 12px; white-space: nowrap;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        pointer-events: none;
      }
    `;
    document.head.appendChild(css);
  }

  function makeEl(tag, attrs, children) {
    const el = document.createElement(tag);
    if (attrs) Object.entries(attrs).forEach(([k, v]) => el[k] = v);
    if (children) children.forEach(c => el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c));
    return el;
  }

  let dropdownEl = null;
  let toastEl = null;
  let toastTimer = null;
  let badgeEl = null;
  let tipEl = null;

  function removeDropdown() {
    if (dropdownEl) { dropdownEl.remove(); dropdownEl = null; }
  }

  function removeBadge() {
    if (tipEl) { tipEl.remove(); tipEl = null; }
    if (badgeEl) { badgeEl.remove(); badgeEl = null; }
  }

  function removeToast() {
    if (toastTimer) { clearTimeout(toastTimer); toastTimer = null; }
    if (toastEl) { toastEl.remove(); toastEl = null; }
  }

  function showFillDropdown(field, profile, fieldType) {
    removeDropdown();
    const rect = field.getBoundingClientRect();
    dropdownEl = makeEl('div', {className: 'dudou-fill-dropdown'}, [
      makeEl('div', {className: 'dudou-dropdown-header', textContent: 'Dudou'}),
      makeEl('button', {
        textContent: 'Fill with Dudou',
        onclick: () => {
          const form = field.form || field.closest('form');
          if (!form) { removeDropdown(); return; }
          const fills = [];
          form.querySelectorAll('input, select, textarea').forEach(el => {
            const ac = el.autocomplete || '';
            if (ac && profile[ac] != null) {
              const tag = el.tagName.toLowerCase();
              const id = `${tag}_${el.name || el.id || ''}`;
              fills.push({fieldId: id, value: profile[ac]});
            }
          });
          if (fills.length > 0) {
            chrome.runtime.sendMessage({
              type: 'dudou.autofill.fill',
              payload: {fills}
            }, () => window.dispatchEvent(new CustomEvent('dudou-filled', {detail: {fills}})));
          }
          removeDropdown();
        }
      }),
    ]);
    let top = rect.bottom + window.scrollY + 4;
    let left = rect.left + window.scrollX;
    if (left + 180 > window.innerWidth) left = window.innerWidth - 190;
    if (left < 0) left = 4;
    dropdownEl.style.top = top + 'px';
    dropdownEl.style.left = left + 'px';
    document.body.appendChild(dropdownEl);

    const closeHandler = (e) => {
      if (!dropdownEl || dropdownEl.contains(e.target)) return;
      removeDropdown();
      document.removeEventListener('mousedown', closeHandler);
    };
    setTimeout(() => document.addEventListener('mousedown', closeHandler), 0);
  }

  function showPresenceBadge(field) {
    removeBadge();
    const rect = field.getBoundingClientRect();
    badgeEl = makeEl('div', {
      className: 'dudou-badge',
      textContent: 'D',
      style: `top:${rect.top + window.scrollY + 4}px;left:${rect.right + window.scrollX + 4}px`,
    });
    tipEl = makeEl('div', {
      className: 'dudou-badge-tip',
      textContent: 'Dudou — No saved login',
      style: `top:${rect.top + window.scrollY + 4}px;left:${rect.right + window.scrollX + 28}px`,
    });
    badgeEl.onmouseenter = () => { if (tipEl) tipEl.style.display = 'block'; };
    badgeEl.onmouseleave = () => { if (tipEl) tipEl.style.display = 'none'; };
    if (tipEl) tipEl.style.display = 'none';
    document.body.appendChild(badgeEl);
    document.body.appendChild(tipEl);
  }

  function showSaveToast(values, onResumeSubmit) {
    removeToast();
    const origin = values._origin || ORIGIN;
    const siteLabel = new URL(location.href).hostname;
    let dismissed = false;

    function done() {
      if (dismissed) return;
      dismissed = true;
      removeToast();
      if (onResumeSubmit) onResumeSubmit();
    }

    toastEl = makeEl('div', {className: 'dudou-save-toast'}, [
      makeEl('div', {className: 'dudou-toast-title', textContent: `Save login for ${siteLabel}?`}),
      makeEl('div', {className: 'dudou-toast-actions'}, [
        makeEl('button', {
          className: 'dudou-btn-secondary',
          textContent: 'Never',
          onclick: done,
        }),
        makeEl('button', {
          className: 'dudou-btn-primary',
          textContent: 'Save',
          onclick: () => {
            chrome.runtime.sendMessage({
              type: 'dudou.autofill.saveProfile',
              payload: {origin, data: values}
            });
            done();
          },
        }),
      ]),
    ]);
    document.body.appendChild(toastEl);
    toastTimer = setTimeout(done, 8000);
  }

  function removeAll() {
    removeDropdown();
    removeBadge();
    removeToast();
  }

  window.__dudouAutofill = {
    hideDropdown: removeAll,

    showBadge(field) {
      injectStyles();
      removeBadge();
      const rect = field.getBoundingClientRect();
      badgeEl = makeEl('div', {
        className: 'dudou-badge',
        textContent: 'D',
        style: `top:${rect.top + window.scrollY + 4}px;left:${rect.right + window.scrollX + 4}px`,
      });
      document.body.appendChild(badgeEl);
    },

    async checkAndShowFill(field, origin, fieldType) {
      injectStyles();
      chrome.runtime.sendMessage(
        {type: 'dudou.autofill.getProfile', payload: {origin}},
        (response) => {
          if (response && response.profile && response.profile[fieldType] != null) {
            showFillDropdown(field, response.profile, fieldType);
          } else {
            showPresenceBadge(field);
          }
        }
      );
    },

    async checkAndShowSave(values, onShow, onResumeSubmit) {
      const origin = values._origin || ORIGIN;
      chrome.runtime.sendMessage(
        {type: 'dudou.autofill.getProfile', payload: {origin}},
        (response) => {
          if (response && response.profile) {
            if (onResumeSubmit) onResumeSubmit();
            return;
          }
          injectStyles();
          showSaveToast(values, onResumeSubmit);
          onShow && onShow();
        }
      );
    },
  };

  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    switch (message.type) {
      case 'dudou.autofill.showSuggestions':
        injectStyles();
        sendResponse({ok: true});
        break;
      case 'dudou.autofill.hideDropdown':
        removeAll();
        sendResponse({ok: true});
        break;
    }
  });
})();
