// i18n.jsx — language strings (English / Hebrew), context, hook, and toggle.
const STRINGS = {
  en: {
    welcome: 'Welcome',
    confirmation: 'Confirmation',
    checkIn: 'Check-in',
    checkOut: 'Check-out',
    weather: 'Weather',
    availableNow: 'Available now',
    walkRightIn: 'Walk right in',
    yourApartments: 'Your apartments',
    aptOfTotal: 'Apartment {n} of {total}',
    guestsNights: '{guests} guests · {nights} nights',
    room: 'Room', floor: 'Floor', building: 'Building',
    buildingCode: 'Building code', personalPin: 'Personal PIN',
    connect: 'Connect', wifiAccess: 'Wi-Fi access',
    wifiNetwork: 'Wi-Fi network', wifiPassword: 'Wi-Fi password',
    whereYouAre: 'Location', address: 'Address',
    googleMaps: 'Google Maps', waze: 'Waze',
    livingHere: 'Living here', everythingInApt: 'Everything in the apartment', readMore: 'Read more',
    aroundCorner: 'Around the corner', ourPicksIn: 'our picks in {city}',
    needHand: 'Need assistance?', hostRepliesMinutes: 'we typically reply within minutes',
    supportBody: 'Anything at all — a wobbly tap, an extra towel, a forgotten toothbrush. We’re around the clock.',
    whatsapp: 'WhatsApp', email: 'Email', call: 'Call',
    today: 'Today', videoGuide: 'Video guide', saveAsImage: 'Save as image',
    pinNote: 'This PIN grants access to your apartment. Only share it with guests included in your reservation.',
    completeCheckout: "I'm out — complete check-out",
    checkedOut: 'Checked out — safe travels, {name}.',
    hostAgain: 'we hope to host you again soon',
    coBelongings: 'Take all your belongings — don’t forget the safebox!',
    coLights: 'Turn off the lights & AC',
    coKeys: 'Drop keys in the lockbox · code {code}',
    coDoor: 'Make sure the door is shut behind you',
    weReplyMinutes: 'We reply within minutes', contactUs: 'Contact us',
    guests: 'Guests', nights: 'nights', yourDates: 'Your dates', now: 'now',
    stayNotStarted: 'Your stay hasn’t started yet', opensOn: 'This page opens on {when}.',
    stayEnded: 'Your stay has ended', stayEndedBody: 'Thank you for staying with master. We hope to host you again soon.',
    stayEndedActually: 'Actually,', stayEndedCta: 'Here is 5% OFF for your next stay',
    luggageStorage: 'Luggage Storage', luggageStorageSub: 'leave your bags for the day',
    checkoutFailed: 'Something went wrong. Please try again or contact us.',
    breakfast: 'Breakfast', breakfastIncluded: 'Included in your stay', navBreakfast: 'Breakfast',
    navGettingIn: 'Getting in', navConnect: 'Connect', navLocation: 'Location',
    navLiving: 'Living here', navExplore: 'Explore', navCheckout: 'Check-out',
    footer: '© master'
  },
  he: {
    welcome: 'ברוכים הבאים',
    confirmation: 'מספר אישור',
    checkIn: 'צ׳ק־אין',
    checkOut: 'צ׳ק־אאוט',
    weather: 'מזג אוויר',
    availableNow: 'זמין עכשיו',
    walkRightIn: 'אפשר להיכנס',
    yourApartments: 'הדירות שלך',
    aptOfTotal: 'דירה {n} מתוך {total}',
    guestsNights: '{guests} אורחים · {nights} לילות',
    room: 'חדר', floor: 'קומה', building: 'בניין',
    buildingCode: 'קוד בניין', personalPin: 'קוד אישי',
    connect: 'התחברות', wifiAccess: 'גישה ל־Wi-Fi',
    wifiNetwork: 'רשת Wi-Fi', wifiPassword: 'סיסמת Wi-Fi',
    whereYouAre: 'איפה אתם', address: 'כתובת',
    googleMaps: 'Google Maps', waze: 'Waze',
    livingHere: 'החיים כאן', everythingInApt: 'כל מה שיש בדירה', readMore: 'קראו עוד',
    aroundCorner: 'מעבר לפינה', ourPicksIn: 'ההמלצות שלנו ב{city}',
    needHand: 'צריכים סיוע?', hostRepliesMinutes: 'בדרך כלל אנחנו משיבים תוך דקות',
    supportBody: 'כל דבר — ברז רופף, מגבת נוספת, מברשת שיניים שנשכחה. אנחנו כאן מסביב לשעון.',
    whatsapp: 'וואטסאפ', email: 'אימייל', call: 'טלפון',
    today: 'היום', videoGuide: 'מדריך וידאו', saveAsImage: 'שמירה כתמונה',
    pinNote: 'הקוד מעניק גישה לדירה שלכם. שתפו אותו רק עם אורחים הכלולים בהזמנה.',
    completeCheckout: 'סיימתי — להשלמת היציאה',
    checkedOut: 'עשיתם צ׳ק־אאוט — נסיעה טובה, {name}.',
    hostAgain: 'נשמח לארח אתכם שוב בקרוב',
    coBelongings: 'קחו את כל החפצים שלכם — אל תשכחו את הכספת!',
    coLights: 'כבו את האורות והמזגן',
    coKeys: 'השאירו את המפתחות בתיבת המפתחות · קוד {code}',
    coDoor: 'ודאו שהדלת ננעלה אחריכם',
    weReplyMinutes: 'אנחנו משיבים תוך דקות', contactUs: 'צרו קשר',
    guests: 'אורחים', nights: 'לילות', yourDates: 'התאריכים שלך', now: 'עכשיו',
    stayNotStarted: 'השהות שלך עוד לא התחילה', opensOn: 'הדף ייפתח בתאריך {when}.',
    stayEnded: 'השהות שלך הסתיימה', stayEndedBody: 'תודה שהתארחתם אצל master. נשמח לארח אתכם שוב בקרוב.',
    stayEndedActually: 'בעצם,', stayEndedCta: 'הנה 5% הנחה לשהות הבאה שלכם',
    luggageStorage: 'אחסון מזוודות', luggageStorageSub: 'השאירו את התיקים שלכם ליום',
    checkoutFailed: 'משהו השתבש. נסו שוב או צרו קשר.',
    breakfast: 'ארוחת בוקר', breakfastIncluded: 'כלולה בשהות שלך', navBreakfast: 'ארוחת בוקר',
    navGettingIn: 'כניסה', navConnect: 'התחברות', navLocation: 'מיקום',
    navLiving: 'החיים כאן', navExplore: 'לגלות', navCheckout: 'יציאה',
    footer: '© master'
  }
};

