// Shared components: Logo, NavBar, Footer, Button, ProductCard, etc.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Icons (inline SVG) ──────────────────────────
function Icon({ name, size = 18, stroke = 1.6 }) {
  const common = {
    width: size, height: size,
    fill: "none", stroke: "currentColor",
    strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round",
    viewBox: "0 0 24 24"
  };
  const paths = {
    bag: <><path d="M5 8h14l-1 12H6L5 8Z" /><path d="M9 8a3 3 0 1 1 6 0" /></>,
    chevL: <polyline points="14 6 8 12 14 18" />,
    chevR: <polyline points="10 6 16 12 10 18" />,
    chevD: <polyline points="6 9 12 15 18 9" />,
    plus: <><path d="M12 5v14" /><path d="M5 12h14" /></>,
    minus: <path d="M5 12h14" />,
    x: <><path d="M6 6l12 12" /><path d="M18 6L6 18" /></>,
    check: <polyline points="4 12 10 18 20 6" />,
    search: <><circle cx="11" cy="11" r="7" /><path d="M21 21l-4-4" /></>,
    grid: <><rect x="4" y="4" width="7" height="7" /><rect x="13" y="4" width="7" height="7" /><rect x="4" y="13" width="7" height="7" /><rect x="13" y="13" width="7" height="7" /></>,
    list: <><path d="M8 6h13" /><path d="M8 12h13" /><path d="M8 18h13" /><circle cx="4" cy="6" r="1" /><circle cx="4" cy="12" r="1" /><circle cx="4" cy="18" r="1" /></>,
    dashboard: <><rect x="3" y="3" width="8" height="10" /><rect x="13" y="3" width="8" height="6" /><rect x="13" y="11" width="8" height="10" /><rect x="3" y="15" width="8" height="6" /></>,
    box: <><path d="M3 8l9-5 9 5v8l-9 5-9-5z" /><path d="M3 8l9 5 9-5" /><path d="M12 13v8" /></>,
    users: <><circle cx="9" cy="8" r="3" /><path d="M3 20a6 6 0 0 1 12 0" /><circle cx="17" cy="9" r="2" /><path d="M16 14a5 5 0 0 1 5 5" /></>,
    chart: <><path d="M4 19h16" /><path d="M6 16V9" /><path d="M11 16V5" /><path d="M16 16v-7" /></>,
    settings: <><circle cx="12" cy="12" r="3" /><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4.8a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.4a7 7 0 0 0-2 1.2l-2.4-.8-2 3.4 2 1.6A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.6 2 3.4 2.4-.8a7 7 0 0 0 2 1.2L10 21h4l.5-2.4a7 7 0 0 0 2-1.2l2.4.8 2-3.4-2-1.6c0-.4.1-.8.1-1.2Z" /></>,
    log: <><path d="M9 21V3" /><path d="M14 5l4-2v18l-4-2" /></>,
    leaf: <><path d="M11 20A7 7 0 0 1 4 13c0-5 4-9 9-9h7v7a7 7 0 0 1-7 9Z" /><path d="M4 20l7-7" /></>,
    fb: <path d="M14 22v-9h3l1-4h-4V7c0-1.2.4-2 2-2h2V1.2A22 22 0 0 0 15 1c-3.2 0-5 1.8-5 5v3H7v4h3v9z" stroke="none" fill="currentColor" />,
    ig: <><rect x="3" y="3" width="18" height="18" rx="5" /><circle cx="12" cy="12" r="4" /><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" stroke="none" /></>,
    pin: <><path d="M12 22s-7-7-7-12a7 7 0 0 1 14 0c0 5-7 12-7 12Z" /><circle cx="12" cy="10" r="2.5" /></>,
    phone: <path d="M22 16.9v3a2 2 0 0 1-2.2 2 19 19 0 0 1-8.3-3 19 19 0 0 1-6-6 19 19 0 0 1-3-8.4A2 2 0 0 1 4.5 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.6a2 2 0 0 1-.4 2.1L8.4 9.7a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2-.5c.9.3 1.8.5 2.7.6a2 2 0 0 1 1.7 2Z" />,
    mail: <><rect x="2" y="5" width="20" height="14" rx="2" /><path d="M2 7l10 7 10-7" /></>,
    eye: <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></>,
    upload: <><path d="M12 16V4" /><polyline points="7 9 12 4 17 9" /><path d="M5 20h14" /></>,
    dollar: <><path d="M12 2v20" /><path d="M17 6H9.5a3 3 0 0 0 0 6h5a3 3 0 0 1 0 6H6" /></>,
    trash: <><path d="M3 6h18" /><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" /></>,
    edit: <><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" /></>
  };
  return <svg {...common}>{paths[name] || null}</svg>;
}

