/* Shared chrome for The Handify: Logo, Ticker, Header, Footer, CartDrawer + small UI bits. */

const fmt = (n) =>
  "$" + Number(n).toLocaleString("en-US", { maximumFractionDigits: 0 });

// ----- small bits ---------------------------------------------------------
function Eyebrow({ children, style }) {
  return (
    <span
      style={Object.assign(
        {
          fontFamily: "var(--mono)",
          fontSize: "11px",
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          color: "var(--ink-soft)",
        },
        style || {}
      )}
    >
      {children}
    </span>
  );
}

function Logo({ onClick, size = 1 }) {
  return (
    <button className="logo-btn" onClick={onClick} aria-label="The Handify home">
      <span className="logo-the">the</span>
      <span className="logo-mark" style={{ fontSize: `${2.1 * size}rem` }}>
        HANDIFY
      </span>
    </button>
  );
}

// ----- ticker -------------------------------------------------------------
function Ticker({ items }) {
  const line = items.join("  ·  ");
  const repeated = [line, line, line];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        {repeated.map((t, i) => (
          <span className="ticker-seg" key={i}>
            {t} &nbsp;·&nbsp;
          </span>
        ))}
      </div>
    </div>
  );
}

// ----- header -------------------------------------------------------------
function Header({ route, navigate, cartCount, onCartOpen, onSearch, searchValue }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const links = [
    { label: "Artists", route: "directory" },
    { label: "News", route: "news" },
    { label: "Shop", route: "shop" },
    { label: "About", route: "about" },
  ];
  const isActive = (r) =>
    route.name === r || (r === "directory" && (route.name === "profile" || route.name === "artwork"));

  const go = (r) => {
    navigate({ name: r });
    setMenuOpen(false);
  };

  return (
    <header className="site-header">
      <div className="header-inner">
        <Logo onClick={() => go("home")} />

        <nav className="nav-desktop">
          {links.map((l) => (
            <button
              key={l.route}
              className={"nav-link" + (isActive(l.route) ? " is-active" : "")}
              onClick={() => go(l.route)}
            >
              {l.label}
            </button>
          ))}
        </nav>

        <div className="header-actions">
          <button
            className="icon-btn"
            aria-label="Search"
            onClick={() => {
              setSearchOpen((s) => !s);
            }}
          >
            <SearchIcon />
            <span className="icon-label">Search</span>
          </button>
          <button className="icon-btn cart-btn" aria-label="Cart" onClick={onCartOpen}>
            <BagIcon />
            <span className="icon-label">Cart</span>
            {cartCount > 0 && <span className="cart-count">{cartCount}</span>}
          </button>
          <button
            className="icon-btn menu-btn"
            aria-label="Menu"
            onClick={() => setMenuOpen((m) => !m)}
          >
            <span className={"burger" + (menuOpen ? " open" : "")}>
              <i></i>
              <i></i>
            </span>
          </button>
        </div>
      </div>

      {searchOpen && (
        <div className="header-search">
          <div className="header-search-inner">
            <Eyebrow>Search</Eyebrow>
            <input
              autoFocus
              className="search-input"
              placeholder="Search artists, fields, cities…"
              value={searchValue}
              onChange={(e) => onSearch(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  navigate({ name: "directory" });
                  setSearchOpen(false);
                }
              }}
            />
            <button className="link-btn" onClick={() => { navigate({ name: "directory" }); setSearchOpen(false); }}>
              Browse all →
            </button>
          </div>
        </div>
      )}

      {menuOpen && (
        <div className="nav-mobile">
          {[{ label: "Home", route: "home" }, ...links].map((l) => (
            <button key={l.route} className="nav-mobile-link" onClick={() => go(l.route)}>
              {l.label}
            </button>
          ))}
        </div>
      )}
    </header>
  );
}

