// shared.jsx — reusable chrome + primitives. Exported to window.
const { Icon } = window;

function Logo({ onClick, className }) {
  return (
    <button className={"brandlogo " + (className || "")} onClick={onClick} aria-label="MegaTech home">
      <img src="assets/logo-megatech-mark.png" alt="MegaTech" />
    </button>
  );
}

function Badge({ badge, lang }) {
  if (!badge) return null;
  return <span className={"badge badge--" + (badge.tone || "neutral")}>{badge[lang]}</span>;
}

function Stars({ value = 0, size = 15 }) {
  const full = Math.round(value);
  return (
    <span className="stars" aria-label={value + " out of 5"}>
      {[1, 2, 3, 4, 5].map((i) => (
        <Icon key={i} name="star" size={size} stroke={0} fill="currentColor"
          className={i <= full ? "" : "empty"} />
      ))}
    </span>
  );
}

function StockLine({ stock, t }) {
  if (stock <= 0) return <span className="stockline stockline--out"><span className="dot" style={{ background: "var(--fg4)" }} />{t.outOfStock}</span>;
  if (stock <= 12) return <span className="stockline stockline--low"><span className="dot" style={{ background: "var(--warning)" }} />{t.lowStock} · {stock} {t.unitsLeft}</span>;
  return <span className="stockline stockline--in"><span className="dot" style={{ background: "var(--success)" }} />{t.inStock}</span>;
}

function QtyStepper({ value, onChange, small, max = 99 }) {
  return (
    <div className={"qty " + (small ? "qty--sm" : "")}>
      <button onClick={() => onChange(Math.max(1, value - 1))} aria-label="Decrease"><Icon name="minus" size={small ? 16 : 18} /></button>
      <span className="v num-tabular">{value}</span>
      <button onClick={() => onChange(Math.min(max, value + 1))} aria-label="Increase"><Icon name="plus" size={small ? 16 : 18} /></button>
    </div>
  );
}

// Product image: shows the admin-uploaded photo, or a static category placeholder if none.
function ProductMedia({ product, lang = "en" }) {
  if (product.img) {
    return <img src={product.img} alt={product.name[lang]}
      style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />;
  }
  return (
    <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg-raised)" }}>
      <CatMedallion catId={product.cat} size={64} />
    </div>
  );
}

// Renders an uploaded image icon if the category has one, else the line icon.
function CatGlyph({ cat, size = 24 }) {
  if (cat && cat.img) {
    return <img src={cat.img} alt="" style={{ width: size, height: size, objectFit: "contain", display: "block" }} />;
  }
  return <Icon name={(cat && cat.icon) || "package"} size={size} />;
}

// Small inline category-icon medallion (used in cart/table/thumbs where no slot)
function CatMedallion({ catId, size = 26 }) {
  const { CATEGORIES } = window;
  const c = CATEGORIES.find((x) => x.id === catId);
  return <CatGlyph cat={c} size={size} />;
}

function AnnouncementBar({ t }) {
  return (
    <div className="announce">
      <Icon name="truck" size={15} />
      <span>{t.announce}</span>
    </div>
  );
}

function TopBar({ t, lang, onToggleLang, view, onSetView, cartCount, onOpenCart, onLogo, query, onQuery, auth, onSignIn, onSignOut, onAdmin, onAction, onNav, onProducts, onSolutions }) {
  const { AccountMenu } = window;
  return (
    <header className="topbar">
      <div className="container">
        <div className="topbar__row">
          <Logo onClick={onLogo} />
          {view !== "admin" && (
            <nav className="nav">
              <button className="nav__link" onClick={onProducts}>{t.navProducts}</button>
              <button className="nav__link" onClick={onSolutions}>{t.navSolutions}</button>
              <button className="nav__link" onClick={() => onNav("support")}>{t.navContact}</button>
            </nav>
          )}
          {view !== "admin" && (
            <div className="searchbar">
              <Icon name="search" size={18} />
              <input value={query} onChange={(e) => onQuery(e.target.value)} placeholder={t.search} />
            </div>
          )}
          <div className="topbar__actions">
            <button className="langtoggle" onClick={onToggleLang} aria-label="Toggle language">
              <Icon name="globe" size={17} />{lang === "en" ? "العربية" : "EN"}
            </button>
            {view !== "admin" && (
              <button className="iconbtn" onClick={onOpenCart} aria-label="Open cart">
                <Icon name="cart" size={22} />
                {cartCount > 0 && <span className="iconbtn__count num-tabular">{cartCount}</span>}
              </button>
            )}
            {auth ? (
              <AccountMenu auth={auth} lang={lang} t={t} onAdmin={onAdmin} onSignOut={onSignOut} onAction={onAction} />
            ) : (
              <button className="btn btn--secondary" onClick={onSignIn}>
                <Icon name="user" size={18} />{t.signIn}
              </button>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}

function TrustBar({ t }) {
  const items = [
    { ic: "shield", title: t.trustWarranty, sub: "MegaTech certified" },
    { ic: "truck", title: t.trustShipping, sub: "2–4 business days" },
    { ic: "headset", title: t.trustSupport, sub: "Phone · chat · on-site" },
    { ic: "refresh", title: t.trustReturns, sub: "No-questions returns" },
  ];
  return (
    <div className="trustbar">
      <div className="container">
        <div className="trustbar__row">
          {items.map((it) => (
            <div className="trustitem" key={it.ic}>
              <div className="ic"><Icon name={it.ic} size={22} /></div>
              <div>
                <div className="t">{it.title}</div>
                <div className="s">{it.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Footer({ t, lang }) {
  const cols = [
    { h: t.fHardware, links: ["Cashier systems", "Receipt printers", "Barcode scanners", "Cash drawers", "Customer displays"] },
    { h: t.fSolutions, links: ["Retail", "Restaurants", "Pharmacies", "Supermarkets", "Enterprise"] },
    { h: t.fSupport, links: ["Help center", "Installation", "Warranty"] },
  ];
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__top">
          <div className="footer__brand">
            <span className="logo"><img src="assets/logo-megatech.png" alt="MegaTech" /></span>
            <p>{t.footerTag}. {lang === "en" ? "Point-of-sale hardware and software, deployed and supported across the region." : "أجهزة وبرمجيات نقاط البيع، مُركّبة ومدعومة في كل المنطقة."}</p>
          </div>
          {cols.map((c) => (
            <div className="footer__col" key={c.h}>
              <h5>{c.h}</h5>
              {c.links.map((l) => <a key={l}>{l}</a>)}
            </div>
          ))}
        </div>
        <div className="footer__bottom">
          <span className="copy">{t.rights}</span>
          <div className="footer__pays">
            {["credit-card", "credit-card", "cash", "shield"].map((p, i) => (
              <span className="pay" key={i}><Icon name={p} size={16} /></span>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Logo, Badge, Stars, StockLine, QtyStepper, ProductMedia, CatGlyph, CatMedallion, AnnouncementBar, TopBar, TrustBar, Footer });
