import '@shopify/ui-extensions/preact';
import { render } from "preact";

// Entry point: Renders the Extension component into the page body
export default async () => {
  render(<Extension />, document.body);
};

function Extension() {
  // 1. CONFIGURATION
  // This is your ngrok URL configured in .env
  const SERVER_URL = "https://conclude-party-paralyses.ngrok-free.dev";

  // --- DATA FETCHING ---
  // Grabs the Order ID robustly from the global shopify object
  // @ts-ignore
  let rawId = shopify.orderConfirmation?.value?.order?.id;
  if (!rawId) {
    // @ts-ignore
    rawId = shopify.order?.id?.value;
  }
  const orderId = rawId ? rawId.split('/').pop() : "order_id";

  // Get total amount, buyer email, and shop domain
  // @ts-ignore
  const amount = shopify.cost?.totalAmount?.value?.amount || "0.00";
  // @ts-ignore
  const email = shopify.buyerIdentity?.email?.value || shopify.order?.email?.value || "customer@example.com";
  // @ts-ignore
  const shopDomain = shopify.shop?.myshopifyDomain || "";

  // 2. CONSTRUCT PAYMENT LINK
  const paymentLink = `${SERVER_URL}/start-payment?order_id=${orderId}&amount=${amount}&email=${email}&shop=${shopDomain}`;

  console.log("DEBUG INTERAC BUTTON:", { orderId, amount, email, shopDomain, paymentLink });

  // 3. RENDER THE UI (Using Web Components)
  return (
    <s-banner heading="Complete Your Interac Payment" tone="warning">
      <s-stack gap="base">
        <s-text>
          Order <s-text>#{orderId}</s-text> has been placed.
        </s-text>
        <s-text>
          Please click the button below to complete your Interac e-Transfer.
        </s-text>
        <s-button href={paymentLink} variant="primary">
          Pay with Interac Now
        </s-button>
      </s-stack>
    </s-banner>
  );
}