/* ============================================================
   AfricaMart — App shell & router
   ============================================================ */

// Catches JS errors in any child tree so one broken component
// can't crash the entire SPA.
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(err) { return { error: err }; }
  componentDidCatch(err, info) { console.error("[AfricaMart] Uncaught error:", err, info); }
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div style={{ padding: "80px 24px", textAlign: "center", fontFamily: "DM Sans, sans-serif" }}>
        <div style={{ fontSize: 40, marginBottom: 16 }}>⚠️</div>
        <h2 style={{ fontSize: 22, marginBottom: 8 }}>Something went wrong</h2>
        <p style={{ color: "#666", marginBottom: 24 }}>{this.state.error.message}</p>
        <button onClick={() => { this.setState({ error: null }); window.location.reload(); }}
          style={{ padding: "10px 24px", background: "#1a2e44", color: "#fff", border: "none", borderRadius: 8, cursor: "pointer", fontSize: 15 }}>
          Reload page
        </button>
      </div>
    );
  }
}

function computeSEO(route) {
  const { page, params = {} } = route;
  const base = { url: "/", title: "AfricaMart — Pan-African B2B Marketplace", description: "Source from verified suppliers across all 54 African countries. Steel, agriculture, construction, textiles and more.", ogType: "website" };
  if (page === "browse") return { ...base, url: "/browse" + (params.cat ? "/" + params.cat : ""), title: (params.cat ? AM.catById[params.cat].name + " — " : "") + "Browse products | AfricaMart", description: "Search and compare products from verified African suppliers. Filter by category, country, MOQ and price." };
  if (page === "suppliers") return { ...base, url: "/suppliers", title: "Verified suppliers across Africa | AfricaMart", description: "Discover vetted manufacturers, exporters and distributors across all 54 African countries." };
  if (page === "rfq") return { ...base, url: "/rfq", title: "RFQ Board — Request for Quotation | AfricaMart", description: "Post your sourcing requirements and receive quotes from verified suppliers across Africa." };
  if (page === "auth") return { ...base, url: "/" + (params.mode || "login"), title: (params.mode === "register" ? "Create account" : "Log in") + " | AfricaMart" };
  if (page === "dashboard") return { ...base, url: "/dashboard", title: ((params.role || "buyer") === "supplier" ? "Supplier" : "Buyer") + " dashboard | AfricaMart" };
  if (page === "store") {
    const s = AM.supplierBySlug[params.slug] || AM.SUPPLIERS[0];
    const c = AM.countryByCode[s.country];
    const isPremium = params.variant === "premium" || (params.variant !== "standard" && s.tier === "premium");
    if (isPremium) {
      // white-label: supplier's OWN domain & branding, no AfricaMart
      const domain = "https://www." + s.slug.replace(/-/g, "") + ".com";
      return {
        url: "/", ogType: "website", whiteLabel: true, domain,
        title: s.name + " — " + s.tags.slice(0, 2).join(", ") + " | " + c.name,
        description: s.bio.slice(0, 155),
        jsonld: { "@context": "https://schema.org", "@type": "Organization", name: s.name, url: domain, address: { "@type": "PostalAddress", addressCountry: c.name }, aggregateRating: { "@type": "AggregateRating", ratingValue: s.rating, reviewCount: s.reviews }, makesOffer: s.tags },
      };
    }
    return {
      url: "/store/" + s.slug, ogType: "profile",
      title: s.name + " — " + (s.kind === "service" ? (s.serviceType + " service provider") : "Supplier") + " on AfricaMart | " + c.name,
      description: s.bio.slice(0, 155),
      jsonld: { "@context": "https://schema.org", "@type": s.kind === "service" ? "ProfessionalService" : "Organization", name: s.name, address: { "@type": "PostalAddress", addressCountry: c.name }, aggregateRating: { "@type": "AggregateRating", ratingValue: s.rating, reviewCount: s.reviews }, makesOffer: s.tags },
    };
  }
  if (page === "product") {
    const p = AM.productBySlug[params.slug] || AM.PRODUCTS[0];
    const s = AM.supplierById[p.supplier];
    return {
      url: "/product/" + p.slug, ogType: "product",
      title: p.name + " — " + s.name + " | AfricaMart",
      description: p.desc.slice(0, 155),
      jsonld: { "@context": "https://schema.org", "@type": "Product", name: p.name, sku: p.sku, category: AM.catById[p.cat].name, brand: { "@type": "Brand", name: s.name }, offers: { "@type": "Offer", price: p.priceUSD, priceCurrency: "USD", availability: "https://schema.org/InStock", eligibleQuantity: { "@type": "QuantitativeValue", minValue: p.moq, unitText: p.moqUnit } } },
    };
  }
  return base;
}

