const DEFAULT_BLOCKLIST = ['youtube.com', 'tiktok.com', 'instagram.com', 'reddit.com', 'x.com'];
const APP_URL = 'https://goal-axis.vercel.app';

const focusActive = document.getElementById('focusActive');
const blocklist = document.getElementById('blocklist');
const save = document.getElementById('save');
const openApp = document.getElementById('openApp');
const status = document.getElementById('status');
const focusStat = document.getElementById('focusStat');
const penaltyStat = document.getElementById('penaltyStat');
const focusStatus = document.getElementById('focusStatus');
const penaltyStatus = document.getElementById('penaltyStatus');
const penaltyBox = document.getElementById('penaltyBox');
const penaltyMessage = document.getElementById('penaltyMessage');
const penaltyTimer = document.getElementById('penaltyTimer');
const chips = document.getElementById('chips');

const SITE_LABELS = {
  'youtube.com': 'YouTube',
  'youtu.be': 'YouTube',
  'tiktok.com': 'TikTok',
  'instagram.com': 'Instagram',
  'reddit.com': 'Reddit',
  'x.com': 'X',
  'twitter.com': 'X',
  'facebook.com': 'Facebook',
  'vk.com': 'VK',
  'snapchat.com': 'Snapchat',
  'telegram.org': 'Telegram',
  'web.telegram.org': 'Telegram',
  'discord.com': 'Discord',
  'twitch.tv': 'Twitch',
};

function normalizeList(value) {
  return value
    .split('\n')
    .map((line) =>
      line
        .trim()
        .toLowerCase()
        .replace(/^https?:\/\//, '')
        .replace(/^www\./, '')
        .split('/')[0]
    )
    .filter(Boolean);
}

function formatRemaining(until) {
  const diff = Math.max(0, until - Date.now());
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  if (hours > 0) return `${hours}ч ${minutes}м`;
  return `${minutes}м`;
}

function isPenaltyBlocking(state) {
  if (!state.penaltyActive) return false;
  if (!state.penaltyUntil) return true;
  return Date.now() < state.penaltyUntil;
}

function renderChips(list) {
  chips.innerHTML = '';
  const unique = [...new Set(list.map((site) => SITE_LABELS[site] || site))].slice(0, 8);
  unique.forEach((label) => {
    const chip = document.createElement('span');
    chip.className = 'chip';
    chip.textContent = label;
    chips.appendChild(chip);
  });
}

function renderStatus(state) {
  const focusOn = Boolean(state.focusActive);
  const penaltyOn = isPenaltyBlocking(state);

  focusActive.checked = focusOn;
  focusStatus.textContent = focusOn ? 'Активен' : 'Выкл';
  focusStat.classList.toggle('on', focusOn);

  penaltyStatus.textContent = penaltyOn ? 'Активен' : 'Выкл';
  penaltyStat.classList.toggle('on', penaltyOn);

  if (penaltyOn) {
    penaltyBox.classList.add('visible');
    penaltyMessage.textContent = state.penaltyMessage || 'Штраф: соцсети заблокированы';
    penaltyTimer.textContent = state.penaltyUntil
      ? `Осталось: ${formatRemaining(state.penaltyUntil)}`
      : 'Блокировка активна';
  } else {
    penaltyBox.classList.remove('visible');
  }

  const effectiveList = [
    ...(state.blocklist || DEFAULT_BLOCKLIST),
    ...(penaltyOn && Array.isArray(state.penaltyBlocklist) ? state.penaltyBlocklist : []),
  ];
  renderChips([...new Set(normalizeList(effectiveList.join('\n')))]);
}

async function loadState() {
  const state = await chrome.storage.sync.get({
    focusActive: false,
    penaltyActive: false,
    penaltyUntil: 0,
    penaltyMessage: '',
    blocklist: DEFAULT_BLOCKLIST,
    penaltyBlocklist: [],
  });

  blocklist.value = (state.blocklist || DEFAULT_BLOCKLIST).join('\n');
  renderStatus(state);
}

async function saveState() {
  const current = await chrome.storage.sync.get({
    penaltyActive: false,
    penaltyUntil: 0,
    penaltyMessage: '',
    penaltyBlocklist: [],
    taskLabel: '',
  });

  const nextBlocklist = normalizeList(blocklist.value);
  const nextState = {
    focusActive: focusActive.checked,
    blocklist: nextBlocklist,
    penaltyActive: current.penaltyActive,
    penaltyUntil: current.penaltyUntil,
    penaltyMessage: current.penaltyMessage,
    penaltyBlocklist: current.penaltyBlocklist,
    taskLabel: current.taskLabel || '',
    updatedAt: Date.now(),
  };

  await chrome.storage.sync.set(nextState);
  await chrome.runtime.sendMessage({
    source: 'goal-axis',
    type: 'SET_FOCUS_STATE',
    focusActive: nextState.focusActive,
    blocklist: nextState.blocklist,
    penaltyActive: nextState.penaltyActive,
    penaltyUntil: nextState.penaltyUntil,
    penaltyMessage: nextState.penaltyMessage,
    penaltyBlocklist: nextState.penaltyBlocklist,
    taskLabel: nextState.taskLabel,
  });

  renderStatus(nextState);
  status.textContent = 'Сохранено';
  window.setTimeout(() => {
    status.textContent = '';
  }, 1600);
}

save.addEventListener('click', saveState);
focusActive.addEventListener('change', saveState);
openApp.addEventListener('click', () => chrome.tabs.create({ url: APP_URL }));

blocklist.addEventListener('input', () => {
  renderChips(normalizeList(blocklist.value));
});

loadState();
window.setInterval(loadState, 5000);
