/* ============================================================
   AfricaMart — Supplier storefront (modern, single-scroll)
   ============================================================ */
function StorePage({ nav, currency, params, showToast }) {
  const s = AM.supplierBySlug[params.slug] || AM.SUPPLIERS[0];
  const c = AM.countryByCode[s.country];
  const x = extras(s);
  const [saved, setSaved] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [stuck, setStuck] = useState(false);

  const SECS = ["products", "capabilities", "about", "certs", "reviews", "contact"];
  const SEC_LABELS = { products: "Products", capabilities: "Capabilities", about: "About", certs: "Certifications", reviews: "Reviews", contact: "Contact" };
  const active = useScrollSpy(SECS);

  useEffect(() => {
    const onScroll = () => setStuck(window.scrollY > 360);
    onScroll(); window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const ribbon = [
    { value: x.years + " yrs", label: "In business" },
    { value: x.transactions, label: "Transactions" },
    { value: s.responseRate + "%", label: "Response rate" },
    { value: x.onTime + "%", label: "On-time delivery" },
    { value: x.reorder + "%", label: "Reorder rate" },
    { value: s.rating, label: s.reviews + " reviews" },
  ];

  const goContact = () => scrollToSec("contact");
  const initials = s.name.split(" ").map(w => w[0]).slice(0, 3).join("");

  return (
    <div className="route-anim store-root">
      {/* ===== Sticky compact bar ===== */}
      <div style={{
        position: "sticky", top: "var(--nav-h)", zIndex: 40,
        transform: stuck ? "translateY(0)" : "translateY(-110%)", opacity: stuck ? 1 : 0,
        transition: "transform .28s cubic-bezier(.16,1,.3,1), opacity .2s",
        background: "rgba(255,255,255,.94)", backdropFilter: "blur(12px)", borderBottom: "1px solid var(--border)", boxShadow: "var(--sh-sm)",
      }}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 24px" }}>
          <div style={{ width: 34, height: 34, borderRadius: 8, background: s.color + "1a", color: s.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13, flexShrink: 0 }}>{initials}</div>
          <div style={{ fontWeight: 700, fontSize: 14.5, display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
            <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.name}</span>
            {s.verified && <Icon name="badge-check" size={15} style={{ color: "var(--gold-600)", flexShrink: 0 }} />}
          </div>
          <span className="stuck-rating muted" style={{ fontSize: 13, display: "inline-flex", alignItems: "center", gap: 5 }}><Stars value={s.rating} size={12} /> {s.rating}</span>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={goContact}>Request quote</button>
            <button className="btn btn-gold btn-sm" onClick={goContact}><Icon name="mail" size={15} /> Send inquiry</button>
          </div>
        </div>
      </div>

      {/* ===== Hero banner ===== */}
      <div className="store-hero" style={{ height: 260, background: "linear-gradient(115deg, " + s.color + " 0%, var(--navy-700) 60%, var(--navy-800) 100%)", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, opacity: .4, backgroundImage: "linear-gradient(rgba(255,255,255,.07) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.07) 1px, transparent 1px)", backgroundSize: "44px 44px" }} />
        <div style={{ position: "absolute", top: -90, right: 60, width: 340, height: 340, borderRadius: "50%", background: "radial-gradient(circle, rgba(232,184,75,.20), transparent 70%)" }} />
        {/* floating product tags */}
        <div className="hero-tags" style={{ position: "absolute", right: 40, bottom: 70, display: "flex", flexDirection: "column", gap: 10, alignItems: "flex-end" }}>
          {s.tags.slice(0, 3).map((t, i) => (
            <span key={t} style={{ background: "rgba(255,255,255,.12)", border: "1px solid rgba(255,255,255,.2)", color: "#fff", padding: "6px 14px", borderRadius: 999, fontSize: 13, fontWeight: 500, backdropFilter: "blur(4px)", marginRight: i * 18 }}>{t}</span>
          ))}
        </div>
        {/* verified ribbon */}
        {s.verified && (
          <div style={{ position: "absolute", top: 20, left: 24, display: "inline-flex", alignItems: "center", gap: 7, background: "rgba(232,184,75,.16)", border: "1px solid rgba(232,184,75,.4)", color: "var(--gold-400)", padding: "6px 13px", borderRadius: 999, fontSize: 12.5, fontWeight: 700, backdropFilter: "blur(4px)" }}>
            <Icon name="shield-check" size={14} /> AfricaMart Verified Supplier
          </div>
        )}
      </div>

      <div className="wrap" style={{ padding: "0 24px" }}>
        {/* ===== Profile header card ===== */}
        <div className="card store-header" style={{ marginTop: -64, padding: 24, display: "flex", gap: 22, alignItems: "flex-start", flexWrap: "wrap", position: "relative", zIndex: 2 }}>
          <div style={{ width: 104, height: 104, borderRadius: 20, background: s.color + "22", color: s.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 36, flexShrink: 0, border: "4px solid #fff", boxShadow: "var(--sh-md)" }}>{initials}</div>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <h1 style={{ fontSize: 27, letterSpacing: "-.02em" }}>{s.name}</h1>
              {s.verified && s.tier !== "verified" && <span className="badge badge-verified"><Icon name="badge-check" size={12} /> Verified</span>}
              <TierBadge tier={s.tier} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 11, flexWrap: "wrap", fontSize: 14, color: "var(--ink-600)" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Flag code={s.country} size={15} /> {c.name}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="building-2" size={15} style={{ color: "var(--ink-400)" }} /> {s.type}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Stars value={s.rating} /> <b style={{ color: "var(--ink-900)" }}>{s.rating}</b> <span className="muted">({s.reviews})</span></span>
              <span className="badge badge-green"><Icon name="zap" size={12} /> Replies {s.responseTime}</span>
            </div>
            <p className="muted" style={{ marginTop: 12, fontSize: 14, lineHeight: 1.55, maxWidth: 640 }}>{s.bio.slice(0, 150)}…</p>
          </div>
          <div className="store-cta" style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 210 }}>
            <button className="btn btn-gold btn-block" onClick={goContact}><Icon name="mail" size={16} /> Send inquiry</button>
            <button className="btn btn-navy btn-block" onClick={goContact}><Icon name="file-text" size={16} /> Request quote</button>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => { setSaved(!saved); showToast(saved ? "Removed from saved" : "Saved supplier", saved ? "heart" : "heart"); }}>
                <Icon name="heart" size={16} style={{ fill: saved ? "var(--red-600)" : "none", color: saved ? "var(--red-600)" : "currentColor" }} /> {saved ? "Saved" : "Save"}
              </button>
              <div style={{ position: "relative", flex: 1 }}>
                <button className="btn btn-ghost btn-block" onClick={() => setShareOpen(o => !o)}><Icon name="share-2" size={16} /> Share</button>
                {shareOpen && (
                  <div className="card route-anim" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, padding: 6, zIndex: 10, width: 160, boxShadow: "var(--sh-md)" }}>
                    {[["link", "Copy link"], ["mail", "Email"], ["message-circle", "WhatsApp"]].map(([ic, l]) => (
                      <button key={l} onClick={() => { setShareOpen(false); showToast(l === "Copy link" ? "Link copied" : "Sharing via " + l); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "9px 10px", borderRadius: 7, fontSize: 13.5, fontWeight: 500 }} onMouseEnter={e => e.currentTarget.style.background = "var(--navy-50)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                        <Icon name={ic} size={15} style={{ color: "var(--ink-500)" }} /> {l}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* ===== Trust ribbon ===== */}
        <div className="card store-ribbon" style={{ marginTop: 14, padding: 0, display: "grid", gridTemplateColumns: "repeat(6,1fr)", overflow: "hidden" }}>
          {ribbon.map((r, i) => (
            <div key={r.label} style={{ padding: "18px 16px", borderLeft: i ? "1px solid var(--border)" : "none", textAlign: "center" }}>
              <div style={{ fontSize: 22, fontWeight: 800, color: "var(--navy-800)", letterSpacing: "-.02em" }}>{r.value}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>{r.label}</div>
            </div>
          ))}
        </div>

        {/* ===== Section nav (sticky) ===== */}
        <nav className="store-nav thin-scroll" style={{ position: "sticky", top: "var(--nav-h)", zIndex: 30, background: "var(--paper)", display: "flex", gap: 4, marginTop: 18, borderBottom: "1px solid var(--border)", overflowX: "auto" }}>
          {SECS.map(id => (
            <button key={id} onClick={() => scrollToSec(id)} style={{
              padding: "14px 16px", fontWeight: 600, fontSize: 14.5, whiteSpace: "nowrap",
              color: active === id ? "var(--navy-800)" : "var(--ink-500)",
              borderBottom: "2.5px solid " + (active === id ? "var(--gold-500)" : "transparent"), marginBottom: -1,
            }}>{SEC_LABELS[id]}</button>
          ))}
        </nav>

        {/* ===== Sections ===== */}
        <StoreProducts supplier={s} nav={nav} currency={currency} showToast={showToast} />
        <StoreCapabilities supplier={s} />
        <StoreAbout supplier={s} />
        <StoreCerts supplier={s} showToast={showToast} />
        <StoreReviews supplier={s} />
        <StoreContact supplier={s} showToast={showToast} />
        <div style={{ height: 48 }} />
      </div>

      {/* ===== Floating chat ===== */}
      <button onClick={goContact} title="Chat with supplier" style={{
        position: "fixed", left: 18, bottom: 18, zIndex: 55, height: 50, borderRadius: 999, padding: "0 20px",
        background: "var(--navy-800)", color: "#fff", boxShadow: "var(--sh-lg)", display: "flex", alignItems: "center", gap: 9, fontWeight: 600, fontSize: 14,
      }}>
        <Icon name="message-circle" size={20} style={{ color: "var(--gold-400)" }} /> Chat
      </button>
    </div>
  );
}

/* ---------- Inquiry form (shared with product page) ---------- */
function InquiryForm({ supplier, product, showToast }) {
  const [sent, setSent] = useState(false);
  if (sent) return (
    <div className="card route-anim" style={{ padding: 40, textAlign: "center" }}>
      <div style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--green-50)", color: "var(--green-600)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
        <Icon name="check" size={30} />
      </div>
      <h3 style={{ fontSize: 20 }}>Inquiry sent to {supplier.name}</h3>
      <p className="muted" style={{ marginTop: 8 }}>They typically reply {supplier.responseTime}. You'll get an email and can track it in your dashboard.</p>
      <button className="btn btn-ghost" style={{ marginTop: 18 }} onClick={() => setSent(false)}>Send another</button>
    </div>
  );
  return (
    <form className="card" style={{ padding: 28 }} onSubmit={e => { e.preventDefault(); setSent(true); showToast && showToast("Inquiry sent to " + supplier.name); }}>
      <h3 style={{ fontSize: 19, marginBottom: 4 }}>Send inquiry</h3>
      <p className="muted" style={{ fontSize: 13.5, marginBottom: 18 }}>to {supplier.name}{product ? " · about " + product.name : ""}</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div><label className="field-label">Quantity needed</label><input className="input" placeholder="e.g. 50 MT" required /></div>
        <div><label className="field-label">Delivery country</label>
          <select className="select" required defaultValue="">
            <option value="" disabled>Select…</option>
            {AM.COUNTRIES.map(co => <option key={co.code}>{co.name}</option>)}
          </select>
        </div>
      </div>
      <div style={{ marginTop: 14 }}><label className="field-label">Message</label>
        <textarea className="textarea" rows="4" defaultValue={product ? "Hi, I'm interested in " + product.name + ". Please share your best price and lead time." : "Hi, I'd like more information about your products."} required /></div>
      <label style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, fontSize: 13.5, color: "var(--ink-600)" }}>
        <input type="checkbox" defaultChecked style={{ width: 15, height: 15, accentColor: "var(--navy-700)" }} /> Request a formal quotation (RFQ)
      </label>
      <button type="submit" className="btn btn-gold btn-block btn-lg" style={{ marginTop: 18 }}><Icon name="send" size={16} /> Send inquiry</button>
    </form>
  );
}

Object.assign(window, { StorePage, InquiryForm });
