"use client";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { fetchStorefrontInfo, StorefrontInfo } from "./_lib/storeApiCalls";
import { useCart } from "./_lib/useCart";
import { useCustomerAuth } from "./_lib/useCustomerAuth";

export default function StoreLayout({ children }: { children: React.ReactNode }) {
  const params = useParams<{ orgSlug: string }>();
  const orgSlug = params.orgSlug;
  const [info, setInfo] = useState<StorefrontInfo | null>(null);
  const [notFound, setNotFound] = useState(false);
  const { itemCount } = useCart(orgSlug);
  const { customer, isLoggedIn, logout } = useCustomerAuth(orgSlug);

  useEffect(() => {
    fetchStorefrontInfo(orgSlug)
      .then(setInfo)
      .catch(() => setNotFound(true));
  }, [orgSlug]);

  if (notFound) {
    return (
      <div className="d-flex flex-column align-items-center justify-content-center" style={{ minHeight: "100vh" }}>
        <span className="fa-solid fa-shop-slash fs-1 text-body-tertiary mb-3" />
        <h3>Store not found</h3>
        <p className="text-body-tertiary">This store link doesn&apos;t exist or is no longer public.</p>
      </div>
    );
  }

  return (
    <div className="d-flex flex-column" style={{ minHeight: "100vh", background: "var(--phoenix-body-bg, #f9fafd)" }}>
      {info?.banner_text && (
        <div className="bg-primary text-white text-center py-1 small">{info.banner_text}</div>
      )}

      <header className="bg-white border-bottom sticky-top">
        <div className="container py-3 d-flex align-items-center gap-4 flex-wrap">
          <Link href={`/${orgSlug}`} className="d-flex align-items-center gap-2 text-decoration-none text-dark">
            {info?.logo_url ? (
              <img src={info.logo_url} alt={info.store_name} height={36} />
            ) : (
              <span className="fa-solid fa-shop fs-3 text-primary" />
            )}
            <span className="fw-bold fs-5">{info?.store_name ?? "Loading..."}</span>
          </Link>

          <div className="ms-auto d-flex align-items-center gap-3">
            <Link href={`/${orgSlug}/track`} className="text-decoration-none small text-body-secondary">
              <span className="fa-solid fa-truck-fast me-1" />Track Order
            </Link>

            {isLoggedIn ? (
              <div className="dropdown">
                <button className="btn btn-sm btn-subtle-secondary dropdown-toggle" data-bs-toggle="dropdown">
                  <span className="fa-solid fa-user me-1" />{customer?.name?.split(" ")[0]}
                </button>
                <ul className="dropdown-menu dropdown-menu-end">
                  <li><Link className="dropdown-item" href={`/${orgSlug}/account/orders`}>My Orders</Link></li>
                  <li><button className="dropdown-item" onClick={logout}>Log Out</button></li>
                </ul>
              </div>
            ) : (
              <Link href={`/${orgSlug}/account/login`} className="btn btn-sm btn-subtle-secondary">
                <span className="fa-solid fa-user me-1" />Sign In
              </Link>
            )}

            <Link href={`/${orgSlug}/cart`} className="btn btn-sm btn-primary position-relative">
              <span className="fa-solid fa-cart-shopping me-1" />Cart
              {itemCount > 0 && (
                <span className="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                  {itemCount}
                </span>
              )}
            </Link>
          </div>
        </div>
      </header>

      <main className="flex-grow-1">
        <div className="container py-4">{children}</div>
      </main>

      <footer className="bg-white border-top py-4 mt-5">
        <div className="container d-flex flex-wrap justify-content-between gap-3 small text-body-tertiary">
          <span>&copy; {new Date().getFullYear()} {info?.store_name ?? ""}. All rights reserved.</span>
          {(info?.contact_email || info?.contact_phone) && (
            <span>
              {info?.contact_email && <span className="me-3"><span className="fa-solid fa-envelope me-1" />{info.contact_email}</span>}
              {info?.contact_phone && <span><span className="fa-solid fa-phone me-1" />{info.contact_phone}</span>}
            </span>
          )}
        </div>
      </footer>
    </div>
  );
}