// ─── Logo ────────────────────────────────────────
function Logo({ height = 110, white = false, onClick, className = "nav-logo" }) {
  return (
    <img
      src="assets/logo.png"
      alt="Decades on Main"
      className={className}
      style={{ height, ...(white ? { filter: "invert(1) brightness(1.4)" } : {}), cursor: onClick ? "pointer" : "default" }}
      onClick={onClick} />);


}

// ─── NavBar ──────────────────────────────────────
function NavBar({ route, navigate, cartCount, hideOnTop }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 120);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Close mobile menu on route change
  useEffect(() => {setMenuOpen(false);}, [route.page, route.id, route.filter, route.view]);

  // Lock body scroll while menu open
  useEffect(() => {
    if (menuOpen) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {document.body.style.overflow = prev;};
    }
  }, [menuOpen]);

  // On pages with a hero (home), nav floats transparently with white text;
  // once scrolled it flips to the solid cream bar.
  const transparent = hideOnTop && !scrolled && !menuOpen;
  const hidden = false;

  const links = [
  { id: "home", label: "Home" },
  { id: "about", label: "About" },
  { id: "shop", label: "Shop" },
  { id: "selling", label: "Selling?" },
  { id: "contact", label: "Contact Us" }];


  const isActive = (id) => route.page === id || id === "shop" && route.page === "product";

  return (
    <>
      <nav className={"nav " + (transparent ? "nav--transparent " : "") + (hidden ? "nav--hidden" : "") + (menuOpen ? " nav--menu-open" : "")}>
        <div className="nav-inner">
          {/* LEFT cell — hamburger (mobile) + logo, click logo to go home */}
          <div className="nav-left">
            <button className="nav-hamburger" onClick={() => setMenuOpen((v) => !v)} aria-label="Menu" aria-expanded={menuOpen}>
              <span className={"hamburger-icon " + (menuOpen ? "is-open" : "")}>
                <span></span><span></span><span></span>
              </span>
            </button>
            <Logo height={120} onClick={() => navigate({ page: "home" })} />
          </div>

          {/* RIGHT cell — links + cart on desktop, just cart on mobile */}
          <div className="nav-right">
            <a className={"nav-link nav-links-desktop-item " + (isActive("shop") ? "is-active" : "")}
            onClick={() => navigate({ page: "shop" })}>Shop</a>
            <a className={"nav-link nav-links-desktop-item " + (isActive("about") ? "is-active" : "")}
            onClick={() => navigate({ page: "about" })}>About</a>
            <a className={"nav-link nav-links-desktop-item " + (isActive("selling") ? "is-active" : "")}
            onClick={() => navigate({ page: "selling" })}>Selling?</a>
            <a className={"nav-link nav-links-desktop-item " + (isActive("contact") ? "is-active" : "")}
            onClick={() => navigate({ page: "contact" })}>Contact Us</a>
            <button className={"nav-cta nav-links-desktop-item" + (isActive("consult") ? " is-active" : "")}
            onClick={() => navigate({ page: "consult" })}>Schedule a Consultation</button>
            <button className="nav-cart" onClick={() => navigate({ page: "cart" })} aria-label="Cart">
              <Icon name="bag" size={22} stroke={1.4} />
              {cartCount > 0 && <span className="cart-count">{cartCount}</span>}
            </button>
          </div>
        </div>
      </nav>

      {/* Mobile menu overlay */}
      <div className={"mobile-menu " + (menuOpen ? "is-open" : "")} aria-hidden={!menuOpen}>
        <div className="mobile-menu-inner">
          {links.map((l) =>
          <a key={l.id}
          className={"mobile-menu-link " + (isActive(l.id) ? "is-active" : "")}
          onClick={() => {navigate({ page: l.id });setMenuOpen(false);}}>
              {l.label}
            </a>
          )}
          <a className={"mobile-menu-link mobile-menu-cta " + (isActive("consult") ? "is-active" : "")}
          onClick={() => {navigate({ page: "consult" });setMenuOpen(false);}}>
            Schedule a Consultation
          </a>
          <div className="mobile-menu-foot">
            <a className="mobile-menu-sub" onClick={() => {navigate({ page: "cart" });setMenuOpen(false);}}>
              <Icon name="bag" size={16} /> Cart {cartCount > 0 && `(${cartCount})`}
            </a>
            <div className="mobile-menu-meta">
              <div>18559 High Springs Main St.</div>
              <div>High Springs, FL 32643</div>
              <div style={{ marginTop: 6 }}>(352) 575-3633</div>
              <div style={{ marginTop: 6, fontStyle: "italic" }}>Tue – Sun · 11 – 6</div>
            </div>
          </div>
        </div>
      </div>
    </>);

}

