import { toNumber } from "@/lib/helpers";
import type {
  ProfileBadgeInfo,
  ProfileData,
  PublicProfileResponse,
  SponsorshipProfile,
} from "../commonProfileTypes";
import { pickLocalized } from "@/features/shared/types/cms";
import type { CounterVisibility } from "@/features/profile/accountRecords";

/**
 * One shape for the redesigned profile, whichever endpoint it came from.
 *
 * The page is shared by individuals and volunteer teams, on their own profile
 * (`/volunteer-profile/` or `/organization-profile/`, plus `/account/`) and on
 * the public one (`/public-profile/{id}/`). The payloads disagree on field
 * names and on what they reveal, so each is normalized here once and the view
 * never reads a raw payload.
 */

/**
 * A localized label as the profile payloads carry it.
 *
 * `id` is **optional**, which is not a hedge: `websiteInterestDisplay()` emits
 * only the two labels and no `id` at all, so a required id here claimed a
 * field the website payloads never send — and anything using it as a React
 * key got `undefined` for every row. Matches
 * `commonProfileTypes.LocalizedValue`, which the public payload uses.
 */
export interface LocalizedChoice {
  id?: number | string | null;
  value_en?: string | null;
  value_ar?: string | null;
  slug?: string | null;
}

/**
 * `organization` joined 2026-10-15 with its own design: a team's layout plus
 * a sponsorships tile, the «منظم / راعي» switch in each tab and the badge as
 * a sponsor-tier pill.
 */
export type ProfileKind = "individual" | "team" | "organization";

export type ProfileTab = "opportunities" | "certificates" | "events";

/**
 * The profile's tabs. An individual's certificates are their own business
 * (`/user-certificates/` answers for the caller only), so that tab is offered
 * on their own profile. Events belong to organizations only: a volunteer team
 * cannot publish events and its profile has no Events tab (client answer X2);
 * its historical events stay in the records, not on the profile.
 */
export function profileTabs(kind: ProfileKind, isOwnProfile: boolean): Array<[ProfileTab, string]> {
  const tabs: Array<[ProfileTab, string]> = [["opportunities", "COMMON.OPPORTUNITIES"]];
  if (kind === "organization") tabs.push(["events", "COMMON.EVENTS"]);
  else if (kind === "individual" && isOwnProfile) tabs.push(["certificates", "COMMON.CERTIFICATES"]);
  return tabs;
}

/** The side label of a certificate card, by what it was earned for. */
export function certificateKindLabelKey(kind: string | null | undefined): string {
  if (kind === "volunteering") return "COMMON.CERTIFICATE_KIND_VOLUNTEERING";
  if (kind === "internship") return "COMMON.CERTIFICATE_KIND_INTERNSHIP";
  return "COMMON.CERTIFICATE_KIND_COURSE";
}

export interface IndividualProfileData {
  kind: ProfileKind;
  userId: string;
  /** Real name on your own profile; the public endpoint withholds it (BE-52). */
  name: string;
  /** Shown as `@nickname`. */
  nickname: string | null;
  occupation: string | null;
  /** Teams show «رقم الترخيص» where an individual shows their occupation. */
  licenseNumber: string | null;
  profilePic: string | null;
  genderEn: string | null;
  badge: ProfileBadgeInfo | null;
  /**
   * Position in the configured leaderboard period (`current_rank`, computed
   * live by the backend). Null when the account is not ranked.
   */
  rank: number | null;
  /**
   * PDF p.31 — an organization's sponsorship type and level, from the
   * approved sponsor record the administration linked. Only the public
   * payload sends it; null elsewhere and when none is linked.
   */
  sponsorshipProfile: SponsorshipProfile | null;
  /**
   * BE-127 — a governmental entity's verified mark. Teams only, read from the
   * organization branch's `is_verified`: on a volunteer that same key is the
   * volunteer-verification flag, which must never light this up.
   */
  isGovernmentVerified: boolean;
  stats: {
    hours: number | string;
    volunteerOpportunities: number;
    developmentOpportunities: number;
    /** Organizations only — what they sponsored. Absent elsewhere. */
    sponsorships?: number;
  };
  /**
   * Which stat tiles to render. Hours and volunteering are always true; the
   * backend turns `development` on only once the person has any. A payload
   * that predates the field leaves this null and every tile shows.
   */
  /**
   * The five named `counter_visibility` flags, or null for a payload that
   * predates the field.
   *
   * `CounterVisibility`, not `Record<string, boolean>`: the record form's
   * index signature accepted any key, so `TILES`' `visibilityKey` strings
   * were never checked against the flags the backend actually sends.
   */
  counterVisibility: CounterVisibility | null;
  /**
   * «خبير» — a volunteer who runs their own courses, workshops or spaces.
   * Tagged on the Development chip. Teams never carry it.
   */
  isExpert: boolean;
  /** Only the owner's own profile sends the number; the public one does not. */
  expertOpportunitiesCount: number | null;
  interests: LocalizedChoice[];
  social: {
    twitter: string | null;
    linkedin: string | null;
    instagram: string | null;
    whatsapp: string | null;
    facebook: string | null;
    website: string | null;
  };
}

