// Compact dual-dropdown for the nav: 🌐 language + 🎨 theme.
// Used by PrimaryNav (storefront) and Admin topbar. Reads LOCALES / THEMES
// from globals (already loaded by data/i18n/themes). On change:
//   - yy.setLang(code)  → cookie + localStorage + PATCH /api/me + reload
//   - yy.setTheme(id)   → cookie + localStorage + PATCH /api/me + applyTheme
// "signedIn" decides whether to fire the PATCH. Falling back to cookie-only
// keeps the component useful on public pages where no user is logged in.

const LangThemeMenu = ({ signedIn = false, compact = false }) => {
  const [open, setOpen] = React.useState(null); // 'lang' | 'theme' | null
  const wrapRef = React.useRef(null);

  const currentLang = (typeof yy !== 'undefined' && yy.getLang) ? yy.getLang() : 'en';
  const currentTheme = (typeof yy !== 'undefined' && yy.getTheme) ? yy.getTheme() : 'zen';
  const locales = (typeof LOCALES !== 'undefined' && Array.isArray(LOCALES)) ? LOCALES : [];
  const themesObj = (typeof THEMES !== 'undefined' && THEMES) ? THEMES : {};
  const themeIds = Object.keys(themesObj);

  React.useEffect(() => {
    const onClick = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(null);
    };
    const onEsc = (e) => { if (e.key === 'Escape') setOpen(null); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onEsc);
    return () => {
      document.removeEventListener('mousedown', onClick);
      document.removeEventListener('keydown', onEsc);
    };
  }, []);

  const pickLang = (code) => {
    setOpen(null);
    if (code === currentLang) return;
    yy.setLang(code); // sets cookie + PATCH + reload
  };
  const pickTheme = (id) => {
    setOpen(null);
    if (id === currentTheme) return;
    yy.setTheme(id);
  };

  const currentLocale = locales.find(l => l.code === currentLang) || locales[0];
  const currentThemeObj = themesObj[currentTheme] || themesObj.zen;

  const btnStyle = {
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: compact ? '5px 8px' : '6px 10px',
    borderRadius: 999, border: '1px solid var(--line)',
    background: 'var(--surface)', color: 'var(--ink-2)',
    fontSize: 12, lineHeight: 1, cursor: 'pointer',
  };
  const panelStyle = {
    position: 'absolute', top: 'calc(100% + 6px)', right: 0,
    // 280 fits the longest pair like "Bahasa Indonesia / Indonesian"
    // without forcing the second column to wrap onto a new line.
    minWidth: 280, maxHeight: 360, overflowY: 'auto',
    background: 'var(--surface)', border: '1px solid var(--line)',
    borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
    padding: 6, zIndex: 100,
    whiteSpace: 'nowrap',
  };
  const itemStyle = (active) => ({
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '8px 10px', borderRadius: 6, fontSize: 13, width: '100%',
    textAlign: 'left', background: active ? 'var(--bg-alt)' : 'transparent',
    color: active ? 'var(--ink)' : 'var(--ink-2)',
    fontWeight: active ? 500 : 400, cursor: 'pointer',
    whiteSpace: 'nowrap',
    gap: 16,
  });

  return (
    <div ref={wrapRef} style={{ position: 'relative', display: 'inline-flex', gap: 6 }}>
      {/* Language */}
      <div style={{ position: 'relative' }}>
        <button
          type="button"
          aria-label="Language"
          onClick={() => setOpen(open === 'lang' ? null : 'lang')}
          style={btnStyle}
        >
          <Icon name="globe" size={14} />
          <span>{currentLocale && currentLocale.native}</span>
        </button>
        {open === 'lang' && (
          <div style={panelStyle}>
            {locales.map(l => (
              <button
                key={l.code}
                type="button"
                onClick={() => pickLang(l.code)}
                style={itemStyle(l.code === currentLang)}
              >
                <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.native}</span>
                <span style={{ fontSize: 11, color: 'var(--ink-4)', whiteSpace: 'nowrap', flexShrink: 0 }}>{l.name}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Theme */}
      <div style={{ position: 'relative' }}>
        <button
          type="button"
          aria-label="Theme"
          onClick={() => setOpen(open === 'theme' ? null : 'theme')}
          style={btnStyle}
        >
          <Icon name="palette" size={14} />
          <span>{currentThemeObj && (() => { const k = 'theme.' + currentThemeObj.id; const v = t(k, currentLang); return v !== k ? v : (currentThemeObj.nameEn || currentThemeObj.id); })()}</span>
        </button>
        {open === 'theme' && (
          <div style={panelStyle}>
            {themeIds.map(id => {
              const th = themesObj[id];
              const accent = th && th.tokens && th.tokens['--accent'];
              return (
                <button
                  key={id}
                  type="button"
                  onClick={() => pickTheme(id)}
                  style={itemStyle(id === currentTheme)}
                >
                  <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                    <span style={{
                      width: 14, height: 14, borderRadius: 4,
                      background: accent || '#888',
                      border: '1px solid rgba(0,0,0,0.08)',
                      flexShrink: 0,
                    }}/>
                    <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{(() => { const k = 'theme.' + id; const v = t(k, currentLang); return v !== k ? v : (th.nameEn || th.id); })()}</span>
                  </span>
                  <span style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'capitalize', whiteSpace: 'nowrap', flexShrink: 0 }}>
                    {th.kind ? (() => { const k = 'theme.kind.' + th.kind; const v = t(k, currentLang); return v !== k ? v : th.kind; })() : ''}
                  </span>
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

window.LangThemeMenu = LangThemeMenu;
