// =========================================================
// Shared UI primitives
// =========================================================

// ===== Mountain motif (simple triangles only) =====
function MountainStrip({ position = "bottom" }) {
  return (
    <div className={"mountains " + position} aria-hidden="true">
      <svg viewBox="0 0 1200 110" preserveAspectRatio="none">
        <polygon points="0,110 140,30 270,90 380,10 520,80 640,40 780,90 900,20 1020,75 1140,35 1200,90 1200,110" fill="currentColor" />
        <polygon points="0,110 100,70 220,95 340,55 470,90 600,60 720,95 850,50 970,90 1100,70 1200,95 1200,110" fill="currentColor" opacity="0.5" />
      </svg>
    </div>
  );
}

// ===== Placeholder (striped) =====
function Placeholder({ label, tone, style }) {
  return (
    <div className={"ph" + (tone ? " " + tone : "")} style={style}>
      <span className="ph-label">{label}</span>
    </div>
  );
}

function productPlaceholderTone(id) {
  // pick a tone based on id, but mostly neutral
  const i = parseInt((id || "p0").replace(/\D/g, ""), 10) || 0;
  const r = i % 8;
  if (r === 2) return "dark";
  if (r === 5) return "saffron";
  return "";
}

function productPhLabel(p) {
  return p.cat === "traditional" ? "traditional / " + p.name.split(" ")[0].toLowerCase()
       : p.cat === "guitars"     ? "guitar shot"
       : p.cat === "keyboards"   ? "keyboard shot"
       : p.cat === "audio"       ? "audio gear"
       : "accessory";
}

// ===== Header =====
function SiteHeader({ route, navigate, openCart, openLogin }) {
  const [state] = useStore();
  const count = cartCount(state);
  const isAdminRoute = route?.name === "admin";
  return (
    <React.Fragment>
      <div className="site-top-bar">
        <div className="wrap">
          <span>Free delivery inside Kathmandu Valley · Orders Rs. 20,000+</span>
          <span className="deva">नेपालभर डेलिभरी उपलब्ध</span>
        </div>
      </div>
      <header className="site-header">
        <div className="wrap">
          <div className="brand" onClick={() => navigate({ name: "home" })} style={{ cursor: "pointer" }}>
            <div className="brand-mark"><span className="m">न</span></div>
            <div className="brand-name">
              <span className="en">Nepal Musical Store</span>
              <span className="ne">नेपाल म्युजिकल स्टोर</span>
            </div>
          </div>
          <nav className="nav">
            <button aria-current={route?.name === "home" ? "page" : undefined} onClick={() => navigate({ name: "home" })}>Shop</button>
            <button aria-current={route?.name === "category" ? "page" : undefined} onClick={() => navigate({ name: "category", id: "traditional" })}>Traditional</button>
            <button aria-current={route?.name === "category" && route?.id === "guitars" ? "page" : undefined} onClick={() => navigate({ name: "category", id: "guitars" })}>Guitars</button>
            <button aria-current={route?.name === "category" && route?.id === "keyboards" ? "page" : undefined} onClick={() => navigate({ name: "category", id: "keyboards" })}>Keyboards</button>
            <button aria-current={route?.name === "category" && route?.id === "audio" ? "page" : undefined} onClick={() => navigate({ name: "category", id: "audio" })}>Audio</button>
            <button aria-current={route?.name === "about" ? "page" : undefined} onClick={() => navigate({ name: "about" })}>About</button>
          </nav>
          <div className="header-actions">
            {state.user ? (
              <button className="icon-btn" onClick={() => navigate({ name: "account" })} title={state.user.name}>
                <span style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{state.user.picture || state.user.name?.[0]}</span>
              </button>
            ) : (
              <button className="icon-btn" onClick={openLogin} title="Sign in">
                <UserIcon />
              </button>
            )}
            <button className="icon-btn" onClick={openCart} title="Cart">
              <BagIcon />
              {count > 0 && <span className="badge">{count}</span>}
            </button>
            {!isAdminRoute && (
              <button className="icon-btn" onClick={() => navigate({ name: "admin" })} title="Store keeper view" style={{ marginLeft: 4, borderStyle: "dashed" }}>
                <AdminIcon />
              </button>
            )}
          </div>
        </div>
      </header>
    </React.Fragment>
  );
}

function UserIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <circle cx="12" cy="9" r="4" />
      <path d="M4 20c1.5-4 5-6 8-6s6.5 2 8 6" />
    </svg>
  );
}
function BagIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M5 8h14l-1.2 11a2 2 0 0 1-2 1.8H8.2a2 2 0 0 1-2-1.8L5 8Z" />
      <path d="M9 8V6a3 3 0 0 1 6 0v2" />
    </svg>
  );
}
function AdminIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <rect x="4" y="5" width="16" height="14" />
      <path d="M4 9h16M9 13h6M9 16h4" />
    </svg>
  );
}
function CloseIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M6 6l12 12M18 6 6 18" />
    </svg>
  );
}

// ===== Footer =====
function SiteFooter({ navigate }) {
  return (
    <footer className="site-foot">
      <div className="wrap">
        <div className="top">
          <div>
            <div className="brand" style={{ marginBottom: 20 }}>
              <div className="brand-mark"><span className="m">न</span></div>
              <div className="brand-name">
                <span className="en">Nepal Musical Store</span>
                <span className="ne">नेपाल म्युजिकल स्टोर</span>
              </div>
            </div>
            <p style={{ color: "var(--ink-2)", fontSize: 13, maxWidth: 38 + "ch", margin: 0 }}>
              Curating Nepal's finest musical instruments — from the high-altitude lutes of Solukhumbu to gig-ready amplifiers — since 2018.
            </p>
          </div>
          <div>
            <h4>Shop</h4>
            <ul>
              {CATS.map(c => (
                <li key={c.id}><button onClick={() => navigate({ name: "category", id: c.id })}>{c.en}</button></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>Account</h4>
            <ul>
              <li><button onClick={() => navigate({ name: "account" })}>My Orders</button></li>
              <li><button onClick={() => navigate({ name: "about" })}>About Us</button></li>
              <li><button onClick={() => navigate({ name: "admin" })}>Store Keeper View</button></li>
            </ul>
          </div>
          <div>
            <h4>Visit</h4>
            <ul>
              <li>Putalisadak, Kathmandu</li>
              <li>+977 1-4242424</li>
              <li>hello@nepalmusical.np</li>
              <li style={{ fontFamily: "var(--font-deva)", marginTop: 6 }}>आइतबार – शुक्रबार · १०–८</li>
            </ul>
          </div>
        </div>
        <div className="bot">
          <span>© 2026 Nepal Musical Store</span>
          <span>Cash on Delivery · Kathmandu, Nepal</span>
        </div>
      </div>
    </footer>
  );
}

// ===== Product Card =====
function ProductCard({ p, onClick, onAdd }) {
  const tone = productPlaceholderTone(p.id);
  return (
    <div className="product-card" onClick={() => onClick(p)}>
      <div className="frame">
        <Placeholder label={productPhLabel(p)} tone={tone} />
        {p.tag && <span className={"tag" + (p.tag === "Sale" ? " sale" : p.tag === "New" ? " new" : "")}>{p.tag}</span>}
        <button className="btn small block accent quick-add" onClick={(e) => { e.stopPropagation(); onAdd(p); }}>Add to Cart</button>
      </div>
      <div className="body">
        <div className="meta-row">
          <span className="cat">{CAT_BY_ID[p.cat].en}</span>
          <span className="price">{NPR(p.price)}{p.was && <span className="strike">{NPR(p.was)}</span>}</span>
        </div>
        <span className="name">{p.name}</span>
        <span className="ne">{p.ne}</span>
      </div>
    </div>
  );
}

// ===== Toast =====
function Toast({ message, onDone }) {
  React.useEffect(() => {
    if (!message) return;
    const t = setTimeout(onDone, 2200);
    return () => clearTimeout(t);
  }, [message]);
  if (!message) return null;
  return (
    <div className="toast"><span className="dot" />{message}</div>
  );
}

Object.assign(window, {
  SiteHeader, SiteFooter, ProductCard, Placeholder, MountainStrip, Toast,
  productPlaceholderTone, productPhLabel, CloseIcon
});
