// app/[locale]/(client)/client/layout.tsx
"use client"

import Link from "next/link"
import { ReactNode, useEffect, useMemo, useState } from "react"
import { usePathname, useRouter } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import { BriefcaseBusiness } from "lucide-react"

import {
  LayoutDashboard,
  Briefcase,
  MessageSquareText,
  LifeBuoy,
  LogOut,
  ChevronRight,
  Building2,
  UserCircle2,
} from "lucide-react"

import { getCustomerPortalMe, type CustomerPortalMe } from "@/src/lib/api/customer-portal"

function safeClientLogout(router: ReturnType<typeof useRouter>, locale: string) {
  try {
    if (typeof window !== "undefined") {
      localStorage.removeItem("acx_cp_access")
      localStorage.removeItem("acx_cp_refresh")
    }
  } catch (e) {
    console.warn("Client logout cleanup failed", e)
  }

  router.replace(`/${locale}/client/login?reason=expired`)
}

const ACX = {
  green: "#20B26B",
  green2: "#4FD18B",
  dark: "#0F172A",
  muted: "#64748B",
  bg: "#F7FAF8",
  border: "rgba(15,23,42,.08)",
}

function cx(...c: Array<string | false | null | undefined>) {
  return c.filter(Boolean).join(" ")
}

export default function ClientLayout({ children }: { children: ReactNode }) {
  const t = useTranslations("clientPortal")
  const locale = useLocale()
  const pathname = usePathname()
  const router = useRouter()

  const [me, setMe] = useState<CustomerPortalMe | null>(null)

  useEffect(() => {
    getCustomerPortalMe()
      .then((data) => setMe(data))
      .catch((e) => {
        console.log("customer-portal me error:", e)
        setMe(null)
      })
  }, [])

  const username = me?.user?.username ?? "—"
  const tenantName = me?.tenant?.name ?? me?.institute?.name ?? "—"
  const instituteName = me?.customer?.name ?? "—"

  const nav = useMemo(() => {
    const base = `/${locale}/client`
    return [
      {
        key: "dashboard",
        label: t("dashboard.title"),
        href: `${base}/dashboard`,
        icon: LayoutDashboard,
        enabled: true,
      },
      {
        key: "cases",
        label: t("dashboard.cardCasesTitle"),
        href: `${base}/cases`,
        icon: Briefcase,
        enabled: true,
      },
      {
        key: "messages",
        label: t("dashboard.cardMessagesTitle"),
        href: `${base}/messages`,
        icon: MessageSquareText,
        enabled: true, // ✅ ACTIVÉ
      },
      {
        key: "support",
        label: "Support",
        href: `${base}/support`,
        icon: LifeBuoy,
        enabled: true,
      },
    ]
  }, [locale, t])

  function isActive(href: string) {
    if (!pathname) return false
    if (href === `/${locale}/client/dashboard`) return pathname === href
    return pathname.startsWith(href)
  }

  return (
    <div className="min-h-[100dvh] w-full" style={{ background: ACX.bg }}>
      <div className="flex min-h-[100dvh] w-full">
        {/* SIDEBAR */}
        <aside className="hidden md:flex w-[280px] shrink-0 flex-col border-r bg-white" style={{ borderColor: ACX.border }}>
          {/* Brand */}
          <div className="px-5 py-5 border-b" style={{ borderColor: ACX.border }}>
            <div className="flex items-center gap-3">
              <div
                className="h-11 w-11 rounded-2xl flex items-center justify-center text-white font-bold shadow-sm"
                style={{ background: `linear-gradient(135deg, ${ACX.green}, ${ACX.green2})` }}
              >
                ACX
              </div>
              <div className="min-w-0">
                <div className="text-sm font-semibold text-slate-900 leading-tight">Client Portal</div>
                <div className="text-xs text-slate-500 leading-tight">Espace Client</div>
              </div>
            </div>
          </div>

          {/* Identity card */}
          <div className="px-4 pt-4">
            <div
              className="rounded-2xl border bg-white p-3"
              style={{
                borderColor: "rgba(32,178,107,.18)",
                background: "linear-gradient(180deg, rgba(32,178,107,.08), rgba(255,255,255,1))",
              }}
            >
              <div className="flex items-start gap-3">
                <div
                  className="h-10 w-10 rounded-2xl flex items-center justify-center border"
                  style={{ borderColor: "rgba(32,178,107,.25)", background: "rgba(32,178,107,.10)" }}
                >
                  <UserCircle2 className="h-5 w-5" style={{ color: ACX.green }} />
                </div>

                <div className="min-w-0 flex-1">
                  <div className="text-sm font-semibold text-slate-900 truncate">@{username}</div>

                  <div className="mt-2 space-y-1">
                    <div className="flex items-center gap-2 text-xs text-slate-600">
                      <Building2 className="h-4 w-4" style={{ color: ACX.muted }} />
                      <span className="truncate">
                        <span className="text-slate-500">Via:</span>{" "}
                        <span className="font-medium text-slate-700">{tenantName}</span>
                      </span>
                    </div>

                    <div className="flex items-center gap-2 text-xs text-slate-600">
                      <BriefcaseBusiness className="h-4 w-4" style={{ color: ACX.muted }} />
                      <span className="truncate">
                        <span className="text-slate-500">{t("dashboard.customer")}:</span>{" "}
                        <span className="font-medium text-slate-700">{instituteName}</span>
                      </span>
                    </div>
                  </div>
                </div>

                <span
                  className="shrink-0 text-[11px] px-2 py-0.5 rounded-full border"
                  style={{
                    color: ACX.green,
                    borderColor: "rgba(32,178,107,.25)",
                    background: "rgba(32,178,107,.10)",
                  }}
                  title={t("dashboard.status")}
                >
                  {me?.membership?.status ?? "—"}
                </span>
              </div>
            </div>
          </div>

          {/* Menu */}
          <nav className="p-3 space-y-1">
            {nav.map((item) => {
              const active = isActive(item.href)
              const Icon = item.icon

              if (!item.enabled) {
                return (
                  <div
                    key={item.key}
                    className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 text-sm border bg-white opacity-60"
                    style={{ borderColor: ACX.border }}
                    title={t("dashboard.comingSoon")}
                  >
                    <div className="flex items-center gap-3">
                      <div className="h-9 w-9 rounded-xl border flex items-center justify-center" style={{ borderColor: ACX.border }}>
                        <Icon className="h-4 w-4" style={{ color: ACX.muted }} />
                      </div>
                      <div className="min-w-0">
                        <div className="font-medium text-slate-700">{item.label}</div>
                        <div className="text-[11px] text-slate-500">{t("dashboard.comingSoon")}</div>
                      </div>
                    </div>
                    <ChevronRight className="h-4 w-4 text-slate-400" />
                  </div>
                )
              }

              return (
                <Link
                  key={item.key}
                  href={item.href}
                  className={cx(
                    "flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm border transition-colors",
                    active ? "bg-emerald-50" : "bg-white hover:bg-slate-50"
                  )}
                  style={{ borderColor: active ? "rgba(32,178,107,.25)" : ACX.border }}
                >
                  <div
                    className="h-9 w-9 rounded-xl border flex items-center justify-center"
                    style={{
                      borderColor: active ? "rgba(32,178,107,.25)" : ACX.border,
                      background: active ? "rgba(32,178,107,.08)" : "transparent",
                    }}
                  >
                    <Icon className="h-4 w-4" style={{ color: active ? ACX.green : ACX.muted }} />
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className={cx("font-medium truncate", active ? "text-slate-900" : "text-slate-700")}>
                      {item.label}
                    </div>
                  </div>

                  {active && <span className="h-2 w-2 rounded-full" style={{ background: ACX.green }} />}
                </Link>
              )
            })}
          </nav>

          {/* Footer actions */}
          <div className="mt-auto p-3">
            <button
              type="button"
              onClick={() => safeClientLogout(router, locale)}
              className="w-full inline-flex items-center justify-center gap-2 rounded-xl border bg-white px-3 py-2.5 text-sm hover:bg-slate-50"
              style={{ borderColor: ACX.border }}
              title={t("common.logout")}
            >
              <LogOut className="h-4 w-4" style={{ color: ACX.muted }} />
              <span className="text-slate-700">{t("common.logout")}</span>
            </button>

            <div className="mt-3 text-[11px] text-slate-500 px-1">ACX • Client Portal</div>
          </div>
        </aside>

        {/* MAIN */}
        <div className="flex-1 min-w-0">
          <div className="md:hidden border-b bg-white" style={{ borderColor: ACX.border }}>
            <div className="px-4 py-3 flex items-center justify-between gap-3">
              <div className="min-w-0 flex items-center gap-3">
                <div
                  className="h-10 w-10 rounded-2xl flex items-center justify-center text-white font-bold shrink-0"
                  style={{ background: `linear-gradient(135deg, ${ACX.green}, ${ACX.green2})` }}
                >
                  ACX
                </div>

                <div className="min-w-0">
                  <div className="text-sm font-semibold text-slate-900 leading-tight">Client Portal</div>
                  <div className="text-xs text-slate-500 leading-tight truncate">
                    @{username} • {tenantName} • {instituteName}
                  </div>
                </div>
              </div>

              <button
                type="button"
                onClick={() => safeClientLogout(router, locale)}
                className="inline-flex items-center gap-2 rounded-xl border bg-white px-3 py-2 text-sm shrink-0"
                style={{ borderColor: ACX.border }}
              >
                <LogOut className="h-4 w-4" style={{ color: ACX.muted }} />
                {t("common.logout")}
              </button>
            </div>
          </div>

          <main className="w-full px-4 md:px-6 py-5 md:py-6">{children}</main>
        </div>
      </div>
    </div>
  )
}
