"use client";

import { useEffect, useState } from "react";

/**
 * Blocks the merchant admin when it's opened OUTSIDE Shopify (a plain browser
 * visit to /admin). Real access is only inside the embedded Shopify admin,
 * where App Bridge issues a session token. The backend also rejects tokenless
 * admin API calls (401) — this is the matching, friendlier front door.
 *
 * localhost is allowed so local development keeps working.
 */
export function AdminGate({ children }: { children: React.ReactNode }) {
  const [allowed, setAllowed] = useState<boolean | null>(null);

  useEffect(() => {
    const p = new URLSearchParams(window.location.search);
    const isLocal = ["localhost", "127.0.0.1"].includes(window.location.hostname);
    let demo = false;
    try {
      demo = p.get("demo") === "1" || sessionStorage.getItem("tk_demo") === "1";
    } catch {
      /* ignore */
    }
    const embedded = isLocal || demo || p.has("host") || p.has("shop") || window.top !== window.self;
    setAllowed(embedded);
  }, []);

  if (allowed === null) return null; // avoid a flash before we know
  if (allowed) return <>{children}</>;

  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: "2rem", background: "#f8fafc" }}>
      <div style={{ maxWidth: 460, textAlign: "center" }}>
        <h1 style={{ fontSize: "1.35rem", fontWeight: 700, color: "#0f172a", marginBottom: 12 }}>
          Open this from your Shopify admin
        </h1>
        <p style={{ color: "#475569", lineHeight: 1.6 }}>
          The merchant dashboard runs inside Shopify. Go to your store admin →{" "}
          <strong>Apps</strong> → <strong>Trackopia</strong> to open it. For security, it
          can’t be accessed directly here.
        </p>
      </div>
    </div>
  );
}