/**
 * The union of keys the four payloads this module normalizes may carry.
 *
 * Was `type Raw = any`, with a note saying "the payloads are untyped JSON".
 * They are not untyped — they are four *different* resources, and the reason
 * this module exists is that they disagree. Declaring the union of keys it
 * reads keeps the tolerance (every field is optional, and the `??` chains
 * below still try the alternative spellings in turn) while making a typo a
 * compile error rather than a silent `undefined`. That is the difference `any`
 * was costing: nothing checked that
 * `allTime.total_learn_opportunities` and friends were spelled the way the
 * backend spells them.
 *
 * Every key here was taken from a read in this file; several are alternatives
 * for the same figure, which is deliberate and documented at each `??` chain.
 * `[key: string]: unknown` is **not** added: an index signature would restore
 * exactly the hole being closed.
 */
interface ProfilePayloadFields {
  id?: number | string | null;
  /** BE-127 on `/organization-profile/` — governmental. Teams only; see `isGovernmentVerified`. */
  is_verified?: boolean | null;
  is_government_entity?: boolean | null;
  full_name?: string | null;
  display_name?: string | null;
  nickname?: string | null;
  occupation?: string | null;
  current_status?: string | null;
  profile_pic?: string | null;
  company_name?: string | null;
  license_number?: string | null;
  registration_number?: string | null;
  gender_display?: { value_en?: string | null } | null;
  badge_info?: ProfileBadgeInfo | null;
  /** PDF p.31, on `/organization-profile/` since backend `1983649` (BE-238). */
  sponsorship_profile?: SponsorshipProfile | null;
  /** Leaderboard position, null when unranked — every profile payload sends it. */
  current_rank?: number | string | null;
  interest_display?: LocalizedChoice[] | null;

  /* Counters. The `statistics.all_time` block and the flat keys are two
     generations of the same figures; `statsFrom` tries them in order. */
  statistics?: {
    all_time?: {
      total_hours?: number | string | null;
      total_opportunities?: number | string | null;
      total_volunteer_opportunities?: number | string | null;
      total_learn_opportunities?: number | string | null;
      total_development_opportunities?: number | string | null;
      opportunities_organized?: number | string | null;
    } | null;
  } | null;
  total_hours?: number | string | null;
  total_volunteer_hours?: number | string | null;
  total_opportunities?: number | string | null;
  total_volunteer_opportunities?: number | string | null;
  volunteer_opportunities_count?: number | string | null;
  development_opportunities_count?: number | string | null;
  opportunities_organized?: number | string | null;
  /** Team counters: what the team published. */
  organization_hours?: number | string | null;
  vol_opportunity_organized?: number | string | null;
  learn_opportunity_organized?: number | string | null;
  /** `sponsored_count` on `/organization-profile/`, `sponsored` on the public one. */
  sponsored_count?: number | string | null;
  sponsored?: number | string | null;

  /* BE-97 / the expert flags, on both the own and public payloads. */
  /**
   * `CounterVisibility` — the five named flags — rather than
   * `Record<string, boolean>`: the record form has an index signature, which
   * accepts any key and so would not have caught a renamed flag. The view
   * reads it through its own named fields.
   */
  counter_visibility?: CounterVisibility | null;
  is_expert?: boolean | null;
  expert_opportunities_count?: number | string | null;

  twitter_link?: string | null;
  linkedin_link?: string | null;
  instagram_link?: string | null;
  whatsapp_link?: string | null;
  facebook_link?: string | null;
  website_link?: string | null;
}

/*
 * The public-profile envelope is **not** re-declared here: it already exists
 * as `commonProfileTypes.PublicProfileResponse`, with its `profile_data` typed
 * as `ProfileData`. Declaring a second model of the same payload is how the
 * two drift; the functions below take the existing one.
 *
 * `ProfilePayloadFields` is the own-profile side, where the sources are
 * `/volunteer-profile/`, `/organization-profile/` and `/account/`.
 */
type Raw = ProfilePayloadFields | null | undefined;

