import { Outlet, useLoaderData, useRouteError } from "react-router";
import { boundary } from "@shopify/shopify-app-react-router/server";
import { AppProvider } from "@shopify/shopify-app-react-router/react";
import { authenticate } from "../shopify.server";
import { useTawkTo } from "../hooks/useTawkTo";

// ─── Tawk.to widget credentials ───────────────────────────────────────────────
//
//  These are intentionally hardcoded — they are NOT secrets.
//  The widget script URL is publicly visible to anyone who inspects the page,
//  so there is nothing to protect here. No env vars needed.
//
//  Found in: dashboard.tawk.to → Administration → Chat Widget → embed snippet
//  URL format: https://embed.tawk.to/{PROPERTY_ID}/{WIDGET_ID}
//
const TAWK_PROPERTY_ID = "6a33ef88f29d791d4d81ad27";
const TAWK_WIDGET_ID   = "1jrddvc8r";

// ─── Loader ───────────────────────────────────────────────────────────────────

export const loader = async ({ request }) => {
  const { session } = await authenticate.admin(request);

  return {
    apiKey: process.env.SHOPIFY_API_KEY || "",
    // Pass the shop domain to the client so we can identify the merchant
    // in Tawk.to. The domain is not sensitive — it's the public store URL.
    shop: session.shop || null,
  };
};

// ─── Layout ───────────────────────────────────────────────────────────────────

export default function App() {
  const { apiKey, shop } = useLoaderData();

  // Load Tawk.to widget — only for authenticated merchants.
  // Visitor attributes tag each conversation with the shop domain so you
  // instantly know who you're talking to in the Tawk dashboard.
  useTawkTo(TAWK_PROPERTY_ID, TAWK_WIDGET_ID, {
    shop,
    // name and email are not available without an extra API call —
    // the shop domain alone is usually enough to identify the merchant.
    // Add them here later if you fetch merchant profile data in the loader.
  });

  return (
    <AppProvider embedded apiKey={apiKey}>
      <s-app-nav>
        <s-link href="/app" rel="home">Home</s-link>
      </s-app-nav>
      <Outlet />
    </AppProvider>
  );
}

// Shopify needs React Router to catch some thrown responses, so that their
// headers are included in the response.
export function ErrorBoundary() {
  return boundary.error(useRouteError());
}

export const headers = (headersArgs) => {
  return boundary.headers(headersArgs);
};