// Floating theme toggle — Cinema (current dark) vs Manga (paper ink).
// Always visible top-center. Persists choice to localStorage.

const BNS_THEME_KEY = 'bns-theme';

function loadTheme() {
  try { return localStorage.getItem(BNS_THEME_KEY) || 'cinema'; } catch { return 'cinema'; }
}
function saveTheme(t) {
  try { localStorage.setItem(BNS_THEME_KEY, t); } catch {}
}

function applyTheme(t) {
  document.body.classList.remove('theme-cinema', 'theme-manga');
  document.body.classList.add(`theme-${t}`);
  try {
    window.dispatchEvent(new CustomEvent('bns:themechange', { detail: t }));
  } catch {}
}

// Apply the saved theme before React mounts so reloads preserve Cinema/Manga
// and the page avoids a visible theme flash.
applyTheme(loadTheme());

window.bnsLoadTheme = loadTheme;

function ThemeToggle({ inline = false }) {
  const [theme, setTheme] = React.useState(loadTheme());

  // Keep in sync if the theme changes elsewhere (e.g. another toggle instance)
  React.useEffect(() => {
    const onChange = (e) => setTheme(e.detail || 'cinema');
    window.addEventListener('bns:themechange', onChange);
    return () => window.removeEventListener('bns:themechange', onChange);
  }, []);

  const change = (t) => {
    setTheme(t);
    saveTheme(t);
    applyTheme(t);
    window.bnsTrackEvent?.('theme_switch', { theme: t });
  };

  return (
    <div className={`tt-wrap ${inline ? 'tt-wrap--inline' : ''}`} role="radiogroup" aria-label="Theme">
      <div className="tt">
        <div className={`tt-slider ${theme === 'manga' ? 'is-right' : ''}`}/>
        <button
          className={`tt-btn ${theme === 'cinema' ? 'is-active' : ''}`}
          onClick={() => change('cinema')}
          aria-checked={theme === 'cinema'} role="radio"
        >
          {/* clapper-board icon */}
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 8 L21 8 L20 19 a2 2 0 0 1 -2 2 H6 a2 2 0 0 1 -2 -2 Z"/>
            <path d="M3 8 L5 4 L9 4 L7 8 M9 4 L13 4 L11 8 L7 8 M13 4 L17 4 L15 8 L11 8 M17 4 L21 4 L19 8 L15 8"/>
          </svg>
          <span>Cinema</span>
        </button>
        <button
          className={`tt-btn ${theme === 'manga' ? 'is-active' : ''}`}
          onClick={() => change('manga')}
          aria-checked={theme === 'manga'} role="radio"
        >
          {/* manga / ink book icon */}
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 5 a2 2 0 0 1 2 -2 h6 v17 h-6 a2 2 0 0 1 -2 -2 z"/>
            <path d="M20 5 a2 2 0 0 0 -2 -2 h-6 v17 h6 a2 2 0 0 0 2 -2 z"/>
            <path d="M7 7 h2 M7 10 h2 M15 7 h2 M15 10 h2"/>
          </svg>
          <span>Manga</span>
        </button>
      </div>
    </div>
  );
}

const __ttStyles = `
  .tt-wrap{
    position: fixed; bottom: 22px; right: 22px;
    z-index: 200;
    pointer-events: none;
  }
  /* Inline (docked in a header) — flows normally instead of fixed to a corner */
  .tt-wrap--inline{
    position: static; bottom: auto; right: auto;
    z-index: auto; pointer-events: auto;
  }
  .tt{
    pointer-events: auto;
    position: relative;
    display: flex;
    padding: 4px;
    background: rgba(10, 14, 46, .65);
    border: 1px solid rgba(244,241,232,.14);
    border-radius: 99px;
    backdrop-filter: blur(14px) saturate(140%);
    -webkit-backdrop-filter: blur(14px) saturate(140%);
    box-shadow: 0 8px 24px rgba(0,0,0,.4);
  }
  .tt-slider{
    position:absolute; top:4px; bottom:4px; left:4px;
    width: calc(50% - 4px);
    background: var(--c-about);
    border-radius: 99px;
    transition: transform .28s cubic-bezier(.3,1.4,.3,1);
    box-shadow: 0 2px 0 rgba(0,0,0,.2), 0 0 18px rgba(79,142,255,.4);
  }
  .tt-slider.is-right{ transform: translateX(100%); }
  .tt-btn{
    position: relative; z-index:1;
    display:flex; align-items:center; gap:6px;
    padding: 7px 12px; border-radius: 99px;
    font: 600 11px/1 var(--body); letter-spacing:.06em;
    color: rgba(244,241,232,.55);
    transition: color .2s ease;
  }
  .tt-btn:hover{ color: var(--paper); }
  .tt-btn.is-active{ color: #04061a; font-weight: 700; }

  /* Manga theme: B&W adaptation */
  body.theme-manga .tt{
    background: #faf6ec;
    border-color: #0a0a0a;
    box-shadow: 4px 4px 0 #0a0a0a;
  }
  body.theme-manga .tt-slider{
    background: #0a0a0a;
    box-shadow: 2px 2px 0 transparent;
  }
  body.theme-manga .tt-btn{ color: #0a0a0a; opacity:.55; }
  body.theme-manga .tt-btn.is-active{ color: #faf6ec; opacity: 1; }

  /* Smaller still on mobile */
  @media (max-width: 720px){
    .tt-wrap{ bottom: 14px; right: 14px; }
    .tt-btn{ padding: 7px 10px; font-size: 10px; }
    .tt-btn span{ display:none; }
  }
`;
(function(){
  if (!document.getElementById('bns-tt-styles')){
    const s = document.createElement('style');
    s.id = 'bns-tt-styles'; s.textContent = __ttStyles;
    document.head.appendChild(s);
  }
})();

window.ThemeToggle = ThemeToggle;
