/**
 * "Детали рейса" section shown inside the schedule details page for
 * each flight leg. Mirrors Angular's `flight-details-wrapper` accordion
 * (schedule view): two rows when the data exists.
 *
 *  1. Борт — aircraft type with a link to its Aeroflot info page.
 *  2. Питание на борту — meal-class sub-icons (Эконом / Комфорт /
 *     Бизнес), each rendered ONLY when the API's
 *     `equipment.meal[]` array contains the matching `type`. Matches
 *     Angular's `*ngIf="hasEconomyMeal"` etc. — flights with no meal
 *     data show just the cutlery icon + caption with no sub-icons.
 *
 * Expanded by default, toggled via the header.
 *
 * @module
 */

import { useState, type FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import type { ISimpleFlight } from "@/features/online-board/types.js";
import economIcon from "@/features/online-board/components/details-panels/icons/econom.svg";
import comfortIcon from "@/features/online-board/components/details-panels/icons/comfort.svg";
import businessIcon from "@/features/online-board/components/details-panels/icons/business.svg";
import "./ScheduleLegDetails.scss";

export interface ScheduleLegDetailsProps {
  flight: ISimpleFlight;
}

/** Slug used for the aircraft catalog deep-link on www.aeroflot.ru. */
function aircraftSlug(title: string | undefined | null): string | null {
  if (!title) return null;
  return title
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "");
}