// Merge admin-managed UI-string overrides into STRINGS. Shape: { lang: { key: value } }.
// Empty values are ignored so a blank field falls back to the built-in string.
function applyUiStrings(overrides) {
  if (!overrides || typeof overrides !== 'object') return;
  for (const lang in overrides) {
    const map = overrides[lang];
    if (!map || typeof map !== 'object') continue;
    STRINGS[lang] = STRINGS[lang] || {};
    for (const key in map) {
      const v = map[key];
      if (typeof v === 'string' && v.trim()) STRINGS[lang][key] = v;
    }
  }
}

function tr(lang, key, vars) {
  let s = STRINGS[lang] && STRINGS[lang][key] || STRINGS.en[key] || key;
  if (vars) for (const k in vars) s = s.split('{' + k + '}').join(vars[k]);
  return s;
}

const LangCtx = React.createContext({ lang: 'en', setLang: () => {} });
const useLang = () => React.useContext(LangCtx);
const useT = () => {const { lang } = useLang();return (k, v) => tr(lang, k, v);};

// Right-to-left languages (per the admin's CMS language set).
const RTL_LANGS = new Set(['he', 'ar', 'fa', 'ur', 'ps', 'sd', 'yi', 'dv']);
const isRTL = (lang) => RTL_LANGS.has(lang);

// Endonyms + flags for the languages a property might declare. UI chrome stays
// English for any language without a STRINGS entry; guest CONTENT still localizes
// via the per-document `_i18n` maps.
const LANG_NAMES = {
  en: 'English', he: 'עברית', ar: 'العربية', es: 'Español', fr: 'Français', de: 'Deutsch',
  it: 'Italiano', pt: 'Português', ru: 'Русский', nl: 'Nederlands', pl: 'Polski', tr: 'Türkçe',
  zh: '中文', ja: '日本語', ko: '한국어', uk: 'Українська', ro: 'Română', cs: 'Čeština',
  hu: 'Magyar', el: 'Ελληνικά', sv: 'Svenska', fa: 'فارسی', hi: 'हिन्दी',
};
const LANG_FLAGS = {
  en: '🇬🇧', he: '🇮🇱', ar: '🇸🇦', es: '🇪🇸', fr: '🇫🇷', de: '🇩🇪', it: '🇮🇹', pt: '🇵🇹',
  ru: '🇷🇺', nl: '🇳🇱', pl: '🇵🇱', tr: '🇹🇷', zh: '🇨🇳', ja: '🇯🇵', ko: '🇰🇷', uk: '🇺🇦',
  ro: '🇷🇴', cs: '🇨🇿', hu: '🇭🇺', el: '🇬🇷', sv: '🇸🇪', fa: '🇮🇷', hi: '🇮🇳',
};
const langLabel = (code) => LANG_NAMES[code] || code.toUpperCase();
const langFlag = (code) => LANG_FLAGS[code] || '🌐';

