// i18n.jsx
// Bilingual layer (PL / EN). Provides a React context with { lang, setLang, t }.
// t(key) returns the string/array for the active language, falling back to PL.
// HTML-bearing values are rendered via dangerouslySetInnerHTML at the call site.

(function () {
  const { useState, useEffect, useContext, createContext } = React;

  const STRINGS = {
    pl: {
      // status bar / prompt
      meta_sub: 'v0.1 // terminal narracyjny',
      sfx: 'SFX',
      home: '[HOME]',
      hint_accept: 'akceptuj',
      hint_console: 'konsola',
      hint_select: 'wybierz moduł',
      hint_exit: 'wyjście',
      hint_back: 'powrót',
      hint_copy: 'kopiuj e-mail',

      // intro
      intro_meta: 'Inicjalizacja modułu narracji…',
      intro_enter: 'WEJDŹ',

      // boot log
      boot: [
        'ÐYS.MAINFRAME // zimny rozruch',
        'montowanie narrative.core ........ OK',
        'łączenie identity.module ......... OK',
        'kalibracja tonu głosu ............ OK',
        'ładowanie hologramu operatora .... OK',
        'deszyfrowanie story.kernel ....... OK',
        'handshake z użytkownikiem ........ ?',
      ],
      boot_skip: '[dowolny klawisz] pomiń',

      // menu
      menu_head: 'Wybierz <em>moduł</em>',
      menu_slogan: ['Marka to opowieść.', 'Opowieść to fabuła.', 'Fabuła to klucz.'],
      menu_sub: '// Wszystkie ścieżki prowadzą do tej samej rozmowy.',
      tile_about: 'O mnie',
      tile_about_desc: 'Hologram operatora. Niska siatka, wysoka rozdzielczość intencji.',
      tile_portfolio: 'Portfolio',
      tile_portfolio_desc: 'Archiwum projektów. Marki, narracje, identyfikacje.',
      tile_contact: 'Kontakt',
      tile_contact_desc: 'Otwarty kanał. E-mail, sygnał, odpowiedź.',

      // window titles
      win_about: 'SYS.ABOUT — operator/01',
      win_portfolio: 'SYS.PORTFOLIO — archiwum',
      win_contact: 'SYS.CONTACT — otwarty kanał',
      win_close: '[ESC] ZAMKNIJ',

      // about
      holo_label: 'MESH.PROBE // KLIKNIJ = INTERFERENCE',
      about_h3: 'Buduję <em>marki</em> jak fabuły.',
      about_p1: '<strong>Łukasz Grochólski-Grabau.</strong> Grafik, projektant, strateg komunikacji z ponad 12 latami doświadczenia.',
      about_p2: 'Pracuję z dwoma rodzajami klientów: tymi, którzy dopiero budują markę i chcą zrobić to z sensem od początku, oraz tymi, którzy mają już markę, ale czują, że coś nie gra i nie do końca wiedzą co.',
      about_p3: 'Indywidualna wycena. <em>Porozmawiajmy.</em>',
      about_tags: ['BRANDING', 'NARRACJA', 'IDENTYFIKACJA', 'COPY', 'STRATEGIA'],

      // portfolio
      pf_intro: '// Otwarte archiwum • <em>{n} zapisów</em> • zapytaj o szczegóły',
      pf_projects: [
        { title: 'Świat 2226', meta: 'Branding • Narracja' },
        { title: 'Projekt w toku', meta: 'Identyfikacja • Strategia' },
        { title: 'Archiwum 2024', meta: 'Branding • Print' },
        { title: 'Sygnał', meta: 'Naming • Voice' },
      ],

      // contact
      contact_label: '// Najprostsza droga — wyślij e-mail.',
      contact_copy: 'Kopiuj',
      contact_copied: '✓ Skopiowano',
      contact_sig1: 'Odpowiadam w 24h.',
      contact_sig2: 'Marka to opowieść. Opowieść to fabuła. Fabuła to klucz.',

      // command line
      cmd_hint_title: '// dostępne komendy',
      cmd_hint: [
        ['about', 'o mnie'], ['portfolio', 'archiwum'], ['contact', 'kontakt'],
        ['home', 'menu główne'], ['whoami', 'kim jestem'], ['mail', 'adres e-mail'],
        ['sfx', 'dźwięk on/off'], ['clear', 'wyczyść'],
      ],
      cmd_placeholder: 'wpisz komendę… (esc zamyka)',
      cmd_help: 'komendy: about · portfolio · contact · home · whoami · sfx · clear',
      cmd_whoami: 'operator // brand & narrative studio. marka to fabuła.',
      cmd_unknown: 'nieznana komenda',
      cmd_unknown_tail: '— wpisz "help"',
      cmd_secret: '> autoryzacja operatora … OK. przekierowanie do fontripper…',

      // idle
      idle_msg: '// sygnał uśpiony — wciśnij dowolny klawisz, żeby wrócić',

      // tweaks
      tw_atmosphere: 'Atmosfera',
      tw_grid: 'Grid',
      tw_trail: 'Ślad kursora',
      tw_scanline: 'Scanline',
      tw_glitch: 'Glitch przejść',
      tw_readouts: 'Odczyty live',
      tw_palette: 'Paleta',
      tw_mode: 'Tryb',
      tw_system: 'System',
      tw_replay: 'Odtwórz intro',
      tw_waveform: 'Ghost waveform',
      tw_story: 'Story',
      tw_tempo: 'Tempo revealu',

      // prompt hints
      hint_skip: 'pomiń skan',
      hint_module: 'moduł',
      hint_menu: 'menu',
      hint_copy_short: 'kopiuj',

      // menu tile sub-labels
      tile_about_sub: 'dossier operatora',
      tile_portfolio_sub: 'archiwum projektów',
      tile_contact_sub: 'kanał komunikacji',
      tile_story_sub: 'Polska, 2226',

      // portfolio
      pf_status_intro: '// Otwarte archiwum • <em>{n} rekordy</em> • zapytaj o szczegóły',
      pf_full: [
        { num: '001', title: 'Dysbalans Visual Identity', meta: 'Branding • Narracja', status: 'LIVE', url: 'https://www.behance.net/gallery/249439539/studio-DhysBalans-visual-identity' },
        { num: '002', title: 'Projekt w toku', meta: 'Identyfikacja • Strategia', status: 'WIP', url: 'https://www.behance.net/gallery/249448745/DB00022026-Sara-Balcerzak-visual-identity' },
        { num: '003', title: 'Archiwum 2024', meta: 'Branding • Print', status: 'LIVE' },
        { num: '004', title: 'Sygnał', meta: 'Naming • Voice', status: 'LOCKED', locked: true },
      ],

      // retina scan
      scan_status: [
        'inicjalizacja skanera siatkówki…',
        'mapowanie naczyń włosowatych…',
        'dopasowanie wzorca tęczówki…',
        '[ERR] niezgodność wzorca · 0x4F',
        'rekalibracja sygnału…',
        'weryfikacja biometryczna…',
        'skan pomyślny',
      ],
      scan_log: [
        'ÐYS.MAINFRAME // auth',
        'mount retina.driver ······· OK',
        'biometric.handshake ······· OK',
        'narrative.core ············ OK',
        'identity.module ··········· ····',
        '[WARN] szum sygnału',
        'rekalibracja ·············· OK',
        'identity.module ··········· OK',
        'operator.rozpoznany ······· OK',
      ],
      scan_abort: '[ESC] PRZERWIJ',
      scan_verdict_main: 'SKAN POMYŚLNY',
      scan_verdict_sub: '// DOSTĘP PRZYZNANY',

      // idle
      idle_press: 'naciśnij dowolny klawisz',

      // story (2226)
      win_story: 'SYS.STORY — 2226 // Polska',
      story_cta_line: '// ciąg dalszy w przygotowaniu',
      story_buy: 'Kup opowiadanie',
      story_cta_sub: 'zajawka teraz — całość wkrótce',
      story_html:
`\tU schyłku 2027 roku, pomniejsze konflikty rozprzestrzenione po całym globie, ostatecznie przerodziły się w pełnoskalową, <span class="story-hot">III Wojnę Światową.</span>
Fizyka kwantowa, SI i technologia fuzji jądrowej — rozwijające się w tempie geometrycznym — stały się instrumentami Nowego Imperium Sowieckiego, wymierzonymi przeciwko ludzkości. Dywersanci zaatakowali CERN i ośrodki programu ITER i EAST, doprowadzając do katastrofy na biblijną skalę.

\tW wyniku uszkodzeń reaktorów jądrowych i TOKAMAK, w atmosferze utworzyły się Osobliwości, które zmiotły z powierzchni ziemi 95% życia i ludzkiej infrastruktury.

\tPo 200 latach, nieliczni, którym udało się schować głęboko pod ziemią, utworzyli na zgliszczach dawnej cywilizacji nowe społeczeństwo, podejmujące trud odbudowy świata.

\tChaos, który ogarnął glob, pozwolił wyjść z cienia tym, którzy dotychczas nie uczestniczyli w projektowaniu świata.

\tTak, zaczęła się nowa era.
\tEra ĐysBalans(u).`,

      // bsod easter egg
      bsod_p1: 'Wystąpił błąd nieobsługiwanego marzenia 0x000000DB w module STORY.KERNEL. Strona, której szukasz, jeszcze nie istnieje — albo istnieje wyłącznie w głowie operatora.',
      bsod_p2: '* Naciśnij dowolny klawisz, aby wrócić do rzeczywistości.<br>* Naciśnij CTRL+ALT+DEL, aby udawać, że nic się nie stało.',
      bsod_wait: 'Naciśnij dowolny klawisz, aby kontynuować _',
    },

    en: {
      meta_sub: 'v0.1 // narrative terminal',
      sfx: 'SFX',
      home: '[HOME]',
      hint_accept: 'accept',
      hint_console: 'console',
      hint_select: 'select module',
      hint_exit: 'exit',
      hint_back: 'back',
      hint_copy: 'copy e-mail',

      intro_meta: 'Initializing narrative module…',
      intro_enter: 'ENTER',

      boot: [
        'ÐYS.MAINFRAME // cold boot',
        'mounting narrative.core .......... OK',
        'linking identity.module .......... OK',
        'calibrating tone of voice ........ OK',
        'loading operator hologram ........ OK',
        'decrypting story.kernel .......... OK',
        'handshake with user .............. ?',
      ],
      boot_skip: '[any key] skip',

      menu_head: 'Choose <em>folder</em>',
      menu_slogan: ['A brand is a story.', 'A story is a plot.', 'A plot is the key.'],
      menu_sub: '// All paths lead to the same conversation.',
      tile_about: 'About',
      tile_about_desc: 'Operator hologram. Low poly, high-resolution intent.',
      tile_portfolio: 'Portfolio',
      tile_portfolio_desc: 'Project archive. Brands, narratives, identities.',
      tile_contact: 'Contact',
      tile_contact_desc: 'Open channel. E-mail, signal, reply.',

      win_about: 'SYS.ABOUT — operator/01',
      win_portfolio: 'SYS.PORTFOLIO — archive',
      win_contact: 'SYS.CONTACT — open channel',
      win_close: '[ESC] CLOSE',

      holo_label: 'MESH.PROBE // CLICK = INTERFERENCE',
      about_h3: 'I build <em>brands</em> like stories.',
      about_p1: '<strong>Łukasz Grochólski-Grabau.</strong> Graphic designer, visual identity specialist and communication strategist with over 12 years of experience.',
      about_p2: 'I work with two kinds of clients: those who are building a brand from scratch and want to do it right from the start, and those who already have a brand but feel something is off and can\'t quite put their finger on what.',
      about_p3: 'Individual pricing for every project. <em>Let\'s talk.</em>',
      about_tags: ['BRANDING', 'NARRATIVE', 'IDENTITY', 'COPY', 'STRATEGY'],

      pf_intro: '// Open archive • <em>{n} records</em> • ask for details',
      pf_projects: [
        { title: 'World 2226', meta: 'Branding • Narrative' },
        { title: 'Work in progress', meta: 'Identity • Strategy' },
        { title: 'Archive 2024', meta: 'Branding • Print' },
        { title: 'Signal', meta: 'Naming • Voice' },
      ],

      contact_label: '// Simplest way — send an e-mail.',
      contact_copy: 'Copy',
      contact_copied: '✓ Copied',
      contact_sig1: 'I reply within 24h.',
      contact_sig2: 'A brand is a story. A story is a plot. A plot is the key.',

      cmd_hint_title: '// available commands',
      cmd_hint: [
        ['about', 'about me'], ['portfolio', 'archive'], ['contact', 'contact'],
        ['home', 'main menu'], ['whoami', 'who am i'], ['mail', 'e-mail address'],
        ['sfx', 'sound on/off'], ['clear', 'clear'],
      ],
      cmd_placeholder: 'type a command… (esc closes)',
      cmd_help: 'commands: about · portfolio · contact · home · whoami · sfx · clear',
      cmd_whoami: 'operator // brand & narrative studio. a brand is a story.',
      cmd_unknown: 'unknown command',
      cmd_unknown_tail: '— type "help"',
      cmd_secret: '> operator authorization … OK. redirecting to fontripper…',

      idle_msg: '// signal idle — press any key to return',

      tw_atmosphere: 'Atmosphere',
      tw_grid: 'Grid',
      tw_trail: 'Cursor trail',
      tw_scanline: 'Scanline',
      tw_glitch: 'Transition glitch',
      tw_readouts: 'Live readouts',
      tw_palette: 'Palette',
      tw_mode: 'Mode',
      tw_system: 'System',
      tw_replay: 'Replay intro',
      tw_waveform: 'Ghost waveform',
      tw_story: 'Story',
      tw_tempo: 'Reveal speed',

      hint_skip: 'skip scan',
      hint_module: 'module',
      hint_menu: 'menu',
      hint_copy_short: 'copy',

      tile_about_sub: 'operator dossier',
      tile_portfolio_sub: 'project archive',
      tile_contact_sub: 'comms channel',
      tile_story_sub: 'Poland, 2226',

      pf_status_intro: '// Open archive • <em>{n} records</em> • ask for details',
      pf_full: [
        { num: '001', title: 'Dysbalans Visual Identity', meta: 'Branding • Narrative', status: 'LIVE', url: 'https://www.behance.net/gallery/249439539/studio-DhysBalans-visual-identity' },
        { num: '002', title: 'Work in progress', meta: 'Identity • Strategy', status: 'WIP', url: 'https://www.behance.net/gallery/249448745/DB00022026-Sara-Balcerzak-visual-identity' },
        { num: '003', title: 'Archive 2024', meta: 'Branding • Print', status: 'LIVE' },
        { num: '004', title: 'Signal', meta: 'Naming • Voice', status: 'LOCKED', locked: true },
      ],

      scan_status: [
        'initializing retina scanner…',
        'mapping capillaries…',
        'matching iris pattern…',
        '[ERR] pattern mismatch · 0x4F',
        'recalibrating signal…',
        'biometric verification…',
        'scan successful',
      ],
      scan_log: [
        'ÐYS.MAINFRAME // auth',
        'mount retina.driver ······· OK',
        'biometric.handshake ······· OK',
        'narrative.core ············ OK',
        'identity.module ··········· ····',
        '[WARN] signal noise',
        'recalibration ············· OK',
        'identity.module ··········· OK',
        'operator.recognized ······· OK',
      ],
      scan_abort: '[ESC] ABORT',
      scan_verdict_main: 'SCAN SUCCESSFUL',
      scan_verdict_sub: '// ACCESS GRANTED',

      idle_press: 'press any key',

      win_story: 'SYS.STORY — 2226 // Poland',
      story_cta_line: '// to be continued',
      story_buy: 'Buy the story',
      story_cta_sub: 'teaser now — full version soon',
      story_html:
`\tAt the end of 2027, minor conflicts scattered across the globe finally escalated into a full-scale <span class="story-hot">Third World War.</span>
Quantum physics, artificial intelligence and nuclear fusion technology — advancing at geometric speed — became instruments of the New Soviet Empire, turned against humanity. Saboteurs struck CERN and the facilities of the ITER and EAST programs, triggering a catastrophe of biblical proportions.

\tThe damage to nuclear reactors and TOKAMAK devices gave rise to Singularities in the atmosphere — anomalies that wiped 95% of all life and human infrastructure from the face of the earth.

\tTwo hundred years later, the few who had managed to shelter deep underground built a new society from the ruins of the old civilization, and began the long work of rebuilding the world.

\tThe chaos that had consumed the globe allowed those who had never been invited to shape it — to finally step out of the shadows.

\tAnd so, a new era began.
\tThe era of ĐysBalans.`,

      bsod_p1: 'An unhandled dream error 0x000000DB occurred in module STORY.KERNEL. The page you are looking for does not exist yet — or exists only in the operator\'s head.',
      bsod_p2: '* Press any key to return to reality.<br>* Press CTRL+ALT+DEL to pretend nothing happened.',
      bsod_wait: 'Press any key to continue _',
    },
  };

  const LangContext = createContext({ lang: 'pl', setLang: () => {}, t: (k) => k });

  function LangProvider({ children }) {
    const [lang, setLangState] = useState(() => {
      try { return localStorage.getItem('dys_lang') || 'pl'; } catch { return 'pl'; }
    });
    function setLang(l) {
      setLangState(l);
      try { localStorage.setItem('dys_lang', l); } catch {}
    }
    useEffect(() => {
      document.documentElement.lang = lang;
    }, [lang]);
    const t = (key) => {
      const dict = STRINGS[lang] || STRINGS.pl;
      return dict[key] !== undefined ? dict[key] : (STRINGS.pl[key] !== undefined ? STRINGS.pl[key] : key);
    };
    return React.createElement(LangContext.Provider, { value: { lang, setLang, t } }, children);
  }

  function useLang() { return useContext(LangContext); }

  // PL/EN toggle styled exactly like the other status-bar buttons (SFX / VO / HOME)
  function LangToggle() {
    const { lang, setLang } = useLang();
    return (
      <button
        onClick={() => { setLang(lang === 'pl' ? 'en' : 'pl'); window.Audio && window.Audio.tick(); }}
        aria-label="Język / Language"
      >
        LANG: {lang.toUpperCase()}
      </button>
    );
  }

  Object.assign(window, { LangContext, LangProvider, useLang, LangToggle });
})();
