// AppShell.jsx — Top navigation + app shell wrapper
const { useState: useShellState, useEffect: useShellEffect } = React;

// ── Global Work / Personal filter ──
// Single source of truth shared across Dashboard, Tasks and the topnav toggle.
// Persisted to localStorage; cross-component sync via custom event.
const WP_FILTER_KEY = 'el-wp-filter';
const WP_FILTER_EVENT = 'el-wp-filter-change';

function getWpFilter() {
  const v = localStorage.getItem(WP_FILTER_KEY);
  if (v === 'Work' || v === 'Personal') return v;
  // Migrate legacy 'el-dash-filter' value if present
  const legacy = localStorage.getItem('el-dash-filter');
  if (legacy === 'Work' || legacy === 'Personal') return legacy;
  return 'Personal';
}

function useWpFilter() {
  const [filter, setFilter] = React.useState(() => getWpFilter());
  React.useEffect(() => {
    const handler = (e) => {
      const v = (e && e.detail) || getWpFilter();
      if (v === 'Work' || v === 'Personal') setFilter(v);
    };
    window.addEventListener(WP_FILTER_EVENT, handler);
    return () => window.removeEventListener(WP_FILTER_EVENT, handler);
  }, []);
  function update(next) {
    if (next !== 'Work' && next !== 'Personal') return;
    localStorage.setItem(WP_FILTER_KEY, next);
    setFilter(next);
    window.dispatchEvent(new CustomEvent(WP_FILTER_EVENT, { detail: next }));
  }
  return [filter, update];
}

function WorkPersonalToggle({ size = 'md' }) {
  const [filter, setFilter] = useWpFilter();
  const [lang, setLang] = React.useState(() => localStorage.getItem('el-lang') || 'no');
  React.useEffect(() => {
    const handler = e => setLang(e.detail || localStorage.getItem('el-lang') || 'no');
    window.addEventListener('el-lang-change', handler);
    return () => window.removeEventListener('el-lang-change', handler);
  }, []);
  const labels = lang === 'en'
    ? { Work: 'Work', Personal: 'Personal' }
    : { Work: 'Jobb', Personal: 'Privat' };
  const idx = filter === 'Work' ? 0 : 1;
  return (
    <div className={`el-wp-pill el-wp-${size}`} role="group" aria-label="Work / Personal">
      <span className="el-wp-thumb" style={{ transform: `translateX(${idx * 100}%)` }} />
      <button
        type="button"
        className={`el-wpb${filter === 'Work' ? ' active' : ''}`}
        onClick={() => setFilter('Work')}
        aria-pressed={filter === 'Work'}
      >
        <i className="ti ti-briefcase"></i>
        <span>{labels.Work}</span>
      </button>
      <button
        type="button"
        className={`el-wpb${filter === 'Personal' ? ' active' : ''}`}
        onClick={() => setFilter('Personal')}
        aria-pressed={filter === 'Personal'}
      >
        <i className="ti ti-home"></i>
        <span>{labels.Personal}</span>
      </button>
    </div>
  );
}

const NAV_ROUTES = [
  { key: 'dashboard', hash: '#/dashboard', label: 'Hjem', en: 'Home' },
  { key: 'tasks',     hash: '#/tasks',     label: 'Oppgaver', en: 'Tasks' },
  { key: 'projects',  hash: '#/projects',  label: 'Prosjekter', en: 'Projects' },
  { key: 'journal',   hash: '#/journal',   label: 'Journal', en: 'Journal' },
  { key: 'routines',  hash: '#/routines',  label: 'Rutiner', en: 'Routines' },
  { key: 'goals',     hash: '#/goals',     label: 'Mål', en: 'Goals' },
  { key: 'balance',   hash: '#/balance',   label: 'Balanse', en: 'Balance' },
  { key: 'notes',     hash: '#/notes',     label: 'Notater', en: 'Notes' },
  { key: 'prompts',   hash: '#/prompts',   label: 'Prompts', en: 'Prompts' },
];

const ROUTE_LABELS = {
  dashboard: 'Hjem',
  tasks: 'Oppgaver',
  projects: 'Prosjekter',
  journal: 'Journal',
  routines: 'Rutiner',
  goals: 'Mål',
  balance: 'Balanse',
  notes: 'Notater',
  prompts: 'Prompts',
};

function AppShell({ currentRoute, onNavigate, uiMode, onToggleMode, children }) {
  const [lang, setLang] = useShellState(
    () => localStorage.getItem('el-lang') || 'no'
  );

  useShellEffect(() => {
    const handler = e => setLang(e.detail || localStorage.getItem('el-lang') || 'no');
    window.addEventListener('el-lang-change', handler);
    return () => window.removeEventListener('el-lang-change', handler);
  }, []);

  function getLabel(route) {
    if (lang === 'en') {
      const r = NAV_ROUTES.find(n => n.key === route);
      return r ? r.en : route;
    }
    return ROUTE_LABELS[route] || route;
  }

  function handleNavClick(e, hash, key) {
    e.preventDefault();
    onNavigate(key);
    window.location.hash = hash;
  }

  function handleLogoClick(e) {
    e.preventDefault();
    onNavigate('dashboard');
    window.location.hash = '#/dashboard';
  }

  return (
    <div className="v2-app">
      <nav className="el-topnav">
        <div className="el-topnav-in">
          {/* Logo */}
          <button className="el-nav-logo" onClick={handleLogoClick} title="EasyLife Home">
            <div className="logo-ring">
              <div className="logo-chk">
                <svg viewBox="0 0 14 14" fill="none">
                  <path d="M3 7.5l2.5 2.5L11 4.5" stroke="#00e676" strokeWidth="2.2"
                    strokeLinecap="round" strokeLinejoin="round"
                    style={{ filter: 'drop-shadow(0 0 3px rgba(0,230,118,.5))' }} />
                </svg>
              </div>
            </div>
            <span className="el-nav-brand">EasyLife</span>
          </button>

          <div className="el-nav-divider"></div>

          {/* Active page context */}
          <span className="el-nav-ctx">{getLabel(currentRoute)}</span>

          {/* Center nav links */}
          <div className="el-nav-links">
            {NAV_ROUTES.map(route => (
              <a
                key={route.key}
                href={route.hash}
                className={`el-nav-link${currentRoute === route.key ? ' active' : ''}`}
                onClick={e => handleNavClick(e, route.hash, route.key)}
              >
                {lang === 'en' ? route.en : route.label}
              </a>
            ))}
          </div>

          {/* Right side */}
          <div className="el-nav-right">
            {/* Global Work / Personal filter — replaces the old Easy/Pro pill here.
                Easy/Pro lives inside the avatar menu. */}
            <WorkPersonalToggle />

            {/* Avatar menu (contains Easy/Pro toggle) */}
            <AvatarMenu currentRoute={currentRoute} uiMode={uiMode} onToggleMode={onToggleMode} />
          </div>
        </div>
      </nav>

      <main className="v2-main">
        {children}
      </main>
    </div>
  );
}