// ----- footer -------------------------------------------------------------
function Footer({ navigate }) {
  const cols = [
    { h: "Discover", links: [["Artists", "directory"], ["News", "news"], ["Shop", "shop"]] },
    { h: "Platform", links: [["About", "about"], ["For artists", "about"], ["Contact", "about"]] },
  ];
  return (
    <footer className="site-footer">
      <div className="footer-top">
        <div className="footer-brand">
          <span className="logo-the">the</span>
          <span className="footer-mark">HANDIFY</span>
          <p className="footer-slogan">A world of handmade art</p>
        </div>
        <div className="footer-cols">
          {cols.map((c) => (
            <div className="footer-col" key={c.h}>
              <Eyebrow>{c.h}</Eyebrow>
              {c.links.map(([label, r]) => (
                <button key={label} className="footer-link" onClick={() => navigate({ name: r })}>
                  {label}
                </button>
              ))}
            </div>
          ))}
          <div className="footer-col">
            <Eyebrow>Newsletter</Eyebrow>
            <div className="footer-news">
              <input className="footer-input" placeholder="Email address" />
              <button className="footer-sub">→</button>
            </div>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 The Handify</span>
        <span className="footer-dot">Made for the curious</span>
        <span>Terms · Privacy</span>
      </div>
    </footer>
  );
}

