/**
 * @name Timezones
 * @author Kaan
 * @version 2.1.6
 * @description Allows you to display a local timezone you set for a user.
 * @source https://github.com/zrodevkaan/BDPlugins/tree/main/Plugins/Timezones/Timezones.plugin.js
 * @invite t3zMgv7Nvb
 * @stable 634304
 * @canary 635660
 */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/Timezones/index.tsx
var index_exports = {};
__export(index_exports, {
  default: () => Timezones
});
module.exports = __toCommonJS(index_exports);

// helpers/webpack.ts
var { Webpack } = BdApi;

// helpers/index.tsx
var { Webpack: Webpack2, React, ContextMenu, Hooks } = BdApi;
var { createElement, forwardRef } = React;
function orNull(value) {
  return value ?? null;
}
function toOptions({ declaration, ...rest } = {}) {
  return declaration ? { ...rest, declarationFilter: declaration } : rest;
}
function styledBase(tag, cssOrFn) {
  const Styled = (props) => {
    const style = typeof cssOrFn === "function" ? cssOrFn(props) : cssOrFn;
    return createElement(tag, { ...props, style: { ...style, ...props.style } });
  };
  Styled.displayName = `styled.${String(tag)}`;
  return Styled;
}
var styled = new Proxy(styledBase, {
  get: (target, p) => (css) => target(p, css)
});
function ContextMenuHelper(patches) {
  const unpatches = patches.map((p) => ContextMenu.patch(p.navId, p.patch));
  return () => unpatches.forEach((unpatch) => unpatch());
}
async function waitForExportByFilter(filter, options) {
  return orNull(await Webpack2.waitForModule(filter, toOptions(options)));
}
function waitForExportBySource(source, o) {
  return waitForExportByFilter(Webpack2.Filters.bySource(source), o);
}
function lazyExport(getter) {
  let cached;
  const resolve = () => cached ??= getter();
  return new Proxy({}, {
    get: (_, key) => resolve()?.[key],
    set: (_, key, value) => {
      const target = resolve();
      if (target) target[key] = value;
      return true;
    },
    has: (_, key) => {
      const t = resolve();
      return t ? key in t : false;
    },
    ownKeys: () => {
      const t = resolve();
      return t ? Reflect.ownKeys(t) : [];
    },
    getOwnPropertyDescriptor: (_, key) => {
      const t = resolve();
      const desc = t ? Reflect.getOwnPropertyDescriptor(t, key) : void 0;
      return desc && { ...desc, configurable: true };
    }
  });
}
function waitAndPatch(patcher, filter, key, callback) {
  const controller = new AbortController();
  let unpatch = null;
  let cancelled = false;
  waitForExportByFilter(filter, { signal: controller.signal }).then((mod) => {
    if (!cancelled && mod) unpatch = patcher.after(mod, key, callback);
  }).catch(() => {
  });
  return () => {
    cancelled = true;
    controller.abort();
    unpatch?.();
  };
}
function lazyStore(name) {
  return lazyExport(() => Webpack2.getStore(name));
}
var Stores = {
  User: lazyStore("UserStore"),
  Guild: lazyStore("GuildStore"),
  Channel: lazyStore("ChannelStore"),
  GuildMember: lazyStore("GuildMemberStore"),
  SelectedGuild: lazyStore("SelectedGuildStore"),
  SelectedChannel: lazyStore("SelectedChannelStore"),
  Message: lazyStore("MessageStore")
};

