// header.js — V1 (Sub-brand) + V5 (Under-header banner) + Nytt-knapp
// Idempotent. Exporterar window.headerHTML och window.initializeHeader(root?)

(function () {
  const ROLE_KEY = 'gm.role';
  const BANNER_UNTIL_KEY = 'gm.roleBannerDismissedUntil';
  const ROLES = { chef: 'Chef', egen: 'Egen', medarbetare: 'Medarbetare' };
  const VALID = new Set(Object.keys(ROLES));

  const headerHTML = `
<style>
  :root{
    --accent:#2ecc71;
    --dark:#34495e; --muted:#7f8c8d; --bg:#fff; --bg-soft:#f7f9fb; --border:#dce0e3;
    --shadow:0 4px 6px rgba(0,0,0,.08);
    --header-h:64px; --bottom-h:70px;
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
  }
  :root[data-role="chef"]        { --accent:#3b82f6; }
  :root[data-role="egen"]        { --accent:#f59e0b; }
  :root[data-role="medarbetare"] { --accent:#2ecc71; }

  *{box-sizing:border-box} body{margin:0;color:var(--dark);background:var(--bg)}

  .app-header{
    position:sticky;top:0;z-index:999;height:var(--header-h);
    display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:16px;
    padding:0 24px;border-bottom:1px solid var(--border);background:var(--bg);box-shadow:var(--shadow);
  }
  .header-left,.header-center,.header-right{display:flex;align-items:center;gap:16px}
  .brand{display:flex;align-items:center;gap:12px; position:relative; }
  .brand a{display:flex;align-items:center;height:36px}
  .brand img{height:100%;width:auto;display:block}
  .brand-sub{display:inline-flex;align-items:center;gap:6px;font-weight:800;color:var(--accent);cursor:pointer;white-space:nowrap}
  .brand-sub:hover{text-decoration:underline}
  .brand-sub .chev{width:14px;height:14px;display:inline-block}
  .brand-sub .chev path{stroke:currentColor;stroke-width:1.5;fill:none}

  .main-nav{
    justify-self:start;
    margin-left: max(0px, calc((100% - 1100px)/2 + 65px));
  }

  .main-nav ul{margin:0;padding:0;list-style:none;display:flex;gap:8px;background:#ecf0f1;border-radius:8px;padding:4px}
  .main-nav a{display:block;text-decoration:none;color:var(--dark);padding:8px 12px;border-radius:6px;font-weight:600;white-space:nowrap}
  .main-nav a:hover{background:#e6eaee}
  .main-nav a.active{background:#fff;box-shadow:0 2px 4px rgba(0,0,0,.1)}

  .header-right{gap:16px}
  .btn-expert{background:var(--accent);color:#fff;border:0;padding:8px 16px;border-radius:999px;font-weight:700;cursor:pointer}
  .btn-expert:hover{filter:brightness(.96)}
  .icon-wrapper{position:relative}
  .icon-button{background:none;border:0;cursor:pointer;border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;}
  .icon-button:hover{background:#ecf0f1}
  .icon-button svg{width:24px;height:24px;stroke:var(--muted)}
  .avatar{width:40px;height:40px;border-radius:50%;border:2px solid transparent;cursor:pointer}
  .avatar:hover{border-color:var(--accent)}
  .notification-badge{position:absolute;top:4px;right:4px;background:#e74c3c;color:#fff;border-radius:9999px;font-size:10px;padding:2px 6px;line-height:1;border:2px solid #fff;pointer-events:none}
  
  .dropdown-panel{display:none;position:absolute;top:calc(100% + 8px);right:0;width:max-content;min-width:240px;background:#fff;border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow);overflow:hidden; z-index: 1001;}
  .dropdown-panel.show{display:block}
  .dropdown-header{padding:12px 16px;font-weight:700;border-bottom:1px solid var(--border)}
  .dropdown-content{padding:8px;max-height:300px;overflow:auto}
  .dropdown-content a{display:flex;align-items:center;gap:12px;padding:10px 12px;text-decoration:none;color:var(--dark);border-radius:6px; font-size:15px; white-space:nowrap;}
  .dropdown-content a:hover{background:#f4f7f6}
  .dropdown-content .divider{height:1px;background:var(--border);margin:6px 0}
  .notification-item{padding:12px;border-bottom:1px solid var(--border);font-size:.9em}
  .notification-item:last-child{border-bottom:none}

  .btn-create {
    background: var(--bg-soft); border: 1px solid var(--border); border-radius: 6px; padding: 8px 16px;
    font-weight: 600; color: var(--dark); cursor: pointer; display: flex; align-items: center; gap: 8px;
    transition: background-color 0.2s;
  }
  .btn-create:hover { background-color: #e6eaee; }
  .btn-create .caret {
    width: 0; height: 0; border-left: 4px solid transparent;
    border-right: 4px solid transparent; border-top: 4px solid currentColor;
  }
  
  .animated-text-wrapper {
    height: 1.2em;
    line-height: 1.2em;
    overflow: hidden;
    display: inline-block;
    vertical-align: middle;
  }
  #text-ticker {
    transition: transform 0.5s cubic-bezier(0.76, 0, 0.24, 1);
  }
  #text-ticker span {
    display: block;
    height: 1.2em;
  }

  /* V5: Under-header banner */
  .role-banner{
    position:sticky;top:var(--header-h);z-index:998;
    background:var(--bg-soft);border-bottom:1px solid var(--border);
    display:flex;align-items:center;gap:10px;justify-content:center;
    padding:6px 12px;font-size:13px;
  }
  .role-pill{display:inline-flex;align-items:center;gap:8px;background:#fff;border:1px solid var(--border);border-radius:999px;padding:4px 10px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
  .role-dot{width:8px;height:8px;border-radius:999px;background:var(--accent)}
  .role-name{font-weight:800;color:var(--accent)}
  .role-banner a{color:var(--accent);text-decoration:none}
  .role-banner a:hover{text-decoration:underline}
  .banner-close{margin-left:8px;background:none;border:0;cursor:pointer;padding:4px;color:var(--muted)}

  /* Väljare (ALLTID under brand-sub) */
  .role-pop{
    position:absolute; top:calc(100% + 8px); left:0;
    min-width:280px;background:#fff;border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow);
    padding:10px;display:none;z-index:1000;
  }
  .role-pop.show{display:block}
  .role-switch{display:flex;gap:4px;background:#ecf0f1;border-radius:999px;padding:4px}
  .role-tab{flex:1;border:0;background:transparent;cursor:pointer;border-radius:999px;padding:8px 10px;font-weight:700}
  .role-tab[aria-selected="true"]{background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.08)}

  @media (max-width:800px){
    .app-header{padding:0 16px}
    .main-nav{display:none}
    .btn-expert{display:none}
    body{padding-bottom:var(--bottom-h)}
  }

  .bottom-tab-bar{display:none}
  @media (max-width:800px){
    .bottom-tab-bar{
      position:fixed;left:0;right:0;bottom:0;height:var(--bottom-h);background:#fff;border-top:1px solid var(--border);
      display:grid;grid-template-columns:repeat(5,1fr);align-items:center;z-index:1000;box-shadow:0 -2px 6px rgba(0,0,0,.06)
    }
    .bottom-tab-bar a{display:flex;flex-direction:column;align-items:center;justify-content:center;text-decoration:none;color:var(--dark);font-size:12px;gap:4px;height:100%}
    .bottom-tab-bar a.active{font-weight:700;color:var(--accent)}
    .bottom-tab-bar .icon{width:22px;height:22px;stroke:currentColor;fill:none}
  }
</style>

<header class="app-header">
  <div class="header-left">
    <div class="brand" id="brand">
      <a href="../prototyp_hem/hem_3_header-injected.html" aria-label="Gå till startsidan">
        <img src="../prototyp_global/gomonday_logo.png" alt="Go Monday">
      </a>
      <span class="brand-sub" id="brand-sub">
        <span id="brand-sub-text">Medarbetare</span>
        <svg class="chev" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>
      </span>

      <div class="role-pop" id="role-pop" role="dialog" aria-label="Byt version">
        <div class="role-switch" role="tablist" aria-label="Välj version">
          <button class="role-tab" role="tab" data-role="chef" aria-selected="false">Chef</button>
          <button class="role-tab" role="tab" data-role="egen" aria-selected="false">Egen</button>
          <button class="role-tab" role="tab" data-role="medarbetare" aria-selected="false">Medarbetare</button>
        </div>
      </div>
    </div>
  </div>

  <div class="header-center">
    <nav class="main-nav" aria-label="Huvudnavigering">
      <ul>
        <li><a href="../prototyp_hem/hem_3_header-injected.html" data-navkey="hem">Hem</a></li>
        <li><a href="../prototyp_mojligheter/mojligheter_3_insikter.html" data-navkey="insikter">Mina insikter</a></li>
        <li><a href="../prototyp_mojligheter/mojligheter_3_spar.html" data-navkey="spar">Mina spår</a></li>
        <li><a href="../prototyp_skapa/material_11.html" data-navkey="material">Mitt material</a></li>
      </ul>
    </nav>
  </div>

  <div class="header-right">
    <div class="icon-wrapper">
        <button class="btn-create dropdown-toggle" id="create-button">
            <div class="animated-text-wrapper">
                <div id="text-ticker">
                    <span>+ Nytt</span>
                    <span>Nytt CV</span>
                    <span>Nytt brev</span>
                    <span>Nytt spår</span>
                    <span>Ny insikt</span>
                    <span>Nytt CV</span> 
                </div>
            </div>
            <span class="caret"></span>
        </button>
        <div class="dropdown-panel">
            <div class="dropdown-content">
                <a href="#">📄 Skapa CV</a>
                <a href="#">✉️ Skapa brev</a>
                <a href="#">🔗 Skapa LinkedIn-utkast</a>
                <div class="divider"></div>
                <a href="#">🛤️ Lägg till spår</a>
                <a href="#">💡 Lägg till insikt</a>
            </div>
        </div>
    </div>

    <button class="btn-expert">Experthjälp</button>

    <div class="icon-wrapper">
      <button class="icon-button dropdown-toggle" id="notifications-toggle" aria-label="Notifieringar">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
            d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75V9a6 6 0 10-12 0v.75a8.967 8.967 0 01-2.312 6.02c1.733.64 3.56 1.085 5.454 1.31m5.715 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
        </svg>
      </button>
      <div class="notification-badge" id="notification-badge">1</div>
      <div id="notifications-panel" class="dropdown-panel">
        <div class="dropdown-header">Notifieringar</div>
        <div class="dropdown-content">
          <div class="notification-item">Påminnelse: Du har ett samtal bokat imorgon kl. 10.00.</div>
        </div>
      </div>
    </div>

    <div class="icon-wrapper">
      <img src="https://i.pravatar.cc/40" alt="Användaravatar" class="avatar dropdown-toggle" id="avatar-toggle">
      <div id="avatar-menu" class="dropdown-panel">
        <div class="dropdown-header">Min profil</div>
        <div class="dropdown-content">
          <a href="#">Inställningar</a>
          <a href="#">Fakturor</a>
          <a href="#">Fråga oss</a>
          <a href="#" id="menu-change-role">Byt version …</a>
          <div class="divider"></div>
          <a href="#">Logga ut</a>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="role-banner" id="role-banner" hidden>
  <span class="role-pill">
    <span class="role-dot" aria-hidden="true"></span>
    <span>Du använder <strong>Go Monday <span class="role-name" id="banner-role-name">Medarbetare</span></strong></span>
  </span>
  <a href="#" id="banner-change">Byt</a>
  <button class="banner-close" id="banner-close" aria-label="Stäng">✕</button>
</div>

<nav class="bottom-tab-bar">
  <a href="../prototyp_hem/hem_3_header-injected.html" data-navkey="hem">
    <svg class="icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
        d="M2.25 12l8.954-8.955a1.125 1.125 0 011.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75V15a2.25 2.25 0 012.25-2.25h0A2.25 2.25 0 0114.25 15v6h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h7.5" />
    </svg>
    <span>Hem</span>
  </a>
  <a href="../prototyp_mojligheter/mojligheter_2b_insikter.html" data-navkey="insikter">
    <svg class="icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
        d="M6.115 5.19l3.143 4.886c.101.157.13.351.076.533l-1.16 3.867a1.125 1.125 0 001.161.886l.143.048a1.125 1.125 0 00.868.495l.55 1.1" />
    </svg>
    <span>Mina insikter</span>
  </a>
  <a href="../prototyp_mojligheter/mojligheter_2b_spar.html" data-navkey="spar">
    <svg class="icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
        d="M3.375 19.5h17.25M3.375 4.5h17.25M3.375 9.125h17.25M3.375 14.875h17.25M6 9.125h12M6 14.875h7.5" />
    </svg>
    <span>Mina spår</span>
  <a href="../prototyp_skapa/skapa_8.html" data-navkey="skapa">
    <svg class="icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
        d="M3.375 19.5h17.25M3.375 4.5h17.25M3.375 9.125h17.25M3.375 14.875h17.25M6 9.125h12M6 14.875h7.5" />
    </svg>
    <span>Mitt material</span>
  </a>
  <a href="#" data-navkey="expert">
    <svg class="icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
        d="M15.75 6a3 3 0 11-6 0 3 3 0 016 0zM4.5 20.25a8.25 8.25 0 1115 0" />
    </svg>
    <span>Experthjälp</span>
  </a>
</nav>
`;

  let INIT_DONE = false;

function initDropdowns(root) {
    const scope = root || document;
    const allToggles = scope.querySelectorAll('.dropdown-toggle');
    
    function closeAllPopups() {
      scope.querySelectorAll('.dropdown-panel.show, .role-pop.show').forEach(panel => panel.classList.remove('show'));
    }

    allToggles.forEach(toggle => {
      toggle.addEventListener('click', (e) => {
        e.stopPropagation();
        const wrapper = e.target.closest('.icon-wrapper');
        if (!wrapper) return;
        
        const panel = wrapper.querySelector('.dropdown-panel');
        if (!panel) return;

        const isAlreadyShown = panel.classList.contains('show');
        closeAllPopups();
        if (!isAlreadyShown) panel.classList.add('show');
      });
    });

    document.addEventListener('click', (e) => {
      if (!e.target.closest('.dropdown-toggle') && !e.target.closest('.dropdown-panel') && !e.target.closest('.role-pop')  && !e.target.closest('#brand-sub')) {
        closeAllPopups();
      }
    });
  }

  function initActiveNav(root) {
    const scope = root || document;
    const currentPath = location.pathname.toLowerCase();
    scope.querySelectorAll('a[data-navkey]').forEach(a => {
      const key = a.dataset.navkey;
      if (currentPath.includes(`/${key}_`) || currentPath.endsWith(`${key}.html`)) {
        a.classList.add('active');
      }
    });
  }
  
  function initCreateButtonAnimation() {
    const button = document.getElementById('create-button');
    const ticker = document.getElementById('text-ticker');
    if (!button || !ticker) return;

    const items = ticker.querySelectorAll('span');
    if (items.length <= 1) return;

    const itemHeight = items[0].offsetHeight;
    const totalRealItems = items.length - 1;

    let currentIndex = 1;
    let animationInterval = null;

    function goToIndex(index, isAnimated = true) {
        ticker.style.transition = isAnimated ? 'transform 0.5s cubic-bezier(0.76, 0, 0.24, 1)' : 'none';
        ticker.style.transform = `translateY(-${index * itemHeight}px)`;
    }

    function startAnimationLoop() {
        if (animationInterval) clearInterval(animationInterval);

        animationInterval = setInterval(() => {
            goToIndex(currentIndex);

            if (currentIndex >= totalRealItems) {
                setTimeout(() => {
                    goToIndex(1, false);
                    currentIndex = 2;
                }, 500);
            } else {
                currentIndex++;
            }
        }, 2000);
    }

    function stopAndReset() {
        if (animationInterval) clearInterval(animationInterval);
        animationInterval = null;
        goToIndex(0);
    }

    button.addEventListener('mouseenter', stopAndReset);
    button.addEventListener('click', stopAndReset);

    button.addEventListener('mouseleave', () => {
        const menu = button.closest('.icon-wrapper').querySelector('.dropdown-panel');
        if (!menu || !menu.classList.contains('show')) {
           setTimeout(startAnimationLoop, 750);
        }
    });

    document.addEventListener('click', () => {
        const menu = button.closest('.icon-wrapper').querySelector('.dropdown-panel');
         if ((!menu || !menu.classList.contains('show')) && !animationInterval) {
            setTimeout(startAnimationLoop, 750);
        }
    });

    setTimeout(startAnimationLoop, 1500);
  }

  function getRole() {
    const v = localStorage.getItem(ROLE_KEY);
    return VALID.has(v) ? v : 'medarbetare';
  }
  function applyRole(r, root) {
    document.documentElement.setAttribute('data-role', r);
    const scope = root || document;
    const brandSubText = scope.getElementById('brand-sub-text');
    const bannerRoleName = scope.getElementById('banner-role-name');
    if (brandSubText) brandSubText.textContent = ROLES[r];
    if (bannerRoleName) bannerRoleName.textContent = ROLES[r];
    scope.querySelectorAll('.role-tab').forEach(btn => {
      btn.setAttribute('aria-selected', String(btn.dataset.role === r));
    });
  }
    function setRole(r, root) {
      if (!VALID.has(r)) return;
      localStorage.setItem(ROLE_KEY, r);
      
      window.dispatchEvent(new CustomEvent('roleChanged'));
      
      applyRole(r, root);
      maybeShowBanner(true, root);
    }

  function addDays(date, n) { const d = new Date(date); d.setDate(d.getDate() + n); return d; }
  function shouldShowBanner(force) {
    if (force) return true;
    const until = localStorage.getItem(BANNER_UNTIL_KEY);
    if (!until) return true;
    return new Date(until) <= new Date();
  }
  function maybeShowBanner(force, root) {
    const banner = (root || document).getElementById('role-banner');
    if (!banner) return;
    banner.hidden = !shouldShowBanner(force);
  }

  function initRoleUI(root) {
    const scope = root || document;
    const brandSub = scope.getElementById('brand-sub');
    const rolePop  = scope.getElementById('role-pop');
    const banner   = scope.getElementById('role-banner');
    const bannerChange = scope.getElementById('banner-change');
    const bannerClose  = scope.getElementById('banner-close');
    const menuChangeRole = scope.getElementById('menu-change-role');

    if (bannerClose) bannerClose.setAttribute('type', 'button');

    applyRole(getRole(), root);
    maybeShowBanner(false, root);

    function openPop() { rolePop && rolePop.classList.add('show'); }
    function closePop(e) {
        if (!e || (!e.target.closest('#role-pop') && !e.target.closest('#brand-sub'))) {
          rolePop && rolePop.classList.remove('show');
        }
    }

    brandSub && brandSub.addEventListener('click', (e) => {
      e.stopPropagation();
      rolePop && rolePop.classList.toggle('show');
    });
    bannerChange && bannerChange.addEventListener('click', (e) => {
      e.preventDefault(); e.stopPropagation();
      openPop();
    });
    menuChangeRole && menuChangeRole.addEventListener('click', (e) => {
      e.preventDefault(); e.stopPropagation();
      openPop();
    });

    scope.querySelectorAll('.role-tab').forEach(btn => {
      btn.addEventListener('click', () => { setRole(btn.dataset.role, root); closePop(); });
    });

    if (banner) {
      banner.addEventListener('click', (e) => {
        const closeClicked = e.target.closest('#banner-close');
        if (!closeClicked) return;
        e.preventDefault(); e.stopPropagation();
        const next = addDays(new Date(), 7).toISOString();
        localStorage.setItem(BANNER_UNTIL_KEY, next);
        banner.hidden = true;
        banner.style.display = 'none';
      });
    }
  }

  window.headerHTML = headerHTML;

  window.initializeHeader = function initializeHeader(root) {
    if (initializeHeader._done) return;
    initializeHeader._done = true;
    initDropdowns(root);
    initActiveNav(root);
    initRoleUI(root);
    initCreateButtonAnimation();
  };
})();