"use client";

import Link from "next/link";
import type { Session } from "next-auth";
import type { PlanCode } from "@prisma/client";
import { ReferenceBrandLogo } from "@/components/dashboard/reference-brand-logo";
import { DashboardNav } from "@/components/dashboard/dashboard-nav";
import { useLanguage } from "@/lib/i18n/context";
import type { Locale } from "@/lib/i18n/translations";
import { PLANS } from "@/config/plans";

function initials(name?: string | null, email?: string | null) {
  if (name) {
    const parts = name.trim().split(/\s+/);
    return `${parts[0]?.[0] ?? ""}${parts[1]?.[0] ?? ""}`.toUpperCase() || "?";
  }
  return email?.[0]?.toUpperCase() ?? "?";
}

const LANGUAGE_OPTIONS: Array<{ locale: Locale; label: string }> = [
  { locale: "es", label: "ES" },
  { locale: "en", label: "ENG" },
];

function SidebarLanguageSwitch() {
  const { locale, setLocale } = useLanguage();

  return (
    <div className="sidebar-language" role="group" aria-label="Language">
      <span className="sidebar-language-icon" aria-hidden="true">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <circle cx="12" cy="12" r="9" />
          <path d="M3 12h18" />
          <path d="M12 3c2.3 2.5 3.4 5.5 3.4 9S14.3 18.5 12 21" />
          <path d="M12 3C9.7 5.5 8.6 8.5 8.6 12S9.7 18.5 12 21" />
        </svg>
      </span>
      <span className="sidebar-language-options">
        {LANGUAGE_OPTIONS.map((option) => (
          <button
            key={option.locale}
            type="button"
            onClick={() => setLocale(option.locale)}
            aria-pressed={locale === option.locale}
            className={locale === option.locale ? "active" : undefined}
          >
            {option.label}
          </button>
        ))}
      </span>
    </div>
  );
}

/**
 * Ported to match REFERENCIA/toknext_react_reference's DashboardOverviewReference
 * sidebar DOM/classes exactly (`.sidebar`/`.brand`/`.nav-group`/`.upgrade`,
 * see src/styles/toknext-reference.css) — a fixed desktop rail with no
 * collapse state, since the approved reference doesn't define one. The prior
 * collapsible sidebar was a TokNext-only affordance not present in the
 * reference; it's dropped in favor of matching the approved design exactly.
 */
export function DashboardSidebar({
  user,
  plan,
  showBillingWarning = false,
  hasPaidAccess = false,
  inDrawer = false,
}: {
  user: Session["user"];
  plan: PlanCode;
  showBillingWarning?: boolean;
  /** Real plan-access state (from getUserPlan()) — the upgrade card below
   * only ever renders for a genuinely unpaid account, never as decoration. */
  hasPaidAccess?: boolean;
  /** True when rendered inside the mobile Sheet drawer instead of the
   * persistent in-grid position — see the .sidebar-drawer override in
   * toknext-reference.css (the reference itself has no drawer state). */
  inDrawer?: boolean;
}) {
  const { t } = useLanguage();
  const s = t.dashboard.sidebar;
  const planName = t.plans[PLANS[plan].translationKey].name;

  return (
    <aside className={inDrawer ? "sidebar sidebar-drawer" : "sidebar"}>
      <div className="brand">
        <ReferenceBrandLogo className="brand-mark" />
        <div className="brand-copy">
          <div className="brand-name">
            Tok<span>Next</span>
          </div>
          <div className="brand-sub">{s.tagline}</div>
        </div>
      </div>

      <DashboardNav showBillingWarning={showBillingWarning} />

      <div className="sidebar-footer-tools">
        <SidebarLanguageSwitch />

        {!hasPaidAccess && (
          <div className="upgrade">
            <div className="upgrade-title">
              <svg className="crown" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="m3 7 4 4 5-7 5 7 4-4-2 11H5L3 7Z" />
                <path d="M5 21h14" />
              </svg>
              {s.upgradeTitle}
            </div>
            <p>{s.upgradeDescription}</p>
            <Link href="/dashboard/billing">
              <button type="button">{s.upgradeButton}</button>
            </Link>
          </div>
        )}

        {hasPaidAccess && (
          <Link href="/dashboard/billing" className="account-profile" aria-label={`${user.name ?? user.email ?? planName} — ${planName}`}>
            <span className="account-avatar">{initials(user.name, user.email)}</span>
            <span className="account-copy">
              <strong>{user.name || user.firstName || user.email}</strong>
              <small>{planName}</small>
            </span>
            <svg className="account-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
              <path d="m9 18 6-6-6-6" />
            </svg>
          </Link>
        )}
      </div>
    </aside>
  );
}