// Language dropdown. `onDark` for green topbar/sidebar; `align` controls the
// menu edge ('start'|'end'); `full` stretches to container width; `up` opens upward.
function LangToggle({ onDark = false, align = 'start', full = false, up = false, compact = false }) {
  const { lang, setLang } = useLang();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onDoc = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, []);
  // Languages offered are those the reservation's properties declare (set by the
  // app on window.PORTAL_LANGS); always at least English.
  const codes = (typeof window !== 'undefined' && Array.isArray(window.PORTAL_LANGS) && window.PORTAL_LANGS.length) ? window.PORTAL_LANGS : ['en'];
  const flags = LANG_FLAGS;
  const opts = codes.map((c) => [c, langLabel(c)]);
  const current = opts.find((o) => o[0] === lang) || opts[0];
  const baseText = onDark ? 'var(--on-topbar)' : 'var(--fg)';
  const border = onDark ? 'rgba(249,244,234,0.34)' : 'var(--line-strong)';
  const menuBg = onDark ? 'var(--topbar)' : 'var(--surface)';
  const rtl = lang === 'he';
  // Wrapper is dir=ltr, so left/right are physical. The end-aligned topbar toggle
  // sits on the right in English and the left in Hebrew — anchor the menu to the
  // same edge it hugs so it always opens on-screen and readable.
  const side = full ? 'left' : align === 'end' ? rtl ? 'left' : 'right' : rtl ? 'right' : 'left';
  const globe =
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.2" aria-hidden="true">
      <circle cx="8" cy="8" r="6.3" /><path d="M1.7 8h12.6M8 1.7c1.9 1.8 2.9 4 2.9 6.3s-1 4.5-2.9 6.3C6.1 12.5 5.1 10.3 5.1 8S6.1 3.5 8 1.7Z" />
    </svg>;

  return (
    <div ref={ref} dir={rtl ? 'rtl' : 'ltr'} style={{ position: 'relative', display: full ? 'block' : 'inline-block', flexShrink: 0 }}>
      <button onClick={() => setOpen((o) => !o)} aria-haspopup="listbox" aria-expanded={open} aria-label="Language" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: compact ? 5 : 10, width: full ? '100%' : 'auto',
        padding: compact ? '4px 2px' : '8px 12px', border: compact ? 'none' : '1px solid ' + border, background: 'transparent', color: baseText,
        fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em', cursor: 'pointer', lineHeight: 1
      }}>
        {compact ?
        <>
          <span style={{ fontSize: 18, lineHeight: 1 }}>{langFlag(lang)}</span>
          <svg width="8" height="5" viewBox="0 0 12 8" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s ease', opacity: 0.8 }} aria-hidden="true"><path d="M1 1.5l5 5 5-5" /></svg>
        </> :
        <>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>{globe} {current[1]}</span>
          <svg width="10" height="6" viewBox="0 0 12 8" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s ease' }} aria-hidden="true"><path d="M1 1.5l5 5 5-5" /></svg>
        </>
        }
      </button>
      {open &&
      <div role="listbox" style={{
        position: 'absolute', [up ? 'bottom' : 'top']: 'calc(100% + 4px)', [side]: 0,
        minWidth: full ? '100%' : 170, background: menuBg, border: '1px solid ' + border, zIndex: 80,
        boxShadow: '0 10px 28px rgba(0,0,0,0.20)'
      }}>
          {opts.map(([code, label]) => {
          const on = code === lang;
          return (
            <button key={code} role="option" aria-selected={on} onClick={() => {setLang(code);setOpen(false);}} style={{
              display: 'block', width: '100%', textAlign: 'start', whiteSpace: 'nowrap', padding: '9px 14px', border: 'none',
              background: on ? onDark ? 'rgba(249,244,234,0.14)' : 'var(--bg-2)' : 'transparent',
              color: baseText, fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em', cursor: 'pointer'
            }}><span style={{ marginInlineEnd: 8 }}>{langFlag(code)}</span>{label}</button>);

        })}
        </div>
      }
    </div>);

}

Object.assign(window, { STRINGS, tr, applyUiStrings, LangCtx, useLang, useT, LangToggle, isRTL, RTL_LANGS, langLabel, langFlag });