// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Mon compte — la carte de membre Groupe KA (même gabarit que sur Lou·Ka :
// carte KA-ID, grille d'informations, plateformes, actions).
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import QRCode from "qrcode";
import { getSessionUser } from "@/lib/auth";
import { ensureKaId } from "@/lib/db";
import { SSO_CLIENTS } from "@/lib/sso";
import { roleLabel, roleCard } from "@/lib/roles";
import {
  db,
  parseSocials,
  favoritesOf,
  type UserRow,
  type FavoriteRow,
} from "@/lib/db";
import RemoveFavorite from "./RemoveFavorite";
import LogoutButton from "./LogoutButton";
import CopyKaId from "./CopyKaId";
import AvatarEditor from "./AvatarEditor";
import RolePicker from "./RolePicker";
import ProfileForm from "./ProfileForm";
import CopyText from "./CopyText";

export const metadata: Metadata = {
  title: "Mon KA ID | Groupe KA",
  description: "Votre compte unique pour les plateformes du Groupe KA.",
};

export const dynamic = "force-dynamic";

const PLATFORM_URLS: Record<string, string> = {
  "lou-ka": "https://www.lou-ka.com",
  "immo-ka": "https://www.immo-ka.com",
  "vrai-prix": "https://www.vrai-prix.com",
  valoplex: "https://www.valoplex.com",
  "auto-ka": "https://www.auto-ka.com",
  "fabri-ka": "https://www.fabri-ka.com",
  "food-ka": "https://www.food-ka.com",
  "ora-ka": "https://www.ora-ka.com",
};

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  const d = new Date(iso.includes("T") ? iso : iso.replace(" ", "T") + "Z");
  if (Number.isNaN(d.getTime())) return "—";
  return d
    .toLocaleDateString("fr-CA", {
      day: "numeric",
      month: "long",
      year: "numeric",
    })
    .replace(/^1 /, "1ᵉʳ ");
}

const APP_ACCENTS: Record<string, string> = {
  "lou-ka": "#d9f26b",
  "immo-ka": "#e23744",
  "vrai-prix": "#ff5148",
  valoplex: "#ff9f45",
  "auto-ka": "#ff5a2a",
  "fabri-ka": "#C4532E",
  "food-ka": "#d9f26b",
  "ora-ka": "#d9f26b",
};