export const ScheduleLegDetails: FC<ScheduleLegDetailsProps> = ({ flight }) => {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState<boolean>(true);

  const leg = flight.routeType === "Direct" ? flight.leg : flight.legs[0];
  if (!leg) return null;

  const aircraft =
    leg.equipment?.aircraft?.actual?.title ??
    leg.equipment?.aircraft?.scheduled?.title ??
    "";
  const slug = aircraftSlug(aircraft);
  // External Aeroflot page that describes the aircraft model. Angular
  // uses a curated slug map; the simple kebab-case works for common
  // models (e.g. sukhoi-superjet-100).
  const planeUrl = slug
    ? `https://www.aeroflot.ru/ru-ru/about/aircrafts/${slug}`
    : null;

  return (
    <div className="schedule-leg-details" data-testid="schedule-leg-details">
      <button
        type="button"
        className="schedule-leg-details__header"
        onClick={() => setExpanded((v) => !v)}
        aria-expanded={expanded}
      >
        <span className="schedule-leg-details__title">
          {t("SHARED.DETAILS-FLIGHT")}
        </span>
        <span
          className={`schedule-leg-details__chevron${
            expanded ? "" : " schedule-leg-details__chevron--collapsed"
          }`}
          aria-hidden="true"
        >
          <svg viewBox="-6 -8 24 24" width="20" height="20" fill="currentColor">
            <path d="M1.41 7.41 6 2.83l4.59 4.58L12 6 6 0 0 6Z" />
          </svg>
        </span>
      </button>

      {expanded && (
        <div className="schedule-leg-details__body">
          {aircraft && (
            <div className="schedule-leg-details__row">
              <span
                className="schedule-leg-details__icon schedule-leg-details__icon--plane"
                aria-hidden="true"
              >
                {/* Aircraft 'company crane' icon — copied verbatim from
                    Angular's sprite (`/assets/img/sprite.svg#company`).
                    This is what the legacy details panel uses next to
                    the 'Борт' caption, NOT the simpler plane glyph. */}
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 47.488 46.928"
                  width="34"
                  height="34"
                >
                  <g
                    transform="translate(-1.586 -0.987)"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M32.5,12l-21-6.5c-1,0-1.139-.01-1.366.226L7.5,8a.922.922,0,0,0-.245.763.9.9,0,0,0,.44.662L25.5,19" />
                    <path d="M12,37,3,46" />
                    <path d="M14,41.5l-5,5" />
                    <path d="M46.173,8.537l0,0L22.721,32.233a1,1,0,0,0-.246.994l1.918,6.308-3.655,3.652-4.709-8.5a1,1,0,0,0-.391-.391l-8.6-4.75L10.7,25.889,17.007,27.8a1,1,0,0,0,1-.254L41.453,3.857l0,0h0A7,7,0,0,1,44.32,2.173a2.981,2.981,0,0,1,3.053.564,2.883,2.883,0,0,1,.465,3.051,7.357,7.357,0,0,1-1.663,2.747Zm-25.5,34.711h0Zm.1.014h0ZM6.966,29.5h0l-.032.057Zm3.694-3.622h0Z" />
                    <path d="M14.5,6.5l-4,4" />
                    <path d="M38,17l6.5,21c0,1,.01,1.139-.226,1.366L42,42a.922.922,0,0,1-.763.245.9.9,0,0,1-.662-.44L31,24" />
                    <path d="M43.5,35l-4,4" />
                  </g>
                </svg>
              </span>
              <span className="schedule-leg-details__label">
                {t("SHARED.PLANE")}
              </span>
              {planeUrl ? (
                <a
                  className="schedule-leg-details__link"
                  href={planeUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {aircraft}
                </a>
              ) : (
                <span className="schedule-leg-details__value">{aircraft}</span>
              )}
            </div>
          )}

          {/* Питание на борту — meal-class sub-icons gated by what the
              API reports in `equipment.meal[]` (matches Angular's
              *ngIf="hasEconomyMeal" etc). Schedule view also shows the
              row when meal data is missing — just no sub-icons. */}
          {(() => {
            const meals = leg.equipment?.meal ?? [];
            const types = new Set(meals.map((m) => m.type));
            return (
              <div className="schedule-leg-details__row schedule-leg-details__row--meals">
                <span
                  className="schedule-leg-details__icon schedule-leg-details__icon--dining"
                  aria-hidden="true"
                >
                  {/* Cloche/serving-dome icon copied verbatim from
                      Angular's toolkit/icons/dining/dining-icon.component
                      so the panel matches the legacy 'Питание на борту'
                      glyph (small dome with handle on a base line). */}
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 44 34"
                    width="34"
                    height="26"
                  >
                    <g transform="translate(-3 -15.853)">
                      <path
                        d="M7.807 43.151a21.729 21.729 0 0 1-.184-2.83c0-10.552 7.566-19.105 16.9-19.105s16.9 8.554 16.9 19.105a21.733 21.733 0 0 1-.184 2.83"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      />
                      <path
                        d="m7.623 41.688 2.323 6.031A2 2 0 0 0 11.813 49h25.418a2 2 0 0 0 1.869-1.281l2.323-6.031"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      />
                      <rect
                        width="1.913"
                        height="5.85"
                        rx=".957"
                        transform="translate(23.548 15.853)"
                        fill="currentColor"
                      />
                      <rect
                        width="44"
                        height="1.95"
                        rx=".975"
                        transform="translate(3 41.201)"
                        fill="currentColor"
                      />
                    </g>
                  </svg>
                </span>
                <span className="schedule-leg-details__label">
                  {t("SHARED.FOOD")}
                </span>
                <div className="schedule-leg-details__meals">
                  {types.has("Economy") && (
                    <MealPill icon="econom" labelKey="FOOD.ECONOMY" t={t} />
                  )}
                  {types.has("Comfort") && (
                    <MealPill icon="comfort" labelKey="FOOD.COMFORT" t={t} />
                  )}
                  {types.has("Business") && (
                    <MealPill icon="business" labelKey="FOOD.BUSINESS" t={t} />
                  )}
                </div>
              </div>
            );
          })()}
        </div>
      )}
    </div>
  );
};

interface MealPillProps {
  icon: "econom" | "comfort" | "business";
  labelKey: string;
  t: (k: string) => string;
}

const MEAL_ICONS: Record<MealPillProps["icon"], string> = {
  econom: economIcon,
  comfort: comfortIcon,
  business: businessIcon,
};

const MealPill: FC<MealPillProps> = ({ icon, labelKey, t }) => (
  <span
    className={`schedule-leg-details__meal schedule-leg-details__meal--${icon}`}
  >
    <img
      className="schedule-leg-details__meal-icon"
      src={MEAL_ICONS[icon]}
      alt=""
      aria-hidden="true"
    />
    <span className="schedule-leg-details__meal-caption">{t(labelKey)}</span>
  </span>
);
