"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { usePermission } from "@/hooks/usePermission";
import { useToast } from "@/lib/toast";

export default function EPaperGuard({ children }: { children: React.ReactNode }) {
  const { isGuest, isPremium } = usePermission();
  const router = useRouter();
  const { error: showError } = useToast();

  useEffect(() => {
    if (isGuest) {
      showError("Sign in to access the e-paper");
      router.replace("/login");
    } else if (!isPremium) {
      showError("Subscribe to access the daily e-paper");
      router.replace("/subscribe");
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isGuest, isPremium]);

  if (isGuest || !isPremium) {
    return (
      <div style={{ minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg, #f8f9fb)" }}>
        <div style={{ textAlign: "center", padding: "2rem" }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "rgba(193,39,45,0.08)", border: "1.5px solid rgba(193,39,45,0.2)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 1rem" }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--brand, #C1272D)" strokeWidth="2" strokeLinecap="round">
              <rect x="3" y="11" width="18" height="11" rx="2" />
              <path d="M7 11V7a5 5 0 0 1 10 0v4" />
            </svg>
          </div>
          <p style={{ fontWeight: 700, color: "var(--ink, #0e0e11)", marginBottom: "0.25rem" }}>
            {isGuest ? "Sign in required" : "Premium required"}
          </p>
          <p style={{ fontSize: "0.875rem", color: "var(--text-2, #6b7280)" }}>Redirecting…</p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
