"use client";

"use client";

import { useCallback, useRef, useState } from "react";
import type { HomeContent, MenuItem } from "@/lib/content";
import { trackEvent, trackNav } from "@/components/Tracking";
import Image from "@/components/Image";
import { useCartStore } from "@/lib/cart-store";

const F = { fontFamily: "Lato,sans-serif" };

export default function Header({
  content,
  menuItems,
}: {
  content: HomeContent;
  menuItems?: MenuItem[];
}) {
  const { hero, header } = content;
  const links = menuItems || [];
  const cartCount = useCartStore((s) => s.itemCount);
  const cartItems = useCartStore((s) => s.items);
  const cartTotal = useCartStore((s) => s.total);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const showDropdown = useCallback(() => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    setDropdownOpen(true);
  }, []);

  const hideDropdown = useCallback(() => {
    timeoutRef.current = setTimeout(() => setDropdownOpen(false), 200);
  }, []);

  const handleBlur = useCallback((e: React.FocusEvent) => {
    if (!dropdownRef.current?.contains(e.relatedTarget as Node)) {
      hideDropdown();
    }
  }, [hideDropdown]);

  return (
    <header style={{ position: "sticky", top: 0, zIndex: 80, background: "rgba(255,255,255,.55)", backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)", borderBottom: "1px solid rgba(255,255,255,.6)" }}>
      <div className="header-bar" style={{ maxWidth: 1280, margin: "0 auto", padding: "0 56px", height: 80, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
        <a href="/" onClick={() => trackNav("Header", "logo")} style={{ display: "inline-flex" }}>
          <Image src={header.logo || "/img/logo.webp"} alt="Sigma Tax Pro" style={{ height: 38, width: "auto" }} />
        </a>

        <nav className="desktop-nav" style={{ display: "flex", gap: 30, ...F, fontSize: 15, color: "#3a4044", alignItems: "center" }}>
          {links.map((link) =>
            link.children && link.children.length > 0 ? (
              <DropdownItem key={link.id} item={link} />
            ) : (
              <a key={link.id} href={link.url} onClick={() => trackNav("Header", link.label)} style={{ ...F, color: "#3a4044", whiteSpace: "nowrap", lineHeight: "80px" }}>
                {link.label}
              </a>
            )
          )}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <a className="header-tel" href={hero.phoneHref || "tel:+18663864769"} onClick={() => trackEvent("cta_click", { click_text: hero.phoneDisplay, click_url: hero.phoneHref })} style={{ display: "inline-flex", alignItems: "center", gap: 7, ...F, fontSize: 14, fontWeight: 700, color: "#022f31" }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
            {hero.phoneDisplay}
          </a>
          <div ref={dropdownRef} style={{ position: "relative" }} onMouseEnter={showDropdown} onMouseLeave={hideDropdown} onFocus={showDropdown} onBlur={handleBlur}>
            <a href="/checkout/" aria-label="View shopping cart" aria-haspopup="true" aria-expanded={dropdownOpen} onClick={() => trackNav("Header", "cart")} style={{ position: "relative", display: "inline-flex", alignItems: "center", justifyContent: "center", width: 38, height: 38, borderRadius: "50%", background: "rgba(255,255,255,.7)", border: "1px solid rgba(255,255,255,.8)", boxShadow: "0 8px 20px rgba(2,47,49,.1)", transition: "background .12s" }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#022f31" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
              {cartCount > 0 && (
                <span style={{ position: "absolute", top: -4, right: -4, background: "#dc2626", color: "#fff", fontSize: 10, fontWeight: 700, minWidth: 18, height: 18, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center", lineHeight: 1, padding: "0 4px" }}>
                  {cartCount > 99 ? "99+" : cartCount}
                </span>
              )}
            </a>
            {dropdownOpen && cartCount > 0 && (
              <div style={{ position: "absolute", top: "100%", right: 0, paddingTop: 12, zIndex: 100 }} onMouseEnter={showDropdown} onMouseLeave={hideDropdown}>
                <div style={{ background: "rgba(255,255,255,.94)", backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)", border: "1px solid rgba(255,255,255,.85)", borderRadius: 18, boxShadow: "0 24px 54px rgba(2,47,49,.16)", padding: 16, minWidth: 280, maxWidth: 340 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: "#022f31", marginBottom: 12 }}>Cart ({cartCount})</div>
                  {cartItems.slice(0, 4).map((item) => (
                    <div key={item.key} style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 10, fontSize: 13 }}>
                      {item.image && <Image src={item.image} alt={item.name} style={{ width: 36, height: 36, borderRadius: 6, objectFit: "cover" }} />}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "#31353a" }}>{item.name}</div>
                        <div style={{ color: "#515a63", fontSize: 12 }}>Qty: {item.quantity}</div>
                      </div>
                      <div style={{ color: "#022f31", fontWeight: 600, whiteSpace: "nowrap" }}>${(item.priceRaw * item.quantity).toFixed(2)}</div>
                    </div>
                  ))}
                  {cartItems.length > 4 && <div style={{ fontSize: 12, color: "#515a63", textAlign: "center", marginBottom: 8 }}>+{cartItems.length - 4} more items</div>}
                  <div style={{ borderTop: "1px solid #e0e0e0", margin: "8px 0", paddingTop: 10, display: "flex", justifyContent: "space-between", fontSize: 14, fontWeight: 700, color: "#022f31" }}>
                    <span>Total</span>
                    <span>${cartTotal}</span>
                  </div>
                  <a href="/checkout/" onClick={() => trackNav("Header", "cart")} className="btn-gold" style={{ display: "block", textAlign: "center", padding: "10px", fontSize: 14, borderRadius: 10, marginTop: 4 }}>
                    View Cart & Checkout
                  </a>
                </div>
              </div>
            )}
          </div>
          <a className="header-cta hv0" href={header.ctaUrl || "#lead"} onClick={() => trackEvent("cta_click", { click_text: header.ctaText, click_url: header.ctaUrl })} style={{ background: "linear-gradient(135deg,#13a3a6,#006568)", color: "#fff", ...F, fontWeight: 700, fontSize: 14, padding: "12px 24px", borderRadius: 999, cursor: "pointer", boxShadow: "0 8px 20px rgba(0,101,104,.3)", transition: "filter .12s, transform .14s" }}>
            {header.ctaText}
          </a>
          <details className="mnav-btn">
            <summary aria-label="Menu">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#022f31" strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
            </summary>
            <div className="mnav-panel">
              <div className="mnav-top">
                <a className="home" href="/" style={{ ...F }}>Home</a>
                <a className="cta" href="/download-demos/" style={{ ...F }}>Free demo</a>
              </div>
              {links.filter((l) => l.children?.length).map((group) => (
                <div key={group.id} className="mnav-grp">
                  <span className="gl" style={{ ...F }}>{group.label}</span>
                  {group.children?.map((child) => (
                    <a key={child.id} href={child.url} style={{ ...F }}>{child.label}</a>
                  ))}
                </div>
              ))}
            </div>
          </details>
        </div>
      </div>
    </header>
  );
}

function DropdownItem({ item }: { item: MenuItem }) {
  const children = item.children || [];
  return (
    <div className="nav-dropdown" style={{ position: "relative" }}>
      <span tabIndex={0} aria-haspopup="true" style={{ ...F, fontSize: 15, color: "#3a4044", lineHeight: "80px" }}>
        {item.label}
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 4 }}><polyline points="6 9 12 15 18 9"></polyline></svg>
      </span>
      <div className="dropdown-menu" style={{ visibility: "hidden", opacity: 0, transform: "translateY(6px)", transition: "opacity .14s, transform .14s, visibility .14s", position: "absolute", top: "100%", left: "-14px", paddingTop: 12, zIndex: 90 }}>
        <div style={{ background: "rgba(255,255,255,.94)", backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)", border: "1px solid rgba(255,255,255,.85)", borderRadius: 18, boxShadow: "0 24px 54px rgba(2,47,49,.16)", padding: 10, display: "flex", flexDirection: "column", minWidth: 236 }}>
          {children.map((child) => (
            <a key={child.id} href={child.url} target={child.target || undefined} onClick={() => trackNav("Header", child.label)} style={{ ...F, fontSize: 14, color: "#31353a", padding: "10px 14px", borderRadius: 12, whiteSpace: "nowrap" }}>{child.label}</a>
          ))}
        </div>
      </div>
    </div>
  );
}
