/* global React, DCIcons */
const { IconSearch, IconUser, IconCart, IconPin, IconPhone, IconArrow, IconChev } = DCIcons;

function ThemeToggle() {
  const [theme, setTheme] = React.useState(() => {
    if (typeof document === "undefined") return "light";
    return document.documentElement.dataset.theme || localStorage.getItem("dc-theme") || "light";
  });
  React.useEffect(() => {
    const onChange = () => setTheme(document.documentElement.dataset.theme || "light");
    const obs = new MutationObserver(onChange);
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, []);
  const flip = () => {
    const next = theme === "dark" ? "light" : "dark";
    document.documentElement.dataset.theme = next;
    try { localStorage.setItem("dc-theme", next); } catch(e) {}
    // Notify Tweaks panel if it's listening
    window.parent?.postMessage?.({type:"__edit_mode_set_keys", edits:{theme: next}}, "*");
    setTheme(next);
  };
  const isDark = theme === "dark";
  return (
    <button className="topbar-theme" onClick={flip}
      aria-label={isDark ? "Byt till ljust läge" : "Byt till mörkt läge"}
      title={isDark ? "Ljust läge" : "Mörkt läge"}>
      <span className="ic" aria-hidden="true">
        {isDark ? (
          // moon
          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7Z"/>
          </svg>
        ) : (
          // sun
          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="8" cy="8" r="3"/>
            <path d="M8 1.5v1.5M8 13v1.5M14.5 8H13M3 8H1.5M12.5 3.5l-1 1M4.5 11.5l-1 1M12.5 12.5l-1-1M4.5 4.5l-1-1"/>
          </svg>
        )}
      </span>
      <span className="lbl">{isDark ? "Ljust" : "Mörkt"}</span>
    </button>
  );
}

function LangSwitch() {
  const LANGS = [
    { code: "sv", label: "Svenska", flag: (
      <svg viewBox="0 0 16 10" aria-hidden="true">
        <rect width="16" height="10" fill="#006aa7"/>
        <rect x="5" width="2" height="10" fill="#fecc00"/>
        <rect y="4" width="16" height="2" fill="#fecc00"/>
      </svg>
    )},
    { code: "no", label: "Norsk", flag: (
      <svg viewBox="0 0 16 12" aria-hidden="true">
        <rect width="16" height="12" fill="#ef2b2d"/>
        <rect x="5" width="2" height="12" fill="#fff"/>
        <rect y="5" width="16" height="2" fill="#fff"/>
        <rect x="5.5" width="1" height="12" fill="#002868"/>
        <rect y="5.5" width="16" height="1" fill="#002868"/>
      </svg>
    )},
    { code: "da", label: "Dansk", flag: (
      <svg viewBox="0 0 16 12" aria-hidden="true">
        <rect width="16" height="12" fill="#c8102e"/>
        <rect x="5" width="2" height="12" fill="#fff"/>
        <rect y="5" width="16" height="2" fill="#fff"/>
      </svg>
    )},
    { code: "en", label: "English", flag: (
      <svg viewBox="0 0 60 30" aria-hidden="true">
        <clipPath id="lg-uk-c"><path d="M0,0 v30 h60 v-30 z"/></clipPath>
        <clipPath id="lg-uk-c2"><path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z"/></clipPath>
        <g clipPath="url(#lg-uk-c)">
          <path d="M0,0 v30 h60 v-30 z" fill="#012169"/>
          <path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" strokeWidth="6"/>
          <path d="M0,0 L60,30 M60,0 L0,30" clipPath="url(#lg-uk-c2)" stroke="#C8102E" strokeWidth="4"/>
          <path d="M30,0 v30 M0,15 h60" stroke="#fff" strokeWidth="10"/>
          <path d="M30,0 v30 M0,15 h60" stroke="#C8102E" strokeWidth="6"/>
        </g>
      </svg>
    )},
  ];
  const [code, setCode] = React.useState(() => {
    if (typeof localStorage === "undefined") return "sv";
    return localStorage.getItem("dc-lang") || "sv";
  });
  const [open, setOpen] = React.useState(false);
  const rootRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (rootRef.current && !rootRef.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); };
  }, [open]);
  const pick = (c) => { setCode(c); try { localStorage.setItem("dc-lang", c); } catch(e){} setOpen(false); };
  const active = LANGS.find(l => l.code === code) || LANGS[0];
  const others = LANGS.filter(l => l.code !== code);
  return (
    <div className={"topbar-lang-wrap" + (open ? " open" : "")} ref={rootRef}
         onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <button type="button" className="topbar-lang-btn" aria-label={"Språk: " + active.label}
              aria-haspopup="true" aria-expanded={open}
              onClick={() => setOpen(o => !o)}>
        <span className="flag">{active.flag}</span>
      </button>
      <div className="topbar-lang-menu" role="menu">
        {others.map(l => (
          <button key={l.code} type="button" className="topbar-lang-opt" role="menuitem"
                  title={l.label} aria-label={l.label}
                  onClick={() => pick(l.code)}>
            <span className="flag">{l.flag}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function TopBar() {
  return (
    <div className="topbar">
      <div className="container topbar-inner">
        <div className="topbar-left">
          <span className="topbar-pill"><span className="dot"/> Snabb leverans · 14 dagars öppet köp</span>
        </div>
        <div className="topbar-right">
          <a className="topbar-info" href="kontakta-oss.html"><IconPin size={14}/> Muskötgatan 2, Helsingborg</a>
          <a className="topbar-info" href="tel:0421608839"><IconPhone size={14}/> 042-16 08 39</a>
          <LangSwitch/>
          <span className="topbar-divider" aria-hidden="true"/>
          <ThemeToggle/>
        </div>
      </div>
    </div>
  );
}

function BrandD() {
  // Bold "D" with a tire-tread pattern shattering off to the left.
  return (
    <span className="brand-d" aria-hidden="true">
      <svg viewBox="0 0 116 100" preserveAspectRatio="xMidYMid meet">
        <defs>
          <clipPath id="brandDClip">
            {/* The D silhouette */}
            <path d="M40 6 H70 C92 6 108 24 108 50 C108 76 92 94 70 94 H40 Z"/>
          </clipPath>
        </defs>
        {/* Solid right side of the D (the bowl) */}
        <path className="brand-d-body" d="M40 6 H70 C92 6 108 24 108 50 C108 76 92 94 70 94 H40 Z"/>
        {/* The white counter (hole) of the D */}
        <path className="brand-d-hole" d="M56 24 H68 C82 24 90 34 90 50 C90 66 82 76 68 76 H56 Z"/>
        {/* Tread rows clipped to the left stem + extending left as shatter */}
        <g className="brand-d-tread">
          {Array.from({ length: 7 }).map((_, r) => {
            const y = 9 + r * 12.4;
            return (
              <g key={r} className="brand-d-row" style={{ "--r": r }}>
                {/* solid tread blocks (within stem) */}
                {Array.from({ length: 4 }).map((_, i) => (
                  <rect key={"b" + i} x={20 + i * 7} y={y} width={5.2} height={8} rx="1"/>
                ))}
                {/* shatter fragments fanning left */}
                {Array.from({ length: 5 }).map((_, i) => {
                  const fx = 16 - i * 3.6;
                  const fy = y + ((r + i) % 3) - 1;
                  const sz = 3.4 - i * 0.5;
                  return <rect key={"f" + i} x={fx} y={fy} width={Math.max(1.2, sz)} height={Math.max(1.4, sz + 1)} rx=".6" opacity={0.85 - i * 0.15}/>;
                })}
              </g>
            );
          })}
        </g>
      </svg>
    </span>
  );
}

function Brand() {
  return (
    <a href="index.html" className="brand" aria-label="Däckcentrum">
      <span className="brand-logo">
        <span className="d1">D</span>äckcentrum
      </span>
    </a>
  );
}

const NAV = [
  { label: "Däck", href: "dack.html" },
  { label: "Fälg", href: "falg.html" },
  { label: "Kompletta hjul", href: "kompletta-hjul.html" },
  { label: "Däckhotell", href: "dackhotell.html" },
  { label: "Hjulinställning", href: "tjanst-hjulinstallning.html" },
  { label: "Fälgrenovering", href: "tjanst-falgrenovering.html" },
  { label: "DC Wheels", href: "dc-wheels.html" }
];

function MobileMenu({ open, onClose, activeIndex }) {
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  return (
    <>
      <div className={"mobile-menu-scrim" + (open ? " on" : "")} onClick={onClose} aria-hidden="true"/>
      <aside className={"mobile-menu" + (open ? " on" : "")} aria-hidden={!open} aria-label="Huvudmeny">
        <div className="mm-head">
          <a href="index.html" className="brand" aria-label="Däckcentrum">
            <span className="brand-logo"><span className="d1">D</span>äckcentrum</span>
          </a>
          <button className="mm-close" onClick={onClose} aria-label="Stäng meny">
            <svg viewBox="0 0 20 20" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <path d="M5 5l10 10M15 5L5 15"/>
            </svg>
          </button>
        </div>
        <nav className="mm-nav">
          {NAV.map((item, i) => (
            <a key={item.label} href={item.href || "#"} className={"mm-link" + (i === activeIndex ? " active" : "")}>
              <span>{item.label}</span>
              <span className="mm-arrow"><IconArrow size={16}/></span>
            </a>
          ))}
        </nav>
        <div className="mm-divider"/>
        <div className="mm-secondary">
          <a href="om-oss.html">Om oss</a>
          <a href="kontakta-oss.html">Kontakt</a>
          <a href="faq.html">FAQ</a>
          <a href="aterforsaljare.html">Återförsäljare</a>
          <a href="lediga-jobb.html">Jobb</a>
          <a href="mitt-konto.html">Mitt konto</a>
        </div>
        <div className="mm-foot">
          <a className="mm-info" href="tel:0421608839"><IconPhone size={14}/> 042-16 08 39</a>
          <a className="mm-info" href="kontakta-oss.html"><IconPin size={14}/> Muskötgatan 2, Helsingborg</a>
          <a className="book-btn mm-book" href="https://booking.eontyre.com/511" target="_blank" rel="noopener" data-no-loader="true">Boka tid</a>
        </div>
      </aside>
    </>
  );
}

function Header({ activeIndex }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  // Auto-detect from URL when not explicitly set
  const computedActive = React.useMemo(() => {
    if (typeof activeIndex === "number") return activeIndex;
    try {
      const path = (window.location.pathname.split("/").pop() || "").toLowerCase();
      if (!path || path === "index.html") return -1; // home → no nav item highlighted
      const i = NAV.findIndex(n => (n.href || "").toLowerCase() === path);
      return i;
    } catch { return -1; }
  }, [activeIndex]);

  return (
    <header className="header">
      <div className="container header-inner">
        <button className="hamburger-btn" aria-label="Öppna meny" onClick={() => setMenuOpen(true)}>
          <span/><span/><span/>
        </button>
        <Brand/>
        <nav className="nav">
          {NAV.map((item, i) => (
            <div key={item.label} className={"nav-item" + (i === computedActive ? " active" : "")}
                 tabIndex={0} role="button">
              <a href={item.href || "#"}>{item.label}</a>
              {item.mega && <span className="caret" aria-hidden="true"><svg viewBox="0 0 8 8" width="8" height="8"><path d="M1 2.5L4 5.5L7 2.5" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg></span>}
              {item.mega && (
                <div className="nav-mega">
                  {item.mega.map(m => (
                    <a key={m.name} href={m.href || "#"}>
                      <span>{m.name}</span>
                      {m.tag && <span className="tag">{m.tag}</span>}
                    </a>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>
        <div className="header-right">
          <button className="icon-btn" aria-label="Sök"
            onClick={() => window.dispatchEvent(new CustomEvent("dc:search:open"))}><IconSearch/></button>
          <button className="icon-btn" aria-label="Mitt konto"
            onClick={() => {
              if (window.DCAuth?.isLoggedIn?.()) {
                window.location.href = "mitt-konto.html";
              } else {
                window.dispatchEvent(new CustomEvent("dc:auth:open", { detail: { mode: "login" } }));
              }
            }}><IconUser/></button>
          {window.DCCartUI ? <window.DCCartUI.CartPillButton/> : (
            <a href="checkout.html" className="cart-pill" aria-label="Varukorg">
              <IconCart size={18}/>
              <span className="count zero">0</span>
            </a>
          )}
          <a href="https://booking.eontyre.com/511" target="_blank" rel="noopener" data-no-loader="true" className="book-btn">Boka tid</a>
        </div>
      </div>
      <MobileMenu open={menuOpen} onClose={() => setMenuOpen(false)} activeIndex={computedActive}/>
    </header>
  );
}

window.DCHeader = Header;
window.DCTopBar = TopBar;
