import React from "react";
import Link from "next/link";
import pool from "@/lib/db";
import { ArrowRight, Flame, Truck, Award, Sparkles, ArrowUpRight, Clock, ShieldCheck, Leaf } from "lucide-react";
import { Promo, CommunityPost } from "@/types";
import { getSiteSettings } from "@/lib/settings";
import { BUSINESS_CONFIG, getWhatsAppUrl } from "@/config/business";

export default async function HomePage() {
  const settings = await getSiteSettings();
  let promos: Promo[] = [];
  let community: CommunityPost[] = [];

  try {
    if (settings.enable_promotions) {
      const [promoRows] = await pool.query(
        "SELECT * FROM promos WHERE is_active = 1 AND is_home = 1 ORDER BY id DESC LIMIT 6"
      );
      promos = (promoRows as any[]).map((r) => ({
        ...r,
        image: r.image?.startsWith("http") ? r.image : `/uploads/promos/${r.image}`
      }));
    }

    if (settings.enable_community) {
      const [communityRows] = await pool.query(
        "SELECT * FROM community WHERE is_active = 1 ORDER BY id DESC LIMIT 4"
      );
      community = (communityRows as any[]).map((r) => ({
        ...r,
        media: r.media?.startsWith("http") ? r.media : `/uploads/community/${r.media}`
      }));
    }
  } catch (err) {
    console.error("Error loading home data:", err);
  }

  const phone = process.env.NEXT_PUBLIC_WHATSAPP_NUMBER || "573001526282";

  return (
    <div className="space-y-32 md:space-y-44 pb-36 bg-[#F7F5F0]">
      {/* Overlapping Hero Section */}
      <section className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 pt-8 sm:pt-12">
        {/* Large Visual Photography Canvas */}
        <div className="relative h-[420px] sm:h-[500px] md:h-[580px] w-full rounded-[8px] overflow-hidden">
          <div
            className="absolute inset-0 bg-cover bg-center scale-100"
            style={{ backgroundImage: "url('/assets/pizza_hoven.webp')" }}
          />
          <div className="absolute inset-0 bg-gradient-to-t from-[#083F78]/80 via-[#083F78]/40 to-transparent" />
          
          <div className="absolute top-6 left-6 sm:top-8 sm:left-8">
            <span className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-[6px] text-xs font-black tracking-wider uppercase bg-[#67d2f2] text-[#083F78]">
              <Sparkles size={13} />
              <span>Pizzería 100% Artesanal • Horno Tipo Siciliano</span>
            </span>
          </div>
        </div>

        {/* Overlapping Architectural Content Card */}
        <div className="relative -mt-24 sm:-mt-32 md:-mt-40 z-20 max-w-4xl mx-auto bg-white border border-[#a1a39e]/25 p-8 sm:p-14 rounded-[8px]">
          <div className="space-y-6 text-center sm:text-left">
            <div className="space-y-3">
              <span className="text-xs font-bold tracking-widest uppercase text-[#a1a39e] block font-artisan-sans">
                Sector Galicia • Pereira, Risaralda
              </span>
              <h1 className="text-3xl sm:text-5xl md:text-6xl font-artisan-serif font-bold text-[#083F78] leading-[1.1] tracking-tight">
                El Arte del Fuego & la Masa Madre
              </h1>
            </div>

            <p className="text-sm sm:text-base text-[#2b394a]/85 leading-relaxed font-artisan-sans max-w-2xl">
              Harinas seleccionadas, 48 horas de fermentación lenta natural e ingredientes frescos de primera calidad. Horneadas en horno tipo siciliano sobre piedra con entregas directas en Galicia y Pereira.
            </p>

            {/* Action Group: Solid Warm Gold CTA + Deep Blue Ghost Button */}
            <div className="flex flex-col sm:flex-row items-center gap-3.5 pt-2">
              <Link
                href="/menu"
                className="w-full sm:w-auto inline-flex items-center justify-center gap-2 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black px-8 py-3.5 rounded-[8px] transition duration-150 text-xs sm:text-sm tracking-wider uppercase shadow-md shadow-[#ffc324]/20"
              >
                <span>Ver Menú & Carta</span>
                <ArrowRight size={16} />
              </Link>

              <a
                href={getWhatsAppUrl("¡Hola Sanlore Pizza! Deseo consultar la carta artesanal y pedir a domicilio en Pereira / Galicia 🍕")}
                target="_blank"
                rel="noopener noreferrer"
                className="w-full sm:w-auto inline-flex items-center justify-center gap-2 border border-[#083F78] text-[#083F78] hover:bg-[#ffc324]/10 hover:border-[#ffc324] font-bold px-7 py-3.5 rounded-[8px] transition duration-150 text-xs sm:text-sm tracking-wider uppercase"
              >
                <span>Pedir por WhatsApp</span>
                <ArrowUpRight size={16} />
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* Modern Bento Grid System - Asymmetric Block Layout */}
      <section className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 space-y-8">
        <div className="max-w-xl space-y-2">
          <span className="text-xs font-bold tracking-widest uppercase text-[#a1a39e] font-artisan-sans">
            Pilares de Calidad
          </span>
          <h2 className="text-2xl sm:text-4xl font-artisan-serif font-bold text-[#083F78]">
            Ingredientes Frescos & Proceso Artesanal
          </h2>
        </div>

        {/* Bento Grid Layout */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* Bento Card 1 (Span 2 columns): Sourdough Fermentation Story */}
          <div className="md:col-span-2 bg-white border border-[#a1a39e]/20 p-8 sm:p-12 rounded-[8px] flex flex-col justify-between space-y-6">
            <div className="space-y-4 max-w-xl">
              <span className="inline-block px-3 py-1 rounded-[6px] text-xs font-black bg-[#67d2f2]/20 text-[#083F78]">
                48 Horas de Maduración
              </span>
              <h3 className="text-2xl sm:text-3xl font-artisan-serif font-bold text-[#083F78]">
                Masa Madre & Fermentación Lenta
              </h3>
              <p className="text-xs sm:text-sm text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                Elaboramos nuestra masa mediante un proceso artesanal de fermentación lenta natural por 48 horas. Sin prisas, respetando los tiempos biológicos para lograr una masa ligera y de fácil digestión.
              </p>
            </div>

            <div className="pt-4 border-t border-[#a1a39e]/15 flex items-center gap-6 text-xs text-[#083F78] font-bold">
              <div className="flex items-center gap-2">
                <Clock size={16} className="text-[#67d2f2]" />
                <span>48h de Maduración</span>
              </div>
              <div className="flex items-center gap-2">
                <ShieldCheck size={16} className="text-[#67d2f2]" />
                <span>100% Sin Conservantes</span>
              </div>
            </div>
          </div>

          {/* Bento Card 2 (Span 1 column): Traditional Wood Oven */}
          <div className="bg-[#083F78] text-[#F7F5F0] p-8 sm:p-10 rounded-[8px] flex flex-col justify-between space-y-6">
            <div className="space-y-3">
              <div className="w-12 h-12 bg-white/10 rounded-[8px] flex items-center justify-center text-[#67d2f2]">
                <Flame size={24} />
              </div>
              <h3 className="text-xl sm:text-2xl font-artisan-serif font-bold text-white">
                Horno Tipo Siciliano
              </h3>
              <p className="text-xs text-[#F7F5F0]/80 leading-relaxed font-artisan-sans">
                Cocción precisa sobre piedra refractaria en horno tipo siciliano, sellando la frescura de los ingredientes y logrando un dorado artesanal perfecto.
              </p>
            </div>

            <div className="text-2xl font-mono font-bold text-[#67d2f2]">
              Horno <span className="text-xs text-white/70 font-sans font-normal">Tipo Siciliano</span>
            </div>
          </div>

          {/* Bento Card 3 (Span 1 column): Clean Ingredients */}
          <div className="bg-white border border-[#a1a39e]/20 p-8 sm:p-10 rounded-[8px] flex flex-col justify-between space-y-6">
            <div className="space-y-3">
              <div className="flex items-center gap-2 text-[#67d2f2]">
                <Leaf size={18} />
                <span className="text-xs font-bold uppercase tracking-wider text-[#a1a39e]">
                  Calidad de Origen
                </span>
              </div>
              <h3 className="text-xl sm:text-2xl font-artisan-serif font-bold text-[#083F78]">
                Ingredientes Frescos
              </h3>
              <p className="text-xs text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                Salsas de tomate maduro, quesos seleccionados y hierbas aromáticas frescas en cada porción.
              </p>
            </div>

            <div className="text-xs font-bold text-[#083F78] tracking-wider uppercase">
              Selección Diaria
            </div>
          </div>

          {/* Bento Card 4 (Span 2 columns): Fast Thermal Delivery */}
          <div className="md:col-span-2 bg-white border border-[#a1a39e]/20 p-8 sm:p-12 rounded-[8px] flex flex-col sm:flex-row items-center justify-between gap-6">
            <div className="space-y-3 max-w-lg">
              <div className="w-10 h-10 bg-[#67d2f2]/15 text-[#083F78] rounded-[8px] flex items-center justify-center">
                <Truck size={20} />
              </div>
              <h3 className="text-xl sm:text-2xl font-artisan-serif font-bold text-[#083F78]">
                Cobertura en Pereira y Galicia
              </h3>
              <p className="text-xs sm:text-sm text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                Empaques especializados que conservan el calor y el punto de la pizza recién salida del horno.
              </p>
            </div>

            <Link
              href="/contacto"
              className="shrink-0 inline-flex items-center gap-2 border border-[#083F78] text-[#083F78] hover:bg-[#083F78]/5 font-bold px-6 py-3 rounded-[8px] text-xs tracking-wider uppercase transition"
            >
              <span>Ver Cobertura</span>
              <ArrowRight size={14} />
            </Link>
          </div>
        </div>
      </section>

      {/* Featured Promos - Asymmetric Block Grid */}
      {settings.enable_promotions && promos.length > 0 && (
        <section className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 space-y-10">
          <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-[#a1a39e]/20 pb-6">
            <div>
              <span className="text-xs font-bold tracking-widest uppercase text-[#a1a39e] font-artisan-sans">
                Especialidades de la Casa
              </span>
              <h2 className="text-2xl sm:text-4xl font-artisan-serif font-bold text-[#083F78]">
                Promociones Destacadas
              </h2>
            </div>
            <Link
              href="/promos"
              className="text-xs font-bold tracking-wider uppercase text-[#083F78] hover:text-[#67d2f2] inline-flex items-center gap-1.5 transition"
            >
              <span>Ver todas las promos</span>
              <ArrowRight size={14} />
            </Link>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {promos.map((p) => {
              const promoUrl =
                p.link ||
                getWhatsAppUrl(`¡Hola Sanlore Pizza! Quiero pedir la promo "${p.title}" a domicilio en Pereira / Galicia.`);

              return (
                <div
                  key={p.id}
                  className="bg-white border border-[#a1a39e]/20 rounded-[8px] overflow-hidden flex flex-col justify-between group transition hover:border-[#a1a39e]/40"
                >
                  <div>
                    {p.image && (
                      <div className="h-60 overflow-hidden bg-[#F7F5F0]">
                        <img
                          src={p.image}
                          alt={p.title}
                          className="w-full h-full object-cover group-hover:scale-105 transition duration-500"
                        />
                      </div>
                    )}
                    <div className="p-7 space-y-3">
                      <div className="flex items-center justify-between gap-2">
                        <h3 className="font-artisan-serif font-bold text-[#083F78] text-xl">
                          {p.title}
                        </h3>
                        <span className="shrink-0 px-2.5 py-0.5 rounded-[4px] text-[10px] font-black bg-[#67d2f2]/20 text-[#083F78]">
                          Horno 450°
                        </span>
                      </div>
                      <p className="text-xs sm:text-sm text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                        {p.description}
                      </p>
                    </div>
                  </div>

                  <div className="p-7 pt-0">
                    <a
                      href={promoUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="w-full inline-flex items-center justify-center gap-2 bg-[#67d2f2] hover:bg-[#52cbe9] text-[#083F78] font-black py-3 rounded-[8px] text-xs uppercase tracking-wider transition"
                    >
                      <span>Pedir Promo por WhatsApp</span>
                      <ArrowUpRight size={14} />
                    </a>
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      )}

      {/* PromoCard Callout Banner */}
      {settings.enable_promocard && (
        <section className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12">
          <div className="bg-[#083F78] text-[#F7F5F0] rounded-[8px] p-8 sm:p-16 border border-white/10 flex flex-col lg:flex-row items-center justify-between gap-10">
            <div className="space-y-4 max-w-xl text-center lg:text-left">
              <span className="inline-flex items-center gap-2 px-3 py-1 rounded-[6px] text-xs font-black bg-[#67d2f2] text-[#083F78] uppercase tracking-wider">
                <Award size={14} />
                <span>Programa PromoCard</span>
              </span>
              <h2 className="text-3xl sm:text-5xl font-artisan-serif font-bold text-white tracking-tight leading-[1.15]">
                Tu décima pizza artesanal corre por nuestra cuenta.
              </h2>
              <p className="text-sm sm:text-base text-[#F7F5F0]/85 leading-relaxed font-artisan-sans">
                Sistema de lealtad directo por celular. Cada pedido suma sellos automáticos sin cupones ni aplicaciones de terceros.
              </p>
            </div>

            <div className="flex flex-col sm:flex-row gap-3.5 w-full lg:w-auto shrink-0">
              <Link
                href="/promocard"
                className="inline-flex items-center justify-center gap-2 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black px-8 py-4 rounded-[8px] text-xs sm:text-sm tracking-wider uppercase transition shadow-md shadow-[#ffc324]/20"
              >
                <span>Consultar Mis Puntos</span>
                <ArrowRight size={16} />
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* Community Moments */}
      {settings.enable_community && community.length > 0 && (
        <section className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 space-y-10">
          <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-[#a1a39e]/20 pb-6">
            <div className="space-y-1">
              <span className="text-xs font-bold tracking-widest uppercase text-[#a1a39e] font-artisan-sans">
                Comunidad Sanlore
              </span>
              <h2 className="text-2xl sm:text-4xl font-artisan-serif font-bold text-[#083F78]">
                Momentos Compartidos
              </h2>
            </div>
            <p className="text-xs text-[#2b394a]/70 font-artisan-sans max-w-xs">
              La experiencia de la auténtica mesa artesanal en Pereira y Galicia.
            </p>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {community.map((c) => (
              <div
                key={c.id}
                className="bg-white border border-[#a1a39e]/20 rounded-[8px] overflow-hidden group hover:border-[#a1a39e]/40 transition"
              >
                {c.media && (
                  <img
                    src={c.media}
                    alt={c.title}
                    className="w-full h-52 object-cover group-hover:scale-105 transition duration-500"
                  />
                )}
                <div className="p-6 space-y-1.5">
                  <h3 className="font-artisan-serif font-bold text-[#083F78] text-base">{c.title}</h3>
                  <p className="text-xs text-[#2b394a]/70 line-clamp-2 font-artisan-sans">{c.message}</p>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
