/* ============================================================
   AfricaMart — Shared components
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;
const AM = window.AM;

/* ---------- Lucide icon ---------- */
function Icon({ name, size = 20, sw = 1.6, className = "", style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const i = document.createElement("i");
      i.setAttribute("data-lucide", name);
      i.setAttribute("width", size);
      i.setAttribute("height", size);
      i.setAttribute("stroke-width", sw);
      ref.current.appendChild(i);
      window.lucide.createIcons();
    }
  }, [name, size, sw]);
  return <span ref={ref} className={"lic " + className}
    style={{ display: "inline-flex", width: size, height: size, lineHeight: 0, ...style }} />;
}

/* ---------- Flag chip (3 vertical stripes) ---------- */
function Flag({ code, size = 18, round = false }) {
  const c = AM.countryByCode[code];
  if (!c) return null;
  const [a, b, d] = c.flag;
  return (
    <span title={c.name} style={{
      display: "inline-block", width: size * 1.4, height: size, borderRadius: round ? "50%" : 3,
      overflow: "hidden", border: "1px solid rgba(0,0,0,.12)", flexShrink: 0, verticalAlign: "middle",
    }}>
      <span style={{ display: "flex", width: "100%", height: "100%" }}>
        <span style={{ flex: 1, background: a }} />
        <span style={{ flex: 1, background: b }} />
        <span style={{ flex: 1, background: d }} />
      </span>
    </span>
  );
}

/* ---------- Stars ---------- */
function Stars({ value, size = 14 }) {
  const full = Math.floor(value);
  const half = value - full >= 0.5;
  return (
    <span className="stars" aria-label={value + " out of 5"}>
      {[0, 1, 2, 3, 4].map(i => (
        <Icon key={i} name={i < full ? "star" : (i === full && half ? "star-half" : "star")}
          size={size} sw={i < full || (i === full && half) ? 0 : 1.6}
          style={{ fill: i < full || (i === full && half) ? "var(--gold-500)" : "none",
            color: i < full || (i === full && half) ? "var(--gold-500)" : "var(--ink-300)" }} />
      ))}
    </span>
  );
}

/* ---------- Price formatting ---------- */
function fmtPrice(usd, cur = "USD") {
  const c = AM.CURRENCIES[cur] || AM.CURRENCIES.USD;
  const v = usd * c.rate;
  const formatted = v >= 100
    ? Math.round(v).toLocaleString()
    : v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return c.sym + formatted;
}

/* ---------- Category icon tile ---------- */
function CatIcon({ cat, size = 26 }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      width: size + 20, height: size + 20, borderRadius: 12,
      background: cat.hue + "16", color: cat.hue, flexShrink: 0,
    }}>
      <Icon name={cat.icon} size={size} sw={1.7} />
    </span>
  );
}

/* ---------- Product image placeholder ---------- */
function ProductPh({ product, h = 200, icon }) {
  const cat = AM.catById[product.cat];
  return (
    <div className="ph" style={{ height: h, background: cat.hue + "0e" }}>
      <Icon name={icon || cat.icon} size={Math.min(h * 0.32, 64)} sw={1.2}
        className="ph-icon" style={{ color: cat.hue + "88" }} />
      <span className="mono" style={{
        position: "absolute", bottom: 8, left: 10, fontSize: 10, color: "var(--ink-400)",
        background: "rgba(255,255,255,.7)", padding: "2px 6px", borderRadius: 4, zIndex: 1,
      }}>{product.sku}</span>
    </div>
  );
}

/* ---------- Tier badge ---------- */
function TierBadge({ tier }) {
  if (tier === "premium") return <span className="badge badge-premium"><Icon name="crown" size={11} /> Premium</span>;
  if (tier === "verified") return <span className="badge badge-verified"><Icon name="badge-check" size={11} /> Verified</span>;
  return <span className="badge badge-gray">Free</span>;
}

/* ---------- Product card ---------- */
function ProductCard({ product, nav, cur = "USD" }) {
  const s = AM.supplierById[product.supplier];
  return (
    <a className="card" onClick={() => nav("product", { slug: product.slug })} style={{
      cursor: "pointer", overflow: "hidden", display: "flex", flexDirection: "column",
      transition: "transform .16s, box-shadow .16s",
    }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = "var(--sh-md)"; e.currentTarget.style.transform = "translateY(-3px)"; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = "var(--sh-sm)"; e.currentTarget.style.transform = "none"; }}>
      <ProductPh product={product} h={172} />
      <div style={{ padding: "14px 16px 16px", display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 15, lineHeight: 1.3, minHeight: 38 }}>{product.name}</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
          <span style={{ fontWeight: 700, fontSize: 19, color: "var(--navy-800)" }}>{fmtPrice(product.priceUSD, cur)}</span>
          <span className="muted" style={{ fontSize: 13 }}>/ {product.unit}</span>
        </div>
        <div className="muted" style={{ fontSize: 12.5 }}>MOQ {product.moq} {product.moqUnit}</div>
        <div style={{ marginTop: "auto", paddingTop: 10, borderTop: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 7 }}>
          <Flag code={s.country} size={14} />
          <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--ink-700)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.name}</span>
          {s.verified && <Icon name="badge-check" size={14} style={{ color: "var(--gold-600)", marginLeft: "auto", flexShrink: 0 }} />}
        </div>
      </div>
    </a>
  );
}

/* ---------- Supplier card ---------- */
function SupplierCard({ supplier, nav }) {
  const c = AM.countryByCode[supplier.country];
  return (
    <a className="card" onClick={() => nav("store", { slug: supplier.slug })} style={{
      cursor: "pointer", padding: 18, display: "flex", flexDirection: "column", gap: 12,
      transition: "transform .16s, box-shadow .16s",
    }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = "var(--sh-md)"; e.currentTarget.style.transform = "translateY(-3px)"; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = "var(--sh-sm)"; e.currentTarget.style.transform = "none"; }}>
      <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
        <div style={{
          width: 52, height: 52, borderRadius: 12, background: supplier.color + "1a",
          color: supplier.color, display: "flex", alignItems: "center", justifyContent: "center",
          fontWeight: 700, fontSize: 20, flexShrink: 0,
        }}>{supplier.name.split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 15.5, display: "flex", alignItems: "center", gap: 6 }}>
            {supplier.name}
            {supplier.verified && <Icon name="badge-check" size={15} style={{ color: "var(--gold-600)" }} />}
          </div>
          <div className="muted" style={{ fontSize: 13, display: "flex", alignItems: "center", gap: 6, marginTop: 3 }}>
            <Flag code={supplier.country} size={13} /> {c.name} · {supplier.type}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13 }}>
        <Stars value={supplier.rating} /> <b>{supplier.rating}</b>
        <span className="muted">({supplier.reviews})</span>
        <span style={{ marginLeft: "auto" }}><TierBadge tier={supplier.tier} /></span>
      </div>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        {supplier.tags.slice(0, 3).map(t => (
          <span key={t} className="badge badge-gray">{t}</span>
        ))}
      </div>
    </a>
  );
}

Object.assign(window, {
  Icon, Flag, Stars, fmtPrice, CatIcon, ProductPh, TierBadge, ProductCard, SupplierCard,
});
