// App Proxy root: /apps/deal-of-the-hour
// Returns a full HTML storefront page showing the current deal.
import type { LoaderFunctionArgs } from "react-router";
import prisma from "../db.server";
import widgetCss from "../../extensions/deal-widget/assets/deal-widget.css?raw";
import widgetJs from "../../extensions/deal-widget/assets/deal-widget.js?raw";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  // Accept header check — if JSON is requested (widget JS), redirect to the data endpoint.
  const accept = request.headers.get("accept") ?? "";
  if (accept.includes("application/json") && !accept.includes("text/html")) {
    return Response.redirect(new URL("/apps/deal-of-the-hour/current-deal", request.url), 302);
  }

  // Resolve shop from the signed app proxy query params Shopify appends.
  const url = new URL(request.url);
  const shop = url.searchParams.get("shop") ?? "";

  // Load settings to get the proxy subpath (needed by the widget JS).
  let proxySubpath = "deal-of-the-hour";
  if (shop) {
    try {
      const settings = await prisma.appSettings.findUnique({ where: { shop } });
      if (settings) proxySubpath = "deal-of-the-hour";
    } catch { /* fall back */ }
  }

  const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Deal of the Hour</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    body {
      margin: 0;
      padding: 24px 16px 48px;
      background: #f9fafb;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    }
    .page-wrap {
      max-width: 860px;
      margin: 0 auto;
    }
    .page-header {
      text-align: center;
      margin-bottom: 32px;
    }
    .page-header h1 {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 8px;
      color: #202223;
    }
    .page-header p {
      font-size: 16px;
      color: #6d7175;
      margin: 0;
    }
    .no-deal {
      text-align: center;
      padding: 48px 24px;
      background: #fff;
      border-radius: 12px;
      border: 1px solid #e1e3e5;
      color: #6d7175;
      font-size: 16px;
    }
  </style>
</head>
<body>
  <div class="page-wrap">
    <div class="page-header">
      <h1>Deal of the Hour</h1>
      <p>A new deal every hour &mdash; while supplies last!</p>
    </div>

    <div
      id="doth-widget-page"
      class="doth-widget"
      data-block-id="page"
      data-proxy-subpath="${proxySubpath}"
      data-shop="${shop}"
      data-label-available="AVAILABLE"
      data-label-last="LAST"
      data-label-selling-fast="SELLING FAST!"
      data-label-sold-out="SOLD OUT"
      data-label-sold-slot="sold this deal slot"
      data-label-save="Save"
      data-label-urgency="* Stock is rapidly decreasing"
    >
      <div class="doth-skeleton" id="doth-skeleton-page">
        <div class="doth-skeleton__header">
          <div class="doth-skeleton__line doth-skeleton__line--title"></div>
          <div class="doth-skeleton__line doth-skeleton__line--subtitle"></div>
        </div>
        <div class="doth-skeleton__media"></div>
        <div class="doth-skeleton__info">
          <div class="doth-skeleton__line doth-skeleton__line--short"></div>
          <div class="doth-skeleton__line doth-skeleton__line--wide"></div>
          <div class="doth-skeleton__line doth-skeleton__line--medium"></div>
          <div class="doth-skeleton__line doth-skeleton__line--narrow"></div>
          <div class="doth-skeleton__line doth-skeleton__line--wide"></div>
          <div class="doth-skeleton__line doth-skeleton__line--btn"></div>
        </div>
      </div>
      <div class="doth-card" id="doth-content-page" style="display:none">
        <div class="doth-card__header">
          <h2 class="doth-section-title">Deal of the Hour</h2>
          <p class="doth-section-subtitle">A new deal every hour &mdash; while supplies last!</p>
        </div>
        <div class="doth-card__media">
          <div class="doth-live-pill"><span class="doth-live-dot"></span>LIVE DEAL</div>
          <a id="doth-img-link-page" href="#" class="doth-card__img-link">
            <img class="doth-card__img" id="doth-img-page" src="" alt="" loading="lazy" />
          </a>
        </div>
        <div class="doth-card__info">
          <span class="doth-discount-circle" id="doth-disc-circle-page" style="display:none"></span>
          <div class="doth-countdown-block">
            <div class="doth-countdown-block__label">OFFER ENDS IN</div>
            <div class="doth-countdown-block__digits" id="doth-timer-page">00 : 00 : 00</div>
          </div>
          <a class="doth-product-title" id="doth-name-page" href="#">--</a>
          <div class="doth-product-desc" id="doth-desc-page" style="display:none"></div>
          <div class="doth-inv" id="doth-inventory-page" style="display:none">
            <div class="doth-inv__header">
              <span class="doth-inv__count" id="doth-inv-count-page"></span>
              <span class="doth-inv__warning" id="doth-inv-warning-page" style="display:none"></span>
            </div>
            <div class="doth-inv__track">
              <div class="doth-inv__fill" id="doth-inv-bar-page" style="width:0%"></div>
            </div>
            <div class="doth-inv__sub" id="doth-inv-sub-page"></div>
          </div>
          <div class="doth-price-block">
            <div class="doth-price-block__label">YOUR DEAL PRICE</div>
            <div class="doth-price-block__row">
              <span class="doth-price-block__new" id="doth-price-new-page">--</span>
              <span class="doth-price-block__old" id="doth-price-old-page" style="display:none"></span>
            </div>
            <span class="doth-price-block__savings" id="doth-savings-page" style="display:none"></span>
          </div>
          <a class="doth-btn-cart" id="doth-btn-page" href="#">Add to Cart</a>
          <a class="doth-more-info" id="doth-more-info-page" href="#">More product information &rarr;</a>
        </div>
      </div>
      <div class="doth-upcoming" id="doth-upcoming-page" style="display:none">
        <div class="doth-upcoming__header">
          <span class="doth-upcoming__label">COMING UP NEXT</span>
          <span class="doth-upcoming__count-badge" id="doth-upcoming-count-page">0</span>
        </div>
        <div class="doth-upcoming__list" id="doth-upcoming-list-page"></div>
      </div>
      <div class="doth-empty" id="doth-empty-page" style="display:none">
        <p>No deal running right now. Check back soon!</p>
      </div>
    </div>
  </div>

  <style>${widgetCss}</style>
  <script>${widgetJs}</script>
</body>
</html>`;

  return new Response(html, {
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-store",
      "Access-Control-Allow-Origin": "*",
    },
  });
};
