import React, {
  useEffect,
  useId,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";

type Language = "ru" | "en";
type Scene = "before" | "after" | "connection";
type Product = "pulse" | "connect" | "scenario";
type Panel =
  | Product
  | "account"
  | "messages"
  | "ecosystem"
  | "sparks"
  | null;

type IconName =
  | "arrow"
  | "external"
  | "close"
  | "check"
  | "spark"
  | "message"
  | "apps"
  | "lock";

type Person = {
  id: string;
  name: string;
  age: number;
  city: string;
  interest: string;
  image: string;
};

type NextMove = {
  product: Product;
  label: string;
  title: string;
  description: string;
  action: string;
  note: string;
};

/*
 * All data below is illustrative.
 * Portraits do not identify actual Ember members.
 * No compatibility or private preferences are inferred from photographs.
 */
const PEOPLE: Person[] = [
  {
    id: "alex",
    name: "Alex",
    age: 31,
    city: "Berlin",
    interest: "Cinema",
    image:
      "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=650&h=850&q=85",
  },
  {
    id: "leo",
    name: "Leo",
    age: 29,
    city: "Berlin",
    interest: "Late nights",
    image:
      "https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?auto=format&fit=crop&w=650&h=850&q=85",
  },
  {
    id: "noah",
    name: "Noah",
    age: 33,
    city: "Berlin",
    interest: "Design",
    image:
      "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=650&h=850&q=85",
  },
];

const INTERESTS = [
  { id: "latex", label: "Latex", style: "berry" },
  { id: "cinema", label: "Cinema", style: "cream" },
  { id: "nights", label: "Late nights", style: "rose" },
] as const;

const COPY = {
  ru: {
    today: "Сегодня",
    messages: "Сообщения",
    progress: "Твой путь",
    language: "Язык интерфейса",
    account: "Аккаунт Майи",
    ecosystem: "Продукты Ember",
    greeting: "С возвращением, Майя",
    heading: "Ближе к твоим",
    headingAccent: "желаниям.",
    intro:
      "Люди, с которыми интересно. Шаги, которые помогают узнать друг друга.",
    searching: "Открыта к знакомствам",
    connected: "Есть Connection",
    nextMove: "Следующий шаг",
    nextIndex: "ЛИЧНЫЙ МАРШРУТ",
    peopleEyebrow: "ТВОЙ КРУГ ВОЗМОЖНОСТЕЙ",
    peopleTitle: "Кто тебя зацепит?",
    peopleIntro:
      "Подборка доступна уже сейчас. Pulse добавит больше контекста о предпочтениях.",
    peopleAfter:
      "Pulse пройден. Разрешённые предпочтения могут дополнить поиск.",
    peopleConnection:
      "Наличие Connection не меняет твою доступность для знакомств автоматически.",
    menAction: "Смотреть мужчин",
    peopleNote: "Предварительная подборка · без оценки совместимости",
    peopleNoteAfter: "Демонстрационная подборка · без реального пересчёта",
    openPerson: "Посмотреть",
    interestEyebrow: "ТВОЙ КОНТЕКСТ",
    interestTitle: "То, что тебя притягивает.",
    interestIntro:
      "Интересы задают направление — для людей, идей и будущих встреч.",
    interestIdle: "Выбери интерес, чтобы увидеть, какой контекст он добавляет.",
    interestCinema:
      "Cinema — повод познакомиться через любимые фильмы и идеи свиданий.",
    interestLatex:
      "Latex — интерес для исследования. Чужие предпочтения не определяются по фото.",
    interestNights:
      "Late nights — контекст для вечерних встреч и людей с похожим ритмом.",
    interestDisclaimer:
      "В прототипе выбор раскрывает контекст, но не меняет профиль и не запускает поиск.",
    journeyEyebrow: "МАЛЕНЬКИЕ ШАГИ. БОЛЬШЕ ВОЗМОЖНОСТЕЙ.",
    journeyTitle: "Знакомства — не только первое фото.",
    journeyText:
      "Узнавай себя, находи точки совпадения и открывай новые возможности Ember.",
    level: "Уровень",
    profileReady: "База профиля",
    preferences: "Предпочтения",
    possibilities: "Возможности",
    ready: "Готово",
    next: "Следующий шаг",
    ahead: "Впереди",
    progressNote:
      "EXP показывает прогресс. Награды и условия открытия возможностей пока не определены.",
    connectionEyebrow: "ВАША СВЯЗЬ",
    connectionTitle: "Знакомство может стать чем-то большим.",
    connectionText:
      "В этом демосостоянии у Майи и Алекса есть Connection. Совместный следующий шаг — идея вечера.",
    connectionAction: "Посмотреть идею следующего шага",
    prototype: "Дизайн-прототип",
    stateLabel: "Состояние Home",
    before: "До Pulse",
    after: "После Pulse",
    connection: "Есть Connection",
    demoNote:
      "Люди и данные вымышлены. Фото иллюстративные. Переключатель демонстрирует состояния, а не продуктовый алгоритм.",
    close: "Закрыть",
    understood: "Понятно",
    handoff: "ПЕРЕХОД В ПРОДУКТ",
    pulseTitle: "Дальше — Pulse.",
    pulseBody:
      "Здесь откроется отдельный продукт, в котором можно исследовать свои предпочтения. Home не дублирует его квиз.",
    pulseFoot:
      "Чтобы посмотреть Home после прохождения, выбери «После Pulse» в демонстрационной панели внизу страницы.",
    connectTitle: "Продолжим в Connect.",
    connectBody:
      "Поиск, подробные анкеты и взаимодействия остаются в Connect. Здесь показана только точка перехода.",
    connectFoot:
      "В прототипе нет реального поиска, отправки лайков или расчёта сексуальной совместимости.",
    scenarioTitle: "Ваш вечер — в Scenario.",
    scenarioBody:
      "Следующий шаг ведёт в Scenario или соответствующего бота: идеи свиданий, совместные активности и сценарии вечера.",
    scenarioFoot:
      "Бот и генерация сценариев в этот Home-прототип не включены.",
    messagesTitle: "Твои сообщения",
    messagesBody:
      "В текущем демосостоянии нет новых сообщений. Счётчики и активность не добавлены ради заполнения экрана.",
    messagesFoot: "Полноценная переписка остаётся в Messaging.",
    accountTitle: "Твой аккаунт Ember",
    accountBody:
      "Майя · единый аккаунт для всей экосистемы. Фото, личные данные, статус и связи находятся в Personal.",
    accountFoot:
      "Personal и настройки здесь не реализованы: текущий прототип посвящён Home.",
    ecosystemTitle: "Одно пространство. Разные возможности.",
    ecosystemBody:
      "Cabinet помогает понять следующий шаг. Специализированные действия выполняются в соответствующем продукте.",
    sparksTitle: "Sparks",
    sparksBody:
      "Расходуемая внутренняя валюта Ember. Это не EXP и не показатель уровня.",
    sparksFoot:
      "Показан демонстрационный баланс. Начисления, покупки и правила экономики не реализованы.",
    photoUnavailable: "Фото недоступно",
    portrait: "Иллюстративный портрет",
    mockProfile: "Вымышленный профиль · иллюстративная фотография",
    productPulse: "Исследовать предпочтения",
    productConnect: "Найти человека",
    productScenario: "Придумать что-то вместе",
  },
  en: {
    today: "Today",
    messages: "Messages",
    progress: "Your journey",
    language: "Interface language",
    account: "Maya's account",
    ecosystem: "Ember products",
    greeting: "Welcome back, Maya",
    heading: "Closer to what",
    headingAccent: "you desire.",
    intro:
      "People worth discovering. Little steps towards understanding each other.",
    searching: "Open to meeting someone",
    connected: "You have a Connection",
    nextMove: "Your next move",
    nextIndex: "A PERSONAL JOURNEY",
    peopleEyebrow: "A WORLD OF POSSIBILITY",
    peopleTitle: "Who catches your eye?",
    peopleIntro:
      "You can explore now. Pulse adds more context about your preferences.",
    peopleAfter:
      "Pulse is complete. Permitted preferences can add context to discovery.",
    peopleConnection:
      "Having a Connection doesn't automatically change your discovery settings.",
    menAction: "Explore men",
    peopleNote: "Preliminary selection · no compatibility scores",
    peopleNoteAfter: "Demo selection · no live recalculation",
    openPerson: "View",
    interestEyebrow: "YOUR CONTEXT",
    interestTitle: "What draws you in.",
    interestIntro:
      "Your interests set a direction — for people, ideas and future encounters.",
    interestIdle: "Choose an interest to explore the context it can bring.",
    interestCinema:
      "Cinema — a way to connect through favourite films and date ideas.",
    interestLatex:
      "Latex — an interest to explore. Other people's preferences aren't inferred from photographs.",
    interestNights:
      "Late nights — context for evening plans and people with a similar rhythm.",
    interestDisclaimer:
      "This demo explains context; it doesn't update your profile or perform a search.",
    journeyEyebrow: "LITTLE STEPS. MORE POSSIBILITIES.",
    journeyTitle: "There's more than a first photo.",
    journeyText:
      "Explore yourself, find common ground and discover more of Ember.",
    level: "Level",
    profileReady: "Profile basics",
    preferences: "Preferences",
    possibilities: "Possibilities",
    ready: "Complete",
    next: "Next move",
    ahead: "Ahead",
    progressNote:
      "EXP reflects progress. Rewards and conditions for unlocking features aren't defined yet.",
    connectionEyebrow: "YOUR CONNECTION",
    connectionTitle: "A connection can become something more.",
    connectionText:
      "In this demo state, Maya and Alex have a Connection. An idea for an evening together is their next opportunity.",
    connectionAction: "Explore the next step",
    prototype: "Design prototype",
    stateLabel: "Home state",
    before: "Before Pulse",
    after: "After Pulse",
    connection: "Has a Connection",
    demoNote:
      "People and data are fictional. Photos are illustrative. The switch demonstrates states, not a product algorithm.",
    close: "Close",
    understood: "Got it",
    handoff: "CONTINUE IN PRODUCT",
    pulseTitle: "Next stop: Pulse.",
    pulseBody:
      "This leads to a separate product for exploring your preferences. Home doesn't reproduce its quiz.",
    pulseFoot:
      "To preview the completed state, choose “After Pulse” in the demo controls at the bottom.",
    connectTitle: "Continue in Connect.",
    connectBody:
      "Search, full profiles and interactions belong in Connect. This is a preview of the handoff.",
    connectFoot:
      "This prototype doesn't run real searches, send likes or calculate sexual compatibility.",
    scenarioTitle: "Your evening, with Scenario.",
    scenarioBody:
      "This step leads to Scenario or its bot: date ideas, shared activities and plans for an evening.",
    scenarioFoot:
      "The bot and scenario generation are outside this Home prototype.",
    messagesTitle: "Your messages",
    messagesBody:
      "There are no new messages in this demo state. Counts and activity haven't been invented to fill the screen.",
    messagesFoot: "Full conversations belong in Messaging.",
    accountTitle: "Your Ember account",
    accountBody:
      "Maya · one account across Ember. Photos, personal details, status and Connections belong in Personal.",
    accountFoot:
      "Personal and settings aren't implemented here. This prototype focuses on Home.",
    ecosystemTitle: "One space. Different possibilities.",
    ecosystemBody:
      "Cabinet helps you find your next step. Specialised actions stay in their respective products.",
    sparksTitle: "Sparks",
    sparksBody:
      "Ember's spendable internal currency. Not EXP, and not a measure of your level.",
    sparksFoot:
      "This is a demo balance. Earning, purchases and economy rules aren't implemented.",
    photoUnavailable: "Photo unavailable",
    portrait: "Illustrative portrait",
    mockProfile: "Fictional profile · illustrative photograph",
    productPulse: "Explore your preferences",
    productConnect: "Find someone",
    productScenario: "Create something together",
  },
};

function getNextMove(scene: Scene, language: Language): NextMove {
  const ru = language === "ru";

  /*
   * Explicit demonstration states, NOT a production context router.
   * Completion events, permissions and ranking would arrive from real products.
   */
  const moves: Record<Scene, NextMove> = {
    before: {
      product: "pulse",
      label: "Pulse",
      title: ru
        ? "Химия начинается с тебя."
        : "Chemistry starts with you.",
      description: ru
        ? "Узнай, что тебя притягивает. Pulse поможет учитывать желания и сексуальные предпочтения — не только первое впечатление."
        : "Explore what draws you in. Pulse adds desires and sexual preferences to the picture — beyond a first impression.",
      action: ru ? "Пройти Pulse" : "Take Pulse",
      note: ru
        ? "Можно знакомиться и без Pulse."
        : "You can meet people without taking Pulse.",
    },
    after: {
      product: "connect",
      label: "Connect",
      title: ru
        ? "Теперь — к знакомству."
        : "Now, meet someone.",
      description: ru
        ? "Ты уже исследовала свои предпочтения. Продолжи поиск: разрешённые данные Pulse смогут добавить ему контекста."
        : "You've explored your preferences. Continue discovering people with the context you're comfortable sharing.",
      action: ru ? "Продолжить в Connect" : "Continue in Connect",
      note: ru
        ? "Использование результатов зависит от разрешений."
        : "Using your results depends on permissions.",
    },
    connection: {
      product: "scenario",
      label: "Scenario",
      title: ru
        ? "А если этот вечер — ваш?"
        : "What if tonight is yours?",
      description: ru
        ? "Есть человек, с которым хочется продолжить. Найдите идею вечера: от необычного свидания до совместного эксперимента."
        : "There's someone you'd like to get closer to. Find an idea for an evening, a different kind of date or something new to try together.",
      action: ru ? "Найти идею вечера" : "Find an evening idea",
      note: ru
        ? "Создание сценария — в Scenario."
        : "Create your plan in Scenario.",
    },
  };

  return moves[scene];
}

function Icon({
  name,
  size = 20,
  className = "",
}: {
  name: IconName;
  size?: number;
  className?: string;
}) {
  const paths: Record<IconName, ReactNode> = {
    arrow: <path d="M5 12h14m-6-6 6 6-6 6" />,
    external: <path d="M6 18 18 6M6 6h12v12" />,
    close: <path d="m6 6 12 12M18 6 6 18" />,
    check: <path d="m5 12 4 4L19 6" />,
    spark: (
      <path d="m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4L12 3Z" />
    ),
    message: (
      <path d="M20 11.5a8 8 0 0 1-8 8H5l-3 2v-10a9 9 0 0 1 18 0ZM7 10h8m-8 4h5" />
    ),
    lock: (
      <>
        <rect x="5" y="10" width="14" height="11" rx="3" />
        <path d="M8 10V7a4 4 0 0 1 8 0v3m-4 5v2" />
      </>
    ),
    apps: (
      <>
        {[5, 12, 19].map((x) =>
          [5, 12, 19].map((y) => (
            <circle
              key={`${x}-${y}`}
              cx={x}
              cy={y}
              r="1.3"
              fill="currentColor"
              stroke="none"
            />
          )),
        )}
      </>
    ),
  };

  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      className={className}
    >
      {paths[name]}
    </svg>
  );
}

