'use client';

import { CSSProperties, useEffect, useMemo, useRef, useState, useTransition } from 'react';

import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useSearchParams } from 'next/navigation';

import { Loader2, X } from 'lucide-react';
import { IoHomeOutline } from 'react-icons/io5';
import { RiCrossFill } from 'react-icons/ri';

import Breadcrumbs, { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import CreationCard from '@/components/creations/CreationCard';
import CreatorAvatar from '@/components/creators/CreatorAvatar';
import { Select, SelectContent, SelectItem, SelectTrigger } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { metaAttributes110 } from '@/utils/filterUtils';
import { parallelPathsFilters } from '@/utils/parallelPathsHelpers';

import { MetaAttribute110 } from '@/types/Category';
import { CreationListItem, CreatorTimelineCategory } from '@/types/Creation';
import { CreatorData, CreatorListData } from '@/types/Creator';

import { Link, useRouter } from '@/i18n/navigation';

const TIMELINE_CATEGORIES: CreatorTimelineCategory[] = ['alkotas', 'eletut'];

const TIMELINE_YEAR_PATTERN = /\b(1\d{3}|20\d{2})\b/;
const TIMELINE_LINE_BACKGROUND =
  'linear-gradient(180deg, rgba(223,207,111,0) 0px, rgba(223,207,111,0) 56px, rgba(223,207,111,0.36) 92px, #dfcf6f 132px, #dfcf6f 100%)';
const TIMELINE_LINE_SOLID = '#dfcf6f';
const LIFE_LANE_BACKGROUND = 'rgba(184, 218, 220, 0.24)';
const CREATION_LANE_BACKGROUND = 'rgba(223, 207, 111, 0.06)';

type TimelineYear = number | 'unknown';

interface TimelineRowData {
  year: TimelineYear;
  left: CreationListItem[];
  right: CreationListItem[];
}

interface DesktopCombinedRowData {
  year: TimelineYear;
  leftCreations: CreationListItem[];
  rightCreations: CreationListItem[];
  leftLife: CreationListItem[];
  rightLife: CreationListItem[];
}

interface ParallelPathsClientProps {
  className?: string;
  category?: string | null;
  nameList: CreatorListData[];
  creatorLeft: CreatorData | null;
  creatorRight: CreatorData | null;
  dataLeft?: CreationListItem[];
  dataRight?: CreationListItem[];
  lifeLeft?: CreationListItem[] | null;
  lifeRight?: CreationListItem[] | null;
  locale: string;
}

function getCreationYear(item: CreationListItem): TimelineYear {
  if (typeof item.labelYear === 'number' && Number.isFinite(item.labelYear)) {
    if (item.labelYear === 1000) {
      return 'unknown';
    }
    return item.labelYear;
  }

  const source = item.label || '';
  const match = source.match(TIMELINE_YEAR_PATTERN);
  if (match?.[0]) {
    const parsedYear = Number.parseInt(match[0], 10);
    return parsedYear === 1000 ? 'unknown' : parsedYear;
  }

  return 'unknown';
}

function getSafeTimelineCategory(value: string | null | undefined): CreatorTimelineCategory {
  if (!value) {
    return 'alkotas';
  }

  return TIMELINE_CATEGORIES.includes(value as CreatorTimelineCategory)
    ? (value as CreatorTimelineCategory)
    : 'alkotas';
}

function getSafeCreationList(data?: CreationListItem[] | null): CreationListItem[] {
  return Array.isArray(data) ? data : [];
}

function getOrCreateMapValue<K, V>(map: Map<K, V>, key: K, createValue: () => V): V {
  const existing = map.get(key);
  if (existing) {
    return existing;
  }

  const created = createValue();
  map.set(key, created);
  return created;
}

function compareTimelineYearsDesc(yearA: TimelineYear, yearB: TimelineYear) {
  if (yearA === 'unknown' && yearB === 'unknown') return 0;
  if (yearA === 'unknown') return 1;
  if (yearB === 'unknown') return -1;
  return yearB - yearA;
}

function getTimelineColumnCount(width: number): number {
  let columns = 1;
  if (width > 380) columns = 2;
  if (width > 520) columns = 3;
  if (width > 768) columns = 4;
  if (width > 1024) columns = 5;
  if (width > 1280) columns = 6;
  if (width > 1500) columns = 7;
  if (width > 1800) columns = 8;
  return columns;
}

function getStickyHeaderOffset(): number {
  if (typeof window === 'undefined') {
    return 0;
  }

  const root = document.documentElement;
  const raw = window.getComputedStyle(root).getPropertyValue('--header-h');
  const value = Number.parseFloat(raw.replace('px', '').trim());
  return Number.isFinite(value) ? value : 0;
}

function buildTimelineRows(
  leftData?: CreationListItem[] | null,
  rightData?: CreationListItem[] | null
): TimelineRowData[] {
  const safeLeftData = getSafeCreationList(leftData);
  const safeRightData = getSafeCreationList(rightData);

  const grouped = new Map<TimelineYear, { left: CreationListItem[]; right: CreationListItem[] }>();

  for (const item of safeLeftData) {
    const year = getCreationYear(item);
    const row = getOrCreateMapValue(grouped, year, () => ({
      left: [],
      right: [],
    }));
    row.left.push(item);
  }

  for (const item of safeRightData) {
    const year = getCreationYear(item);
    const row = getOrCreateMapValue(grouped, year, () => ({
      left: [],
      right: [],
    }));
    row.right.push(item);
  }

  return Array.from(grouped.entries())
    .sort(([yearA], [yearB]) => compareTimelineYearsDesc(yearA, yearB))
    .map(([year, value]) => ({ year, left: value.left, right: value.right }))
    .filter((row) => row.left.length > 0 || row.right.length > 0);
}

function getCreationCardKey(item: CreationListItem, index: number): string {
  if (item.alkotasAzonosito) {
    return item.alkotasAzonosito;
  }

  if (typeof item.id === 'number') {
    return `${item.cardType}-${item.id}`;
  }

  if (item.hivatkozas) {
    return `${item.cardType}-${item.hivatkozas}-${index}`;
  }

  return `${item.cardType}-${item.nev || 'item'}-${index}`;
}

function getYearDisplay(year: TimelineYear): string {
  return year === 'unknown' ? '----' : String(year);
}

function getCreatorCardNameSizeClass(name?: string): string {
  const compactNameLength = (name || '').replace(/[\s-]+/g, '').length;
  if (compactNameLength >= 24) {
    return 'text-[11.5px] sm:text-[12.5px] tracking-[-0.018em]';
  }
  if (compactNameLength >= 20) {
    return 'text-[12px] sm:text-[13.25px] tracking-[-0.014em]';
  }
  return 'text-[12.5px] sm:text-[14px] tracking-[-0.01em]';
}

function TimelineYearLabel({ year }: { year: TimelineYear }) {
  if (year === 'unknown') {
    return null;
  }

  return (
    <div className="pointer-events-none absolute left-1/2 top-0 h-10 w-5 -translate-x-1/2 lg:w-4">
      <div className="flex h-full w-full items-start justify-center">
        <span className="mt-1 -rotate-90 origin-center whitespace-nowrap text-[13px] font-bold leading-none tracking-[0.1em] text-mma-blue lg:mt-1.5 lg:text-[15px] lg:tracking-[0.14em]">
          {getYearDisplay(year)}
        </span>
      </div>
    </div>
  );
}

function buildDesktopCombinedRows(
  leftCreations?: CreationListItem[] | null,
  rightCreations?: CreationListItem[] | null,
  leftLife?: CreationListItem[] | null,
  rightLife?: CreationListItem[] | null
): DesktopCombinedRowData[] {
  const safeLeftCreations = getSafeCreationList(leftCreations);
  const safeRightCreations = getSafeCreationList(rightCreations);
  const safeLeftLife = getSafeCreationList(leftLife);
  const safeRightLife = getSafeCreationList(rightLife);

  const grouped = new Map<TimelineYear, DesktopCombinedRowData>();
  const getDesktopRow = (year: TimelineYear) =>
    getOrCreateMapValue(grouped, year, () => ({
      year,
      leftCreations: [],
      rightCreations: [],
      leftLife: [],
      rightLife: [],
    }));

  safeLeftCreations.forEach((item) => {
    const year = getCreationYear(item);
    getDesktopRow(year).leftCreations.push(item);
  });
  safeRightCreations.forEach((item) => {
    const year = getCreationYear(item);
    getDesktopRow(year).rightCreations.push(item);
  });
  safeLeftLife.forEach((item) => {
    const year = getCreationYear(item);
    getDesktopRow(year).leftLife.push(item);
  });
  safeRightLife.forEach((item) => {
    const year = getCreationYear(item);
    getDesktopRow(year).rightLife.push(item);
  });

  return Array.from(grouped.values())
    .sort((a, b) => compareTimelineYearsDesc(a.year, b.year))
    .filter(
      (row) =>
        row.leftCreations.length > 0 ||
        row.rightCreations.length > 0 ||
        row.leftLife.length > 0 ||
        row.rightLife.length > 0
    );
}

export default function ParallelPathsClient({
  className,
  category,
  nameList,
  creatorLeft,
  creatorRight,
  dataLeft,
  dataRight,
  lifeLeft,
  lifeRight,
  locale,
}: ParallelPathsClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations('parallelPathsPage');
  const tNavigation = useTranslations('navigation.menu');
  const [isNavigating, startTransition] = useTransition();
  const [showCompactCreatorHeader, setShowCompactCreatorHeader] = useState(false);
  const creatorHeaderSentinelRef = useRef<HTMLDivElement | null>(null);
  const creatorHeaderRef = useRef<HTMLDivElement | null>(null);
  const [creatorHeaderHeight, setCreatorHeaderHeight] = useState(0);
  const [viewportWidth, setViewportWidth] = useState(0);
  const isHuLocale = locale === 'hu';

  const leftParam = t('urlParams.left');
  const rightParam = t('urlParams.right');
  const categoryParam = t('urlParams.category');

  const activeCategory = getSafeTimelineCategory(searchParams.get(categoryParam) || category);

  const creationRows = useMemo(() => buildTimelineRows(dataLeft, dataRight), [dataLeft, dataRight]);
  const lifeRows = useMemo(() => buildTimelineRows(lifeLeft, lifeRight), [lifeLeft, lifeRight]);
  const mobileRows = useMemo(
    () => (activeCategory === 'eletut' ? lifeRows : creationRows),
    [activeCategory, creationRows, lifeRows]
  );
  const knownMobileRows = useMemo(
    () => mobileRows.filter((row) => row.year !== 'unknown'),
    [mobileRows]
  );
  const unknownMobileRows = useMemo(
    () => mobileRows.filter((row) => row.year === 'unknown'),
    [mobileRows]
  );
  const unknownMobileLeftItems = useMemo(
    () => unknownMobileRows.flatMap((row) => row.left),
    [unknownMobileRows]
  );
  const unknownMobileRightItems = useMemo(
    () => unknownMobileRows.flatMap((row) => row.right),
    [unknownMobileRows]
  );
  const desktopCombinedRows = useMemo(
    () => buildDesktopCombinedRows(dataLeft, dataRight, lifeLeft, lifeRight),
    [dataLeft, dataRight, lifeLeft, lifeRight]
  );
  const knownDesktopCombinedRows = useMemo(
    () => desktopCombinedRows.filter((row) => row.year !== 'unknown'),
    [desktopCombinedRows]
  );
  const unknownDesktopCombinedRows = useMemo(
    () => desktopCombinedRows.filter((row) => row.year === 'unknown'),
    [desktopCombinedRows]
  );
  const unknownLeftItems = useMemo(
    () => unknownDesktopCombinedRows.flatMap((row) => [...row.leftCreations, ...row.leftLife]),
    [unknownDesktopCombinedRows]
  );
  const unknownRightItems = useMemo(
    () => unknownDesktopCombinedRows.flatMap((row) => [...row.rightCreations, ...row.rightLife]),
    [unknownDesktopCombinedRows]
  );
  const useDesktopCombinedLayout = isHuLocale;
  const desktopTimelineColumns = useMemo(() => {
    const columns = getTimelineColumnCount(viewportWidth);
    const evenColumns = columns - (columns % 2);
    return Math.max(2, evenColumns);
  }, [viewportWidth]);
  const sideColumns = Math.max(1, desktopTimelineColumns / 2);
  const leftCreationColumns = Math.max(1, sideColumns - 1);
  const rightCreationColumns = Math.max(1, sideColumns - 1);
  const leftDesktopTemplate = `repeat(${leftCreationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`;
  const rightDesktopTemplate = `minmax(0, 1fr) repeat(${rightCreationColumns}, minmax(0, 1fr))`;
  const hasTimelineData =
    mobileRows.length > 0 || (useDesktopCombinedLayout && desktopCombinedRows.length > 0);
  const hasKnownMobileRows = knownMobileRows.length > 0;
  const hasUnknownMobileRows =
    unknownMobileLeftItems.length > 0 || unknownMobileRightItems.length > 0;
  const hasKnownDesktopRows = knownDesktopCombinedRows.length > 0;
  const hasUnknownDesktopRows = unknownLeftItems.length > 0 || unknownRightItems.length > 0;
  const visibleCreators = [creatorLeft, creatorRight].filter((creator): creator is CreatorData =>
    Boolean(creator)
  );
  const areAllVisibleCreatorsDeceased =
    visibleCreators.length > 0 &&
    visibleCreators.every((creator) => Boolean(creator.elhalalozasIdeje));
  const timelineTopOffset = Math.max(creatorHeaderHeight + 10, 0);
  const mobileTimelineTopOffset = areAllVisibleCreatorsDeceased ? timelineTopOffset : 0;
  const timelineLineBackground = areAllVisibleCreatorsDeceased
    ? TIMELINE_LINE_SOLID
    : TIMELINE_LINE_BACKGROUND;
  const desktopTimelineTopOffset = areAllVisibleCreatorsDeceased ? timelineTopOffset : 0;
  const showMobileTimelineLine = hasKnownMobileRows;
  const showDesktopTimelineLine = useDesktopCombinedLayout
    ? hasKnownDesktopRows
    : hasKnownMobileRows;
  const shouldShowCompactStickyHeader = hasTimelineData && showCompactCreatorHeader;
  const breadcrumbItems = useMemo(
    () =>
      [
        {
          label: locale === 'en' ? 'Home' : 'Főoldal',
          href: { pathname: '/' },
          icon: <IoHomeOutline />,
          ariaLabel: locale === 'en' ? 'Home' : 'Főoldal',
        },
        {
          label: tNavigation('creators'),
          href: { pathname: '/alkotok' },
        },
        {
          label: t('title'),
          href: { pathname: '/parhuzamos-eletutak' },
        },
      ] satisfies BreadcrumbItem[],
    [locale, t, tNavigation]
  );

  useEffect(() => {
    const updateWidth = () => {
      setViewportWidth(window.innerWidth);
    };
    updateWidth();
    window.addEventListener('resize', updateWidth);
    return () => window.removeEventListener('resize', updateWidth);
  }, []);

  useEffect(() => {
    const target = creatorHeaderSentinelRef.current;
    if (!hasTimelineData || !target || typeof IntersectionObserver === 'undefined') {
      setShowCompactCreatorHeader(false);
      return;
    }

    let observer: IntersectionObserver | null = null;

    const setupObserver = () => {
      observer?.disconnect();
      const topOffset = getStickyHeaderOffset();
      observer = new IntersectionObserver(
        ([entry]) => {
          setShowCompactCreatorHeader(!entry.isIntersecting);
        },
        {
          root: null,
          threshold: 0,
          rootMargin: `-${topOffset}px 0px 0px 0px`,
        }
      );
      observer.observe(target);
    };

    setupObserver();
    window.addEventListener('resize', setupObserver);

    return () => {
      window.removeEventListener('resize', setupObserver);
      observer?.disconnect();
    };
  }, [hasTimelineData]);

  useEffect(() => {
    const header = creatorHeaderRef.current;
    if (!header) return;

    const updateHeight = () => {
      const nextHeight = header.getBoundingClientRect().height;
      setCreatorHeaderHeight((prevHeight) =>
        Math.abs(prevHeight - nextHeight) < 0.5 ? prevHeight : nextHeight
      );
    };

    updateHeight();

    if (typeof ResizeObserver === 'undefined') {
      window.addEventListener('resize', updateHeight);
      return () => window.removeEventListener('resize', updateHeight);
    }

    const resizeObserver = new ResizeObserver(updateHeight);
    resizeObserver.observe(header);
    return () => resizeObserver.disconnect();
  }, []);

  const updateQuery = (
    values: Record<string, string | null>,
    method: 'push' | 'replace' = 'push'
  ) => {
    const params = new URLSearchParams(searchParams.toString());

    Object.entries(values).forEach(([key, value]) => {
      if (value && value.length > 0) {
        params.set(key, value);
      } else {
        params.delete(key);
      }
    });

    if (isHuLocale) {
      if (!params.get(categoryParam)) {
        params.set(categoryParam, activeCategory);
      }
    } else {
      params.delete(categoryParam);
    }

    const nextRoute = {
      pathname: '/parhuzamos-eletutak' as const,
      query: Object.fromEntries(params.entries()),
    };

    startTransition(() => {
      if (method === 'replace') {
        router.replace(nextRoute);
        return;
      }

      router.push(nextRoute);
    });
  };

  const handleMode = (mode: CreatorTimelineCategory) => {
    if (!isHuLocale || mode === activeCategory) return;
    updateQuery({ [categoryParam]: mode }, 'replace');
  };

  const handleLeftCreatorSelect = (id: string) => {
    updateQuery({ [leftParam]: id });
  };

  const handleRightCreatorSelect = (id: string) => {
    updateQuery({ [rightParam]: id });
  };

  return (
    <section className={cn('w-full bg-white text-[#151720]', className)}>
      <div className="px-site pb-10 lg:pb-14">
        <div className="mx-auto flex max-w-boxed flex-col">
          <header className="space-y-4">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
              <div className="min-w-0 flex-1">
                <Breadcrumbs items={breadcrumbItems} sticky={false} />
              </div>

              {isHuLocale ? (
                <div className="flex flex-wrap gap-1.5 lg:hidden">
                  {parallelPathsFilters.map((filter) => {
                    const active = activeCategory === filter.key;
                    return (
                      <button
                        key={filter.key}
                        type="button"
                        onClick={() => handleMode(filter.key as CreatorTimelineCategory)}
                        className={cn(
                          'px-3 py-1.5 text-[10px] font-semibold uppercase tracking-[0.2em] transition sm:px-4 sm:py-2 sm:text-[11px] sm:tracking-[0.24em]',
                          active
                            ? 'bg-[#151720] text-white'
                            : 'border border-[#151720]/25 bg-white/70 text-[#151720]/80 hover:bg-[#151720]/10'
                        )}
                      >
                        {t(filter.labelKey)}
                      </button>
                    );
                  })}
                </div>
              ) : null}
            </div>
          </header>

          <div className="relative">
            {hasTimelineData ? (
              <>
                {showMobileTimelineLine ? (
                  <div
                    className="pointer-events-none absolute bottom-0 left-1/2 -translate-x-1/2 lg:hidden"
                    style={{ top: `${mobileTimelineTopOffset}px` }}
                  >
                    <div className="h-full w-4" style={{ background: timelineLineBackground }} />
                  </div>
                ) : null}
                {showDesktopTimelineLine ? (
                  <div
                    className="pointer-events-none absolute bottom-0 left-1/2 hidden -translate-x-1/2 lg:block"
                    style={{ top: `${desktopTimelineTopOffset}px` }}
                  >
                    <div className="h-full w-4" style={{ background: timelineLineBackground }} />
                  </div>
                ) : null}
              </>
            ) : null}
            <div
              ref={creatorHeaderRef}
              className="relative z-[1] grid grid-cols-2 gap-4 py-1 sm:gap-6 lg:gap-8"
            >
              <ParallelHeader
                side="left"
                creator={creatorLeft}
                nameList={nameList}
                isNavigating={isNavigating}
                creationColumns={leftCreationColumns}
                onChange={handleLeftCreatorSelect}
              />
              <ParallelHeader
                side="right"
                creator={creatorRight}
                nameList={nameList}
                isNavigating={isNavigating}
                creationColumns={rightCreationColumns}
                onChange={handleRightCreatorSelect}
              />
            </div>
            {isNavigating ? (
              <div className="pointer-events-none absolute left-1/2 top-2 z-30 -translate-x-1/2 rounded-full bg-white/92 p-1.5 text-[#151720]/70 shadow-[0_10px_22px_-14px_rgba(21,23,32,0.45)]">
                <Loader2 className="h-4 w-4 animate-spin" />
              </div>
            ) : null}
            <div ref={creatorHeaderSentinelRef} className="h-px w-full" />
            <ParallelCompactStickyHeader
              isVisible={shouldShowCompactStickyHeader}
              leftCreator={creatorLeft}
              rightCreator={creatorRight}
              leftCreationColumns={leftCreationColumns}
              rightCreationColumns={rightCreationColumns}
              showSectionLabels={useDesktopCombinedLayout}
            />

            <div className="">
              {!hasTimelineData ? (
                <div className="border border-[#151720]/15 bg-white/80 px-6 py-10 text-center text-sm font-semibold uppercase tracking-[0.14em] text-[#151720]/60">
                  {t('noData')}
                </div>
              ) : (
                <>
                  <div className="relative space-y-8 lg:hidden">
                    {knownMobileRows.map((row) => (
                      <ParallelRow key={row.year} row={row} />
                    ))}
                    {hasUnknownMobileRows ? (
                      <ParallelMobileUnknownSection
                        leftItems={unknownMobileLeftItems}
                        rightItems={unknownMobileRightItems}
                      />
                    ) : null}
                  </div>

                  <div className="relative hidden space-y-8 lg:block">
                    {useDesktopCombinedLayout
                      ? [
                          ...(hasKnownDesktopRows
                            ? [
                                <div key="known-section" className="relative">
                                  <div className="pointer-events-none absolute inset-0 z-0 grid grid-cols-2 gap-4 xl:gap-6">
                                    <div
                                      className="grid min-w-0 gap-3 pr-4 lg:[grid-template-columns:var(--parallel-left-template)]"
                                      style={
                                        {
                                          '--parallel-left-template': leftDesktopTemplate,
                                        } as CSSProperties
                                      }
                                    >
                                      <div
                                        style={{
                                          gridColumn: `1 / span ${leftCreationColumns}`,
                                          backgroundColor: CREATION_LANE_BACKGROUND,
                                        }}
                                      />
                                      <div
                                        style={{
                                          gridColumn: `${leftCreationColumns + 1} / span 1`,
                                          backgroundColor: LIFE_LANE_BACKGROUND,
                                        }}
                                      />
                                    </div>
                                    <div
                                      className="grid min-w-0 gap-3 pl-4 lg:[grid-template-columns:var(--parallel-right-template)]"
                                      style={
                                        {
                                          '--parallel-right-template': rightDesktopTemplate,
                                        } as CSSProperties
                                      }
                                    >
                                      <div
                                        style={{
                                          backgroundColor: LIFE_LANE_BACKGROUND,
                                        }}
                                      />
                                      <div
                                        style={{
                                          gridColumn: `2 / span ${rightCreationColumns}`,
                                          backgroundColor: CREATION_LANE_BACKGROUND,
                                        }}
                                      />
                                    </div>
                                  </div>

                                  <ParallelDesktopSectionLabels
                                    leftCreationColumns={leftCreationColumns}
                                    rightCreationColumns={rightCreationColumns}
                                  />
                                  {knownDesktopCombinedRows.map((row) => (
                                    <ParallelDesktopCombinedRow
                                      key={row.year}
                                      row={row}
                                      leftCreationColumns={leftCreationColumns}
                                      rightCreationColumns={rightCreationColumns}
                                    />
                                  ))}
                                </div>,
                              ]
                            : []),
                          ...(hasUnknownDesktopRows
                            ? [
                                <ParallelDesktopUnknownSection
                                  key="unknown-section"
                                  leftItems={unknownLeftItems}
                                  rightItems={unknownRightItems}
                                  sideColumns={sideColumns}
                                />,
                              ]
                            : []),
                        ]
                      : [
                          ...knownMobileRows.map((row) => <ParallelRow key={row.year} row={row} />),
                          ...(hasUnknownMobileRows
                            ? [
                                <ParallelDesktopUnknownSection
                                  key="unknown-section-simple"
                                  leftItems={unknownMobileLeftItems}
                                  rightItems={unknownMobileRightItems}
                                  sideColumns={sideColumns}
                                />,
                              ]
                            : []),
                        ]}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ParallelRow({ row }: { row: TimelineRowData }) {
  return (
    <article className="relative pt-10">
      <TimelineYearLabel year={row.year} />

      <div className="grid grid-cols-2 gap-4 sm:gap-6 lg:gap-8">
        <TimelineColumn align="left" items={row.left} />
        <TimelineColumn align="right" items={row.right} />
      </div>
    </article>
  );
}

function ParallelDesktopSectionLabels({
  leftCreationColumns,
  rightCreationColumns,
}: {
  leftCreationColumns: number;
  rightCreationColumns: number;
}) {
  const t = useTranslations('parallelPathsPage');
  const leftTemplate = `repeat(${leftCreationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`;
  const rightTemplate = `minmax(0, 1fr) repeat(${rightCreationColumns}, minmax(0, 1fr))`;
  const leftLabelSpanStyle = {
    gridColumn: `span ${leftCreationColumns} / span ${leftCreationColumns}`,
  };
  const rightLabelSpanStyle = {
    gridColumn: `span ${rightCreationColumns} / span ${rightCreationColumns}`,
  };

  return (
    <div className="relative z-10 grid grid-cols-2 gap-4 xl:gap-6 pb-4 lg:pb-8">
      <div
        className="grid min-w-0 gap-3 pr-4 lg:[grid-template-columns:var(--parallel-left-template)]"
        style={{ '--parallel-left-template': leftTemplate } as CSSProperties}
      >
        <div
          className="flex h-8 items-center truncate border border-[#dfcf6f]/45 bg-[#dfcf6f]/22 px-3 text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#6d6430] sm:text-[11px]"
          style={leftLabelSpanStyle}
        >
          {t('filters.creations')}
        </div>
        <div className="flex h-8 items-center justify-center truncate border border-[#b8dadc]/55 bg-[#b8dadc]/28 px-3 text-center text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#4b6d73] sm:text-[11px]">
          {t('filters.lifeEvents')}
        </div>
      </div>

      <div
        className="grid min-w-0 gap-3 pl-4 lg:[grid-template-columns:var(--parallel-right-template)]"
        style={{ '--parallel-right-template': rightTemplate } as CSSProperties}
      >
        <div className="flex h-8 items-center justify-center truncate border border-[#b8dadc]/55 bg-[#b8dadc]/28 px-3 text-center text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#4b6d73] sm:text-[11px]">
          {t('filters.lifeEvents')}
        </div>
        <div
          className="flex h-8 items-center justify-end truncate border border-[#dfcf6f]/45 bg-[#dfcf6f]/22 px-3 text-right text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#6d6430] sm:text-[11px]"
          style={rightLabelSpanStyle}
        >
          {t('filters.creations')}
        </div>
      </div>
    </div>
  );
}

function ParallelDesktopCombinedRow({
  row,
  leftCreationColumns,
  rightCreationColumns,
}: {
  row: DesktopCombinedRowData;
  leftCreationColumns: number;
  rightCreationColumns: number;
}) {
  const leftTemplate = `repeat(${leftCreationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`;
  const rightTemplate = `minmax(0, 1fr) repeat(${rightCreationColumns}, minmax(0, 1fr))`;

  return (
    <article className="relative z-10">
      <TimelineYearLabel year={row.year} />

      <div className="grid grid-cols-2 gap-4 xl:gap-6">
        <div
          className="grid min-w-0 gap-3 pr-4 lg:[grid-template-columns:var(--parallel-left-template)]"
          style={{ '--parallel-left-template': leftTemplate } as CSSProperties}
        >
          <TimelineColumn
            align="left"
            items={row.leftCreations}
            fixedColumns={leftCreationColumns}
            gridColumnSpan={leftCreationColumns}
          />
          <TimelineInnerLane side="left" items={row.leftLife} />
        </div>

        <div
          className="grid min-w-0 gap-3 pl-4 lg:[grid-template-columns:var(--parallel-right-template)]"
          style={{ '--parallel-right-template': rightTemplate } as CSSProperties}
        >
          <TimelineInnerLane side="right" items={row.rightLife} />
          <TimelineColumn
            align="right"
            items={row.rightCreations}
            fixedColumns={rightCreationColumns}
            gridColumnSpan={rightCreationColumns}
          />
        </div>
      </div>
    </article>
  );
}

function ParallelDesktopUnknownSection({
  leftItems,
  rightItems,
  sideColumns,
}: {
  leftItems: CreationListItem[];
  rightItems: CreationListItem[];
  sideColumns: number;
}) {
  const sideTemplate = `repeat(${sideColumns}, minmax(0, 1fr))`;

  return (
    <section className="relative z-10 pt-2">
      <div className="pointer-events-none absolute -top-10 bottom-0 left-1/2 z-20 w-4 -translate-x-1/2 bg-white" />
      <div className="grid grid-cols-2 gap-4 xl:gap-6">
        <div className="min-w-0 pr-4">
          <div
            className="grid gap-2 pb-2 pr-1"
            style={{ gridTemplateColumns: sideTemplate } as CSSProperties}
          >
            {leftItems.map((item, index) => (
              <div key={`unknown-left-${getCreationCardKey(item, index)}`} className="min-w-0">
                <CreationCard data={item} vertical lifeTitleLines={5} />
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 pl-4">
          <div
            className="grid gap-2 pb-2 pr-1"
            style={{ gridTemplateColumns: sideTemplate } as CSSProperties}
          >
            {rightItems.map((item, index) => (
              <div key={`unknown-right-${getCreationCardKey(item, index)}`} className="min-w-0">
                <CreationCard data={item} vertical lifeTitleLines={5} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function ParallelMobileUnknownSection({
  leftItems,
  rightItems,
}: {
  leftItems: CreationListItem[];
  rightItems: CreationListItem[];
}) {
  return (
    <section className="relative z-10 pt-2">
      <div className="pointer-events-none absolute -top-10 bottom-0 left-1/2 z-20 w-4 -translate-x-1/2 bg-white" />
      <div className="grid grid-cols-2 gap-4 sm:gap-6 lg:gap-8">
        <TimelineColumn align="left" items={leftItems} fixedColumns={1} />
        <TimelineColumn align="right" items={rightItems} fixedColumns={1} />
      </div>
    </section>
  );
}

function TimelineInnerLane({ items, side }: { items: CreationListItem[]; side: 'left' | 'right' }) {
  return (
    <div className={cn('min-w-0 pl-1')}>
      <div className="flex flex-col gap-2 pb-2 pr-1">
        {items.map((item, index) => (
          <div key={`${side}-${getCreationCardKey(item, index)}`} className="min-w-0">
            <CreationCard data={item} vertical lifeTitleLines={6} />
          </div>
        ))}
      </div>
    </div>
  );
}

function TimelineColumn({
  items,
  align,
  fixedColumns,
  gridColumnSpan,
}: {
  items: CreationListItem[];
  align: 'left' | 'right';
  fixedColumns?: number;
  gridColumnSpan?: number;
}) {
  const isLeft = align === 'left';
  const hasFixedColumns = typeof fixedColumns === 'number' && fixedColumns > 0;
  const hasGridColumnSpan = typeof gridColumnSpan === 'number' && gridColumnSpan > 0;

  return (
    <div
      className={cn('min-w-0', !hasFixedColumns && (isLeft ? 'pr-4' : 'pl-4'))}
      style={
        hasGridColumnSpan
          ? ({
              gridColumn: `span ${gridColumnSpan} / span ${gridColumnSpan}`,
            } as CSSProperties)
          : undefined
      }
    >
      <div
        className={cn(
          'grid gap-2 pb-2 pr-1',
          hasFixedColumns ? '' : 'grid-cols-[repeat(auto-fit,minmax(148px,220px))]',
          !hasFixedColumns && (isLeft ? 'justify-end' : 'justify-start')
        )}
        style={
          hasFixedColumns
            ? ({
                gridTemplateColumns: `repeat(${fixedColumns}, minmax(0, 1fr))`,
              } as CSSProperties)
            : undefined
        }
      >
        {items.map((item, index) => (
          <div key={getCreationCardKey(item, index)} className="min-w-0">
            <CreationCard data={item} vertical lifeTitleLines={5} />
          </div>
        ))}
      </div>
    </div>
  );
}

function CreatorAvatarBlock({
  side,
  creator,
  isNavigating,
  isStickyCompact,
  avatarContainerClassName,
  onPrimaryAction,
  selectCreatorLabel,
  clearSelectionLabel,
}: {
  side: 'left' | 'right';
  creator: CreatorData | null;
  isNavigating: boolean;
  isStickyCompact: boolean;
  avatarContainerClassName: string;
  onPrimaryAction: () => void;
  selectCreatorLabel: string;
  clearSelectionLabel: string;
}) {
  const displayName = creator?.nev || creator?.alkotoAzonosito || '';
  const nameSizeClass = getCreatorCardNameSizeClass(displayName);
  const cornerClass =
    side === 'left'
      ? 'left-0 top-0 -translate-x-1/4 -translate-y-1/4'
      : 'right-0 top-0 translate-x-1/4 -translate-y-1/4';

  return (
    <div className={cn('mx-auto w-full min-w-0', avatarContainerClassName)}>
      <div className="relative">
        {creator ? (
          <Link
            href={{
              pathname: '/alkoto/[id]',
              params: { id: creator.alkotoAzonosito },
            }}
            className="block w-full"
          >
            <CreatorAvatar
              imageKey={creator.profilkep?.key}
              name={creator.nev}
              wrapperClassName="w-full rounded-full border border-[#151720]/10"
              imageClassName="rounded-full duration-200 ease-out"
              width={320}
              height={320}
            />
          </Link>
        ) : (
          <div className="aspect-square w-full rounded-full border border-[#151720]/12 bg-white/70" />
        )}

        {!isStickyCompact && creator ? (
          <button
            type="button"
            onClick={onPrimaryAction}
            disabled={isNavigating}
            aria-label={clearSelectionLabel}
            title={clearSelectionLabel}
            className={cn(
              'absolute z-10 inline-flex h-7 w-7 items-center justify-center rounded-full bg-white/94 text-[#151720]/82 shadow-[0_6px_16px_-10px_rgba(21,23,32,0.55)] transition hover:bg-[#151720] hover:text-white disabled:cursor-not-allowed disabled:opacity-60',
              cornerClass
            )}
          >
            <X className="h-4 w-4" />
          </button>
        ) : null}
      </div>

      {!isStickyCompact ? (
        <div className="mt-1 min-h-[3.35rem] min-w-0 text-center">
          {creator ? (
            <Link
              href={{
                pathname: '/alkoto/[id]',
                params: { id: creator.alkotoAzonosito },
              }}
              className={cn(
                'inline-flex max-w-full items-center justify-center gap-0.5 text-center font-semibold uppercase leading-tight text-[#151720] transition hover:text-[#151720]/75 hover:underline',
                nameSizeClass
              )}
              title={displayName}
            >
              <span className="min-w-0 overflow-hidden whitespace-nowrap text-clip">
                {creator.elhalalozasIdeje ? (
                  <RiCrossFill className="mr-[2px] inline-block align-[-0.08em] text-[11px] text-[#151720]/75" />
                ) : null}
                {displayName}
              </span>
            </Link>
          ) : (
            <div className="truncate text-[11px] font-semibold uppercase tracking-[0.14em] text-[#151720] sm:text-sm sm:tracking-[0.16em]">
              {selectCreatorLabel}
            </div>
          )}
          {creator?.szakma ? (
            <div className="mt-0.5 truncate text-xs font-medium text-[#151720]/65">
              {creator.szakma}
            </div>
          ) : (
            <div className="mt-0.5 h-[1rem]" />
          )}
        </div>
      ) : null}
    </div>
  );
}

function CreatorStickyCompactBlock({
  creator,
  side,
  selectCreatorLabel,
}: {
  creator: CreatorData | null;
  side: 'left' | 'right';
  selectCreatorLabel: string;
}) {
  const isLeftSide = side === 'left';
  const textOrderClass = isLeftSide ? 'order-1' : 'order-2';
  const avatarOrderClass = isLeftSide ? 'order-2' : 'order-1';

  return (
    <div className="flex w-full min-w-0 items-center gap-2.5">
      <div className={cn('hidden shrink-0 lg:flex', avatarOrderClass)}>
        {creator ? (
          <Link
            href={{
              pathname: '/alkoto/[id]',
              params: { id: creator.alkotoAzonosito },
            }}
            className="block h-11 w-11"
          >
            <CreatorAvatar
              imageKey={creator.profilkep?.key}
              name={creator.nev}
              wrapperClassName="h-11 w-11 rounded-full border border-[#151720]/10"
              imageClassName="rounded-full"
              width={88}
              height={88}
            />
          </Link>
        ) : (
          <div className="h-11 w-11 rounded-full border border-[#151720]/12 bg-white/70" />
        )}
      </div>

      <div
        className={cn(
          'min-w-0 flex-1 text-center',
          textOrderClass,
          isLeftSide ? 'lg:text-right' : 'lg:text-left'
        )}
      >
        {creator ? (
          <Link
            href={{
              pathname: '/alkoto/[id]',
              params: { id: creator.alkotoAzonosito },
            }}
            className="block w-full text-[11px] font-semibold uppercase tracking-[0.14em] text-[#151720] transition hover:text-[#151720]/75 hover:underline sm:text-sm sm:tracking-[0.16em]"
          >
            <span className="block min-w-0 whitespace-normal leading-tight">
              {creator.elhalalozasIdeje ? (
                <RiCrossFill className="mr-[2px] inline-block align-[-0.08em] text-[11px] text-[#151720]/75" />
              ) : null}
              <span className="inline break-words">{creator.nev || creator.alkotoAzonosito}</span>
            </span>
          </Link>
        ) : (
          <div className="truncate text-[11px] font-semibold uppercase tracking-[0.14em] text-[#151720] sm:text-sm sm:tracking-[0.16em]">
            {selectCreatorLabel}
          </div>
        )}
      </div>
    </div>
  );
}

function ParallelCompactStickyHeader({
  isVisible,
  leftCreator,
  rightCreator,
  leftCreationColumns,
  rightCreationColumns,
  showSectionLabels,
}: {
  isVisible: boolean;
  leftCreator: CreatorData | null;
  rightCreator: CreatorData | null;
  leftCreationColumns: number;
  rightCreationColumns: number;
  showSectionLabels: boolean;
}) {
  const t = useTranslations('parallelPathsPage');
  const leftTemplate = `repeat(${leftCreationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`;
  const rightTemplate = `minmax(0, 1fr) repeat(${rightCreationColumns}, minmax(0, 1fr))`;
  const leftTextSpanStyle = {
    gridColumn: `span ${leftCreationColumns} / span ${leftCreationColumns}`,
  };
  const rightTextSpanStyle = {
    gridColumn: `span ${rightCreationColumns} / span ${rightCreationColumns}`,
  };

  return (
    <div className="pointer-events-none sticky top-[calc(var(--header-h))] z-30 h-0">
      <div
        className={cn(
          'pointer-events-auto border-b border-[#151720]/10 bg-white/95 shadow-[0_10px_24px_-22px_rgba(21,23,32,0.3)] transition-all duration-150 ease-out',
          isVisible ? 'translate-y-0 opacity-100' : '-translate-y-1 opacity-0 pointer-events-none'
        )}
      >
        <div className="grid grid-cols-2 gap-4 py-1 sm:gap-6 lg:gap-8">
          <div className="min-w-0">
            <div
              className="grid w-full grid-cols-1 gap-2 lg:gap-3 lg:[grid-template-columns:var(--parallel-header-template)]"
              style={
                {
                  '--parallel-header-template': leftTemplate,
                } as CSSProperties
              }
            >
              <div className="hidden lg:block" style={leftTextSpanStyle} aria-hidden />
              <div className="min-w-0 flex justify-center lg:justify-end">
                <CreatorStickyCompactBlock
                  creator={leftCreator}
                  side="left"
                  selectCreatorLabel={t('selectCreator')}
                />
              </div>
            </div>
          </div>

          <div className="min-w-0">
            <div
              className="grid w-full grid-cols-1 gap-2 lg:gap-3 lg:[grid-template-columns:var(--parallel-header-template)]"
              style={
                {
                  '--parallel-header-template': rightTemplate,
                } as CSSProperties
              }
            >
              <div className="min-w-0 flex justify-center lg:justify-start">
                <CreatorStickyCompactBlock
                  creator={rightCreator}
                  side="right"
                  selectCreatorLabel={t('selectCreator')}
                />
              </div>
              <div className="hidden lg:block" style={rightTextSpanStyle} aria-hidden />
            </div>
          </div>
        </div>

        {showSectionLabels ? (
          <div className="hidden border-t border-[#151720]/10 py-1 lg:block">
            <ParallelCompactStickySectionLabels
              leftCreationColumns={leftCreationColumns}
              rightCreationColumns={rightCreationColumns}
            />
          </div>
        ) : null}
      </div>
    </div>
  );
}

function ParallelCompactStickySectionLabels({
  leftCreationColumns,
  rightCreationColumns,
}: {
  leftCreationColumns: number;
  rightCreationColumns: number;
}) {
  const t = useTranslations('parallelPathsPage');
  const leftTemplate = `repeat(${leftCreationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`;
  const rightTemplate = `minmax(0, 1fr) repeat(${rightCreationColumns}, minmax(0, 1fr))`;
  const leftLabelSpanStyle = {
    gridColumn: `span ${leftCreationColumns} / span ${leftCreationColumns}`,
  };
  const rightLabelSpanStyle = {
    gridColumn: `span ${rightCreationColumns} / span ${rightCreationColumns}`,
  };

  return (
    <div className="grid grid-cols-2 gap-4 sm:gap-6">
      <div
        className="grid min-w-0 gap-3 pr-4 lg:[grid-template-columns:var(--parallel-left-template)]"
        style={{ '--parallel-left-template': leftTemplate } as CSSProperties}
      >
        <div
          className="flex h-7 items-center truncate border px-3 text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#6d6430] sm:text-[11px]"
          style={
            {
              ...leftLabelSpanStyle,
              borderColor: 'rgba(223, 207, 111, 0.62)',
              backgroundColor: 'rgba(223, 207, 111, 0.44)',
            } as CSSProperties
          }
        >
          {t('filters.creations')}
        </div>
        <div
          className="flex h-7 items-center justify-center truncate border px-3 text-center text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#4b6d73] sm:text-[11px]"
          style={{
            borderColor: 'rgba(184, 218, 220, 0.78)',
            backgroundColor: 'rgba(184, 218, 220, 0.48)',
          }}
        >
          {t('filters.lifeEvents')}
        </div>
      </div>

      <div
        className="grid min-w-0 gap-3 pl-4 lg:[grid-template-columns:var(--parallel-right-template)]"
        style={{ '--parallel-right-template': rightTemplate } as CSSProperties}
      >
        <div
          className="flex h-7 items-center justify-center truncate border px-3 text-center text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#4b6d73] sm:text-[11px]"
          style={{
            borderColor: 'rgba(184, 218, 220, 0.78)',
            backgroundColor: 'rgba(184, 218, 220, 0.48)',
          }}
        >
          {t('filters.lifeEvents')}
        </div>
        <div
          className="flex h-7 items-center justify-end truncate border px-3 text-right text-[10.5px] font-bold uppercase tracking-[0.24em] text-[#6d6430] sm:text-[11px]"
          style={
            {
              ...rightLabelSpanStyle,
              borderColor: 'rgba(223, 207, 111, 0.62)',
              backgroundColor: 'rgba(223, 207, 111, 0.44)',
            } as CSSProperties
          }
        >
          {t('filters.creations')}
        </div>
      </div>
    </div>
  );
}

interface ParallelHeaderProps {
  side: 'left' | 'right';
  creator: CreatorData | null;
  nameList: CreatorListData[];
  isNavigating: boolean;
  creationColumns: number;
  onChange: (id: string) => void;
}

const ParallelHeader: React.FC<ParallelHeaderProps> = ({
  side,
  creator,
  nameList,
  isNavigating,
  creationColumns,
  onChange,
}) => {
  const t = useTranslations('parallelPathsPage');
  const tCategories = useTranslations('categories');
  const [isEditing, setIsEditing] = useState(!creator?.alkotoAzonosito);
  const [draftCategory, setDraftCategory] = useState(metaAttributes110[0]?.key || 'architecture');
  const [draftCreatorId, setDraftCreatorId] = useState(creator?.alkotoAzonosito || '');

  const filteredCreators = useMemo(
    () => nameList.filter((item) => (draftCategory ? item.tipus === draftCategory : true)),
    [draftCategory, nameList]
  );

  useEffect(() => {
    const creatorId = creator?.alkotoAzonosito || '';
    setDraftCreatorId(creatorId);
    if (!creatorId) {
      setIsEditing(true);
      return;
    }
    setIsEditing(false);

    const matchedCreator = nameList.find((item) => item.alkotoAzonosito === creatorId);
    if (matchedCreator?.tipus) {
      setDraftCategory(matchedCreator.tipus);
    }
  }, [creator?.alkotoAzonosito, nameList]);

  const selectedCategoryMeta = useMemo(
    () => metaAttributes110.find((item) => item.key === draftCategory) || metaAttributes110[0],
    [draftCategory]
  );

  const draftCreator = useMemo(
    () => nameList.find((item) => item.alkotoAzonosito === draftCreatorId) || null,
    [draftCreatorId, nameList]
  );

  const handleCategoryChange = (value: string) => {
    setDraftCategory(value);
    setDraftCreatorId((prev) => {
      const current = nameList.find((item) => item.alkotoAzonosito === prev);
      return current?.tipus === value ? prev : '';
    });
  };

  const handleCreatorSelect = (selectedId: string) => {
    if (!selectedId) return;

    setDraftCreatorId(selectedId);
    onChange(selectedId);
  };

  const handlePrimaryAction = () => {
    if (creator?.alkotoAzonosito) {
      onChange('');
    }
    setDraftCreatorId('');
    setIsEditing(true);
  };
  const isLeftSide = side === 'left';
  const avatarContainerClassName = 'max-w-[170px] lg:max-w-none';
  const desktopHeaderTemplate = isLeftSide
    ? `repeat(${creationColumns}, minmax(0, 1fr)) minmax(0, 1fr)`
    : `minmax(0, 1fr) repeat(${creationColumns}, minmax(0, 1fr))`;
  const desktopTextSpanStyle = {
    gridColumn: `span ${creationColumns} / span ${creationColumns}`,
  };

  return (
    <div
      className={cn(
        'relative min-w-0 py-2 transition-opacity duration-150 ease-out',
        isNavigating ? 'opacity-80' : 'opacity-100'
      )}
      aria-busy={isNavigating}
    >
      {isEditing ? (
        <div
          className="grid w-full grid-cols-1 gap-2 lg:gap-3 lg:[grid-template-columns:var(--parallel-header-template)]"
          style={
            {
              '--parallel-header-template': desktopHeaderTemplate,
            } as CSSProperties
          }
        >
          {isLeftSide ? (
            <div className="hidden lg:block" style={desktopTextSpanStyle} aria-hidden />
          ) : null}

          <div
            className={cn(
              'min-w-0 flex justify-center',
              isLeftSide ? 'lg:justify-end' : 'lg:justify-start'
            )}
          >
            <div className="w-full">
              <div className={cn('mx-auto w-full min-w-0', avatarContainerClassName)}>
                <div className="aspect-square w-full rounded-full border border-[#151720]/12 bg-white/70" />
              </div>

              <div className="mt-2.5 border border-[#151720]/12 bg-white/92 p-2.5 shadow-[0_10px_24px_-20px_rgba(21,23,32,0.45)]">
                <div className="grid gap-2">
                  <Select
                    value={draftCategory}
                    onValueChange={handleCategoryChange}
                    disabled={isNavigating}
                  >
                    <SelectTrigger className="h-10 min-w-0 overflow-hidden border-[#151720]/20 bg-white px-2.5 pr-3 text-sm font-semibold text-[#151720] shadow-none focus:ring-1 focus:ring-[#151720]/45">
                      <span className="block min-w-0 max-w-full truncate whitespace-nowrap">
                        {selectedCategoryMeta ? tCategories(selectedCategoryMeta.labelKey) : ''}
                      </span>
                    </SelectTrigger>
                    <SelectContent>
                      {metaAttributes110.map((item: MetaAttribute110) => (
                        <SelectItem key={item.key} value={item.key}>
                          <span className="flex items-center gap-2 pr-2">
                            <Image
                              src={`/assets/images/icons/light/${item.icon}`}
                              alt={tCategories(item.labelKey)}
                              width={18}
                              height={18}
                              className="shrink-0"
                            />
                            <span className="min-w-0 truncate">{tCategories(item.labelKey)}</span>
                          </span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>

                  <Select
                    value={draftCreatorId || undefined}
                    onValueChange={handleCreatorSelect}
                    disabled={isNavigating}
                  >
                    <SelectTrigger className="h-10 min-w-0 overflow-hidden border-[#151720]/20 bg-white px-2.5 pr-3 text-sm font-semibold text-[#151720] shadow-none focus:ring-1 focus:ring-[#151720]/45">
                      {draftCreator ? (
                        <span className="block min-w-0 max-w-full truncate whitespace-nowrap">
                          {draftCreator.nev || draftCreator.alkotoAzonosito}
                        </span>
                      ) : (
                        <span className="block min-w-0 max-w-full truncate whitespace-nowrap text-[#151720]/55">
                          {t('selectCreator')}
                        </span>
                      )}
                    </SelectTrigger>
                    <SelectContent className="w-[min(32rem,calc(100vw-1rem))] min-w-[var(--radix-select-trigger-width)] max-w-[calc(100vw-1rem)]">
                      {filteredCreators.map((item) => (
                        <SelectItem key={item.alkotoAzonosito} value={item.alkotoAzonosito}>
                          <span className="grid w-full min-w-0 max-w-full grid-cols-[2.25rem_minmax(0,1fr)] items-center gap-2 overflow-hidden pr-2">
                            <CreatorAvatar
                              imageKey={item.profilkep?.key}
                              name={item.nev}
                              width={72}
                              height={72}
                              wrapperClassName="h-9 w-9 shrink-0 rounded-full"
                              imageClassName="rounded-full"
                            />
                            <span className="min-w-0 overflow-hidden leading-tight">
                              <span className="block w-full truncate">
                                {item.nev || item.alkotoAzonosito}
                              </span>
                              {item.szakma ? (
                                <span className="block w-full truncate text-[11px] font-medium text-[#151720]/55">
                                  {item.szakma}
                                </span>
                              ) : null}
                            </span>
                          </span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </div>

          {!isLeftSide ? (
            <div className="hidden lg:block" style={desktopTextSpanStyle} aria-hidden />
          ) : null}
        </div>
      ) : (
        <div
          className="grid w-full grid-cols-1 gap-2 lg:gap-3 lg:[grid-template-columns:var(--parallel-header-template)]"
          style={
            {
              '--parallel-header-template': desktopHeaderTemplate,
            } as CSSProperties
          }
        >
          {isLeftSide ? (
            <>
              <div
                className="hidden min-w-0 flex-col items-center lg:flex lg:items-end lg:pr-4 lg:text-right"
                style={desktopTextSpanStyle}
              />

              <div className={cn('min-w-0 justify-center lg:justify-end', 'flex')}>
                <CreatorAvatarBlock
                  side="left"
                  creator={creator}
                  isNavigating={isNavigating}
                  isStickyCompact={false}
                  avatarContainerClassName={avatarContainerClassName}
                  onPrimaryAction={handlePrimaryAction}
                  selectCreatorLabel={t('selectCreator')}
                  clearSelectionLabel={t('clearSelection')}
                />
              </div>
            </>
          ) : (
            <>
              <div className={cn('min-w-0 justify-center lg:justify-start', 'flex')}>
                <CreatorAvatarBlock
                  side="right"
                  creator={creator}
                  isNavigating={isNavigating}
                  isStickyCompact={false}
                  avatarContainerClassName={avatarContainerClassName}
                  onPrimaryAction={handlePrimaryAction}
                  selectCreatorLabel={t('selectCreator')}
                  clearSelectionLabel={t('clearSelection')}
                />
              </div>

              <div
                className="hidden min-w-0 flex-col items-center lg:flex lg:items-start lg:pl-4 lg:text-left"
                style={desktopTextSpanStyle}
              />
            </>
          )}
        </div>
      )}
    </div>
  );
};
