import store_default from "../../../npm/hybrids/src/store.js";
import router_default from "../../../npm/hybrids/src/router.js";
import { html } from "../../../npm/hybrids/src/template/index.js";
import { msg } from "../../../npm/hybrids/src/localize.js";
import { findParentDomain } from "../../../utils/domains.js";
import ManagedConfig from "../../../store/managed-config.js";
import Options, { getPausedDetails, isGloballyPaused, revokeGlobalPause } from "../../../store/options.js";
import { lang, numberFormatter } from "../../../ui/labels.js";
import { ZAP_AUTORELOAD_DISABLED_HOSTNAMES } from "../../../utils/urls.js";
import Resources from "../../../store/resources.js";
import { clearAlert, showAlert } from "../components/alert.js";
import { getCurrentTab, openHref } from "../../../utils/tabs.js";
import Notification from "../store/notification.js";
import TabStats from "../../../store/tab-stats.js";
import clear_cookies_default from "./clear-cookies.js";
import ElementPickerSelectors from "../../../store/element-picker-selectors.js";
import "../assets/sleep.js";
import report_confirm_default from "./report-confirm.js";
import report_form_default from "./report-form.js";
import report_category_default from "./report-category.js";
import menu_default from "./menu.js";
import pause_assistant_default from "./pause-assistant.js";
import protection_status_default from "./protection-status.js";
import tracker_details_default from "./tracker-details.js";
import trackers_report_default from "./trackers-report.js";
import whotracksme_default from "./whotracksme.js";
//#region src/pages/panel/views/main.js
/**
* Ghostery Browser Extension
* https://www.ghostery.com/
*
* Copyright 2017-present Ghostery GmbH. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/
var PANEL_URL = chrome.runtime.getURL("/pages/panel/index.html");
var SETTINGS_URL = chrome.runtime.getURL("/pages/settings/index.html#@settings-privacy");
var ONBOARDING_URL = chrome.runtime.getURL("/pages/onboarding/index.html#@onboarding-views-main?scrollToTop=1");
var reloadTimeout;
function reloadTab(host, event) {
	clearTimeout(reloadTimeout);
	event.preventDefault();
	event.stopPropagation();
	reloadTimeout = setTimeout(async () => {
		clearAlert();
		const tab = await getCurrentTab();
		if (tab && tab.url !== PANEL_URL) chrome.tabs.reload(tab.id);
		reloadTimeout = null;
	}, 500);
}
async function togglePause(host, event) {
	const { paused, pauseType } = event.target;
	const { options, stats } = host;
	if (paused) {
		const pausedHostname = findParentDomain(options.paused, stats.hostname);
		store_default.set(options, { paused: { [pausedHostname]: null } });
	} else await store_default.set(options, { paused: { [stats.hostname]: { revokeAt: pauseType && Date.now() + 3600 * 1e3 * pauseType } } });
	await chrome.runtime.sendMessage({
		action: "reporting:updateHostnamePause",
		hostname: stats.hostname,
		paused: !paused
	});
	showAlert(html`
    <panel-alert type="danger">
      ${paused ? msg`Ghostery has been resumed on this site.` : msg`Ghostery is paused on this site.`}
      <ui-text type="body-s" layout="block" underline>
        <a href="#" onclick="${reloadTab}" layout="row inline gap:0.5 items:center ::color:inherit"
          >Reload to see changes</a
        >.
      </ui-text>
    </panel-alert>
  `);
}
async function toggleZapped(host, event) {
	const { options, stats, paused } = host;
	const zappedHostname = findParentDomain(options.zapped, stats.hostname) || stats.hostname;
	await store_default.set(options, { zapped: { [zappedHostname]: paused ? true : null } });
	if (!ZAP_AUTORELOAD_DISABLED_HOSTNAMES.find((h) => zappedHostname.endsWith(h))) await reloadTab(host, event);
}
async function toggleGlobalPause(host) {
	await revokeGlobalPause(host.options);
	showAlert(html`
    <panel-alert type="danger">
      Ghostery has been resumed.
      <ui-text type="body-s" layout="block" underline>
        <a href="#" onclick="${reloadTab}" layout="row inline gap:0.5 items:center ::color:inherit"
          >Reload to see changes</a
        >.
      </ui-text>
    </panel-alert>
  `);
}
function setStatsType(host, event) {
	const { type } = event.target;
	store_default.set(host.options, { panel: { statsType: type } });
}
function openLogger() {
	const url = chrome.runtime.getURL("/pages/logger/index.html");
	window.open(url, "Ghostery Logger", "toolbar=no,width=1000,height=500");
	window.close();
}
async function openElementPicker() {
	const tab = await getCurrentTab();
	if (tab) {
		await chrome.runtime.sendMessage({
			action: "openElementPicker",
			tabId: tab.id
		});
		await chrome.tabs.update(tab.id, { active: true });
		window.close();
	}
}
var main_default = {
	[router_default.connect]: { stack: [
		clear_cookies_default,
		menu_default,
		pause_assistant_default,
		protection_status_default,
		report_category_default,
		report_form_default,
		report_confirm_default,
		tracker_details_default,
		trackers_report_default,
		whotracksme_default
	] },
	options: store_default(Options),
	stats: store_default(TabStats),
	notification: store_default(Notification),
	managedConfig: store_default(ManagedConfig),
	elementPickerSelectors: store_default(ElementPickerSelectors),
	resources: store_default(Resources),
	paused: ({ options, stats }) => store_default.ready(options, stats) && getPausedDetails(options, stats.hostname),
	globalPause: ({ options }) => store_default.ready(options) && isGloballyPaused(options),
	contentBlocksSelectors: ({ elementPickerSelectors, stats }) => store_default.ready(stats, elementPickerSelectors) && elementPickerSelectors.hostnames[stats.hostname]?.length || 0,
	consentManaged: ({ resources, options, stats, paused }) => store_default.ready(resources, options, stats) && !paused && options.blockAnnoyances && resources.autoconsent[stats.domain],
	render: ({ options, stats, notification, managedConfig, paused, globalPause, contentBlocksSelectors, consentManaged }) => html`
    <template layout="column grow relative">
      ${store_default.ready(options, managedConfig) && html`
        ${options.terms && html`
          <ui-header>
            ${store_default.ready(stats) && (managedConfig.disableUserControl || options.mode === "zap" && paused) && html`<ui-text type="label-m">${stats.displayHostname}</ui-text>`}
            ${options.mode === "default" && html`<ui-icon name="logo" slot="icon" layout="size:2.5"></ui-icon>`}
            ${options.mode === "zap" && html`<ui-icon name="logo-zap" slot="icon" layout="margin:left:-1"></ui-icon>`}
            ${!managedConfig.disableUserControl && html`
              <ui-action slot="actions">
                <a href="${router_default.url(menu_default)}" data-qa="button:menu">
                  <ui-icon name="menu" color="primary"></ui-icon>
                </a>
              </ui-action>
            `}
          </ui-header>
          ${store_default.ready(stats) && !managedConfig.disableUserControl && (options.mode !== "zap" || !paused) && html`
            <panel-actions hostname="${stats.displayHostname}">
              <panel-actions-button
                onclick="${openElementPicker}"
                disabled="${paused}"
                icon="hide-element"
              >
                <button>
                  <panel-actions-icon name="hide-element"></panel-actions-icon>
                  Hide content block
                  <ui-icon name="chevron-right" color="tertiary" layout="size:2"></ui-icon>
                </button>
              </panel-actions-button>
              <panel-actions-button>
                <a href="${router_default.url(report_category_default)}">
                  <panel-actions-icon name="report"></panel-actions-icon>
                  Report an issue
                  <ui-icon name="chevron-right" color="tertiary" layout="size:2"></ui-icon>
                </a>
              </panel-actions-button>
              <panel-actions-button>
                <a href="${router_default.url(clear_cookies_default)}" data-qa="button:clear-cookies">
                  <panel-actions-icon name="cookie"></panel-actions-icon>
                  Clear cookies
                  <ui-icon name="chevron-right" color="tertiary" layout="size:2"></ui-icon>
                </a>
              </panel-actions-button>
              <panel-actions-button>
                <button onclick="${openLogger}">
                  <panel-actions-icon name="open-book"></panel-actions-icon>
                  View detailed logs
                  <ui-icon name="chevron-right" color="tertiary" layout="size:2"></ui-icon>
                </button>
              </panel-actions-button>
              <panel-actions-button>
                <a
                  onclick="${openHref}"
                  href="${chrome.runtime.getURL("/pages/settings/index.html#@settings-website-details?domain=" + stats.hostname)}"
                  data-qa="button:website-settings"
                >
                  <panel-actions-icon name="settings"></panel-actions-icon>
                  Open website settings
                  <ui-icon name="external-link" color="tertiary" layout="size:2"></ui-icon>
                </a>
              </panel-actions-button>
            </panel-actions>
          `}
        `}
        ${!options.terms && html`
          <div layout="::background:danger-primary">
            <ui-button type="danger" layout="height:6 margin:1.5" data-qa="button:enable">
              <a href="${ONBOARDING_URL}" layout="row center gap:0.5" onclick="${openHref}">
                <ui-icon name="play"></ui-icon>
                Enable Ghostery
              </a>
            </ui-button>
          </div>
        `}
        ${options.terms && store_default.ready(stats) && !managedConfig.disableUserControl && (options.mode === "default" || globalPause) && html`
          <panel-pause
            onaction="${globalPause ? toggleGlobalPause : togglePause}"
            paused="${paused || globalPause}"
            global="${globalPause}"
            managed="${paused?.managed}"
            assist="${paused?.assist}"
            revokeAt="${globalPause?.revokeAt || paused?.revokeAt}"
            data-qa="component:pause"
          >
            ${!!paused?.revokeAt && !paused.assist && html`
              <div layout="row center">
                <ui-action>
                  <a
                    href="${router_default.url(report_category_default)}"
                    layout="row center gap padding:0.5:1:1 margin:top:-1"
                  >
                    <ui-text type="body-s">Something wrong?</ui-text>
                    <ui-text type="label-s" layout="row inline items:center gap:0.5">
                      Report an issue
                      <ui-icon name="chevron-right" layout="size:1.5"></ui-icon>
                    </ui-text>
                  </a>
                </ui-action>
              </div>
            `}
            ${!!paused?.assist && html`
              <div layout="row center">
                <ui-action>
                  <a
                    href="${router_default.url(pause_assistant_default)}"
                    layout="row center padding:0.5:1:1 margin:top:-1"
                  >
                    <ui-text type="label-s" color="onbrand" layout="row items:center gap:0.5">
                      Paused by Browsing Assistant
                      <ui-icon name="info" layout="size:1.5"></ui-icon>
                    </ui-text>
                  </a>
                </ui-action>
              </div>
            `}
          </panel-pause>
        `}
        ${options.terms && store_default.ready(stats) && !managedConfig.disableUserControl && options.mode === "zap" && !globalPause && html`
          <panel-zap
            onclick="${toggleZapped}"
            zapped="${!paused}"
            data-qa="button:zap:${paused ? "enable" : "disable"}"
          >
            ${paused ? html`
                  <div layout="row items:center gap">
                    ${lang === "en" ? html`<ui-icon name="zap-with-text"></ui-icon>` : html`<ui-icon name="zap"></ui-icon> Block ads`}
                  </div>
                ` : msg`Show ads`}
          </panel-zap>
        `}
        <panel-container>
          ${store_default.ready(stats) ? html`
                <ui-stats
                  categories="${stats.topCategories}"
                  type="${options.panel.statsType}"
                  ontypechange="${setStatsType}"
                  layout="margin:1.5:1.5:1"
                >
                  <ui-tooltip position="bottom" slot="actions">
                    <span slot="content">WhoTracks.Me Reports</span>
                    <ui-action-button layout="size:4.5">
                      <a href="${router_default.url(whotracksme_default)}">
                        <ui-icon name="whotracksme" color="primary"></ui-icon>
                      </a>
                    </ui-action-button>
                  </ui-tooltip>
                  ${!stats.groupedTrackers.length && html`
                    <ui-list layout="grow margin:0.5:0" slot="list">
                      <ui-text type="body-s" color="secondary" layout="grow row center">
                        No activities detected
                      </ui-text>
                    </ui-list>
                  `}
                  ${stats.groupedTrackers.map(([name, trackers]) => html`
                      <ui-list
                        name="${name}"
                        layout:last-of-type="margin:bottom:0.5"
                        layout:first-of-type="margin:top:0.5"
                        slot="list"
                      >
                        <div slot="header" layout="row items:center gap">
                          <ui-text type="label-s">${trackers.length}</ui-text>
                        </div>

                        <section layout="column gap:0.5">
                          ${trackers.map((tracker) => html`
                              <div layout="row gap content:space-between items:center">
                                <ui-text type="body-s">
                                  <a
                                    href="${router_default.url(tracker_details_default, { trackerId: tracker.id })}"
                                    layout="row items:center gap:0.5 padding:0.5:0"
                                    data-qa="button:tracker:${tracker.id}"
                                  >
                                    <ui-tooltip>
                                      <span slot="content"> View activity details </span>
                                      <ui-tracker-name> ${tracker.name} </ui-tracker-name>
                                    </ui-tooltip>
                                    <ui-stats-badge>
                                      ${numberFormatter.format(tracker.requestsCount)}
                                    </ui-stats-badge>
                                    ${tracker.blocked && html`<ui-icon
                                      name="block-s"
                                      color="danger-primary"
                                      data-qa="icon:tracker:${tracker.id}:blocked"
                                    ></ui-icon>`}
                                    ${tracker.modified && html`<ui-icon
                                      name="eye"
                                      color="brand-primary"
                                      data-qa="icon:tracker:${tracker.id}:modified"
                                    ></ui-icon>`}
                                  </a>
                                </ui-text>
                                ${options.terms && !managedConfig.disableUserControl && !paused && !globalPause && html`
                                  <ui-action-button layout="shrink:0 width:4.5">
                                    <a
                                      href="${router_default.url(protection_status_default, { trackerId: tracker.id })}"
                                      layout="row center relative"
                                      data-qa="button:tracker:protection-status:${tracker.id}"
                                    >
                                      <panel-protection-status-icon
                                        options="${options}"
                                        trackerId="${tracker.id}"
                                        hostname="${stats.hostname}"
                                      ></panel-protection-status-icon>
                                    </a>
                                  </ui-action-button>
                                `}
                              </div>
                            `)}
                        </section>
                      </ui-list>
                    `)}
                </ui-stats>
                <panel-feedback layout="margin:1:0:1.5">
                  ${stats.trackersBlocked > 0 && html`
                    <panel-feedback-button
                      type="blocked"
                      icon="block-s"
                      value="${numberFormatter.format(stats.trackersBlocked)}"
                      href="${router_default.url(trackers_report_default, { type: "blocked" })}"
                    >
                      Trackers blocked
                    </panel-feedback-button>
                  `}
                  ${stats.trackersModified > 0 && html`
                    <panel-feedback-button
                      type="modified"
                      icon="eye"
                      value="${numberFormatter.format(stats.trackersModified)}"
                      href="${router_default.url(trackers_report_default, { type: "modified" })}"
                    >
                      Trackers modified
                    </panel-feedback-button>
                  `}
                  ${consentManaged && html`
                    <panel-feedback-button type="autoconsent" icon="autoconsent-managed">
                      Consent managed
                    </panel-feedback-button>
                  `}
                  ${contentBlocksSelectors > 0 && html`
                    <panel-feedback-button
                      type="content"
                      icon="hide-element"
                      value="${contentBlocksSelectors}"
                      href="${chrome.runtime.getURL("/pages/settings/index.html#@settings-website-details?domain=" + stats.hostname)}"
                      external
                    >
                      Blocked manually
                    </panel-feedback-button>
                  `}
                </panel-feedback>
              ` : html`
                <div layout="column items:center gap margin:1.5">
                  <img src="${"/assets/sleep-BmCTahGd.svg"}" alt="Ghosty sleeping" layout="size:160px" />
                  <ui-text type="label-l" layout="block:center width:::210px margin:top">
                    Ghostery has nothing to do on this page
                  </ui-text>
                  <ui-text type="body-m" layout="block:center width:::245px">
                    Navigate to a website to see Ghostery in action.
                  </ui-text>
                </div>
              `}
          <ui-action hidden="${globalPause}" inert="${managedConfig.disableUserControl}">
            <a
              href="${options.terms ? SETTINGS_URL : ONBOARDING_URL}"
              class="${{ last: managedConfig.disableUserControl || !store_default.ready(notification) }}"
              onclick="${openHref}"
              layout="block margin:1.5:1.5:0.5"
              layout.last="margin:bottom:1.5"
            >
              <panel-options-item
                icon="block-ads"
                enabled="${options.blockAds}"
                terms="${options.terms}"
              >
                Ad-Blocking
              </panel-options-item>
              <panel-options-item
                icon="anti-tracking"
                enabled="${options.blockTrackers}"
                terms="${options.terms}"
              >
                Anti-Tracking
              </panel-options-item>
              <panel-options-item
                icon="never-consent"
                enabled="${options.blockAnnoyances}"
                terms="${options.terms}"
              >
                Never-Consent
              </panel-options-item>
            </a>
          </ui-action>
        </panel-container>
        ${!managedConfig.disableUserControl && store_default.ready(notification) && !store_default.error(notification) && html`<panel-notification></panel-notification>`}
      `}
    </template>
  `
};
//#endregion
export { main_default as default };