function Photo({
  src,
  alt,
  className = "",
  fallback,
  eager = false,
}: {
  src: string;
  alt: string;
  className?: string;
  fallback: string;
  eager?: boolean;
}) {
  const [failed, setFailed] = useState(false);

  useEffect(() => setFailed(false), [src]);

  if (failed) {
    return (
      <span className={`photo-fallback ${className}`} role="img" aria-label={alt}>
        {fallback}
      </span>
    );
  }

  return (
    <img
      className={className}
      src={src}
      alt={alt}
      loading={eager ? "eager" : "lazy"}
      decoding="async"
      referrerPolicy="no-referrer"
      onError={() => setFailed(true)}
    />
  );
}

function Dialog({
  title,
  closeLabel,
  onClose,
  children,
}: {
  title: string;
  closeLabel: string;
  onClose: () => void;
  children: ReactNode;
}) {
  const titleId = useId();
  const dialogRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const previouslyFocused = document.activeElement as HTMLElement | null;
    const oldOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const frame = requestAnimationFrame(() => {
      dialogRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
    });

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onClose();
        return;
      }

      if (event.key !== "Tab") return;

      const elements = Array.from(
        dialogRef.current?.querySelectorAll<HTMLElement>(
          'button:not([disabled]), a[href], input, select, textarea, [tabindex="0"]',
        ) ?? [],
      ).filter((element) => element.getClientRects().length > 0);

      const first = elements[0];
      const last = elements[elements.length - 1];

      if (!first || !last) {
        event.preventDefault();
        return;
      }

      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    document.addEventListener("keydown", onKeyDown);

    return () => {
      cancelAnimationFrame(frame);
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = oldOverflow;
      previouslyFocused?.focus();
    };
  }, [onClose]);

  return (
    <div
      className="dialog-backdrop"
      onClick={(event) => {
        if (event.target === event.currentTarget) onClose();
      }}
    >
      <div
        ref={dialogRef}
        className="dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
      >
        <button
          type="button"
          className="icon-button dialog-close"
          aria-label={closeLabel}
          onClick={onClose}
        >
          <Icon name="close" />
        </button>
        <h2 id={titleId}>{title}</h2>
        {children}
      </div>
    </div>
  );
}

