<svelte:options customElement="payment-widget" />

<script>import { Button } from "@requestnetwork/shared-components/button";
import Modal from "@requestnetwork/shared-components/modal.svelte";
import { onDestroy, onMount } from "svelte";
import CurrencySelector from "./components/currency-selector.svelte";
import PaymentComplete from "./components/payment-complete.svelte";
import PaymentConfirmation from "./components/payment-confirmation.svelte";
import PoweredBy from "@requestnetwork/shared-components/powered-by.svelte";
import { getSupportedCurrencies } from "./utils/currencies";
import { initWalletConnector } from "./utils/walletConnector";
export let sellerInfo;
export let productInfo;
export let amountInUSD;
export let supportedCurrencies;
export let sellerAddress = "";
export let persistRequest = true;
export let showRNBranding = true;
export let builderId = "";
export let onPaymentSuccess;
export let onError;
let web3Modal = null;
let currencyDetails;
let isCheckingConnection = false;
let selectedCurrency = null;
let connectionCheckInterval = null;
let currentPaymentStep = "currency";
$:
  currencyDetails = getSupportedCurrencies(supportedCurrencies);
$:
  isConnected = false;
$:
  isModalOpen = false;
$: {
  if (isModalOpen && !isConnected) {
    isModalOpen = false;
    currentPaymentStep = "currency";
  }
}
$: {
  if (!isModalOpen) {
    selectedCurrency = null;
    currentPaymentStep = "currency";
  }
}
async function checkConnectionStatus() {
  if (isCheckingConnection)
    return;
  isCheckingConnection = true;
  const modalConnected = web3Modal?.getIsConnected() ?? false;
  isConnected = modalConnected;
  isCheckingConnection = false;
}
function startConnectionCheck() {
  if (connectionCheckInterval)
    return;
  connectionCheckInterval = setInterval(checkConnectionStatus, 500);
}
function stopConnectionCheck() {
  if (connectionCheckInterval) {
    clearInterval(connectionCheckInterval);
    connectionCheckInterval = null;
  }
}
onMount(() => {
  web3Modal = initWalletConnector();
  if (web3Modal) {
    web3Modal.subscribeEvents(handleWeb3ModalEvents);
    startConnectionCheck();
  }
});
function handleWeb3ModalEvents(newEvent) {
  if (newEvent.data.event === "MODAL_LOADED") {
    checkWalletState();
  }
  if (newEvent.data.event === "CONNECT_SUCCESS") {
    checkWalletState();
    isConnected = true;
  } else if (newEvent.data.event === "DISCONNECT_SUCCESS") {
    checkWalletState();
  }
}
let scrollPosition = 0;
function toggleBodyScroll(isDisabled) {
  if (isDisabled) {
    scrollPosition = window.pageYOffset;
    document.body.style.overflow = "hidden";
    document.body.style.position = "fixed";
    document.body.style.top = `-${scrollPosition}px`;
    document.body.style.width = "100%";
  } else {
    document.body.style.removeProperty("overflow");
    document.body.style.removeProperty("position");
    document.body.style.removeProperty("top");
    document.body.style.removeProperty("width");
    window.scrollTo(0, scrollPosition);
  }
}
$:
  toggleBodyScroll(isModalOpen);
onDestroy(() => {
  stopConnectionCheck();
  toggleBodyScroll(false);
});
function checkWalletState() {
  isConnected = web3Modal?.getIsConnected() ?? false;
}
</script>

