// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// pages/Profil.tsx : profil utilisateur — carte de membre Groupe KA (KA-ID),
//   profil Groupe KA en lecture seule (saisi au hub groupe-ka.com), actions.
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { fetchMe, logout } from "../api";
import type { Socials, User } from "../api";
import { Ico } from "../components/Icons";

const fmtEpoch = (ts: number | null | undefined): string => {
  if (!ts) return "—";
  return new Date(ts * 1000).toLocaleDateString("fr-CA", {
    day: "numeric", month: "long", year: "numeric",
  }).replace(/^1 /, "1ᵉʳ ");
};

const SOCIAL_BASE: Record<string, string> = {
  instagram: "https://www.instagram.com/",
  facebook: "https://www.facebook.com/",
  x: "https://x.com/",
  linkedin: "https://www.linkedin.com/in/",
  tiktok: "https://www.tiktok.com/@",
  youtube: "https://www.youtube.com/@",
};

function socialUrl(key: string, value: string): string {
  const v = value.trim();
  if (/^https?:\/\//i.test(v)) return v;
  if (key === "website") return `https://${v}`;
  return (SOCIAL_BASE[key] ?? "https://") + v.replace(/^@/, "");
}

const SOCIAL_FIELDS: { key: keyof Socials; label: string }[] = [
  { key: "instagram", label: "Instagram" },
  { key: "facebook", label: "Facebook" },
  { key: "x", label: "X (Twitter)" },
  { key: "linkedin", label: "LinkedIn" },
  { key: "tiktok", label: "TikTok" },
  { key: "youtube", label: "YouTube" },
];

/** Profil géré au HUB Groupe KA — LECTURE SEULE (édition sur groupe-ka.com). */
function HubProfileSection({ me }: { me: User }) {
  const socialLinks = SOCIAL_FIELDS.filter((s) => (me.socials?.[s.key] ?? "").trim());
  return (
    <section className="hub-profile">
      <h3>Mon profil Groupe KA</h3>
      {me.bio && <p className="hub-bio">{me.bio}</p>}
      <div className="pub-meta">
        {(me.job_title || me.company) && (
          <span className="stat-chip">
            {[me.job_title, me.company].filter(Boolean).join(" · ")}
          </span>
        )}
        {me.city && <span className="stat-chip">{me.city}</span>}
        {me.age != null && <span className="stat-chip">{me.age} ans</span>}
        {me.website && (
          <a className="stat-chip" href={socialUrl("website", me.website)}
             target="_blank" rel="noopener noreferrer">Site web ↗</a>
        )}
        {socialLinks.map((s) => (
          <a key={s.key} className="stat-chip hub-social-chip"
             href={socialUrl(s.key, me.socials![s.key]!)}
             target="_blank" rel="noopener noreferrer" title={s.label}>
            <Ico name={s.key} size={15} /> {s.label}
          </a>
        ))}
      </div>
      <div>
        <a className="btn btn-primary"
           href="https://www.groupe-ka.com/compte"
           target="_blank" rel="noopener noreferrer">
          Modifier mon profil sur groupe-ka.com ↗
        </a>
      </div>
      <p className="hub-hint">
        Votre profil est géré au niveau du groupe : une seule saisie, visible
        sur toutes les plateformes du Groupe KA.
      </p>
    </section>
  );
}

export default function ProfilPage() {
  const [me, setMe] = useState<User | null | undefined>(undefined);
  const [copied, setCopied] = useState(false);
  const nav = useNavigate();

  useEffect(() => {
    fetchMe().then((r) => setMe(r.user)).catch(() => setMe(null));
  }, []);

  const copyKaId = async () => {
    if (!me?.ka_id) return;
    try {
      await navigator.clipboard.writeText(me.ka_id);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch { /* presse-papiers indisponible */ }
  };

  if (me === undefined) {
    return <div className="container profil"><div className="notice">Chargement…</div></div>;
  }

  if (me === null) {
    return (
      <div className="container profil">
        <span className="kicker">Mon compte</span>
        <h1>Connectez-vous pour <span className="hl">votre profil</span>.</h1>
        <p className="lede">
          Connectez-vous avec votre compte <b>KA ID</b> — vous recevrez votre
          identifiant de membre, valide dans tout l'écosystème Groupe KA.
        </p>
        <a className="btn btn-primary" href="/api/auth/ka/login?next=%2Fprofil">
          Se connecter avec KA ID
        </a>
      </div>
    );
  }

  return (
    <div className="container profil">
      <span className="kicker">Mon compte</span>
      <h1>
        {me.name ? <>Salut, <span className="hl">{me.name.split(" ")[0]}</span>.</>
                 : <>Votre <span className="hl">profil</span>.</>}
      </h1>

      {/* ——— Carte de membre Groupe KA ——— */}
      <div className="pc" role="img" aria-label={`Carte de membre ${me.ka_id || me.sub}`}>
        <div className="pc-watermark" aria-hidden="true">KA</div>
        <div className="pc-head">
          <span className="pc-brand">Groupe <span className="pc-ka">KA</span></span>
          <span className="pc-label">Carte de membre · Groupe KA</span>
        </div>
        <div className="pc-id-block">
          <span className="pc-id-label">KA-ID</span>
          <span className="pc-id">{me.ka_id || "—"}</span>
        </div>
        <div className="pc-foot">
          <div className="pc-holder">
            <span className="pc-holder-name">{me.name || me.email}</span>
            {me.role_label && (
              <span className="pc-role-badge">{me.role_label}</span>
            )}
            <span className="pc-holder-since">Membre depuis le {fmtEpoch(me.created_at)}</span>
          </div>
          {me.picture && (
            <img className="pc-avatar" src={me.picture} alt="" referrerPolicy="no-referrer" />
          )}
        </div>
        <div className="pc-strip" aria-hidden="true">
          {Array.from({ length: 28 }).map((_, i) => <i key={i} />)}
        </div>
      </div>

      <button className={`btn btn-ghost pc-copy ${copied ? "ok" : ""}`} onClick={copyKaId}>
        {copied ? "✓ Copié" : "Copier mon KA-ID"}
      </button>

      {/* ——— Informations ——— */}
      <section className="profil-grid">
        <div className="pg-item">
          <span className="pg-label">Nom</span>
          <span className="pg-value">{me.name || "—"}</span>
        </div>
        <div className="pg-item">
          <span className="pg-label">Courriel</span>
          <span className="pg-value">{me.email || "—"}</span>
        </div>
        <div className="pg-item">
          <span className="pg-label">Identifiant membre</span>
          <span className="pg-value mono">{me.ka_id || me.sub}</span>
        </div>
        <div className="pg-item">
          <span className="pg-label">Connexion</span>
          <span className="pg-value">KA ID (groupe-ka.com)</span>
        </div>
        {me.city && (
          <div className="pg-item">
            <span className="pg-label">Ville</span>
            <span className="pg-value">{me.city}</span>
          </div>
        )}
        {me.role_label && (
          <div className="pg-item">
            <span className="pg-label">Statut</span>
            <span className="pg-value">{me.role_label}</span>
          </div>
        )}
        <div className="pg-item">
          <span className="pg-label">Membre depuis</span>
          <span className="pg-value">{fmtEpoch(me.created_at)}</span>
        </div>
        <div className="pg-item">
          <span className="pg-label">Dernière connexion</span>
          <span className="pg-value">{fmtEpoch(me.last_login)}</span>
        </div>
      </section>

      {me.profile_source === "groupe-ka" && <HubProfileSection me={me} />}

      {me.profile_source === "groupe-ka" && me.public && me.public_url && (
        <p className="profil-note">
          Votre profil public :{" "}
          <a href={me.public_url} target="_blank" rel="noopener noreferrer" className="mono">
            {me.public_url.replace(/^https?:\/\//, "")}
          </a>{" "}
          — la visibilité se gère sur groupe-ka.com/compte.
        </p>
      )}

      <p className="profil-note">
        Votre <b>KA-ID</b> est votre identifiant unique dans l'écosystème{" "}
        <a href="https://www.groupe-ka.com" target="_blank" rel="noopener noreferrer">
          Groupe KA
        </a>{" "}
        — il vous suit sur toutes les plateformes du groupe. Toit-Ka ne conserve
        que les informations de ce profil ; rien d'autre, et jamais revendues.
      </p>

      <div className="profil-actions">
        <button
          className="btn btn-ghost"
          onClick={async () => { await logout(); nav("/"); window.location.reload(); }}
        >
          Se déconnecter
        </button>
      </div>
    </div>
  );
}