/**
 * `total_opportunities` mixes attended volunteering with attended development,
 * so until BE-97 A sends `volunteer_opportunities_count` the volunteer figure
 * is derived: total − (development − the development ones they provided).
 */
function statsFrom(profile: Raw) {
  const allTime = profile?.statistics?.all_time ?? {};
  const development = toNumber(
    profile?.development_opportunities_count ??
      allTime.total_learn_opportunities ??
      allTime.total_development_opportunities
  );
  const provided = toNumber(
    profile?.opportunities_organized ?? allTime.opportunities_organized
  );
  const attendedTotal = toNumber(
    allTime.total_opportunities ?? profile?.total_opportunities
  );
  const explicitVolunteer =
    profile?.volunteer_opportunities_count ??
    allTime.total_volunteer_opportunities ??
    profile?.total_volunteer_opportunities;

  return {
    hours: allTime.total_hours ?? profile?.total_volunteer_hours ?? 0,
    volunteerOpportunities:
      explicitVolunteer != null
        ? toNumber(explicitVolunteer)
        : Math.max(0, attendedTotal - Math.max(0, development - provided)),
    developmentOpportunities: development,
  };
}

/** `is_expert` / `counter_visibility`, on both the own and public payloads. */
function expertFrom(profile: Raw) {
  return {
    /* No cast: `counter_visibility` is declared on the payload shape now, so
       the field carries its own type across. The cast it replaces was a
       `Record<string, boolean>`, which is what let the flag names go
       unchecked at the tile table. */
    counterVisibility: profile?.counter_visibility ?? null,
    isExpert: profile?.is_expert === true,
    expertOpportunitiesCount:
      profile?.expert_opportunities_count == null
        ? null
        : toNumber(profile.expert_opportunities_count),
  };
}

/** `current_rank`, or null when the account is unranked (or the value is not a rank). */
export function rankFrom(profile: Raw | ProfileData): number | null {
  const raw = profile?.current_rank;
  if (raw == null || raw === "") return null;
  const rank = toNumber(raw);
  return Number.isInteger(rank) && rank > 0 ? rank : null;
}

/** «type – level» in the current language; empty when neither label exists. */
export function sponsorshipProfileLabel(
  sponsorship: SponsorshipProfile | null | undefined,
  language: string
): string {
  return [sponsorship?.type, sponsorship?.level]
    .map((choice) => pickLocalized(choice?.value_en, choice?.value_ar, language))
    .filter(Boolean)
    .join(" – ");
}

function socialFrom(profile: Raw): IndividualProfileData["social"] {
  return {
    twitter: profile?.twitter_link || null,
    linkedin: profile?.linkedin_link || null,
    instagram: profile?.instagram_link || null,
    whatsapp: profile?.whatsapp_link || null,
    facebook: profile?.facebook_link || null,
    website: profile?.website_link || null,
  };
}

export function fromOwnProfile(
  profile: Raw,
  account: Raw,
  /* `| null` on the names: these come from `authStore.user`, where
     `first_name` / `last_name` mirror nullable columns. */
  fallback: {
    id?: number | string;
    first_name?: string | null;
    last_name?: string | null;
  } | null
): IndividualProfileData {
  return {
    kind: "individual",
    isGovernmentVerified: false,
    licenseNumber: null,
    userId: String(account?.id ?? fallback?.id ?? ""),
    name:
      account?.full_name ||
      [fallback?.first_name, fallback?.last_name].filter(Boolean).join(" "),
    nickname: profile?.nickname || null,
    occupation: profile?.occupation || null,
    profilePic: account?.profile_pic || profile?.profile_pic || null,
    genderEn: profile?.gender_display?.value_en ?? null,
    badge: profile?.badge_info ?? null,
    rank: rankFrom(profile),
    sponsorshipProfile: null,
    stats: statsFrom(profile),
    ...expertFrom(profile),
    interests: profile?.interest_display ?? [],
    social: socialFrom(profile),
  };
}

export function fromPublicProfile(
  response: PublicProfileResponse | null | undefined
): IndividualProfileData {
  /* `?? {}` widened to the declared shape rather than left as `{}`, which
     TypeScript infers as having no keys at all. The endpoint can genuinely
     answer `profile_data: null` — for a profile the viewer may not see — and
     every read below is already optional. */
  const profile: ProfileData | ProfilePayloadFields =
    response?.profile_data ?? {};
  return {
    kind: "individual",
    isGovernmentVerified: false,
    licenseNumber: null,
    userId: String(profile.id ?? ""),
    // `full_name` is null here on purpose; `display_name` is what may be shown.
    name: profile.full_name || profile.display_name || profile.nickname || "",
    nickname: profile.nickname || null,
    occupation: profile.occupation || profile.current_status || null,
    profilePic: profile.profile_pic || null,
    genderEn: profile.gender_display?.value_en ?? null,
    badge: response?.badge_info ?? null,
    rank: rankFrom(profile),
    sponsorshipProfile: null,
    stats: statsFrom(profile),
    ...expertFrom(profile),
    interests: profile.interest_display ?? [],
    social: socialFrom(profile),
  };
}

