import { m as head, d as attr_class, f as stringify, k as escape_html, o as attr, p as attr_style, q as bind_props, r as spread_props, n as ensure_array_like, t as derived } from './index-Cnl871UW.js';
import { I as Icon } from './Icon-DyrkHVnV.js';
import './markdown-W_mTBct0.js';
import { B as Button, h as html } from './Button-C7D5W6wV.js';
import 'dompurify';
import 'marked';

/* empty css                                                  */
function Card($$renderer, $$props) {
  const { children, class: className = "", description, title } = $$props;
  $$renderer.push(`<div${attr_class(`card ${stringify(className)}`)}>`);
  if (title) {
    $$renderer.push("<!--[0-->");
    $$renderer.push(`<div class="card-header"><h2 class="card-title">${escape_html(title)}</h2> `);
    if (description) {
      $$renderer.push("<!--[0-->");
      $$renderer.push(`<p class="card-description">${escape_html(description)}</p>`);
    } else {
      $$renderer.push("<!--[-1-->");
    }
    $$renderer.push(`<!--]--></div>`);
  } else {
    $$renderer.push("<!--[-1-->");
  }
  $$renderer.push(`<!--]--> <div class="card-content">`);
  children($$renderer);
  $$renderer.push(`<!----></div></div>`);
}
function toErrorMessage(err) {
  if (err instanceof Error) {
    return err.message;
  }
  if (typeof err === "string") {
    return err;
  }
  return String(err);
}
function validateInput(inputValue, dataType, validPattern, inProgressPattern, customValidators) {
  let validationResult = "Valid";
  switch (dataType) {
    case "email":
      validationResult = validateEmailInput(inputValue);
      break;
    case "tel":
      validationResult = validPattern === null ? validatePhoneNumber(inputValue) : validateTextWithPattern(inputValue, validPattern, inProgressPattern);
      break;
    case "password":
      validationResult = validatePassword(inputValue, validPattern, inProgressPattern);
      break;
    case "text":
      validationResult = validateTextWithPattern(inputValue, validPattern, inProgressPattern);
      break;
  }
  customValidators.forEach((validator) => {
    const currentResult = validator(inputValue, validationResult);
    if (currentResult === "Invalid") {
      validationResult = "Invalid";
    } else if (currentResult === "InProgress") {
      validationResult = "InProgress";
    } else {
      validationResult = validationResult === "Valid" && currentResult === "Valid" ? "Valid" : validationResult;
    }
  });
  return validationResult;
}
function validateTextWithPattern(inputValue, validationPattern, inProgressPattern) {
  if (validationPattern !== null) {
    if (validationPattern.test(inputValue)) {
      return "Valid";
    } else if (inProgressPattern !== null && inProgressPattern.test(inputValue) || inputValue.length === 0) {
      return "InProgress";
    } else {
      return "Invalid";
    }
  }
  return "Valid";
}
function validatePassword(password, validationPattern, inProgressPattern) {
  if (validationPattern !== null) {
    if (validationPattern.test(password)) {
      return "Valid";
    } else if (inProgressPattern !== null && inProgressPattern.test(password) && password.length === 0) {
      return "InProgress";
    } else {
      return "Invalid";
    }
  }
  return "Valid";
}
function validateEmailInput(emailId) {
  try {
    const validPattern = new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
    const inProgressPattern = new RegExp(/[^ ]{1,}[\w0-9.,_,@]{0,}/);
    if (validPattern.test(emailId)) {
      return "Valid";
    } else if (inProgressPattern.test(emailId) || emailId.length === 0) {
      return "InProgress";
    } else {
      return "Invalid";
    }
  } catch (e) {
    console.error("Email Regex creation failed: ", e);
  }
  return "Valid";
}
function validatePhoneNumber(phoneNumber) {
  try {
    const validationPattern = new RegExp("^[6-9]{1}[0-9]{9}$");
    const inProgressPattern = new RegExp("^[6-9]{1}[0-9]{0,9}$");
    if (validationPattern.test(phoneNumber)) {
      return "Valid";
    } else if (inProgressPattern.test(phoneNumber) || phoneNumber.length === 0) {
      return "InProgress";
    } else {
      return "Invalid";
    }
  } catch (e) {
    console.error("Phone Regex creation failed", e);
  }
  return phoneNumber.length === 10 ? "Valid" : phoneNumber.length > 10 ? "InProgress" : "Invalid";
}
function Input($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      value = "",
      placeholder = "",
      dataType = "text",
      label = "",
      onErrorMessage = "",
      infoMessage = "",
      validators = [],
      disable = false,
      validationPattern = null,
      inProgressPattern = null,
      addFocusColor = false,
      maxLength = 1e3,
      minLength = 0,
      actionInput = false,
      useTextArea = false,
      autoComplete = "on",
      name = "",
      testId = "",
      textTransformers = [],
      textViewPresentation = [],
      onFocus = () => {
      },
      onFocusout = () => {
      },
      onInput = () => {
      },
      onPaste = () => {
      },
      onStateChange = () => {
      },
      onClick = () => {
      },
      onKeyDown = () => {
      },
      classes
    } = $$props;
    function focus() {
      try {
        inputElement?.focus();
        inputElement?.scrollIntoView({ behavior: "smooth", block: "center" });
      } catch (error) {
        console.error("Error focusing or scrolling inputElement:", error);
      }
    }
    function blur() {
      try {
        inputElement?.blur();
      } catch (error) {
        console.error("Error blurring inputElement:", error);
      }
    }
    let inputElement = null;
    let validationState = derived(() => {
      const valueValidation = validateInput(value, dataType, validationPattern, inProgressPattern, validators);
      if (valueValidation === "InProgress" && value.length > 0 && inputElement) ;
      return valueValidation;
    });
    const showErrorMessage = derived(() => validationState() === "Invalid");
    $$renderer2.push(`<div${attr_class(`input-container ${stringify(classes ?? "")}`, "svelte-1y8a925", {
      "input-error": validationState() === "Invalid" && !actionInput
    })}>`);
    if (typeof label === "string" && label !== "" && !actionInput) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<label class="label svelte-1y8a925"${attr("for", name)}>${escape_html(label)}</label>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]--> `);
    if (useTextArea) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<textarea${attr("placeholder", placeholder)}${attr("autocomplete", autoComplete)}${attr("name", name)}${attr_style(`--focus-border: ${stringify(addFocusColor ? 1 : 0)}px;`)}${attr("disabled", disable, true)}${attr("maxlength", dataType === "tel" ? null : maxLength)}${attr("minlength", minLength)}${attr_class("svelte-1y8a925", void 0, { "action-input": actionInput })}>`);
      const $$body = escape_html(value);
      if ($$body) {
        $$renderer2.push(`${$$body}`);
      }
      $$renderer2.push(`</textarea>`);
    } else {
      $$renderer2.push("<!--[-1-->");
      $$renderer2.push(`<input${attr("type", dataType)}${attr("value", value)}${attr("placeholder", placeholder)}${attr("autocomplete", autoComplete)}${attr("name", name)}${attr("data-pw", testId)}${attr("disabled", disable, true)}${attr("maxlength", dataType === "tel" ? null : maxLength)}${attr("minlength", minLength)}${attr_class("svelte-1y8a925", void 0, { "action-input": actionInput })}/>`);
    }
    $$renderer2.push(`<!--]--> `);
    if (onErrorMessage !== "" && showErrorMessage() && !actionInput) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div class="error-message svelte-1y8a925">${escape_html(onErrorMessage)}</div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]--> `);
    if (infoMessage !== "" && !actionInput) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div class="info-message svelte-1y8a925">${escape_html(infoMessage)}</div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]--></div>`);
    bind_props($$props, { value, focus, blur });
  });
}
const closeSvg = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n  <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n  <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n';
function Banner($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      text,
      icon,
      linkText,
      dismissible = false,
      visible = true,
      testId,
      rightContent,
      dismissIcon,
      onclick,
      ondismiss,
      classes
    } = $$props;
    let interactive = derived(() => typeof onclick === "function");
    function handleDismiss(event) {
      event.stopPropagation();
      visible = false;
      ondismiss?.();
    }
    if (visible) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div${attr_class(`banner ${stringify(classes ?? "")}`, "svelte-1omq7oz")}${attr("role", interactive() ? "button" : null)}${attr("tabindex", interactive() ? 0 : null)}${attr("data-pw", typeof testId === "string" ? testId : null)}>`);
      if (typeof icon === "function") {
        $$renderer2.push("<!--[0-->");
        $$renderer2.push(`<div class="banner-icon svelte-1omq7oz">`);
        icon($$renderer2);
        $$renderer2.push(`<!----></div>`);
      } else {
        $$renderer2.push("<!--[-1-->");
      }
      $$renderer2.push(`<!--]--> <div class="banner-text svelte-1omq7oz">${escape_html(text)} `);
      if (typeof linkText === "string" && linkText.length > 0) {
        $$renderer2.push("<!--[0-->");
        $$renderer2.push(`<span class="banner-link-text svelte-1omq7oz">${escape_html(linkText)}</span>`);
      } else {
        $$renderer2.push("<!--[-1-->");
      }
      $$renderer2.push(`<!--]--></div> `);
      if (typeof rightContent === "function") {
        $$renderer2.push("<!--[0-->");
        $$renderer2.push(`<div class="banner-right svelte-1omq7oz">`);
        rightContent($$renderer2);
        $$renderer2.push(`<!----></div>`);
      } else {
        $$renderer2.push("<!--[-1-->");
      }
      $$renderer2.push(`<!--]--> `);
      if (dismissible) {
        $$renderer2.push("<!--[0-->");
        $$renderer2.push(`<div class="banner-dismiss svelte-1omq7oz">`);
        Button($$renderer2, spread_props([
          { onclick: handleDismiss, ariaLabel: "Dismiss" },
          typeof testId === "string" ? { testId: `${testId}-dismiss` } : {},
          {
            children: ($$renderer3) => {
              if (typeof dismissIcon === "function") {
                $$renderer3.push("<!--[0-->");
                dismissIcon($$renderer3);
                $$renderer3.push(`<!---->`);
              } else {
                $$renderer3.push("<!--[-1-->");
                $$renderer3.push(`${html(closeSvg)}`);
              }
              $$renderer3.push(`<!--]-->`);
            },
            $$slots: { default: true }
          }
        ]));
        $$renderer2.push(`<!----></div>`);
      } else {
        $$renderer2.push("<!--[-1-->");
      }
      $$renderer2.push(`<!--]--></div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]-->`);
    bind_props($$props, { visible });
  });
}
function Step($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let { stepIndex, label, icon, classes } = $$props;
    $$renderer2.push(`<div${attr_class(`step ${stringify(classes ?? "")}`, "svelte-ds22du")} role="button" tabindex="0">`);
    if (typeof icon === "string" && icon.length > 0) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div class="step-icon-container"><img class="step-icon"${attr("src", icon)} alt=""/></div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
      $$renderer2.push(`<div class="step-index-container svelte-ds22du"><div class="step-index-text svelte-ds22du">${escape_html(stepIndex)}</div></div>`);
    }
    $$renderer2.push(`<!--]--> <div class="step-text svelte-ds22du">${escape_html(label)}</div> <div class="separator svelte-ds22du"></div></div>`);
  });
}
function Stepper($$renderer, $$props) {
  let { steps, currentStepIndex, classes } = $$props;
  $$renderer.push(`<div${attr_class(`container ${stringify(classes ?? "")}`, "svelte-xw39st")}><!--[-->`);
  const each_array = ensure_array_like(steps);
  for (let stepIndex = 0, $$length = each_array.length; stepIndex < $$length; stepIndex++) {
    let currentStep = each_array[stepIndex];
    $$renderer.push(`<div${attr_class("step-container svelte-xw39st", void 0, {
      "active-step": currentStepIndex === stepIndex,
      "completed-step": currentStepIndex > stepIndex
    })}>`);
    Step($$renderer, {
      label: currentStep.label,
      icon: currentStep.icon,
      stepIndex: stepIndex + 1
    });
    $$renderer.push(`<!----></div>`);
  }
  $$renderer.push(`<!--]--></div>`);
}
function _page($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let serverUrl = "";
    let apiKey = "";
    let deviceToken = "";
    let result = "";
    let loading = false;
    let statusType = "";
    let qrDataUrl = "";
    let qrServerUrl = "";
    let qrLoading = false;
    let qrError = "";
    async function fetchQrCode() {
      if (!apiKey.trim()) {
        qrError = "Save an API key first to generate a QR code";
        return;
      }
      qrLoading = true;
      qrError = "";
      qrDataUrl = "";
      qrServerUrl = "";
      try {
        const response = await fetch("/api/qr-config", { headers: { Authorization: `Bearer ${apiKey.trim()}` } });
        if (!response.ok) {
          const data2 = await response.json();
          qrError = data2.error || "Failed to generate QR code";
          return;
        }
        const data = await response.json();
        qrDataUrl = data.dataUrl;
        qrServerUrl = data.serverUrl;
      } catch (error) {
        qrError = `Network error: ${toErrorMessage(error)}`;
      } finally {
        qrLoading = false;
      }
    }
    function getNativeBridge() {
      if (typeof window === "undefined") {
        return null;
      }
      if (window.ShooterBridge) {
        return window.ShooterBridge;
      }
      if (window.ShooterNativeBridge) {
        return window.ShooterNativeBridge;
      }
      return null;
    }
    function getDefaultServerUrl() {
      return window.location.origin;
    }
    async function saveConfiguration() {
      loading = true;
      result = "";
      statusType = "";
      try {
        const trimmedUrl = serverUrl.trim().replace(/\/+$/, "");
        localStorage.setItem("shooter_config", JSON.stringify({
          apiKey: apiKey.trim(),
          deviceToken: deviceToken.trim(),
          lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
          serverUrl: trimmedUrl || getDefaultServerUrl()
        }));
        const bridge = getNativeBridge();
        if (bridge) {
          bridge.saveConfig?.(JSON.stringify({
            apiKey: apiKey.trim(),
            serverUrl: trimmedUrl || getDefaultServerUrl()
          }));
        }
        const response = await fetch("/api/health");
        if (response.ok) {
          result = "Configuration saved successfully";
          statusType = "success";
        } else {
          result = "Configuration saved but system health check failed";
          statusType = "warning";
        }
      } catch (error) {
        result = `Configuration failed: ${toErrorMessage(error)}`;
        statusType = "error";
      }
      loading = false;
    }
    async function testConfiguration() {
      if (!apiKey.trim()) {
        result = "API key is required for testing";
        statusType = "error";
        return;
      }
      loading = true;
      result = "";
      statusType = "";
      try {
        const testPayload = {
          data: { source: "config-test", timestamp: Date.now() },
          message: `Configuration test at ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`,
          title: "Configuration Test"
        };
        if (deviceToken.trim()) {
          testPayload.deviceToken = deviceToken.trim();
        }
        const response = await fetch("/api/notify", {
          body: JSON.stringify(testPayload),
          headers: {
            Authorization: `Bearer ${apiKey}`,
            "Content-Type": "application/json"
          },
          method: "POST"
        });
        const data = await response.json();
        if (response.ok) {
          result = "Test notification sent successfully";
          statusType = "success";
        } else {
          result = `Test failed: ${data.error || "Unknown error"}`;
          statusType = "error";
        }
      } catch (error) {
        result = `Network error: ${toErrorMessage(error)}`;
        statusType = "error";
      }
      loading = false;
    }
    function clearConfiguration() {
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      head("1gp6n77", $$renderer3, ($$renderer4) => {
        $$renderer4.title(($$renderer5) => {
          $$renderer5.push(`<title>Settings - Shooter</title>`);
        });
        $$renderer4.push(`<meta name="description" content="Configure notification system settings"/>`);
      });
      $$renderer3.push(`<main class="main"><div class="settings-container svelte-1gp6n77"><div class="page-header svelte-1gp6n77"><h1 class="page-title svelte-1gp6n77">Settings</h1> <p class="page-description svelte-1gp6n77">Configure your API credentials and notification preferences</p></div> <div class="settings-grid svelte-1gp6n77"><section class="settings-section svelte-1gp6n77">`);
      Card($$renderer3, {
        title: "Server Configuration",
        description: "Configure server connection and credentials",
        children: ($$renderer4) => {
          Input($$renderer4, {
            name: "serverUrl",
            label: "Server URL",
            dataType: "text",
            placeholder: "https://shooter.breezehq.dev",
            infoMessage: "Base URL of your Shooter server. Apps will reload with this URL on next launch.",
            get value() {
              return serverUrl;
            },
            set value($$value) {
              serverUrl = $$value;
              $$settled = false;
            }
          });
          $$renderer4.push(`<!----> `);
          Input($$renderer4, {
            name: "apiKey",
            label: "API Key",
            dataType: "password",
            placeholder: "Enter your API key",
            infoMessage: "Required for sending notifications",
            get value() {
              return apiKey;
            },
            set value($$value) {
              apiKey = $$value;
              $$settled = false;
            }
          });
          $$renderer4.push(`<!----> `);
          Input($$renderer4, {
            name: "deviceToken",
            label: "Device Token",
            dataType: "text",
            placeholder: "64-character hex string",
            infoMessage: "Device token from app registration",
            classes: "input-mono",
            get value() {
              return deviceToken;
            },
            set value($$value) {
              deviceToken = $$value;
              $$settled = false;
            }
          });
          $$renderer4.push(`<!---->`);
        }
      });
      $$renderer3.push(`<!----> `);
      if (result) {
        $$renderer3.push("<!--[0-->");
        const bannerIcon = statusType === "success" ? "check-circle" : statusType === "error" ? "x-circle" : "alert-triangle";
        {
          let icon = function($$renderer4) {
            Icon($$renderer4, { name: bannerIcon, size: 16 });
          };
          Banner($$renderer3, {
            text: result,
            classes: `banner-${stringify(statusType || "info")}`,
            icon,
            $$slots: { icon: true }
          });
        }
      } else {
        $$renderer3.push("<!--[-1-->");
      }
      $$renderer3.push(`<!--]--> <div class="button-group svelte-1gp6n77">`);
      Button($$renderer3, {
        classes: "btn-secondary",
        onclick: testConfiguration,
        disabled: loading || !apiKey.trim(),
        children: ($$renderer4) => {
          if (!loading) {
            $$renderer4.push("<!--[0-->");
            Icon($$renderer4, { name: "play", size: 14 });
          } else {
            $$renderer4.push("<!--[-1-->");
          }
          $$renderer4.push(`<!--]--> Test Connection`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      Button($$renderer3, {
        classes: "btn-primary",
        onclick: saveConfiguration,
        disabled: loading || !apiKey.trim(),
        showLoader: loading,
        text: "Save Changes"
      });
      $$renderer3.push(`<!----></div></section> <aside class="settings-sidebar svelte-1gp6n77">`);
      Card($$renderer3, {
        title: "Setup Guide",
        children: ($$renderer4) => {
          Stepper($$renderer4, {
            steps: [
              { label: "Get API Key" },
              { label: "Find Device Token" },
              { label: "Test Connection" }
            ],
            currentStepIndex: apiKey.trim() && deviceToken.trim() ? 2 : apiKey.trim() ? 1 : 0,
            classes: "setup-stepper"
          });
        }
      });
      $$renderer3.push(`<!----> `);
      Card($$renderer3, {
        title: "Mobile App Setup",
        description: "Scan to connect your mobile app",
        children: ($$renderer4) => {
          $$renderer4.push(`<div class="qr-section svelte-1gp6n77">`);
          {
            $$renderer4.push("<!--[-1-->");
            if (qrDataUrl) {
              $$renderer4.push("<!--[0-->");
              $$renderer4.push(`<div class="qr-container svelte-1gp6n77"><img${attr("src", qrDataUrl)} alt="QR code for mobile app pairing" class="qr-image svelte-1gp6n77"/></div> <p class="qr-hint svelte-1gp6n77">Scan this QR code with the Shooter iOS or Android app to connect.</p> `);
              if (qrServerUrl) {
                $$renderer4.push("<!--[0-->");
                $$renderer4.push(`<p class="qr-server-url svelte-1gp6n77">Server: <code class="svelte-1gp6n77">${escape_html(qrServerUrl)}</code></p>`);
              } else {
                $$renderer4.push("<!--[-1-->");
              }
              $$renderer4.push(`<!--]-->`);
            } else if (qrLoading) {
              $$renderer4.push("<!--[1-->");
              $$renderer4.push(`<div class="qr-placeholder svelte-1gp6n77"><p class="qr-loading-text svelte-1gp6n77">Generating QR code...</p></div>`);
            } else if (qrError) {
              $$renderer4.push("<!--[2-->");
              $$renderer4.push(`<p class="qr-error svelte-1gp6n77">${escape_html(qrError)}</p>`);
            } else {
              $$renderer4.push("<!--[-1-->");
              $$renderer4.push(`<p class="qr-description svelte-1gp6n77">Generate a QR code containing your server URL and API key. Your mobile app can
                  scan it to auto-configure the connection.</p>`);
            }
            $$renderer4.push(`<!--]--> `);
            Button($$renderer4, {
              classes: "btn-secondary btn-sm",
              onclick: fetchQrCode,
              disabled: qrLoading || !apiKey.trim(),
              text: qrDataUrl ? "Regenerate QR Code" : "Generate QR Code"
            });
            $$renderer4.push(`<!---->`);
          }
          $$renderer4.push(`<!--]--></div>`);
        }
      });
      $$renderer3.push(`<!----> `);
      Card($$renderer3, {
        title: "Danger Zone",
        children: ($$renderer4) => {
          $$renderer4.push(`<p class="danger-description svelte-1gp6n77">Clear all saved configuration data from this device.</p> `);
          Button($$renderer4, {
            classes: "btn-danger btn-sm",
            onclick: clearConfiguration,
            text: "Clear Configuration"
          });
          $$renderer4.push(`<!---->`);
        }
      });
      $$renderer3.push(`<!----></aside></div></div></main>`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}

export { _page as default };
//# sourceMappingURL=_page.svelte-rTrWmhOp.js.map
