// Nav, footer, cart drawer, tweaks panel

const Nav = ({ route, setRoute, cart, setCartOpen, theme, setSearchOpen }) => {
  const items = [
    { id: "home", label: "Hjem" },
    { id: "butikk", label: "Butikk" },
    { id: "sjømatkasse", label: "Sjømatkasse" },
    { id: "abonnement", label: "Abonnement" },
    { id: "catering", label: "Catering" },
    { id: "om", label: "Om oss" },
    { id: "levering", label: "Levering" },
    { id: "kontakt", label: "Kontakt" },
  ];
  const count = cart.reduce((s, x) => s + x.qty, 0);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const goRoute = (id) => { setRoute(id); setMobileOpen(false); };
  // Lukk meny ved route-bytte
  React.useEffect(() => { setMobileOpen(false); }, [route]);
  return (
    <header className="nw-nav">
      <div className="nw-wrap nw-nav-inner">
        <button className="nw-nav-logo" onClick={() => goRoute("home")} aria-label="Havøyet hjem">
          <Logotype variant={theme === "light" ? "black" : "white"} height={32} />
        </button>
        <nav className={"nw-nav-links" + (mobileOpen ? " open" : "")}>
          <ul>
            {items.map(it => (
              <li key={it.id}>
                <button
                  className={route === it.id ? "active" : ""}
                  onClick={() => goRoute(it.id)}
                >{it.label}</button>
              </li>
            ))}
          </ul>
        </nav>
        <div className="nw-nav-actions">
          <button className="nw-nav-btn" aria-label="Søk" onClick={() => setSearchOpen && setSearchOpen(true)} title="Søk produkter"><Search /></button>
          <button className="nw-nav-btn" aria-label="Min konto" onClick={() => goRoute("konto")} title="Min konto">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
          </button>
          <button className="nw-cart-btn" onClick={() => setCartOpen(true)} aria-label="Handlekurv">
            <Bag size={18} />
            {count > 0 && <span className="nw-cart-badge">{count}</span>}
          </button>
          <button className="nw-nav-burger" aria-label={mobileOpen ? "Lukk meny" : "Åpne meny"} aria-expanded={mobileOpen} onClick={() => setMobileOpen(o => !o)}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              {mobileOpen
                ? <><line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/></>
                : <><line x1="4" y1="7"  x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/></>
              }
            </svg>
          </button>
        </div>
      </div>
    </header>
  );
};