function UniversSection({ userId }: { userId: number }) {
  const favs = favoritesOf(userId);
  const byApp = new Map<string, FavoriteRow[]>();
  for (const f of favs) {
    if (!byApp.has(f.app)) byApp.set(f.app, []);
    byApp.get(f.app)!.push(f);
  }
  return (
    <section className="mt-10">
      <p className="kicker">Mon univers Ka · tous mes coups de cœur</p>
      <h2 className="gk-display mt-2 text-[20px] font-bold uppercase">
        Ce que j&apos;ai sauvegardé, partout
      </h2>
      {favs.length === 0 ? (
        <div className="gk-card mt-4 p-6 text-center">
          <p className="text-[13.5px] text-ink-2">
            Vos coups de cœur des plateformes ·Ka apparaîtront ici — tapez ♥
            sur un logement (Lou·Ka), une propriété (Immo·Ka), une auto
            (Auto·Ka), un produit d&apos;ici (Fabri·Ka) ou une aubaine
            d&apos;épicerie (Food·Ka).
          </p>
        </div>
      ) : (
        <div className="mt-4 space-y-6">
          {[...byApp.entries()].map(([app, items]) => (
            <div key={app}>
              <p className="klabel flex items-center gap-2">
                <span
                  aria-hidden="true"
                  className="inline-flex h-[14px] w-[14px] items-center justify-center rounded-[3px] bg-ink"
                >
                  <span
                    className="h-[8px] w-[8px] rounded-[2px]"
                    style={{ background: APP_ACCENTS[app] ?? "#d9f26b" }}
                  />
                </span>
                {(SSO_CLIENTS[app]?.label ?? app)} · {items.length}
              </p>
              <ul className="mt-2 grid gap-3 sm:grid-cols-2">
                {items.map((f) => (
                  <li
                    key={f.item_id}
                    className="gk-card flex items-center gap-3 p-3"
                  >
                    {f.image_url ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={f.image_url}
                        alt=""
                        width={56}
                        height={56}
                        referrerPolicy="no-referrer"
                        className="h-14 w-14 flex-none rounded-md border border-[rgba(20,24,20,0.2)] object-cover"
                      />
                    ) : (
                      <span className="gk-display flex h-14 w-14 flex-none items-center justify-center rounded-md bg-lime-soft text-[18px] font-bold">
                        ♥
                      </span>
                    )}
                    <div className="min-w-0 flex-1">
                      <a
                        href={f.url ?? "#"}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="block truncate text-[13.5px] font-bold underline-offset-4 hover:underline"
                      >
                        {f.title}
                      </a>
                      {f.subtitle && (
                        <p className="truncate text-[12px] text-ink-2">
                          {f.subtitle}
                        </p>
                      )}
                      {f.price_label && (
                        <p className="gk-mono text-[12px] font-bold text-green">
                          {f.price_label}
                        </p>
                      )}
                    </div>
                    <RemoveFavorite app={f.app} itemId={f.item_id} />
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}

function ProfileSection({ userId, kaId }: { userId: number; kaId: string }) {
  const row = db
    .prepare("SELECT * FROM users WHERE id = ?")
    .get(userId) as UserRow;
  return (
    <section className="rise mt-8 [animation-delay:0.25s]">
      <div className="gk-card p-5 sm:p-7">
        <p className="kicker">Mon profil · une saisie, sept plateformes</p>
        <h2 className="gk-display mt-2 text-[18px] font-bold uppercase">
          Personnaliser mon profil
        </h2>
        <div className="mt-5">
          <ProfileForm
            initial={{
              name: row.name ?? "",
              bio: row.bio ?? "",
              city: row.city ?? "",
              phone: row.phone ?? "",
              website: row.website ?? "",
              job_title: row.job_title ?? "",
              company: row.company ?? "",
              birth_date: row.birth_date ?? "",
              socials: parseSocials(row.socials),
              isPublic: !!row.public,
              kaId,
            }}
          />
        </div>
      </div>
    </section>
  );
}

export default async function Compte() {
  const user = await getSessionUser();
  if (!user) redirect("/connexion?next=%2Fcompte");
  const kaId = user.kaId ?? ensureKaId(user.id);
  // Code QR de la carte → page de vérification publique du KA-ID
  const qr = await QRCode.toDataURL(`https://www.groupe-ka.com/m/${kaId}`, {
    margin: 0,
    width: 220,
    color: { dark: "#141814", light: "#ffffff" },
  });

  const infos: [string, React.ReactNode][] = [
    ["Nom", user.name || "—"],
    ["Courriel", user.email],
    [
      "Identifiant membre",
      <span key="k" className="gk-mono">{kaId}</span>,
    ],
    ["Type de compte", roleLabel(user.role) ?? "À choisir ci-dessous"],
    [
      "Connexion",
      (() => {
        const modes = [
          user.hasGoogle && "Google",
          user.hasApple && "Apple",
          user.hasPassword && "mot de passe",
        ].filter(Boolean) as string[];
        return modes.length ? modes.join(" + ") : "Courriel et mot de passe";
      })(),
    ],
    ["Membre depuis", fmtDate(user.createdAt)],
    ["Dernière connexion", fmtDate(user.lastLogin)],
  ];

  return (
    <main className="mx-auto max-w-2xl px-4 pb-16 sm:px-6">
      <section className="pt-12 sm:pt-14">
        <p className="kicker rise">Mon compte · KA ID</p>
        <h1 className="gk-display rise mt-4 text-[clamp(30px,5vw,48px)] leading-[1] font-bold tracking-[-0.035em] uppercase [animation-delay:0.08s]">
          Salut, <span className="hl">{user.name.split(" ")[0]}</span>.
        </h1>
      </section>

      {/* ——— Carte de membre Groupe KA ——— */}
      <div
        className="mc rise [animation-delay:0.14s]"
        role="img"
        aria-label={`Carte de membre ${kaId}`}
      >
        <div className="mc-watermark" aria-hidden="true">
          KA
        </div>
        <div className="mc-head">
          <span className="mc-brand">
            Groupe <span className="mc-ka">KA</span>
          </span>
          <span className="mc-label">Carte de membre · Groupe KA</span>
        </div>
        <div className="mc-id-row">
          <div className="mc-id-block">
            <span className="mc-id-label">KA-ID</span>
            <span className="mc-id">{kaId}</span>
          </div>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            className="mc-qr"
            src={qr}
            alt={`Code QR de vérification du KA-ID ${kaId}`}
            width={78}
            height={78}
          />
        </div>
        <div className="mc-foot">
          <div className="mc-holder">
            <span className="mc-holder-name">{user.name || user.email}</span>
            {roleCard(user.role) && (
              <span className="mc-holder-role">{roleCard(user.role)}</span>
            )}
            <span className="mc-holder-since">
              Membre depuis le {fmtDate(user.createdAt)}
            </span>
          </div>
          {user.avatarUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              className="mc-avatar"
              src={user.avatarUrl}
              alt=""
              referrerPolicy="no-referrer"
            />
          ) : (
            <span className="mc-avatar mc-avatar-empty">
              {(user.name || user.email).charAt(0).toUpperCase()}
            </span>
          )}
        </div>
        <div className="mc-strip" aria-hidden="true">
          {Array.from({ length: 28 }).map((_, i) => (
            <i key={i} />
          ))}
        </div>
      </div>

      <div className="rise mt-4 flex flex-wrap items-center gap-3 [animation-delay:0.2s]">
        {process.env.KA_PASS_DIR && process.env.KA_PASS_TYPE_ID && (
          <a
            href="/api/wallet/pass"
            className="inline-flex min-h-[44px] items-center gap-2 rounded-[10px] bg-black px-5 text-[14px] font-semibold text-white shadow-[4px_4px_0_rgba(20,24,20,0.25)] transition-transform active:translate-x-[2px] active:translate-y-[2px] active:shadow-none"
          >
            <svg width="17" height="17" viewBox="0 0 24 24" aria-hidden="true">
              <path
                fill="currentColor"
                d="M17.05 12.54c-.03-2.9 2.37-4.29 2.48-4.36-1.35-1.97-3.45-2.24-4.2-2.27-1.79-.18-3.49 1.05-4.4 1.05-.9 0-2.3-1.02-3.79-1-1.95.03-3.74 1.13-4.74 2.87-2.02 3.5-.52 8.69 1.45 11.53.96 1.39 2.11 2.95 3.62 2.89 1.45-.06 2-.94 3.76-.94s2.25.94 3.79.91c1.56-.03 2.55-1.42 3.51-2.81 1.1-1.62 1.56-3.18 1.58-3.26-.03-.02-3.03-1.16-3.06-4.61ZM14.16 4.02c.8-.97 1.34-2.32 1.19-3.66-1.15.05-2.55.77-3.38 1.74-.74.85-1.39 2.23-1.22 3.54 1.29.1 2.6-.65 3.41-1.62Z"
              />
            </svg>
            Ajouter à Apple Wallet
          </a>
        )}
        <CopyKaId kaId={kaId} />
        <LogoutButton />
      </div>

      {/* ——— Type de compte (obligatoire — les comptes Google le
              choisissent ici) ——— */}
      {!user.role && (
        <section className="rise mt-8 [animation-delay:0.22s]">
          <div className="gk-card border-[2px] !border-green p-5 sm:p-6">
            <p className="kicker">Une dernière chose · vous êtes…</p>
            <p className="mt-2 text-[13.5px] text-ink-2">
              Choisissez votre type de compte — il sera affiché sur votre
              carte de membre.
            </p>
            <div className="mt-4">
              <RolePicker current={user.role} />
            </div>
          </div>
        </section>
      )}

      {/* ——— Photo de profil ——— */}
      <section className="rise mt-8 [animation-delay:0.23s]">
        <div className="gk-card flex flex-wrap items-center gap-5 p-5 sm:p-6">
          {user.avatarUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={user.avatarUrl}
              alt=""
              width={64}
              height={64}
              referrerPolicy="no-referrer"
              className="h-16 w-16 flex-none rounded-full border-2 border-ink object-cover"
            />
          ) : (
            <span className="gk-display flex h-16 w-16 flex-none items-center justify-center rounded-full border-2 border-ink bg-lime text-[24px] font-bold">
              {(user.name || user.email).charAt(0).toUpperCase()}
            </span>
          )}
          <div className="min-w-0 flex-1">
            <p className="klabel">Photo de profil</p>
            <div className="mt-2">
              <AvatarEditor hasAvatar={!!user.avatarUrl} />
            </div>
          </div>
        </div>
      </section>

      {/* ——— Mon univers Ka (favoris unifiés) ——— */}
      <UniversSection userId={user.id} />

      {/* ——— Mon profil (source de vérité pour toutes les plateformes) ——— */}
      <ProfileSection userId={user.id} kaId={kaId} />

      {/* ——— Informations ——— */}
      <section className="rise mt-8 [animation-delay:0.26s]">
        <div className="gk-card grid gap-x-6 gap-y-0 p-0 sm:grid-cols-2">
          {infos.map(([label, value], i) => (
            <div
              key={label}
              className={`px-5 py-4 sm:px-6 ${i < infos.length - (infos.length % 2 === 0 ? 2 : 1) ? "border-b border-dashed border-[rgba(20,24,20,0.18)]" : ""}`}
            >
              <p className="klabel">{label}</p>
              <p className="mt-1 text-[14px] font-medium break-all">{value}</p>
            </div>
          ))}
        </div>
        <p className="mt-4 text-[12.5px] leading-relaxed text-ink-2">
          Votre <strong className="gk-display">KA-ID</strong> est votre
          identifiant unique dans tout l&apos;écosystème Groupe KA — il vous
          suit sur chaque plateforme. Le hub ne conserve que ce profil : rien
          d&apos;autre, et jamais revendu.
        </p>
      </section>

      {/* ——— Carte physique & NFC ——— */}
      <section className="mt-10">
        <p className="kicker">Carte physique · NFC</p>
        <h2 className="gk-display mt-2 text-[20px] font-bold uppercase">
          Votre carte, en vrai
        </h2>
        <div className="gk-card mt-4 p-5 sm:p-6">
          <p className="text-[13.5px] leading-relaxed text-ink-2">
            Imprimez votre carte au format carte bancaire et collez-y un
            autocollant <strong className="text-ink">NFC (NTAG215, ~1 $)</strong> :
            un simple tap sur un iPhone ou un Android ouvre votre page
            d&apos;identification — comme le code QR, sans appli.
          </p>
          <div className="mt-4 flex flex-wrap items-center gap-3">
            <a href="/compte/carte" className="btn btn-primary">
              Carte imprimable (recto/verso) ↗
            </a>
            <CopyText
              text={`https://www.groupe-ka.com/m/${kaId}`}
              label="Copier le lien à écrire sur la puce NFC"
            />
          </div>
          <ol className="mt-5 space-y-2 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.25)] pt-4 text-[13px] text-ink-2">
            {[
              <>Procurez-vous des autocollants <strong className="text-ink">NTAG215</strong> (Amazon, ~10 $ les 10).</>,
              <>Installez l&apos;appli gratuite <strong className="text-ink">NFC Tools</strong> (iPhone ou Android).</>,
              <>Onglet <strong className="text-ink">Écrire</strong> → Ajouter un enregistrement → <strong className="text-ink">URL</strong> → collez le lien ci-dessus → <strong className="text-ink">Écrire</strong>, en tenant la puce contre le téléphone.</>,
              <>Optionnel : <strong className="text-ink">Verrouiller le tag</strong> pour le rendre non modifiable (irréversible).</>,
              <>Collez la puce au dos de la carte imprimée, dans la zone « NFC ».</>,
            ].map((step, i) => (
              <li key={i} className="flex gap-3">
                <span className="gk-mono flex-none font-bold text-green">
                  0{i + 1}
                </span>
                <span>{step}</span>
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* ——— Plateformes ——— */}
      <section className="mt-10">
        <p className="kicker">Un compte · sept portes</p>
        <h2 className="gk-display mt-2 text-[20px] font-bold uppercase">
          Votre KA ID fonctionne ici
        </h2>
        <p className="mt-2 text-[13.5px] text-ink-2">
          Sur chaque plateforme, choisissez « Se connecter avec KA ID » : vous
          arrivez déjà connecté, avec le même profil et le même KA-ID.
        </p>
        <ul className="mt-5 grid gap-3 sm:grid-cols-2">
          {Object.entries(SSO_CLIENTS).map(([id, c]) => (
            <li key={id}>
              <a
                href={PLATFORM_URLS[id]}
                target="_blank"
                rel="noopener noreferrer"
                className="gk-card gk-card-hover flex items-center justify-between px-5 py-4"
              >
                <span className="gk-display text-[15px] font-bold">
                  {c.label}
                </span>
                <span className="gk-mono text-[11px] text-ink-3">
                  {PLATFORM_URLS[id].replace("https://www.", "")} ↗
                </span>
              </a>
            </li>
          ))}
        </ul>
      </section>

      {/* ——— Actions ——— */}
      <div className="mt-8 flex flex-wrap gap-3">
        <a href="/conditions" className="btn btn-ghost">
          Conditions
        </a>
        <a href="/confidentialite" className="btn btn-ghost">
          Confidentialité
        </a>
        <a href="mailto:admin@groupe-ka.com" className="btn btn-ghost">
          Vie privée : admin@groupe-ka.com
        </a>
      </div>
    </main>
  );
}
