// Icon Manager — toolbar icon = Nithic crystal shield + state dots
// Renders dual-channel signal: bottom-right = threats, bottom-left = AI content

const BADGE_COLORS = {
  threat:   '#ef4444', // red — security threats
  ai:       '#a78bfa', // violet — AI content (matches brand violet)
  warning:  '#f59e0b', // amber — partial / uncertain
  off:      '#374151'
};

// Loaded once at module init (lazily on first use), then reused.
let _bitmapCache = null;

async function loadShieldBitmaps() {
  if (_bitmapCache) return _bitmapCache;
  try {
    const sizes = [16, 32, 48, 128];
    const bitmaps = {};
    for (const size of sizes) {
      // 32 maps to icon48 for HiDPI; 128 reserved for future
      const fileSize = size === 32 ? 48 : size;
      const url = chrome.runtime.getURL(`icons/icon${fileSize}.png`);
      const res = await fetch(url);
      const blob = await res.blob();
      bitmaps[size] = await createImageBitmap(blob);
    }
    _bitmapCache = bitmaps;
    return bitmaps;
  } catch (err) {
    console.error('Failed to load shield bitmaps:', err);
    return null;
  }
}

/**
 * Render the toolbar icon at the given size with state dot overlays.
 *  - bottom-right dot = threat indicator (red/amber/none)
 *  - bottom-left  dot = AI content indicator (violet/none)
 */
async function renderIcon(size, state) {
  const bitmaps = await loadShieldBitmaps();
  const canvas = new OffscreenCanvas(size, size);
  const ctx = canvas.getContext('2d');

  ctx.clearRect(0, 0, size, size);

  if (bitmaps && bitmaps[size]) {
    ctx.drawImage(bitmaps[size], 0, 0, size, size);
  }

  // State dots — only on color states, never on the clean baseline
  const s = size / 16;
  const r = Math.max(2.4 * s, 3); // dot radius

  // Threat dot (bottom-right)
  let threatColor = null;
  if (state.security === 'danger') threatColor = BADGE_COLORS.threat;
  else if (state.security === 'warning') threatColor = BADGE_COLORS.warning;
  if (threatColor) {
    drawDot(ctx, size - r - 1, size - r - 1, r, threatColor);
  }

  // AI content dot (bottom-left)
  if (state.aiContent && state.aiContent !== 'unknown' && state.aiContent !== 'none') {
    drawDot(ctx, r + 1, size - r - 1, r, BADGE_COLORS.ai);
  }

  return ctx.getImageData(0, 0, size, size);
}

function drawDot(ctx, cx, cy, r, color) {
  // White halo for contrast against the shield
  ctx.beginPath();
  ctx.arc(cx, cy, r + 1, 0, Math.PI * 2);
  ctx.fillStyle = '#ffffff';
  ctx.fill();
  // Solid colored dot
  ctx.beginPath();
  ctx.arc(cx, cy, r, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
}

/**
 * Update the toolbar icon and badge for a specific tab.
 * @param {number} tabId
 * @param {object} state - { security, findingsCount, aiContent, aiContentCount? }
 */
export async function updateIcon(tabId, state) {
  try {
    const icon16 = await renderIcon(16, state);
    const icon32 = await renderIcon(32, state);
    await chrome.action.setIcon({ tabId, imageData: { 16: icon16, 32: icon32 } });

    // Badge logic (only one badge possible per tab — pick the most-urgent signal)
    if (state.security === 'disabled') {
      await chrome.action.setBadgeText({ tabId, text: 'OFF' });
      await chrome.action.setBadgeBackgroundColor({ tabId, color: BADGE_COLORS.off });
    } else if (state.findingsCount > 0) {
      // Threats take priority. Red badge with count.
      const text = state.findingsCount > 99 ? '99+' : String(state.findingsCount);
      await chrome.action.setBadgeText({ tabId, text });
      await chrome.action.setBadgeBackgroundColor({
        tabId,
        color: state.security === 'danger' ? BADGE_COLORS.threat : BADGE_COLORS.warning
      });
    } else if (state.aiContentCount > 0) {
      // No threats, but AI content present. Violet badge.
      const text = state.aiContentCount > 99 ? '99+' : String(state.aiContentCount);
      await chrome.action.setBadgeText({ tabId, text });
      await chrome.action.setBadgeBackgroundColor({ tabId, color: BADGE_COLORS.ai });
    } else {
      await chrome.action.setBadgeText({ tabId, text: '' });
    }

    // Tooltip
    const parts = ['Nithic'];
    if (state.security === 'disabled') parts.push('Disabled');
    else if (state.security === 'danger') parts.push('Threat detected');
    else if (state.security === 'warning') parts.push('Caution');
    else if (state.security === 'safe') parts.push('Safe');
    if (state.findingsCount > 0) parts.push(`${state.findingsCount} threat finding${state.findingsCount !== 1 ? 's' : ''}`);
    if (state.aiContentCount > 0) parts.push(`${state.aiContentCount} AI content item${state.aiContentCount !== 1 ? 's' : ''}`);
    await chrome.action.setTitle({ tabId, title: parts.join(' · ') });

  } catch (err) {
    if (!err.message?.includes('No tab with id')) {
      console.error('Icon update error:', err.message);
    }
  }
}