<section class="rn-payment-widget">
  <section class="rn-payment-widget-header">
    {#if sellerInfo?.logo || sellerInfo?.name}
      <div class="rn-payment-widget-header-seller-info">
        {#if sellerInfo.logo}
          <img src={sellerInfo.logo} alt="Seller logo" />
        {/if}
        <h2>{sellerInfo.name}</h2>
      </div>
    {/if}

    {#if productInfo?.name || productInfo?.description || productInfo?.image}
      <div class="rn-payment-widget-header-product-info">
        <div class="rn-payment-widget-header-product-info-body">
          <h2>{productInfo?.name}</h2>
          <span>{productInfo?.description}</span>
        </div>
        {#if productInfo.image}
          <img src={productInfo.image} alt="Product" />
        {/if}
      </div>
    {/if}

    <div class="rn-payment-widget-header-total">
      <span>TOTAL</span>
      <span>{amountInUSD} USD</span>
    </div>
  </section>

  <section class="rn-payment-widget-body">
    <h2>Pay with crypto</h2>
    <Button
      disabled={!amountInUSD ||
        !sellerAddress ||
        amountInUSD === 0 ||
        supportedCurrencies?.length === 0}
      on:click={() => {
        if (!isConnected) {
          web3Modal?.open();
        } else {
          isModalOpen = true;
        }
      }}>Pay</Button
    >
  </section>
  <Modal
    config={{}}
    title="Pay with crypto"
    isOpen={isModalOpen}
    onClose={() => {
      isModalOpen = false;
    }}
  >
    {#if currentPaymentStep === "currency"}
      <CurrencySelector
        {web3Modal}
        currencies={currencyDetails.currencies}
        bind:selectedCurrency
        bind:currentPaymentStep
        bind:isConnected
      />
    {:else if selectedCurrency && currentPaymentStep === "confirmation"}
      <PaymentConfirmation
        sellerName={sellerInfo.name}
        productName={productInfo.name}
        {amountInUSD}
        {sellerAddress}
        {web3Modal}
        {selectedCurrency}
        {persistRequest}
        {onPaymentSuccess}
        {builderId}
        onPaymentError={onError}
        bind:currentPaymentStep
        bind:isConnected
      />
    {:else}
      <PaymentComplete />
    {/if}
  </Modal>
</section>
{#if showRNBranding}
  <div class="rn-payment-widget-branding">
    <PoweredBy />
  </div>
{/if}

<style>@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800;900&display=swap");
body {
  font-family: "Montserrat", sans-serif;
}
h2 {
  padding: 0;
  margin: 0;
}
.rn-payment-widget {
  width: 530px;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #01503a 0%, #002b20 100%);
  border-radius: 20px;
  padding: 0;
}
.rn-payment-widget-branding {
  display: flex;
  justify-content: flex-end;
}
@media (max-width: 600px) {
  .rn-payment-widget {
    width: 100%;
  }
}
.rn-payment-widget-header {
  padding: 30px;
  display: flex;
  flex-direction: column;
  gap: 26px;
}
.rn-payment-widget-header-seller-info {
  display: flex;
  align-items: center;
  gap: 16px;
}
.rn-payment-widget-header-seller-info img {
  width: 46px;
  height: 46px;
  border-radius: 12px;
  object-fit: cover;
}
.rn-payment-widget-header-seller-info h2 {
  color: white;
  font-size: 16px;
  font-weight: 500;
}
.rn-payment-widget-header-product-info {
  display: flex;
  gap: 30px;
  align-items: center;
}
.rn-payment-widget-header-product-info-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 70%;
}
.rn-payment-widget-header-product-info-body h2 {
  color: white;
  font-size: 24px;
  font-weight: 500;
}
.rn-payment-widget-header-product-info-body span {
  color: #d9d9d9;
  font-size: 16px;
  font-weight: 400;
  word-wrap: break-word;
}
.rn-payment-widget-header-product-info img {
  width: 107px;
  height: 107px;
  border-radius: 12px;
  object-fit: cover;
}
.rn-payment-widget-header-total {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.rn-payment-widget-header-total span {
  color: white;
  font-size: 16px;
  font-weight: 500;
}
.rn-payment-widget-body {
  padding: 16px 30px 30px 30px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  gap: 34px;
  margin: 0;
  height: 100%;
  border-radius: 0px 0px 20px 20px;
}
.rn-payment-widget-body h2 {
  color: black;
  font-size: 20px;
  font-weight: 500;
}
:global(body.modal-open) {
  overflow: hidden;
}
:global(.modal-header) {
  padding: 16px !important;
}
:global(.modal-content) {
  padding: 16px !important;
}</style>
