import type { Metadata } from "next";
import CatalogAnalyticsTracker from "@/components/CatalogAnalyticsTracker";
import { clienteDoServidor } from "@/lib/supabase-admin";
import { lerVisaoDaLoja, clienteParaAsTelas, enderecoDeLogin } from "@/lib/loja/visao.server";
import { estaEsgotado, semEsgotados, semPrecos, semPrecosNaLista, semPrecosNosStories } from "@/lib/loja/regras-da-loja";
import { notFound, redirect } from "next/navigation";
import StoreLayout from "@/components/StoreLayout";
import FontesDaLoja from "@/components/FontesDaLoja";
import { miniatura, produtoComFotoMenor, storiesComFotoMenor, TAMANHO } from "@/lib/foto";
import StoreContent from "@/components/StoreContent";
import { VendorShell } from "@/templates/vendor/VendorShell";
import { aparenciaDoVendor } from "@/templates/vendor/aparencia";
import { VendorHome } from "@/templates/vendor/VendorHome";
import { BoutiqueShell } from "@/templates/boutique/BoutiqueShell";
import { aparenciaDaBoutique } from "@/templates/boutique/aparencia";
import { BoutiqueListagem } from "@/templates/boutique/BoutiqueListagem";
import { buildCatalogMetadata } from "@/lib/catalog-metadata";
import { normalizeStoriesGroups } from "@/lib/catalog-stories";
import { caracteristicasDe, carregarLoja } from "@/lib/loja/dados-da-loja";
import { resolveCatalogAppearance } from "@/lib/catalog-appearance";
import { ProvedorDaNavegacao } from "@/components/navegacao/ContextoDaNavegacao";
import { secoesNoAr } from "@/lib/exibicao-da-secao";

export const revalidate = 0;
export const dynamic = "force-dynamic";

type CatalogProduct = {
  id: string;
  name: string;
  price: number;
  image_url?: string | null;
  stock: number;
  unit_type?: string | null;
  price_on_request?: boolean | null;
  min_sale_qty_enabled?: boolean | null;
  min_sale_qty?: number | null;
  max_sale_qty_enabled?: boolean | null;
  max_sale_qty?: number | null;
  allowed_sale_qty_enabled?: boolean | null;
  allowed_sale_quantities?: number[] | null;
  product_price_tiers?: Array<{
    min_qty: number;
    max_qty: number | null;
    unit_price: number;
    sort_order?: number | null;
    active?: boolean | null;
  }>;
  product_attributes?: Array<{ id: string; show_in_store?: boolean | null }>;
  has_variations?: boolean;
};

type CatalogSectionProduct = {
  section_id: string;
  product: CatalogProduct | null;
};
const LEGACY_CONFIG_PREFIX = "[[KTCFG:";
const LEGACY_CONFIG_SUFFIX = "]]";

function normalizeSectionConfig(config: unknown): Record<string, unknown> | null {
  if (config && typeof config === "object") return config as Record<string, unknown>;
  if (typeof config === "string") {
    try {
      const parsed = JSON.parse(config);
      return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
    } catch {
      return null;
    }
  }
  return null;
}

function extractLegacySectionMetadata(rawTitle: string) {
  const title = String(rawTitle || "");
  const start = title.indexOf(LEGACY_CONFIG_PREFIX);
  if (start === -1) return { title, legacyConfig: {} as Record<string, unknown> };
  const end = title.indexOf(LEGACY_CONFIG_SUFFIX, start + LEGACY_CONFIG_PREFIX.length);
  if (end === -1) return { title, legacyConfig: {} as Record<string, unknown> };
  const encoded = title.slice(start + LEGACY_CONFIG_PREFIX.length, end);
  const cleanTitle = `${title.slice(0, start)}${title.slice(end + LEGACY_CONFIG_SUFFIX.length)}`.trim();
  try {
    const parsed = JSON.parse(decodeURIComponent(encoded));
    if (parsed && typeof parsed === "object") return { title: cleanTitle, legacyConfig: parsed as Record<string, unknown> };
  } catch {}
  return { title: cleanTitle, legacyConfig: {} as Record<string, unknown> };
}

export async function generateMetadata(
  props: { params: Promise<{ slug: string; categorySlug: string }> }
): Promise<Metadata> {
  const params = await props.params;
  const { slug, categorySlug } = params;
  const dados = await carregarLoja(slug);
  const profile = dados?.profile;

  if (!profile) {
    return { title: "Loja" };
  }

  const category = (dados?.categories || []).find((c: { slug?: string | null }) => c.slug === categorySlug) ?? null;

  const baseTitle = profile.catalog_name || profile.store_name || "Loja";
  const pageTitle = category?.name ? `${category.name} | ${baseTitle}` : baseTitle;
  return buildCatalogMetadata({
    profile,
    pageTitle,
    pageDescription: category?.name
      ? `Explore os produtos da categoria ${category.name} em ${baseTitle}.`
      : `Explore os produtos de ${baseTitle}.`,
    path: `/c/${categorySlug}`,
  });
}