function applySEO(seo) {
  document.title = seo.title;
  const root = seo.whiteLabel && seo.domain ? seo.domain : "https://africamart.com";
  const set = (sel, attr, val) => { let el = document.head.querySelector(sel); if (el) el.setAttribute(attr, val); };
  set('meta[name="description"]', "content", seo.description);
  set('link[rel="canonical"]', "href", root + seo.url);
  set('meta[property="og:title"]', "content", seo.title);
  set('meta[property="og:description"]', "content", seo.description);
  set('meta[property="og:url"]', "content", root + seo.url);
  set('meta[property="og:type"]', "content", seo.ogType || "website");
  const ld = document.getElementById("ld-json");
  if (ld) ld.textContent = seo.jsonld ? JSON.stringify(seo.jsonld) : "";
}

function App() {
  const [route, setRoute] = useState({ page: "home", params: {} });
  const [currency, setCurrency] = useState("USD");
  const [auth, setAuth] = useState(null);
  const [toastNode, showToast] = useToast();

  const nav = (page, params = {}) => { setRoute({ page, params }); window.scrollTo({ top: 0, behavior: "instant" }); };

  // ── Restore session on mount + listen for auth changes ───────
  useEffect(() => {
    if (!window.supabaseClient) return;

    // Restore existing session (e.g. after Google OAuth redirect)
    DB.auth.getSession().then(session => {
      if (session?.user) setAuth(DB.buildAuthState(session.user));
    }).catch(() => {});

    // Listen for sign-in / sign-out events
    const { data: { subscription } } = DB.auth.onAuthStateChange((event, session) => {
      if (event === "SIGNED_IN" && session?.user) {
        setAuth(DB.buildAuthState(session.user));
      }
      if (event === "SIGNED_OUT") {
        setAuth(null);
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  const seo = useMemo(() => computeSEO(route), [route]);
  useEffect(() => { applySEO(seo); if (window.lucide) window.lucide.createIcons(); }, [seo]);

  const isFull = route.page === "auth"; // auth has its own full layout (no footer)
  const P = route.params;

  // ----- storefront variant: premium (white-label) vs standard -----
  const storeSupplier = route.page === "store" ? (AM.supplierBySlug[P.slug] || AM.SUPPLIERS[0]) : null;
  const storeVariant = storeSupplier
    ? (P.variant === "premium" || (P.variant !== "standard" && storeSupplier.tier === "premium") ? "premium" : "standard")
    : null;
  const whiteLabel = storeVariant === "premium"; // hides ALL AfricaMart chrome

  return (
    <>
      {!whiteLabel && <Navbar nav={nav} route={route} currency={currency} setCurrency={setCurrency} auth={auth} onSignOut={async () => {
        if (window.supabaseClient) { try { await DB.auth.signOut(); } catch (e) {} }
        setAuth(null); nav("home"); showToast("Signed out");
      }} />}
      <main key={route.page + JSON.stringify(P)}>
        {route.page === "home" && <HomePage nav={nav} currency={currency} />}
        {route.page === "browse" && <BrowsePage nav={nav} currency={currency} params={P} />}
        {route.page === "suppliers" && <SuppliersPage nav={nav} />}
        {route.page === "store" && (storeSupplier.kind === "service"
          ? (storeVariant === "premium"
              ? <PremiumServiceStorePage nav={nav} params={P} showToast={showToast} />
              : <ServiceStorePage nav={nav} params={P} showToast={showToast} />)
          : (storeVariant === "premium"
              ? <PremiumStorePage nav={nav} currency={currency} params={P} showToast={showToast} />
              : <StorePage nav={nav} currency={currency} params={P} showToast={showToast} />))}
        {route.page === "product" && <ProductPage nav={nav} currency={currency} params={P} showToast={showToast} />}
        {route.page === "rfq" && <RFQPage nav={nav} showToast={showToast} />}
        {route.page === "auth" && <AuthPage nav={nav} params={P} onAuth={setAuth} showToast={showToast} />}
        {route.page === "dashboard" && <DashboardPage nav={nav} params={P} showToast={showToast} />}
      </main>
      {!isFull && route.page !== "dashboard" && !whiteLabel && <Footer nav={nav} />}
      {!whiteLabel && <SEOInspector seo={seo} />}
      {route.page === "store" && <StorePreviewSwitch supplier={storeSupplier} variant={storeVariant} nav={nav} />}
      {toastNode}
    </>
  );
}

function mountApp() {
  const loader = document.getElementById("am-loader");
  if (loader) loader.remove();
  ReactDOM.createRoot(document.getElementById("root")).render(
    <ErrorBoundary><App /></ErrorBoundary>
  );
}

// If data-loader already finished before this script ran, mount now.
// Otherwise wait for the "am:ready" event it fires.
if (window.AM_READY) {
  mountApp();
} else {
  document.addEventListener("am:ready", mountApp, { once: true });
}
