import Link from "next/link";
import { asc, eq } from "drizzle-orm";
import { db } from "@/db";
import { announcements } from "@/db/schema";
import { getCategories, getSettings } from "@/lib/data";
import { Logo } from "@/components/Logo";
import { CartProvider, CartCount, WishCount, SearchBar, MobileMenu, Announcements, Reveal } from "@/components/store";

const services = [
  { href: "/page/pharmacy-retailing", label: "Pharmacy Retailing" },
  { href: "/page/home-delivery", label: "Home Delivery" },
  { href: "/page/online-pharmacy", label: "My Family Online Pharmacy" },
  { href: "/page/teleconsultation", label: "My Family Teleconsultation" },
  { href: "/prescription", label: "Prescription Upload" },
  { href: "/consultation", label: "Consultation Booking" },
];

export default async function StoreLayout({ children }: { children: React.ReactNode }) {
  const [s, cats, anns] = await Promise.all([getSettings(), getCategories(), db.select().from(announcements).where(eq(announcements.active, true)).orderBy(asc(announcements.sortOrder))]);
  if (s.maintenance) {
    return <div className="min-h-screen grid place-items-center p-8 text-center"><div><Logo /><h1 className="text-2xl font-bold mt-6">We&apos;ll be back shortly</h1><p className="text-slate-500 mt-2">Our website is under scheduled maintenance. Call {s.phones.join(" / ")}.</p></div></div>;
  }
  const wa = "256" + s.whatsapp.replace(/^0/, "");
  const mobileLinks = [{ href: "/", label: "Home" }, { href: "/shop", label: "Shop All Products" }, { href: "/categories", label: "Shop by Category" }, { href: "/shop?offers=1", label: "Offers" }, ...services, { href: "/track", label: "Track Order" }, { href: "/blog", label: "Health Blog" }, { href: "/page/about-us", label: "About Us" }, { href: "/contact", label: "Contact" }, { href: "/account", label: "My Account" }];
  return (
    <CartProvider>
      <Announcements items={anns.map((a) => a.text)} />
      <header className="sticky top-0 z-50 bg-white/95 backdrop-blur border-b border-slate-100">
        <div className="container-x flex items-center gap-4 lg:gap-8 py-3">
          <Link href="/" className="shrink-0"><Logo /></Link>
          <div className="hidden md:flex flex-1"><SearchBar categories={cats} /></div>
          <div className="flex items-center gap-1 sm:gap-2 ml-auto">
            <Link href="/account" className="w-10 h-10 grid place-items-center rounded-full hover:bg-cloud" aria-label="Account"><svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="8" r="4" /><path d="M4 21c1-4 4.5-6 8-6s7 2 8 6" /></svg></Link>
            <Link href="/wishlist" className="relative w-10 h-10 grid place-items-center rounded-full hover:bg-cloud" aria-label="Wishlist"><svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6C19 16.5 12 21 12 21z" /></svg><WishCount /></Link>
            <Link href="/cart" className="relative w-10 h-10 grid place-items-center rounded-full bg-mint text-brand" aria-label="Cart"><svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6h15l-1.5 9h-12z M6 6 5 3H2" /><circle cx="9" cy="20" r="1.3" /><circle cx="18" cy="20" r="1.3" /></svg><CartCount /></Link>
            <MobileMenu links={mobileLinks} />
          </div>
        </div>
        <div className="md:hidden container-x pb-3"><SearchBar categories={cats} /></div>
        <nav className="hidden lg:block border-t border-slate-100">
          <div className="container-x flex items-center gap-7 text-sm font-semibold h-12">
            <div className="relative group">
              <button className="flex items-center gap-2 bg-brand text-white px-4 h-9 rounded-full">☰ Shop by Category ▾</button>
              <div className="absolute left-0 top-full pt-2 hidden group-hover:block">
                <div className="card p-2 w-72 anim-fade">{cats.map((c) => <Link key={c.id} href={`/category/${c.slug}`} className="block px-3 py-2 rounded-lg hover:bg-mint hover:text-brand">{c.name}</Link>)}</div>
              </div>
            </div>
            <Link href="/" className="hover:text-brand">Home</Link>
            <Link href="/shop" className="hover:text-brand">Shop</Link>
            <div className="relative group">
              <button className="hover:text-brand h-12">Services ▾</button>
              <div className="absolute left-0 top-full hidden group-hover:block"><div className="card p-2 w-72 anim-fade">{services.map((l) => <Link key={l.href} href={l.href} className="block px-3 py-2 rounded-lg hover:bg-mint hover:text-brand">{l.label}</Link>)}</div></div>
            </div>
            <Link href="/shop?offers=1" className="hover:text-brand">Offers</Link>
            <Link href="/blog" className="hover:text-brand">Health Blog</Link>
            <Link href="/page/about-us" className="hover:text-brand">About Us</Link>
            <Link href="/contact" className="hover:text-brand">Contact</Link>
            <Link href="/track" className="ml-auto text-royal hover:text-brand">Track Order</Link>
            <a href={`tel:${s.phones[0]}`} className="text-brand">📞 {s.phones[0]}</a>
          </div>
        </nav>
      </header>
      <main className="min-h-[60vh]">{children}</main>
      <Reveal />
      <footer className="mt-20 bg-cloud border-t">
        <div className="container-x py-14 grid gap-10 sm:grid-cols-2 lg:grid-cols-5">
          <div className="lg:col-span-2">
            <Logo />
            <p className="mt-4 text-sm text-slate-600 max-w-sm">{s.tagline} Quality healthcare products, professional advice and convenient delivery for families across Uganda.</p>
            <div className="flex gap-3 mt-5">
              <a href={s.facebook} target="_blank" rel="noopener" className="w-10 h-10 rounded-full bg-[#1877F2] text-white grid place-items-center font-bold hover:scale-110 transition" aria-label="Facebook">f</a>
              <a href={s.tiktok} target="_blank" rel="noopener" className="w-10 h-10 rounded-full bg-black text-white grid place-items-center hover:scale-110 transition" aria-label="TikTok"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M16 3c.3 2.3 1.8 4 4 4.2v3.2c-1.5 0-2.9-.4-4-1.2v6.3A5.5 5.5 0 1 1 10.5 10v3.3a2.3 2.3 0 1 0 2.3 2.3V3H16z" /></svg></a>
              <a href={`https://wa.me/${wa}`} target="_blank" rel="noopener" className="w-10 h-10 rounded-full bg-[#25D366] text-white grid place-items-center hover:scale-110 transition" aria-label="WhatsApp">✆</a>
            </div>
          </div>
          <div><h4 className="font-bold mb-4">Shop</h4><ul className="space-y-2 text-sm text-slate-600">{cats.slice(0, 6).map((c) => <li key={c.id}><Link href={`/category/${c.slug}`} className="hover:text-brand">{c.name}</Link></li>)}</ul></div>
          <div><h4 className="font-bold mb-4">Help</h4><ul className="space-y-2 text-sm text-slate-600">
            {[["/track", "Track Order"], ["/page/faq", "FAQ"], ["/page/shipping-policy", "Shipping & Delivery"], ["/page/returns-policy", "Returns & Refunds"], ["/page/privacy-policy", "Privacy Policy"], ["/page/terms", "Terms & Conditions"], ["/rewards", "Rewards & Loyalty"]].map(([h, l]) => <li key={h}><Link href={h} className="hover:text-brand">{l}</Link></li>)}
          </ul></div>
          <div><h4 className="font-bold mb-4">Contact</h4><ul className="space-y-2 text-sm text-slate-600">
            <li>{s.address}</li>
            <li>{s.phones.map((p) => <a key={p} href={`tel:${p}`} className="block hover:text-brand">📞 {p}</a>)}</li>
            <li><a href={`https://wa.me/${wa}`} className="hover:text-brand">WhatsApp: {s.whatsapp}</a></li>
            <li><a href={`mailto:${s.email}`} className="hover:text-brand break-all">{s.email}</a></li>
            <li className="whitespace-pre-line text-xs">{s.hours}</li>
          </ul></div>
        </div>
        <div className="border-t py-5 text-center text-xs text-slate-500">© {new Date().getFullYear()} {s.siteName}. All rights reserved. Prescription medicines are dispensed only after verification by a licensed pharmacist.</div>
      </footer>
      <a href={`https://wa.me/${wa}`} target="_blank" rel="noopener" aria-label="Chat on WhatsApp" className="fixed bottom-5 right-5 z-50 w-14 h-14 rounded-full bg-[#25D366] text-white grid place-items-center shadow-xl hover:scale-110 transition no-print">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 0 0-8.6 15.1L2 22l5-1.3A10 10 0 1 0 12 2zm5.3 14.2c-.2.6-1.3 1.2-1.8 1.2-.5.1-1 .2-3.3-.7-2.8-1.1-4.5-4-4.7-4.2-.1-.2-1.1-1.5-1.1-2.9s.7-2 1-2.3c.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.9 2.1c.1.2.1.4 0 .5l-.3.5-.4.4c-.1.1-.3.3-.1.6.2.3.8 1.3 1.7 2.1 1.2 1 2.1 1.3 2.4 1.5.3.1.5.1.6-.1l.9-1c.2-.3.4-.2.6-.1l2 .9c.3.2.5.2.5.4.1.1.1.7-.1 1.3z" /></svg>
      </a>
    </CartProvider>
  );
}