// ----- cart drawer --------------------------------------------------------
function CartDrawer({ open, onClose, cart, works, removeFromCart, navigate, dark }) {
  const items = cart
    .map((c) => {
      const w = works.find((x) => x.id === c.id);
      return w ? { ...w, qty: c.qty } : null;
    })
    .filter(Boolean);
  const subtotal = items.reduce((s, w) => s + (w.price || 0) * w.qty, 0);
  const [stage, setStage] = React.useState("cart"); // cart | checkout | done

  React.useEffect(() => {
    if (open) setStage(items.length ? "cart" : "cart");
    // eslint-disable-next-line
  }, [open]);

  return (
    <React.Fragment>
      <div className={"drawer-scrim" + (open ? " open" : "")} onClick={onClose} />
      <aside className={"cart-drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <Eyebrow>
            {stage === "checkout" ? "Checkout" : stage === "done" ? "Order placed" : `Cart · ${items.length}`}
          </Eyebrow>
          <button className="drawer-close" onClick={onClose} aria-label="Close cart">
            ✕
          </button>
        </div>

        {stage === "done" ? (
          <div className="drawer-done">
            <div className="done-mark">✓</div>
            <h3 className="done-title">Thank you.</h3>
            <p className="done-sub">
              This is a prototype — no payment was taken. Your selection has been noted.
            </p>
            <button className="btn-primary full" onClick={onClose}>
              Keep browsing
            </button>
          </div>
        ) : items.length === 0 ? (
          <div className="drawer-empty">
            <p>Your cart is empty.</p>
            <button
              className="btn-primary"
              onClick={() => {
                onClose();
                navigate({ name: "shop" });
              }}
            >
              Visit the shop
            </button>
          </div>
        ) : (
          <React.Fragment>
            <div className="drawer-items">
              {items.map((w) => (
                <div className="drawer-item" key={w.id}>
                  <div className="drawer-thumb">
                    <ArtImage work={w} dark={dark} captionVisible={false} ratio="1 / 1" />
                  </div>
                  <div className="drawer-item-info">
                    <span className="di-artist">{w.artist.name}</span>
                    <span className="di-title">{w.title}</span>
                    <span className="di-medium">{w.medium}</span>
                    <div className="di-row">
                      <span className="di-price">{fmt(w.price)}</span>
                      <button className="di-remove" onClick={() => removeFromCart(w.id)}>
                        Remove
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="drawer-foot">
              <div className="drawer-subtotal">
                <span>Subtotal</span>
                <span className="subtotal-amt">{fmt(subtotal)}</span>
              </div>
              <p className="drawer-note">Shipping & taxes calculated at checkout.</p>
              {stage === "cart" ? (
                <button className="btn-primary full" onClick={() => setStage("checkout")}>
                  Checkout
                </button>
              ) : (
                <button className="btn-primary full" onClick={() => setStage("done")}>
                  Place order — {fmt(subtotal)}
                </button>
              )}
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

// ----- icons --------------------------------------------------------------
function SearchIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
      <circle cx="11" cy="11" r="7" />
      <line x1="16.5" y1="16.5" x2="21" y2="21" />
    </svg>
  );
}
function BagIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
      <path d="M6 8h12l-1 12H7L6 8z" />
      <path d="M9 8a3 3 0 0 1 6 0" />
    </svg>
  );
}
function ArrowIcon({ dir = "right" }) {
  const rot = { right: 0, left: 180, up: -90, down: 90 }[dir] || 0;
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" style={{ transform: `rotate(${rot}deg)` }}>
      <line x1="4" y1="12" x2="20" y2="12" />
      <polyline points="14 6 20 12 14 18" />
    </svg>
  );
}

// ----- Pagination -----------------------------------------------------------
function Pagination({ page, totalPages, onChange }) {
  if (totalPages <= 1) return null;
  const pages = [];
  const delta = 2;
  for (let i = 1; i <= totalPages; i++) {
    if (i === 1 || i === totalPages || (i >= page - delta && i <= page + delta)) {
      pages.push(i);
    } else if (pages[pages.length - 1] !== "…") {
      pages.push("…");
    }
  }
  return (
    <div className="pagination">
      <button className="pg-btn" disabled={page === 1} onClick={() => { onChange(page - 1); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
        <ArrowIcon dir="left" />
      </button>
      {pages.map((p, i) =>
        p === "…" ? (
          <span key={`e${i}`} className="pg-ellipsis">…</span>
        ) : (
          <button key={p} className={"pg-btn" + (p === page ? " pg-active" : "")} onClick={() => { onChange(p); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
            {p}
          </button>
        )
      )}
      <button className="pg-btn" disabled={page === totalPages} onClick={() => { onChange(page + 1); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
        <ArrowIcon dir="right" />
      </button>
    </div>
  );
}

// ----- SocialLinks ----------------------------------------------------------
function SocialLinks({ artist }) {
  const links = [
    { key: "instagram", label: "Instagram", icon: "IG" },
    { key: "tiktok",    label: "TikTok",    icon: "TT" },
    { key: "facebook",  label: "Facebook",  icon: "FB" },
    { key: "pinterest", label: "Pinterest", icon: "PT" },
    { key: "youtube",   label: "YouTube",   icon: "YT" },
    { key: "twitter",   label: "X",         icon: "X"  },
    { key: "telegram",  label: "Telegram",  icon: "TG" },
    { key: "website",   label: "Website",   icon: "WEB"},
    { key: "shopUrl",   label: "Shop",      icon: "SHOP"},
  ].filter((l) => artist[l.key]);

  const phoneHref = artist.phone ? `tel:${artist.phone.replace(/\s/g,"")}` : null;
  const emailHref = artist.email ? `mailto:${artist.email}` : null;

  if (!links.length && !phoneHref && !emailHref) return null;

  return (
    <div className="social-links">
      {links.map((l) => (
        <a key={l.key} href={artist[l.key]} target="_blank" rel="noopener noreferrer" className="social-chip" title={l.label}>
          <span className="sc-icon">{l.icon}</span>
          <span className="sc-label">{l.label}</span>
        </a>
      ))}
      {phoneHref && (
        <a href={phoneHref} className="social-chip" title="Phone">
          <span className="sc-icon">☎</span>
          <span className="sc-label">{artist.phone}</span>
        </a>
      )}
      {emailHref && (
        <a href={emailHref} className="social-chip" title="Email">
          <span className="sc-icon">@</span>
          <span className="sc-label">{artist.email}</span>
        </a>
      )}
    </div>
  );
}

Object.assign(window, { fmt, Eyebrow, Logo, Ticker, Header, Footer, CartDrawer, SearchIcon, BagIcon, ArrowIcon, Pagination, SocialLinks });