/** The governmental mark: the explicit flag, or `is_verified` before it existed. */
function isGovernment(profile: Raw | ProfileData): boolean {
  return (profile?.is_government_entity ?? profile?.is_verified) === true;
}

/**
 * An organization's counters: what it organized, plus what it sponsored.
 */
function organizationStatsFrom(profile: Raw | ProfileData): IndividualProfileData["stats"] {
  return {
    ...teamStatsFrom(profile),
    sponsorships: toNumber(profile?.sponsored_count ?? profile?.sponsored),
  };
}

export function fromOwnOrganizationProfile(profile: Raw, account: Raw): IndividualProfileData {
  return {
    ...fromOwnTeamProfile(profile, account),
    kind: "organization",
    // Not in the organization design; the number stays on the account screen.
    licenseNumber: null,
    // BE-238 (backend `1983649`): the owner payload now sends it, as the public one does.
    sponsorshipProfile: profile?.sponsorship_profile ?? null,
    isGovernmentVerified: isGovernment(profile),
    stats: organizationStatsFrom(profile),
  };
}

export function fromPublicOrganizationProfile(
  response: PublicProfileResponse | null | undefined
): IndividualProfileData {
  return {
    ...fromPublicTeamProfile(response),
    kind: "organization",
    licenseNumber: null,
    sponsorshipProfile: response?.profile_data?.sponsorship_profile ?? null,
    isGovernmentVerified: isGovernment(response?.profile_data),
    stats: organizationStatsFrom(response?.profile_data),
  };
}

/**
 * A team's counters are what it organized: hours, volunteer opportunities and
 * development opportunities it published.
 */
function teamStatsFrom(profile: Raw): IndividualProfileData["stats"] {
  return {
    hours: profile?.organization_hours ?? 0,
    volunteerOpportunities: toNumber(profile?.vol_opportunity_organized),
    developmentOpportunities: toNumber(profile?.learn_opportunity_organized),
  };
}

export function fromOwnTeamProfile(profile: Raw, account: Raw): IndividualProfileData {
  return {
    kind: "team",
    userId: String(account?.id ?? ""),
    // The registered name is the identity of an organization / team (BE-294, same as the
    // directory tile); `nickname` is only the username it was seeded from at sign-up.
    name: profile?.company_name || profile?.display_name || profile?.nickname || account?.full_name || "",
    nickname: account?.nickname || profile?.nickname || null,
    occupation: null,
    licenseNumber: profile?.license_number || profile?.registration_number || null,
    profilePic: account?.profile_pic || null,
    genderEn: null,
    badge: profile?.badge_info ?? null,
    rank: rankFrom(profile),
    // Teams have no sponsorship type/level; the organization mapper sets it.
    sponsorshipProfile: null,
    isGovernmentVerified: profile?.is_verified === true,
    stats: teamStatsFrom(profile),
    // BE-132 (backend `0572fb7`): organizations and teams now send it too.
    counterVisibility: profile?.counter_visibility ?? null,
    isExpert: false,
    expertOpportunitiesCount: null,
    interests: profile?.interest_display ?? [],
    social: socialFrom(profile),
  };
}

export function fromPublicTeamProfile(
  response: PublicProfileResponse | null | undefined
): IndividualProfileData {
  const profile: ProfileData | ProfilePayloadFields =
    response?.profile_data ?? {};
  return {
    kind: "team",
    userId: String(profile.id ?? ""),
    name: profile.company_name || profile.display_name || profile.nickname || "",
    nickname: profile.nickname || null,
    occupation: null,
    licenseNumber: profile.license_number || profile.registration_number || null,
    profilePic: profile.profile_pic || null,
    genderEn: null,
    badge: response?.badge_info ?? null,
    rank: rankFrom(profile),
    sponsorshipProfile: null,
    isGovernmentVerified: profile.is_verified === true,
    stats: teamStatsFrom(profile),
    counterVisibility: profile.counter_visibility ?? null,
    isExpert: false,
    expertOpportunitiesCount: null,
    interests: profile.interest_display ?? [],
    social: socialFrom(profile),
  };
}