export default async function StoreCategoryPage(props: {
  params: Promise<{ slug: string; categorySlug: string }>;
  searchParams?: Promise<{ tema?: string }>;
}) {
  const params = await props.params;
  const buscados = props.searchParams ? await props.searchParams : undefined;
  const { slug, categorySlug } = params;
  /* Pelo servidor (chave de servico), como a busca: os destaques trazem o
     produto junto, e o visitante nao le produto pela API desde a migration 160. */
  const supabase = clienteDoServidor();

  /* A loja inteira, lembrada por dois minutos (lib/loja/dados-da-loja.ts). A
     categoria vem da mesma lembrança: nada de ir ao banco de novo por ela. */
  const dados = await carregarLoja(slug);
  const profile = dados?.profile;

  if (!dados || !profile) {
    return notFound();
  }

  const selectedCategory =
    (dados.categories || []).find((c: { slug?: string | null }) => c.slug === categorySlug) ?? null;

  if (!selectedCategory) {
    return notFound();
  }

  /* Quem esta olhando e o que as regras da loja deixam ver. Loja fechada
     manda para a home, que mostra o recado; loja so para clientes manda
     para o login. */
  const { visao, cliente: clienteDoPortal } = await lerVisaoDaLoja(slug, profile);
  if (visao.lojaFechada) redirect(`/${slug}`);
  if (visao.exigeLoginNaLoja) redirect(enderecoDeLogin(slug, `/${slug}/c/${categorySlug}`));
  const semPreco = !visao.mostrarPreco;

  const esconderEsgotados = visao.regras.esgotado === "hide";
  const listaDaLoja = esconderEsgotados ? semEsgotados(dados.products) : dados.products || [];
  const products = (semPreco ? semPrecosNaLista(listaDaLoja) : listaDaLoja).map((p) => produtoComFotoMenor(p, TAMANHO.card));
  const categories = dados.categories || [];
  /* A seção agendada fora da janela não sai (decidido agora, lib/exibicao-da-secao.ts). */
  const sectionsData = secoesNoAr(dados.sections || [], Date.now());
  const sectionProducts = (dados.sectionProducts || []) as CatalogSectionProduct[];

  const sections = sectionsData?.map((section) => {
    const normalizedConfig = normalizeSectionConfig((section as { config?: unknown }).config);
    const metadata = extractLegacySectionMetadata((section as { title?: string }).title || "");
    const mergedConfig = { ...(metadata.legacyConfig || {}), ...(normalizedConfig || {}) };
    const configMode =
      mergedConfig &&
      "mode" in mergedConfig
        ? mergedConfig.mode
        : undefined;
    const sectionType = configMode ?? section.section_type ?? (section as { type?: unknown }).type;
    return {
      ...section,
      title: metadata.title,
      config: mergedConfig,
      section_type: (
        sectionType === "all_products" ||
        sectionType === "category_products" ||
        sectionType === "subcategory_products" ||
        sectionType === "image_banner" ||
        sectionType === "category_navigator"
          ? sectionType
          : "manual_products"
      ) as "manual_products" | "all_products" | "category_products" | "subcategory_products" | "image_banner" | "category_navigator",
      products: sectionProducts
        .filter((sp) => sp.section_id === section.id)
        .map((sp) => {
          const product = sp.product;
          if (!product) return null;
          if (esconderEsgotados && estaEsgotado(product)) return null;
          return produtoComFotoMenor({
            ...(semPreco ? semPrecos(product) : product),
            has_variations:
              Array.isArray(product.product_attributes) &&
              product.product_attributes.some((atributo: { show_in_store?: boolean | null }) => atributo?.show_in_store !== false),
          }, TAMANHO.card);
        })
        .filter(Boolean) || [],
    };
  }) || [];

  const slideEnabled = false;
  const infoStripEnabledRaw = (profile as { catalog_info_strip_enabled?: boolean | null } | null)?.catalog_info_strip_enabled;
  const infoStripEnabled = infoStripEnabledRaw === null || infoStripEnabledRaw === undefined ? true : Boolean(infoStripEnabledRaw);
  const infoStripItemsRaw = (profile as { catalog_info_strip_items?: unknown } | null)?.catalog_info_strip_items;
  const infoStripItems = Array.isArray(infoStripItemsRaw)
    ? (infoStripItemsRaw as Array<{ icon?: unknown; title?: unknown; subtitle?: unknown }>).map((x) => ({
        icon: typeof x?.icon === "string" ? x.icon : "truck",
        title: typeof x?.title === "string" ? x.title : "",
        subtitle: typeof x?.subtitle === "string" ? x.subtitle : "",
      }))
    : [];

  const banners = slideEnabled
    ? (() => {
        return supabase
          .from("catalog_banners")
          .select("id,image_url,link_type,product_id,link_url,open_in_new_tab,position,created_at")
          .eq("user_id", profile.id)
          .eq("type", "slide")
          .eq("active", true)
          .order("position", { ascending: true })
          .order("created_at", { ascending: true });
      })()
    : null;

  const bannersResult = banners ? await banners : { data: [], error: null };
  const resolvedBanners = bannersResult.error
    ? []
    : (bannersResult.data || []).map((banner) => ({ ...banner, image_url: miniatura(banner.image_url, TAMANHO.banner) }));

  const selectedAnnouncementCoupon = profile.catalog_announcement_coupon_id
    ? await supabase
        .from("catalog_coupons")
        .select("id,code,type,value,active,starts_at,ends_at")
        .eq("id", profile.catalog_announcement_coupon_id)
        .eq("user_id", profile.id)
        .maybeSingle()
        .then((res) => res.data)
    : null;

  const { data: storiesGroupsData } = await supabase
    .from("catalog_story_groups")
    .select("id,title,thumbnail_url,position,items:catalog_story_items(id,image_url,product_id,position,product:products(id,name,price,price_on_request,image_url))")
    .eq("user_id", profile.id)
    .eq("active", true)
    .order("position", { ascending: true });

  const primaryColor = profile.primary_color || "#4F46E5";
  const storeName = profile.catalog_name || profile.store_name || "Loja";
  const logoUrl = miniatura(profile.catalog_logo_url || profile.logo_url, TAMANHO.logo);
  const storiesGroups = storiesComFotoMenor(
    normalizeStoriesGroups(semPreco ? semPrecosNosStories(storiesGroupsData || []) : storiesGroupsData)
  );

  /* No Vendor a página de categoria é uma grade só, então a filtragem que o
     outro template faz na tela precisa acontecer aqui: a categoria escolhida
     mais as filhas dela. */
  const idsDaCategoria = new Set<string>([selectedCategory.id]);
  for (const categoria of (categories || []) as Array<{ id: string; parent_id?: string | null }>) {
    if (categoria.parent_id === selectedCategory.id) idsDaCategoria.add(categoria.id);
  }
  const produtosDaCategoria = ((products || []) as Array<{ category_id?: string | null }>).filter((produto) =>
    produto.category_id ? idsDaCategoria.has(produto.category_id) : false
  );

  /* As mesmas cores e fontes da home: sem isso o cabeçalho cai na cor da marca. */
  const aparencia = resolveCatalogAppearance(profile);

  /* `?tema=` só existe fora de produção, como na home e no produto: abre a
     MESMA categoria em outro template para comparar lado a lado. Na loja
     publicada vale o perfil. */
  const temaPedido = String(buscados?.tema || "").trim();
  const temaDaPagina =
    process.env.NODE_ENV !== "production" && ["vendor", "vitrine", "default", "boutique"].includes(temaPedido)
      ? temaPedido
      : profile.catalog_theme;

  /* A Boutique tem a árvore dela (templates/boutique), com a mesma conta do
     Vendor. Diferente do Vendor, passa quem está logado ao shell (o Vendor
     mostra "Entrar" para quem já entrou: lacuna 1.6.3 do PARIDADE). */
  if (temaDaPagina === "boutique") {
    return (
      <StoreLayout
        primaryColor={primaryColor}
        whatsappNumber={profile.whatsapp}
        cartScope={profile.id || slug}
        storeSlug={slug}
        theme={temaDaPagina}
        chatLigado={profile.store_chat_enabled === true}
        visao={visao}
      >
        <FontesDaLoja perfil={profile} />
        <>
        <CatalogAnalyticsTracker
          slug={slug}
          eventName="page_view"
          categoryId={selectedCategory.id}
          onceKey={`page_view:categoria:${selectedCategory.id}`}
        />
        <CatalogAnalyticsTracker
          slug={slug}
          eventName="category_click"
          categoryId={selectedCategory.id}
          onceKey={`category_click:${selectedCategory.id}`}
        />
        {/* O menu e o rodapé publicados no editor (null = os de sempre). */}
        <ProvedorDaNavegacao navegacao={dados.navegacao}>
        <BoutiqueShell
          slug={slug}
          nomeDaLoja={storeName}
          slogan={profile.catalog_slogan}
          logoUrl={logoUrl}
          corDaMarca={primaryColor}
          aparencia={aparenciaDaBoutique(profile as never)}
          cupomDoAviso={selectedAnnouncementCoupon as never}
          whatsappFlutuante={profile.catalog_whatsapp_float}
          categoriaAtual={selectedCategory.id}
          categorias={(categories || []) as never[]}
          contato={{
            whatsapp: profile.whatsapp,
            telefone: profile.company_phone || profile.phone,
            email: profile.email,
            endereco: profile.catalog_footer_address || profile.address,
            cnpj: profile.catalog_show_document ? profile.cnpj : null,
            instagram: profile.social_instagram,
            facebook: profile.social_facebook,
          }}
          clienteLogado={Boolean(clienteDoPortal)}
        >
          {/* A listagem da Boutique (filtros, ordem e páginas na tela: a
              página entrega todos os produtos da categoria e das filhas). */}
          <BoutiqueListagem
            slug={slug}
            produtos={produtosDaCategoria as never[]}
            categorias={(categories || []) as never[]}
            categoriaAtual={selectedCategory.id}
            titulo={selectedCategory.name}
            clienteId={clienteDoPortal?.id || null}
            favoritos={clienteDoPortal?.favorites || null}
            corDaMarca={primaryColor}
            /* Os rótulos das opções (Cor, Tamanho) só dos produtos desta
               página: o produto enxuto chega sem eles. */
            caracteristicas={caracteristicasDe(dados.caracteristicas, produtosDaCategoria as Array<{ id?: string }>)}
          />
        </BoutiqueShell>
        </ProvedorDaNavegacao>
        </>
      </StoreLayout>
    );
  }

  if (temaDaPagina === "vendor") {
    return (
      <StoreLayout
        primaryColor={primaryColor}
        whatsappNumber={profile.whatsapp}
        cartScope={profile.id || slug}
        storeSlug={slug}
        theme={temaDaPagina}
        chatLigado={profile.store_chat_enabled === true}
        visao={visao}
      >
        <FontesDaLoja perfil={profile} />
        <>
        <CatalogAnalyticsTracker
          slug={slug}
          eventName="page_view"
          categoryId={selectedCategory.id}
          onceKey={`page_view:categoria:${selectedCategory.id}`}
        />
        <CatalogAnalyticsTracker
          slug={slug}
          eventName="category_click"
          categoryId={selectedCategory.id}
          onceKey={`category_click:${selectedCategory.id}`}
        />
        {/* O menu e o rodapé publicados no editor (null = os de sempre). */}
        <ProvedorDaNavegacao navegacao={dados.navegacao}>
        <VendorShell
          slug={slug}
          nomeDaLoja={storeName}
          slogan={profile.catalog_slogan}
          logoUrl={logoUrl}
          corDaMarca={primaryColor}
          aparencia={aparenciaDoVendor(profile as never)}
          cupomDoAviso={selectedAnnouncementCoupon as never}
          whatsappFlutuante={profile.catalog_whatsapp_float}
          categoriaAtual={selectedCategory.id}
          categorias={(categories || []) as never[]}
          contato={{
            whatsapp: profile.whatsapp,
            telefone: profile.company_phone || profile.phone,
            email: profile.email,
            endereco: profile.catalog_footer_address || profile.address,
            cnpj: profile.catalog_show_document ? profile.cnpj : null,
            instagram: profile.social_instagram,
            facebook: profile.social_facebook,
          }}
        >
          <VendorHome
            slug={slug}
            produtos={produtosDaCategoria as never[]}
            categorias={(categories || []) as never[]}
            banners={[]}
            avaliacoes={[]}
            mediaDasAvaliacoes={0}
            nomeDaLoja={storeName}
            logoUrl={logoUrl}
            tituloDaPagina={selectedCategory.name}
            fotoDaPagina={
              (produtosDaCategoria as Array<{ image_url?: string | null; product_images?: Array<{ image_url?: string | null }> | null }>)
                .map((produto) => produto.product_images?.[0]?.image_url || produto.image_url)
                .find(Boolean) || null
            }
            clienteId={clienteDoPortal?.id || null}
            favoritos={clienteDoPortal?.favorites || null}
            provaSocial={{
              ligado: profile.catalog_social_proof_enabled,
              intervaloSegundos: profile.catalog_social_proof_interval_seconds,
              duracaoSegundos: profile.catalog_social_proof_duration_seconds,
              quantosCabem: profile.catalog_social_proof_max_visible,
              posicao: profile.catalog_social_proof_position,
            }}
            subtitulo={`${produtosDaCategoria.length} ${produtosDaCategoria.length === 1 ? "produto" : "produtos"}`}
          />
        </VendorShell>
        </ProvedorDaNavegacao>
        </>
      </StoreLayout>
    );
  }

  return (
    <StoreLayout
      primaryColor={primaryColor}
      whatsappNumber={profile.whatsapp}
      cartScope={profile.id || slug}
      storeSlug={slug}
      theme={temaDaPagina}
      chatLigado={profile.store_chat_enabled === true}
      visao={visao}
    >
      <FontesDaLoja perfil={profile} />
      <ProvedorDaNavegacao navegacao={dados.navegacao}>
      <StoreContent
        loggedClient={clienteParaAsTelas(clienteDoPortal)}
        products={products || []}
        categories={categories || []}
        banners={resolvedBanners}
        sections={sections}
        slideEnabled={slideEnabled}
        infoStripEnabled={infoStripEnabled}
        infoStripItems={infoStripItems}
        slug={slug}
        primaryColor={primaryColor}
        storeName={storeName}
        storeSlogan={profile.catalog_slogan}
        logoUrl={logoUrl}
        showStoreNameInHeader={profile.catalog_show_name_in_header}
        showStoreSloganInHeader={profile.catalog_show_slogan_in_header}
        storeNameColor={profile.catalog_name_color}
        storeSloganColor={profile.catalog_slogan_color}
        catalogHeaderIconColor={profile.catalog_header_icon_color}
        logoEffectEnabled={profile.catalog_logo_effect_enabled}
        logoEffectType={profile.catalog_logo_effect}
        logoEffectSpeed={profile.catalog_logo_effect_speed}
        logoEffectIntensity={profile.catalog_logo_effect_intensity}
        whatsapp={profile.whatsapp}
        whatsappFloat={profile.catalog_whatsapp_float}
        phone={profile.phone}
        companyPhone={profile.company_phone}
        companyWhatsapp={profile.company_whatsapp}
        address={profile.address}
        cnpj={profile.cnpj}
        catalogShowDocument={profile.catalog_show_document}
        headerColor={aparencia.headerColor}
        headerTextColor={aparencia.headerTextColor}
        menuColor={aparencia.menuColor}
        menuTextColor={aparencia.menuTextColor}
        pageBgColor={aparencia.pageBgColor}
        cardButtonColor={aparencia.cardButtonColor}
        fontHeadingFamily={aparencia.fonts.heading}
        fontBodyFamily={aparencia.fonts.body}
        footerColor={profile.catalog_footer_color}
        footerTextColor={profile.catalog_footer_text_color}
        socialFacebook={profile.social_facebook}
        socialInstagram={profile.social_instagram}
        socialTwitter={profile.social_twitter}
        socialLinkedin={profile.social_linkedin}
        socialYoutube={profile.social_youtube}
        announcementEnabled={profile.catalog_announcement_enabled}
        announcementText={profile.catalog_announcement_text}
        announcementCountdownEnabled={profile.catalog_announcement_countdown_enabled}
        announcementCountdownEndAt={profile.catalog_announcement_countdown_end_at}
        announcementShowCouponBadge={profile.catalog_announcement_show_coupon_badge}
        announcementCouponBadgeColor={profile.catalog_announcement_coupon_badge_color}
        announcementBackgroundColor={profile.catalog_announcement_background_color}
        announcementTextColor={profile.catalog_announcement_text_color}
        announcementButtonLabel={profile.catalog_announcement_button_label}
        announcementButtonUrl={profile.catalog_announcement_button_url}
        announcementSticky={profile.catalog_announcement_sticky}
        announcementCoupon={selectedAnnouncementCoupon as any}
        announcementCouponId={profile.catalog_announcement_coupon_id}
        socialProofEnabled={profile.catalog_social_proof_enabled}
        socialProofIntervalSeconds={profile.catalog_social_proof_interval_seconds}
        socialProofPosition={profile.catalog_social_proof_position}
        socialProofDurationSeconds={profile.catalog_social_proof_duration_seconds}
        socialProofMaxVisible={profile.catalog_social_proof_max_visible}
        vitrineProductLayout={profile.catalog_vitrine_product_layout}
        initialSelectedCategoryId={selectedCategory.id}
        hideSections
        productsHeading={selectedCategory.name}
        storiesGroups={storiesGroups}
        catalogStoriesEnabled={profile.catalog_stories_enabled ?? true}
      />
      </ProvedorDaNavegacao>
    </StoreLayout>
  );
}