// ─── Footer ──────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Logo className="footer-logo" />
            <p className="small" style={{ marginTop: 12 }}>
              18559 High Springs Main St.<br />
              High Springs, FL 32643<br />
              (352) 575-3633
            </p>
            <div className="socials" style={{ marginTop: 18 }}>
              <a href="https://www.facebook.com/DecadesOnMain/" target="_blank" rel="noreferrer" aria-label="Facebook"><Icon name="fb" size={16} /></a>
              <a href="https://www.instagram.com/decadesonmain/" target="_blank" rel="noreferrer" aria-label="Instagram"><Icon name="ig" size={16} /></a>
            </div>
          </div>
          <div>
            <h4>Shop</h4>
            <ul>
              <li><a onClick={() => navigate({ page: "shop" })}>All Items</a></li>
              <li><a onClick={() => navigate({ page: "shop", view: "vendor" })}>By Vendor</a></li>
              <li><a onClick={() => navigate({ page: "shop", view: "category" })}>By Category</a></li>
              <li><a onClick={() => navigate({ page: "shop", filter: "new" })}>New Arrivals</a></li>
            </ul>
          </div>
          <div>
            <h4>Visit</h4>
            <ul className="hours-list" style={{ color: "rgba(255,255,255,0.78)" }}>
              <li><span>Mon</span><span style={{ color: "rgba(255,255,255,0.4)", fontStyle: "italic" }}>Closed</span></li>
              <li><span>Tue – Sun</span><span>11 – 6</span></li>
            </ul>
          </div>
          <div>
            <h4>About</h4>
            <ul>
              <li><a onClick={() => navigate({ page: "about" })}>Our Story</a></li>
              <li><a onClick={() => navigate({ page: "contact" })}>Contact</a></li>
              <li><a onClick={() => navigate({ page: "admin" })} style={{ color: "rgba(255,255,255,0.5)" }}>Admin</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Decades on Main. All rights reserved.</span>
          <span>Yesterday's <em>treasures</em> are todays <em>pleasures</em> · High Springs, FL</span>
        </div>
      </div>
    </footer>);

}

// ─── Product image (placeholder) ─────────────────
function ProductImage({ product, tag }) {
  const cat = product.category;
  const tint = window.CATEGORY_TINT[cat] || { bg: "#bba98a", ink: "#fff" };
  const glyph = window.categoryGlyph(cat, tint.ink);
  // texture: subtle paper grain via repeating gradients
  const bg = `
    radial-gradient(circle at 30% 20%, rgba(255,255,255,0.07), transparent 60%),
    radial-gradient(circle at 70% 80%, rgba(0,0,0,0.15), transparent 60%),
    ${tint.bg}
  `;
  return (
    <div className="product-image" style={{ background: product.image_url ? "#efe5d2" : bg }}>
      {product.image_url ?
      <img src={product.image_url} alt={product.name || ""}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} /> :
      <div className="glyph" dangerouslySetInnerHTML={{ __html: glyph }} />}
      {tag && <span className={"tag " + (tag === "Sold" ? "sold" : "")}>{tag}</span>}
    </div>);

}

// ─── Product card ────────────────────────────────
function ProductCard({ product, onClick }) {
  const isSold = product.status === "sold";
  return (
    <article className="product-card" onClick={onClick}>
      <ProductImage product={product} tag={isSold ? "Sold" : null} />
      <div className="product-meta">
        <span className="vendor">{product.vendor || ""}</span>
        <span className="name serif">{product.name}</span>
        <span className={"price" + (isSold ? " sold" : "")}>${Number(product.price || 0).toLocaleString()}</span>
      </div>
    </article>);

}

// ─── Botanical sprig (decorative) ────────────────
function Sprig({ flip, color = "currentColor", size = 60 }) {
  return (
    <svg viewBox="0 0 120 40" width={size * 3} height={size} style={{ transform: flip ? "scaleX(-1)" : "none", color }}>
      <g fill="none" stroke={color} strokeWidth="1.2" strokeLinecap="round">
        <path d="M5 20 Q60 4 115 20" />
        <path d="M20 15 Q25 8 32 11" />
        <path d="M30 13 Q35 6 42 9" />
        <path d="M42 11 Q47 4 54 7" />
        <path d="M58 7 Q63 0 70 4" />
        <path d="M72 7 Q77 0 84 4" />
        <path d="M86 9 Q91 3 98 7" />
      </g>
    </svg>);

}

Object.assign(window, { Icon, Logo, NavBar, Footer, ProductImage, ProductCard, Sprig });