function App() {
  const [language, setLanguage] = useState<Language>("ru");
  const [scene, setScene] = useState<Scene>("before");
  const [panel, setPanel] = useState<Panel>(null);
  const [selectedPerson, setSelectedPerson] = useState<Person | null>(null);
  const [interest, setInterest] = useState<string | null>(null);

  const t = COPY[language];
  const nextMove = getNextMove(scene, language);
  const pulseComplete = scene !== "before";

  useEffect(() => {
    document.documentElement.lang = language;
    document.title =
      language === "ru"
        ? "Ember — твоё пространство"
        : "Ember — your space";
  }, [language]);

  const closePanel = React.useCallback(() => {
    setPanel(null);
    setSelectedPerson(null);
  }, []);

  const openPanel = (nextPanel: Panel) => {
    setSelectedPerson(null);
    setPanel(nextPanel);
  };

  const selectPerson = (person: Person) => {
    setSelectedPerson(person);
    setPanel("connect");
  };

  const interestCopy =
    interest === "latex"
      ? t.interestLatex
      : interest === "cinema"
        ? t.interestCinema
        : interest === "nights"
          ? t.interestNights
          : t.interestIdle;

  const panelContent: Record<
    Exclude<Panel, null>,
    { title: string; body: string; foot?: string }
  > = {
    pulse: {
      title: t.pulseTitle,
      body: t.pulseBody,
      foot: t.pulseFoot,
    },
    connect: {
      title: t.connectTitle,
      body: t.connectBody,
      foot: t.connectFoot,
    },
    scenario: {
      title: t.scenarioTitle,
      body: t.scenarioBody,
      foot: t.scenarioFoot,
    },
    messages: {
      title: t.messagesTitle,
      body: t.messagesBody,
      foot: t.messagesFoot,
    },
    account: {
      title: t.accountTitle,
      body: t.accountBody,
      foot: t.accountFoot,
    },
    ecosystem: {
      title: t.ecosystemTitle,
      body: t.ecosystemBody,
    },
    sparks: {
      title: t.sparksTitle,
      body: t.sparksBody,
      foot: t.sparksFoot,
    },
  };

  return (
    <>
      <header className="header">
        <div className="header-inner">
          <a className="wordmark" href="#home" aria-label="Ember Home">
            ember<span className="brand-dot" />
          </a>

          <nav className="main-nav" aria-label={t.ecosystem}>
            <a href="#home" className="nav-link selected" aria-current="page">
              {t.today}
            </a>
            <button className="nav-link" onClick={() => openPanel("connect")}>
              Connect
            </button>
            <button className="nav-link" onClick={() => openPanel("messages")}>
              {t.messages}
            </button>
            <a href="#journey" className="nav-link">
              {t.progress}
            </a>
          </nav>

          <div className="header-tools">
            <div className="language-switch" role="group" aria-label={t.language}>
              {(["ru", "en"] as const).map((value) => (
                <button
                  key={value}
                  className={language === value ? "active" : ""}
                  aria-pressed={language === value}
                  onClick={() => setLanguage(value)}
                >
                  {value.toUpperCase()}
                </button>
              ))}
            </div>

            <button
              className="sparks-control"
              onClick={() => openPanel("sparks")}
              aria-label="240 Sparks"
            >
              <Icon name="spark" size={17} />
              <span>240</span>
            </button>

            <button
              className="icon-button apps-control"
              aria-label={t.ecosystem}
              onClick={() => openPanel("ecosystem")}
            >
              <Icon name="apps" size={22} />
            </button>

            <button
              className="account-control"
              aria-label={t.account}
              onClick={() => openPanel("account")}
            >
              <Photo
                src="/assets/maya.jpg"
                alt=""
                fallback="M"
                className="avatar"
                eager
              />
            </button>
          </div>
        </div>
      </header>

      <main id="home" className="page-shell">
        <section className="welcome" aria-labelledby="page-title">
          <div>
            <p className="greeting">
              <span className="small-line" />
              {t.greeting}
            </p>
            <h1 id="page-title">
              {t.heading}
              <br />
              <span>{t.headingAccent}</span>
            </h1>
          </div>

          <div className="welcome-aside">
            <span className="context-label">
              <span className="status-dot" />
              {scene === "connection" ? t.connected : t.searching}
            </span>
            <p>{t.intro}</p>
          </div>
        </section>

        <div className="primary-layout">
          <section
            className={`next-card next-card--${nextMove.product}`}
            aria-labelledby="next-title"
          >
            <div className="next-card-top">
              <span className="eyebrow">{t.nextMove}</span>
              <span className="product-label">
                {nextMove.label}
                <Icon name="external" size={13} />
              </span>
            </div>

            <div key={scene} className="next-card-content state-enter">
              <div className="next-symbol" aria-hidden="true">
                <span />
                <span />
                <span />
                <span />
                <span />
              </div>

              <h2 id="next-title">{nextMove.title}</h2>
              <p className="next-description">{nextMove.description}</p>
            </div>

            <div className="next-card-bottom">
              <button
                className="button button-dark full-width"
                onClick={() => openPanel(nextMove.product)}
              >
                {nextMove.action}
                <Icon name="arrow" />
              </button>
              <p className="next-note">{nextMove.note}</p>
            </div>
          </section>

          <section className="people-section" aria-labelledby="people-title">
            <div className="section-heading">
              <div>
                <p className="eyebrow">{t.peopleEyebrow}</p>
                <h2 id="people-title">{t.peopleTitle}</h2>
              </div>
              <span className="section-source">Connect</span>
            </div>

            <p className="section-description">
              {scene === "before"
                ? t.peopleIntro
                : scene === "after"
                  ? t.peopleAfter
                  : t.peopleConnection}
            </p>

            <div className="people-grid">
              {PEOPLE.map((person) => (
                <button
                  className="person-card"
                  key={person.id}
                  onClick={() => selectPerson(person)}
                  aria-label={`${t.openPerson}: ${person.name}, ${person.age}`}
                >
                  <Photo
                    src={person.image}
                    alt={`${t.portrait}: ${person.name}`}
                    fallback={t.photoUnavailable}
                    className="person-photo"
                    eager
                  />
                  <span className="person-shade" />
                  <span className="person-interest">{person.interest}</span>
                  <span className="person-caption">
                    <span className="person-name">
                      {person.name}
                      <span>{person.age}</span>
                    </span>
                    <span className="person-city">{person.city}</span>
                  </span>
                  <span className="person-arrow">
                    <Icon name="external" size={17} />
                  </span>
                </button>
              ))}
            </div>

            <div className="people-bottom">
              <p>
                <Icon name="lock" size={15} />
                {pulseComplete ? t.peopleNoteAfter : t.peopleNote}
              </p>
              <button
                className="button button-dark"
                onClick={() => openPanel("connect")}
              >
                {t.menAction}
                <Icon name="arrow" />
              </button>
            </div>
          </section>
        </div>

        {scene === "connection" && (
          <section className="connection-strip state-enter">
            <Photo
              src={PEOPLE[0].image}
              alt={`${t.portrait}: Alex`}
              fallback="A"
              className="connection-avatar"
            />
            <div className="connection-copy">
              <p className="eyebrow">{t.connectionEyebrow}</p>
              <h2>Maya & Alex</h2>
              <p>{t.connectionText}</p>
            </div>
            <button
              className="icon-button connection-action"
              aria-label={t.connectionAction}
              onClick={() => openPanel("scenario")}
            >
              <Icon name="arrow" />
            </button>
          </section>
        )}

        <section className="interest-section" aria-labelledby="interest-title">
          <div className="interest-heading">
            <p className="eyebrow">{t.interestEyebrow}</p>
            <h2 id="interest-title">{t.interestTitle}</h2>
            <p>{t.interestIntro}</p>
          </div>

          <div className="interest-content">
            <div className="interest-pills">
              {INTERESTS.map((item) => (
                <button
                  key={item.id}
                  className={`interest-pill interest-pill--${item.style} ${
                    interest === item.id ? "is-selected" : ""
                  }`}
                  aria-pressed={interest === item.id}
                  onClick={() =>
                    setInterest((current) =>
                      current === item.id ? null : item.id,
                    )
                  }
                >
                  {item.label}
                  <Icon
                    name={interest === item.id ? "check" : "external"}
                    size={17}
                  />
                </button>
              ))}
            </div>
            <p className="interest-context" aria-live="polite">
              {interestCopy}
            </p>
            {interest && (
              <p className="interest-disclaimer">{t.interestDisclaimer}</p>
            )}
          </div>
        </section>

        <section
          id="journey"
          className="journey-section"
          aria-labelledby="journey-title"
        >
          <div className="journey-intro">
            <p className="eyebrow">{t.journeyEyebrow}</p>
            <h2 id="journey-title">{t.journeyTitle}</h2>
            <p>{t.journeyText}</p>
          </div>

          <div className="journey-detail">
            <div className="journey-level">
              <span className="level-mark">02</span>
              <div>
                <span className="level-label">{t.level} 02</span>
                <span className="exp-label">320 / 500 EXP · demo</span>
              </div>
              <Icon name="spark" size={26} />
            </div>

            <div
              className="progress-track"
              role="progressbar"
              aria-label="EXP"
              aria-valuemin={0}
              aria-valuemax={500}
              aria-valuenow={320}
              aria-valuetext="320 / 500 EXP — demo"
            >
              <span />
            </div>

            <ol className="journey-steps">
              <li className="complete">
                <span className="step-mark">
                  <Icon name="check" size={12} />
                </span>
                <span>{t.profileReady}</span>
                <small>{t.ready}</small>
              </li>
              <li className={pulseComplete ? "complete" : "current"}>
                <span className="step-mark">
                  {pulseComplete ? <Icon name="check" size={12} /> : "2"}
                </span>
                <span>{t.preferences}</span>
                <small>{pulseComplete ? t.ready : t.next}</small>
              </li>
              <li>
                <span className="step-mark">3</span>
                <span>{t.possibilities}</span>
                <small>{t.ahead}</small>
              </li>
            </ol>

            <p className="progress-disclaimer">{t.progressNote}</p>
          </div>
        </section>

        <footer className="page-footer">
          <a className="wordmark footer-wordmark" href="#home">
            ember<span className="brand-dot" />
          </a>
          <span>
            {language === "ru"
              ? "Меньше случайного. Больше твоего."
              : "Less random. More you."}
          </span>
          <span className="footer-caption">HOME / CONCEPT 01</span>
        </footer>

        <aside className="demo-controls" aria-label={t.prototype}>
          <div className="demo-controls-top">
            <span className="demo-label">
              <span />
              {t.prototype}
            </span>

            <div
              className="scene-switch"
              role="group"
              aria-label={t.stateLabel}
            >
              {(["before", "after", "connection"] as const).map((value) => (
                <button
                  key={value}
                  className={scene === value ? "active" : ""}
                  aria-pressed={scene === value}
                  onClick={() => setScene(value)}
                >
                  {t[value]}
                </button>
              ))}
            </div>
          </div>
          <p>{t.demoNote}</p>
        </aside>
      </main>

      {panel && (
        <Dialog
          title={panelContent[panel].title}
          closeLabel={t.close}
          onClose={closePanel}
        >
          {selectedPerson && (
            <div className="dialog-person">
              <Photo
                src={selectedPerson.image}
                alt={`${t.portrait}: ${selectedPerson.name}`}
                fallback={t.photoUnavailable}
                className="dialog-person-photo"
              />
              <div>
                <strong>
                  {selectedPerson.name}, {selectedPerson.age}
                </strong>
                <span>{selectedPerson.city}</span>
                <small>{t.mockProfile}</small>
              </div>
            </div>
          )}

          {panel === "sparks" && (
            <div className="dialog-balance">
              <Icon name="spark" size={30} />
              240 <span>Sparks · demo</span>
            </div>
          )}

          <p className="dialog-body">{panelContent[panel].body}</p>

          {panel === "ecosystem" && (
            <div className="product-list">
              {[
                ["connect", "Connect", t.productConnect],
                ["pulse", "Pulse", t.productPulse],
                ["scenario", "Scenario", t.productScenario],
              ].map(([product, name, description]) => (
                <button
                  key={product}
                  onClick={() => openPanel(product as Product)}
                >
                  <span>
                    <strong>{name}</strong>
                    <small>{description}</small>
                  </span>
                  <Icon name="arrow" />
                </button>
              ))}
            </div>
          )}

          {panelContent[panel].foot && (
            <p className="dialog-footnote">{panelContent[panel].foot}</p>
          )}

          <button
            className="button button-dark full-width"
            onClick={closePanel}
          >
            {t.understood}
            <Icon name="check" size={18} />
          </button>
        </Dialog>
      )}
    </>
  );
}

createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
);