const Footer = ({ setRoute, goShopCat }) => {
  const goCat = (cat) => () => {
    if (typeof goShopCat === "function") goShopCat(cat);
    else { window.__shopInitCat = cat; setRoute("butikk"); }
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const goRoute = (r) => () => { setRoute(r); window.scrollTo({ top: 0, behavior: "smooth" }); };
  const goFAQ = () => {
    setRoute("kontakt");
    setTimeout(() => {
      const el = document.getElementById("faq-section");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      else window.scrollTo({ top: 0, behavior: "smooth" });
    }, 80);
  };
  return (
    <footer className="nw-footer">
      <div className="nw-wrap">
        <div className="nw-footer-top">
          <div className="nw-footer-brand">
            <img src="assets/logo-brand.png" alt="Havøyet" style={{ maxWidth: 200, width: "100%", height: "auto", display: "block" }} />
            <p>Bare fersk sjømat. Hjemlevert i Bergen, alle hverdager og lørdag. Mest villfanget fra Nord-Norge.</p>
            <div style={{ display: "flex", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
              <a className="nw-btn nw-btn-ghost nw-btn-sm" style={{ padding: "8px 14px" }} href="https://www.instagram.com/havoyet/" target="_blank" rel="noopener noreferrer">Instagram</a>
              <a className="nw-btn nw-btn-ghost nw-btn-sm" style={{ padding: "8px 14px" }} href="https://www.tiktok.com/@havoyet" target="_blank" rel="noopener noreferrer">TikTok</a>
              <a className="nw-btn nw-btn-ghost nw-btn-sm" style={{ padding: "8px 14px" }} href="https://www.facebook.com/people/Hav%C3%B8yet/61572845072887/" target="_blank" rel="noopener noreferrer">Facebook</a>
            </div>
          </div>
          <div>
            <h5>Butikk</h5>
            <ul>
              <li><button onClick={goCat("Alle")}>Alle produkter</button></li>
              <li><button onClick={goCat("Rød fisk")}>Rød fisk</button></li>
              <li><button onClick={goCat("Hvit fisk")}>Hvit fisk</button></li>
              <li><button onClick={goCat("Skalldyr og skjell")}>Skalldyr</button></li>
              <li><button onClick={goRoute("sjømatkasse")}>Sjømatkasse</button></li>
            </ul>
          </div>
          <div>
            <h5>Havøyet</h5>
            <ul>
              <li><button onClick={goRoute("om")}>Om Erik & oss</button></li>
              <li><button onClick={goRoute("catering")}>Catering</button></li>
              <li><button onClick={goRoute("levering")}>Levering</button></li>
              <li><button onClick={goRoute("kontakt")}>Kontakt</button></li>
            </ul>
          </div>
          <div>
            <h5>Hjelp</h5>
            <ul>
              <li><button onClick={goFAQ}>FAQ</button></li>
              <li><button onClick={goRoute("personvern")}>Personvern</button></li>
              <li><button onClick={goRoute("vilkår")}>Vilkår</button></li>
              <li><span style={{ color: "var(--hv-fg-3)", cursor: "default" }}>Org.nr. 919 283 441</span></li>
            </ul>
          </div>
        </div>
        <div className="nw-footer-bot">
          <span>© 2026 Havøyet AS · Bergen</span>
          <span>bare fersk sjømat <span style={{ color: "var(--hv-teal)", fontStyle: "italic" }}>~</span></span>
        </div>
      </div>
    </footer>
  );
};

const CartDrawer = ({ open, onClose, cart, setCart, goCheckout }) => {
  const total = cart.reduce((s, x) => s + x.price * x.qty, 0);
  const fee = cart.length === 0 ? 0 : total >= 1100 ? 0 : total >= 700 ? 59 : 199;
  const fraktMsg = cart.length === 0 ? null
    : total >= 1100 ? null
    : total >= 700 ? `${1100 - total} kr unna gratis frakt`
    : `${700 - total} kr unna redusert frakt (59 kr)`;
  const fraktProsent = cart.length === 0 ? 0 : Math.min(total / 1100 * 100, 100);
  const setQty = (slug, q) => {
    if (q <= 0) setCart(cart.filter(x => x.slug !== slug));
    else setCart(cart.map(x => x.slug === slug ? { ...x, qty: q } : x));
  };
  return (
    <>
      <div className={"nw-drawer-bg " + (open ? "open" : "")} onClick={onClose} />
      <aside className={"nw-drawer " + (open ? "open" : "")}>
        <div className="nw-drawer-head">
          <div>
            <Eyebrow plain>Handlekurv</Eyebrow>
            <div style={{ fontFamily: "var(--hv-font-display)", fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em" }}>
              {cart.length ? `${cart.length} ${cart.length === 1 ? "vare" : "varer"}` : "Tom"}
            </div>
          </div>
          <button className="nw-nav-btn" onClick={onClose}><Close /></button>
        </div>
        <div className="nw-drawer-body">
          {cart.length === 0 && (
            <div style={{ textAlign: "center", padding: "40px 20px", color: "var(--hv-fg-3)" }}>
              <WaveGlyph width={80} height={28} animated={true} />
              <p style={{ marginTop: 20, fontSize: 15 }}>Legg i en filet eller to.<br/>Vi pakker den på is og kjører den hjem.</p>
            </div>
          )}
          {cart.map(item => (
            <div className="nw-cart-row" key={item.slug}>
              <div className="nw-cart-thumb"><img src={item.img} alt="" /></div>
              <div>
                <div style={{ fontFamily: "var(--hv-font-display)", fontWeight: 600, fontSize: 17 }}>{item.name}</div>
                <div style={{ fontSize: 12, color: "var(--hv-fg-3)", marginTop: 2 }}>{item.cat}</div>
                <div className="nw-cart-qty">
                  <button onClick={() => setQty(item.slug, item.qty - 1)}><Minus size={14} /></button>
                  <span>{item.qty}</span>
                  <button onClick={() => setQty(item.slug, item.qty + 1)}><Plus size={14} /></button>
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <Price amount={item.price * item.qty} />
              </div>
            </div>
          ))}
        </div>
        <div className="nw-drawer-foot">
          {fraktMsg && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: "var(--hv-teal)", marginBottom: 6 }}>{fraktMsg}</div>
              <div style={{ height: 4, borderRadius: 999, background: "var(--hv-ink-4)", overflow: "hidden" }}>
                <div style={{ height: "100%", width: fraktProsent + "%", borderRadius: 999, background: "var(--hv-teal)", transition: "width 400ms ease" }} />
              </div>
            </div>
          )}
          {total >= 1100 && cart.length > 0 && (
            <div style={{ fontSize: 12, color: "var(--hv-ok)", marginBottom: 12 }}>Gratis frakt!</div>
          )}
          <div className="nw-kalk-line"><span className="lbl">Subtotal</span><span><Price amount={total} /></span></div>
          <div className="nw-kalk-line"><span className="lbl">Levering (Bergen)</span><span>{fee === 0 && cart.length > 0 ? <span style={{ color: "var(--hv-ok)" }}>Gratis</span> : <Price amount={fee} />}</span></div>
          <div className="nw-kalk-line" style={{ borderTop: "1px solid var(--hv-line)", marginTop: 8, paddingTop: 14, fontSize: 16 }}>
            <span style={{ fontWeight: 600 }}>Totalt</span>
            <span className="nw-kalk-total" style={{ fontSize: 28 }}>{total + fee} kr</span>
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
            <Btn style={{ flex: "0 0 33%", fontSize: 13, padding: "10px 8px" }} size="sm" variant="ghost" onClick={() => window.__setCartOpen && window.__setCartOpen(false)}>
              Fortsett å handle
            </Btn>
            <Btn style={{ flex: 1 }} size="lg" onClick={goCheckout || (() => {})}>
              Til kasse <ArrowRight size={16} />
            </Btn>
          </div>
        </div>
      </aside>
    </>
  );
};

// Tweaks panel — hero variant picker, theme, heading
const TweaksPanel = ({ visible, tweaks, setTweaks }) => {
  if (!visible) return null;
  return (
    <div className="nw-tweaks">
      <h6>Tweaks <span style={{ color: "var(--hv-teal)", fontStyle: "italic", fontWeight: 400 }}>~</span></h6>
      <div className="tw-group">
        <label>Hero-variant</label>
        <div className="nw-tw-chips">
          {[1,2,3,4,5].map(v => (
            <button key={v}
              className={"nw-tw-chip" + (tweaks.hero_variant === v ? " active" : "")}
              onClick={() => setTweaks({ hero_variant: v })}
            >{v}</button>
          ))}
        </div>
        <div style={{ fontSize: 11, color: "var(--hv-fg-3)", marginTop: 6 }}>
          {["Kinematisk", "Typografisk", "Ukens fisk", "Manifest-split", "Kortstabel"][tweaks.hero_variant - 1]}
        </div>
      </div>
      <div className="tw-group">
        <label>Tema</label>
        <div className="nw-tw-chips">
          <button className={"nw-tw-chip" + (tweaks.theme === "dark" ? " active" : "")} onClick={() => setTweaks({ theme: "dark" })}><Moon size={14} style={{ verticalAlign: "middle" }}/> Mørk</button>
          <button className={"nw-tw-chip" + (tweaks.theme === "light" ? " active" : "")} onClick={() => setTweaks({ theme: "light" })}><Sun size={14} style={{ verticalAlign: "middle" }}/> Lys</button>
        </div>
      </div>
      <div className="tw-group">
        <label>Hero-overskrift</label>
        <input
          className="nw-tw-input"
          value={tweaks.hero_heading}
          onChange={e => setTweaks({ hero_heading: e.target.value })}
        />
      </div>
    </div>
  );
};

// Statiske sider som kan dukke opp i søk
const SITE_PAGES = [
  { route: "home",        name: "Hjem",          desc: "Forside med ferskvarer og sesongkalender",     keywords: "forside hjem havøyet" },
  { route: "butikk",      name: "Butikk",        desc: "Alle produkter og kategorier",                 keywords: "butikk shop produkter alt" },
  { route: "sjømatkasse", name: "Sjømatkasse",   desc: "Skalldyrkasser og din egen kasse",              keywords: "sjømatkasse skalldyrkasse abonnement kasse" },
  { route: "catering",    name: "Catering",      desc: "Sjømat til selskap og arrangementer",          keywords: "catering selskap arrangement bryllup" },
  { route: "om",          name: "Om oss",        desc: "Historien om Havøyet og Erik",                  keywords: "om oss erik historie havøyet bergen" },
  { route: "levering",    name: "Levering",      desc: "Leveringsdager, soner og priser",              keywords: "levering frakt soner pris dager" },
  { route: "kontakt",     name: "Kontakt",       desc: "Send oss en melding eller ring",                keywords: "kontakt e-post telefon mail melding" },
  { route: "konto",       name: "Min konto",     desc: "Logg inn, bestillinger og favoritter",          keywords: "konto profil innlogging logg inn min" },
  { route: "kasse",       name: "Kassen",        desc: "Fullfør bestillingen din",                      keywords: "kasse checkout betal" },
];

// SearchOverlay — flytende søkefelt under nav, med dropdown-resultater. Ingen mørk backdrop.
const SearchOverlay = ({ open, onClose, goPDP, setRoute }) => {
  const [q, setQ] = React.useState("");
  const inputRef = React.useRef(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setQ("");
      requestAnimationFrame(() => inputRef.current && inputRef.current.focus());
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    const onClickOutside = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) onClose();
    };
    window.addEventListener("keydown", onKey);
    // Litt forsinkelse så åpningsklikket på selve søkeknappen ikke trigger lukking
    const t = setTimeout(() => document.addEventListener("mousedown", onClickOutside), 50);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.removeEventListener("mousedown", onClickOutside);
      clearTimeout(t);
    };
  }, [open, onClose]);

  const results = React.useMemo(() => {
    if (!open) return { pages: [], products: [] };
    const query = q.trim().toLowerCase();
    if (!query) return { pages: [], products: [] };
    const pages = SITE_PAGES
      .filter(p =>
        p.name.toLowerCase().includes(query) ||
        p.desc.toLowerCase().includes(query) ||
        p.keywords.toLowerCase().includes(query)
      )
      .slice(0, 6);
    const products = (window.PRODUCTS || [])
      .filter(p =>
        p.status !== "hidden" && !p.deleted && (
          p.name.toLowerCase().includes(query) ||
          (p.desc && p.desc.toLowerCase().includes(query)) ||
          (p.cat && p.cat.toLowerCase().includes(query))
        )
      )
      .slice(0, 10);
    return { pages, products };
  }, [q, open]);

  if (!open) return null;

  const totalCount = results.pages.length + results.products.length;
  const handlePickProduct = (slug) => { onClose(); goPDP(slug); };
  const handlePickPage    = (route) => { onClose(); setRoute(route); };

  return (
    <div
      role="dialog" aria-label="Søk produkter"
      style={{
        position: "fixed", top: 84, left: 0, right: 0, zIndex: 81,
        padding: "0 24px",
        pointerEvents: "none",          // klikk utenfor kortet treffer siden bak
      }}
    >
      <div
        ref={containerRef}
        style={{
          maxWidth: 560, margin: "0 auto", pointerEvents: "auto",
          background: "var(--hv-ink-2)",
          border: "1px solid var(--hv-line)",
          borderRadius: 14,
          overflow: "hidden",
          boxShadow: "0 18px 48px rgba(0,0,0,0.45)",
        }}
      >
        <div style={{
          display: "flex", alignItems: "center", gap: 12,
          padding: "14px 18px",
          borderBottom: (totalCount || q.trim()) ? "1px solid var(--hv-line)" : "none",
        }}>
          <Search size={18} style={{ color: "var(--hv-fg-3)", flexShrink: 0 }} />
          <input
            ref={inputRef}
            type="search"
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Søk i hele Havøyet …"
            style={{
              flex: 1,
              background: "transparent", border: "none", outline: "none",
              color: "var(--hv-fg-1)", fontSize: 16,
              fontFamily: "var(--hv-font-body)",
            }}
          />
          <button onClick={onClose} aria-label="Lukk søk" style={{
            background: "transparent", border: "1px solid var(--hv-line)",
            color: "var(--hv-fg-3)", borderRadius: 6,
            padding: "3px 8px", fontSize: 11, cursor: "pointer",
          }}>ESC</button>
        </div>
        {q.trim() && totalCount === 0 && (
          <div style={{ padding: "18px 20px", color: "var(--hv-fg-3)", fontSize: 13 }}>
            Ingen treff for «{q}».
          </div>
        )}
        {totalCount > 0 && (
          <div style={{ maxHeight: "56vh", overflowY: "auto" }}>
            {results.pages.length > 0 && (
              <div>
                <div style={{
                  padding: "10px 18px 6px", fontSize: 10, fontWeight: 700,
                  letterSpacing: "0.1em", textTransform: "uppercase",
                  color: "var(--hv-fg-3)",
                }}>Sider</div>
                {results.pages.map(p => (
                  <button key={p.route}
                    onClick={() => handlePickPage(p.route)}
                    style={{
                      display: "flex", alignItems: "center", gap: 12,
                      width: "100%", padding: "10px 18px",
                      background: "transparent", border: "none",
                      borderBottom: "1px solid var(--hv-line)",
                      cursor: "pointer", textAlign: "left",
                      transition: "background 120ms",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(65,193,186,0.08)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <div style={{
                      width: 40, height: 40, borderRadius: 6, flexShrink: 0,
                      background: "var(--hv-ink-3)", border: "1px solid var(--hv-line)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      color: "var(--hv-teal)",
                    }}>
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, color: "var(--hv-fg-1)" }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: "var(--hv-fg-3)", marginTop: 1 }}>{p.desc}</div>
                    </div>
                    <ArrowRight size={14} style={{ color: "var(--hv-fg-3)", flexShrink: 0 }} />
                  </button>
                ))}
              </div>
            )}
            {results.products.length > 0 && (
              <div>
                <div style={{
                  padding: "10px 18px 6px", fontSize: 10, fontWeight: 700,
                  letterSpacing: "0.1em", textTransform: "uppercase",
                  color: "var(--hv-fg-3)",
                }}>Produkter</div>
                {results.products.map(p => (
                  <button key={p.slug}
                    onClick={() => handlePickProduct(p.slug)}
                    style={{
                      display: "flex", alignItems: "center", gap: 12,
                      width: "100%", padding: "10px 18px",
                      background: "transparent", border: "none",
                      borderBottom: "1px solid var(--hv-line)",
                      cursor: "pointer", textAlign: "left",
                      transition: "background 120ms",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(65,193,186,0.08)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <div style={{
                      width: 40, height: 40, borderRadius: 6, overflow: "hidden",
                      background: "var(--hv-ink-3)", flexShrink: 0,
                    }}>
                      {p.img && <img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, color: "var(--hv-fg-1)" }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: "var(--hv-fg-3)", marginTop: 1 }}>{p.cat}</div>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--hv-teal)", fontWeight: 600, fontVariantNumeric: "tabular-nums", flexShrink: 0 }}>
                      {p.price} kr
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { Nav, Footer, CartDrawer, TweaksPanel, SearchOverlay });
