import type { ReviewSchedule } from "@/features/shared/clientReviewPolicy";
import { type OpportunityBadgeFlags } from "./OpportunityBadges";
import type {
  CardBadgePerspective,
  CardBadgeSource,
} from "@/features/opportunities/cardStatusBadges";

/**
 * The card's shapes, its per-list accent colours, and the three small
 * formatters it renders through.
 *
 * Separated from the component because the accent table is a design decision
 * shared by four call sites, and because `formatTimeRange` and `clampText` are
 * the kind of pure helper worth reading on their own.
 */
/*
 * Re-exported, not redeclared. The local copy said `image: string`, while
 * `websiteImageList()` emits `$img->image ? getimg(...) : null` — so an empty
 * column arrives as null. Two types for one payload is how that drifted.
 */
import type {
  OpportunityCardImage as RecordCardImage,
  OpportunityCardInterest,
} from "@/features/opportunities/opportunityRecord";
import type { WebsiteChoiceDisplay } from "@/features/shared/apiPrimitives";

export type { OpportunityCardImage } from "@/features/opportunities/opportunityRecord";

/**
 * The subset of the opportunity payload the card renders. Deliberately
 * structural rather than one of the three call sites' own interfaces — those
 * disagree on optionality, and the card only ever reads these fields.
 */
export interface OpportunityCardItem extends OpportunityBadgeFlags, ReviewSchedule {
  id: number | string;
  /* Nullable on all three resources — `title_en`/`title_ar` are
     `->nullable()` in `create_opportunity_tables` and `create_event_tables`,
     and the card renders `(ar ? title_ar : title_en) || ""`. Declaring them
     `string` made three local row types claim a guarantee the column does not
     give. */
  title_en: string | null;
  title_ar: string | null;
  opportunity_images?: RecordCardImage[] | null;
  start_date?: string | null;
  end_date?: string | null;
  start_time?: string | null;
  end_time?: string | null;
  from_age?: number | string | null;
  to_age?: number | string | null;
  registered_volunteers_count?: number | string | null;
  participants_needed?: number | string | null;
  is_public?: boolean;
  format?: string | null;
  /* `value_en`/`value_ar` are nullable, not merely optional:
     `websiteChoicePayload()` drops a null key entirely, and
     `websiteInterestDisplay()` emits `value_en ?? name_en`, which is null when
     both columns are. The card reads them through `?? ""`. */
  format_display?: WebsiteChoiceDisplay | null;
  learning_type_display?: WebsiteChoiceDisplay | null;
  location_en?: string | null;
  location_ar?: string | null;
  /** The map pin's label — the only place text the current forms send. */
  map_desc?: string | null;
  interest_display?: OpportunityCardInterest[] | null;
  /* The cover pills — see `cardStatusBadges`. All optional: events and older
     rows reuse this card without them. */
  opportunity_type?: string | null;
  opportunity_status?: string | null;
  has_ended?: boolean | null;
  is_paid?: boolean | null;
  payment_status?: string | null;
  cancellation_status?: string | null;
  has_successful_payments?: boolean;
  price?: number | string | null;
  relationship_tags?: CardBadgeSource["relationship_tags"];
  profile_activity_tag?: CardBadgeSource["profile_activity_tag"];
  owner_attendance_status?: CardBadgeSource["owner_attendance_status"];
  action_state?: string | null;
  is_registered?: boolean | null;
  is_registration_open?: boolean | null;
  can_register_while_running?: boolean | null;
  is_registration_closed?: boolean | null;
  /** The creator's own card says «التفاصيل» rather than a join action. */
  created_by?: { id?: number | string | null } | null;
  is_creator?: boolean | null;
}

export interface OpportunityCardProps {
  item: OpportunityCardItem;
  /** Learn & serve swaps the age row for the learning type and the location for "in person". */
  isLearnServe?: boolean;
  /** Where the image, title and detail rows link to. */
  detailHref: string;
  /** Tailwind border colour for the content box, e.g. `border-primary-5`. */
  borderClass: string;
  /** Tailwind background colour for the action button, e.g. `bg-primary-5`. */
  buttonClass: string;
  /** Person icon variant — the homepage tints it per section. */
  peopleIconSrc?: string;
  /** Owner-only controls drawn over the image (delete, edit). */
  headerOverlay?: React.ReactNode;
  /** Status pill shown beside the title on the profile screens. */
  statusPill?: React.ReactNode;
  /** Makes the interest tag clickable, navigating to the filtered list. */
  onTagClick?: (tag: string) => void;
  /** Whose relation the cover pills describe. Defaults to the viewer's. */
  badgePerspective?: CardBadgePerspective;
}

export interface OpportunityAccent {
  /** Border colour for the card's content box. */
  border: string;
  /** Background colour for the action button and the carousel arrows. */
  button: string;
  /** Tinted person icon for the "registered / needed" row. */
  peopleIcon: string;
  /** Tinted delete icon for the owner overlay. */
  deleteIcon: string;
}

/**
 * The card's colour scheme.
 *
 * The homepage tints each section — teal for learn & serve, blue for volunteer
 * opportunities — while every other surface uses the default purple. All three
 * card hosts previously inlined this same three-branch ternary four times each,
 * which is how the tints drifted out of step with the icons.
 */
export const getOpportunityAccent = ({
  isLearnServe = false,
  isOpportunity = false,
  isHomepage = false,
}: {
  isLearnServe?: boolean;
  isOpportunity?: boolean;
  isHomepage?: boolean;
}): OpportunityAccent => {
  if (isHomepage && isLearnServe) {
    return {
      border: "border-primary-803",
      button: "bg-primary-803",
      peopleIcon: "/assets/homepage/person_icon_organized.svg",
      deleteIcon: "/assets/voluneteerevent/card_delete_icon_organized.svg",
    };
  }

  if (isHomepage && isOpportunity) {
    return {
      border: "border-primary-802",
      button: "bg-primary-802",
      peopleIcon: "/assets/homepage/person_icon_blue.svg",
      deleteIcon: "/assets/voluneteerevent/card_delete_icon_blue.svg",
    };
  }

  return {
    border: "border-primary-5",
    button: "bg-primary-5",
    peopleIcon: "/assets/homepage/person.svg",
    deleteIcon: "/assets/voluneteerevent/card_delete_icon.svg",
  };
};

/** A value is "online" if either the enum or the localized display says so. */
export const isOnlineFormat = (item: OpportunityCardItem): boolean =>
  item.format === "ONLINE" ||
  item.format_display?.value_en?.toLowerCase() === "online" ||
  item.format_display?.value_ar?.toLowerCase() === "عن بعد";

/**
 * Clamp to a character budget as well as a CSS line clamp.
 *
 * `line-clamp-1` alone is not enough here: these rows sit in a two-column grid,
 * so a long unbroken location string pushes the neighbouring column instead of
 * ellipsing. The character cap keeps the grid stable.
 */
export const clampText = (value: string, max: number): string =>
  value.length > max ? `${value.slice(0, max)}...` : value;

export { clockTimeRange as formatTimeRange } from "@/features/shared/clockLabel";