// src/Timezones/index.tsx
var { Patcher, Webpack: Webpack3, Data, Utils, Hooks: Hooks2, ContextMenu: ContextMenu2, Components, React: React2 } = new BdApi("Timezones");
var ModalUtils = Webpack3.getByKeys("openModal");
var Modal = Webpack3.getByStrings("actionBarInputLayout", { searchExports: true });
var Selectable = Webpack3.getModule(Webpack3.Filters.byStrings(`"data-mana-component":"select"`), { searchExports: true });
function getTimezones() {
  const now = /* @__PURE__ */ new Date();
  return Intl.supportedValuesOf("timeZone").map((tz) => ({
    timezone: tz,
    currentTime: now.toLocaleString("en-US", {
      timeZone: tz,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false
    }),
    offset: new Intl.DateTimeFormat("en-US", {
      timeZone: tz,
      timeZoneName: "short"
    }).formatToParts(now).find((p) => p.type === "timeZoneName")?.value || ""
  }));
}
var UserTimezoneStore = new class UTS extends Utils.Store {
  timezones = (() => {
    const raw = Data.load("timezones") || {};
    const migrated = {};
    for (const id of Object.keys(raw)) {
      const entry = raw[id];
      if (typeof entry === "string") {
        migrated[id] = { timezoneId: entry, external: false };
      } else {
        migrated[id] = entry;
      }
    }
    Data.save("timezones", migrated);
    return migrated;
  })();
  settings = {
    chatTimezoneDisplay: "CLOCK",
    bannerTimezoneDisplay: "ENABLED",
    timezoneFormat: "12H",
    showSeconds: false,
    showTimezoneAbbreviation: false,
    ...Data.load("settings") || {}
  };
  addTimezone(id, timezoneName, isExternal = false) {
    this.timezones[id] = { timezoneId: timezoneName, external: isExternal };
    Data.save("timezones", this.timezones);
    this.emitChange();
  }
  getTimezone(id) {
    return this.timezones[id]?.timezoneId;
  }
  getTimezoneEntry(id) {
    return this.timezones[id];
  }
  removeTimezone(id) {
    delete this.timezones[id];
    Data.save("timezones", this.timezones);
    this.emitChange();
  }
  setTimezoneSettings(settings) {
    this.settings = { ...this.settings, ...settings };
    Data.save("settings", this.settings);
    this.emitChange();
  }
  async startBadAPI() {
    const ids = BdApi.Webpack.Stores.RelationshipStore.getFriendIDs();
    ids.push(BdApi.Webpack.Stores.UserStore.getCurrentUser().id);
    const res = await BdApi.Net.fetch("https://timezonedb.catvibers.me/api/user/bulk", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(ids)
    });
    const allIds = await res.json();
    for (const id of ids) {
      const existing = this.getTimezoneEntry(id);
      if (existing && !existing.external) continue;
      if (allIds[id]?.timezoneId != null) this.addTimezone(id, allIds[id].timezoneId, true);
    }
  }
  getTimezoneSettings() {
    return this.settings;
  }
}();
var TimezoneOption = styled.div(() => ({
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  width: "100%",
  gap: "8px"
}));
var TimezoneName = styled.span(() => ({
  fontWeight: "500",
  flex: "1"
}));
var TimezoneInfo = styled.span(() => ({
  color: "var(--text-muted)",
  fontSize: "0.875em",
  whiteSpace: "nowrap"
}));
var TimezoneChat = styled.span(() => ({
  color: "var(--chat-text-muted)",
  fontSize: ".75rem",
  display: "inline-flex",
  lineHeight: "1.375rem",
  verticalAlign: "baseline",
  marginLeft: "3px"
}));
var TimezoneText = styled.div(() => {
  return {
    position: "absolute",
    color: "var(--text-default)",
    padding: "5px",
    borderRadius: "5px",
    backgroundColor: "var(--background-base-low)",
    left: "10px",
    top: "10px",
    zIndex: "999",
    textAlign: "center",
    fontWeight: "lighter"
  };
});
var SettingsPanelContainer = styled.div(() => ({
  minHeight: "500px"
}));
var SettingsHeaderGroup = styled.div(() => ({
  display: "flex",
  flexDirection: "column",
  gap: "4px",
  marginBottom: "8px"
}));
var SettingsSection = styled.div(({ displayType }) => {
  return {
    marginTop: "20px",
    alignItems: "center",
    justifyContent: "space-between",
    display: displayType
  };
});
var Header = styled.span(() => ({
  color: "var(--text-strong)",
  fontFamily: "var(--font-primary)",
  fontSize: "18px",
  fontWeight: "700",
  lineHeight: "1.25"
}));
var HeaderDescription = styled.span({
  color: "var(--text-muted)",
  fontFamily: "var(--font-primary)",
  fontSize: "14px",
  fontWeight: "400",
  lineHeight: "1.4"
});
function getUTCOffset(timezone) {
  const date = /* @__PURE__ */ new Date();
  const utcDate = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
  const tzDate = new Date(date.toLocaleString("en-US", { timeZone: timezone }));
  return (tzDate - utcDate) / (1e3 * 60 * 60);
}
function getTimezoneDifference(timezone) {
  const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const localOffset = getUTCOffset(localTimezone);
  const targetOffset = getUTCOffset(timezone);
  const diffHours = targetOffset - localOffset;
  if (diffHours === 0) {
    return "Same timezone";
  } else if (diffHours > 0) {
    return `${diffHours} hour(s) ahead`;
  } else {
    return `${Math.abs(diffHours)} hour(s) behind`;
  }
}
function getCurrentTime(timezone, date = /* @__PURE__ */ new Date()) {
  const settings = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezoneSettings());
  const use24h = settings.timezoneFormat === "24H";
  const includeSeconds = settings.showSeconds;
  let formattedTime = date.toLocaleString("en-US", {
    timeZone: timezone,
    hour: "2-digit",
    minute: "2-digit",
    ...includeSeconds && { second: "2-digit" },
    hour12: !use24h
  });
  if (!use24h) {
    formattedTime = formattedTime.replace(/^0/, "");
  }
  if (settings.showTimezoneAbbreviation) {
    const abbr = new Intl.DateTimeFormat("en-US", {
      timeZone: timezone,
      timeZoneName: "short"
    }).formatToParts(/* @__PURE__ */ new Date()).find((p) => p.type === "timeZoneName")?.value || "";
    return `${formattedTime} ${abbr}`;
  }
  return formattedTime;
}
function Timezone({ user }) {
  const timezone = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezone(user.id));
  const settings = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezoneSettings());
  const time = getCurrentTime(timezone);
  return timezone && settings.bannerTimezoneDisplay === "ENABLED" ? /* @__PURE__ */ BdApi.React.createElement(TimezoneText, { className: "tz-banner" }, time) : null;
}
function returnSpoof(timezone, offset, time) {
  return {
    trim() {
      return `${timezone} ${offset} ${time}`;
    },
    getTime() {
      return timezone;
    },
    toString() {
      return this.getTime() + " " + offset;
    }
  };
}
var SearchableSelect = React2.lazy(async () => ({ default: await waitForExportBySource("Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING;", { declaration: (x) => String(x).includes("matchSorterOptions") }) }));
function TimezoneModal({ user }) {
  const timezone = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezone(user.id));
  const timezones = React2.useMemo(() => getTimezones(), []);
  const node = (timezone2, offset, time) => {
    const timeDiff = getTimezoneDifference(timezone2);
    return /* @__PURE__ */ BdApi.React.createElement(TimezoneOption, null, /* @__PURE__ */ BdApi.React.createElement(TimezoneName, null, timezone2), /* @__PURE__ */ BdApi.React.createElement(TimezoneInfo, null, offset, " \u2022 ", timeDiff));
  };
  const renderTimezone = (tz, offset, time) => {
    return Object.assign(node(tz, offset, time), returnSpoof(tz, offset, time));
  };
  return /* @__PURE__ */ BdApi.React.createElement("div", null, /* @__PURE__ */ BdApi.React.createElement(
    SearchableSelect,
    {
      value: timezone || "Unknown",
      onChange: (e) => UserTimezoneStore.addTimezone(user.id, e, false),
      options: timezones.map((x) => {
        return {
          label: renderTimezone(x.timezone, x.offset, x.currentTime),
          value: `${x.timezone}`
        };
      })
    }
  ));
}
var Clock = () => /* @__PURE__ */ BdApi.React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: 16, height: 16, viewBox: "0 0 24 24" }, /* @__PURE__ */ BdApi.React.createElement(
  "path",
  {
    fill: "var(--interactive-icon-default)",
    d: "M13 12.175V9q0-.425-.288-.712T12 8t-.712.288T11 9v3.575q0 .2.075.388t.225.337l2.525 2.525q.3.3.713.3t.712-.3q.275-.3.275-.712t-.275-.688zM12 6q.425 0 .713-.288T13 5t-.288-.712T12 4t-.712.288T11 5t.288.713T12 6m6 6q0 .425.288.713T19 13t.713-.288T20 12t-.288-.712T19 11t-.712.288T18 12m-6 6q-.425 0-.712.288T11 19t.288.713T12 20t.713-.288T13 19t-.288-.712T12 18m-6-6q0-.425-.288-.712T5 11t-.712.288T4 12t.288.713T5 13t.713-.288T6 12m6 10q-2.075 0-3.9-.788t-3.175-2.137T2.788 15.9T2 12t.788-3.9t2.137-3.175T8.1 2.788T12 2t3.9.788t3.175 2.137T21.213 8.1T22 12t-.788 3.9t-2.137 3.175t-3.175 2.138T12 22"
  }
));
function ChatClock({ user, timestamp }) {
  const timezone = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezone(user.id));
  const settings = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezoneSettings());
  const displayMode = settings?.chatTimezoneDisplay ?? "CLOCK";
  const time = getCurrentTime(timezone, timestamp);
  if (displayMode === "CLOCK") {
    return /* @__PURE__ */ BdApi.React.createElement(Components.Tooltip, { text: time }, (props) => {
      return /* @__PURE__ */ BdApi.React.createElement(
        "div",
        {
          className: "tz-svg",
          ...props,
          style: { display: "inline-flex", marginLeft: "5px", marginTop: "4px", verticalAlign: "top" }
        },
        /* @__PURE__ */ BdApi.React.createElement(Clock, null)
      );
    });
  }
  if (displayMode === "TEXT") {
    return /* @__PURE__ */ BdApi.React.createElement("span", { className: "tz-text" }, /* @__PURE__ */ BdApi.React.createElement(TimezoneChat, null, time, " \u2022"));
  }
  return null;
}
function TimezoneContextMenu({ user }) {
  const entry = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezoneEntry(user.id));
  return /* @__PURE__ */ BdApi.React.createElement(ContextMenu2.Item, { id: "bwah", label: "Timezones" }, /* @__PURE__ */ BdApi.React.createElement(ContextMenu2.Item, { action: () => {
    ModalUtils.openModal((props) => /* @__PURE__ */ BdApi.React.createElement(Modal, { title: `Set Timezone for ${user.username}`, ...props }, /* @__PURE__ */ BdApi.React.createElement(TimezoneModal, { user })));
  }, id: "bwah-1", label: "Set Timezone" }), /* @__PURE__ */ BdApi.React.createElement(
    ContextMenu2.Item,
    {
      action: () => {
        UserTimezoneStore.removeTimezone(user.id);
      },
      id: "bwah-2",
      disabled: !entry,
      color: "danger",
      label: entry?.external ? "Clear Timezone (External)" : "Clear Timezone"
    }
  ));
}
var Timezones = class {
  unpatchAll;
  async start() {
    UserTimezoneStore.startBadAPI();
    const Banner_3 = Webpack3.getBySource('backgroundColor:"COMPLETE"===');
    Patcher.after(Banner_3, "A", (a, b, res) => {
      return [/* @__PURE__ */ BdApi.React.createElement(Timezone, { user: b[0].user }), res];
    });
    waitAndPatch(
      Patcher,
      (x) => String(x.A).includes(".colorRoleId?nul"),
      "A",
      (a, args, res) => {
        const timestamp = new Date(args[0].message.timestamp);
        !!UserTimezoneStore.getTimezone(args[0].message.author.id) && res.props.children.push(
          /* @__PURE__ */ BdApi.React.createElement(ChatClock, { user: args[0].message.author, timestamp })
        );
      }
    );
    this.unpatchAll = ContextMenuHelper([
      {
        navId: "user-context",
        patch: (res, props) => {
          return res.props.children.push(TimezoneContextMenu({ user: props.user }));
        }
      }
    ]);
  }
  getTimezoneComp({ user }) {
    return /* @__PURE__ */ BdApi.React.createElement(Timezone, { user });
  }
  getSettingsPanel() {
    return () => {
      const settings = Hooks2.useStateFromStores([UserTimezoneStore], () => UserTimezoneStore.getTimezoneSettings());
      return /* @__PURE__ */ BdApi.React.createElement(SettingsPanelContainer, null, /* @__PURE__ */ BdApi.React.createElement(SettingsHeaderGroup, null, /* @__PURE__ */ BdApi.React.createElement(Header, null, "Chat timezone display"), /* @__PURE__ */ BdApi.React.createElement(HeaderDescription, null, "Choose how timezones are shown next to message timestamps.")), /* @__PURE__ */ BdApi.React.createElement(
        Selectable,
        {
          value: settings.chatTimezoneDisplay,
          onSelectionChange: (value) => UserTimezoneStore.setTimezoneSettings({ chatTimezoneDisplay: value }),
          options: ["CLOCK", "TEXT", "NONE"].map((x) => ({
            label: x.toLowerCase(),
            value: x
          }))
        }
      ), /* @__PURE__ */ BdApi.React.createElement(SettingsSection, null, /* @__PURE__ */ BdApi.React.createElement(SettingsHeaderGroup, null, /* @__PURE__ */ BdApi.React.createElement(Header, null, "Banner timezone display"), /* @__PURE__ */ BdApi.React.createElement(HeaderDescription, null, "Show or hide timezone on user profile banners.")), /* @__PURE__ */ BdApi.React.createElement(
        Selectable,
        {
          value: settings.bannerTimezoneDisplay,
          onSelectionChange: (value) => UserTimezoneStore.setTimezoneSettings({ bannerTimezoneDisplay: value }),
          options: ["ENABLED", "DISABLED"].map((x) => ({
            label: x.toLowerCase(),
            value: x
          }))
        }
      )), /* @__PURE__ */ BdApi.React.createElement(SettingsSection, null, /* @__PURE__ */ BdApi.React.createElement(SettingsHeaderGroup, null, /* @__PURE__ */ BdApi.React.createElement(Header, null, "Time format"), /* @__PURE__ */ BdApi.React.createElement(HeaderDescription, null, "Choose between 12-hour (AM/PM) or 24-hour format.")), /* @__PURE__ */ BdApi.React.createElement(
        Selectable,
        {
          value: settings.timezoneFormat,
          onSelectionChange: (value) => UserTimezoneStore.setTimezoneSettings({ timezoneFormat: value }),
          options: [
            { label: "12-hour (2:30 PM)", value: "12H" },
            { label: "24-hour (14:30)", value: "24H" }
          ]
        }
      )), /* @__PURE__ */ BdApi.React.createElement(SettingsSection, { displayType: "flex" }, /* @__PURE__ */ BdApi.React.createElement(SettingsHeaderGroup, null, /* @__PURE__ */ BdApi.React.createElement(Header, null, "Show seconds"), /* @__PURE__ */ BdApi.React.createElement(HeaderDescription, null, "Include seconds in time display (e.g., 2:30:45 PM).")), /* @__PURE__ */ BdApi.React.createElement(
        Components.SwitchInput,
        {
          value: settings.showSeconds,
          onChange: (value) => UserTimezoneStore.setTimezoneSettings({ showSeconds: value })
        }
      )), /* @__PURE__ */ BdApi.React.createElement(SettingsSection, { displayType: "flex" }, /* @__PURE__ */ BdApi.React.createElement(SettingsHeaderGroup, null, /* @__PURE__ */ BdApi.React.createElement(Header, null, "Show timezone abbreviation"), /* @__PURE__ */ BdApi.React.createElement(HeaderDescription, null, "Show timezone abbreviation after time (e.g., 2:30 PM EST).")), /* @__PURE__ */ BdApi.React.createElement(
        Components.SwitchInput,
        {
          value: settings.showTimezoneAbbreviation,
          onChange: (value) => UserTimezoneStore.setTimezoneSettings({ showTimezoneAbbreviation: value })
        }
      )));
    };
  }
  stop() {
    Patcher.unpatchAll();
    this.unpatchAll();
  }
};
