/* ============================================================
   AfricaMart — Buyer & Supplier dashboards
   ============================================================ */
function DashboardPage({ nav, params, showToast }) {
  const [authUser, setAuthUser] = useState(null);
  const [authChecked, setAuthChecked] = useState(!window.supabaseClient);
  const [section, setSection] = useState("overview");

  useEffect(() => {
    if (!window.supabaseClient) return;
    DB.auth.getSession().then(session => {
      if (session && session.user) setAuthUser(session.user);
      else nav("auth", { mode: "login" });
    }).catch(() => {}).finally(() => setAuthChecked(true));
  }, []);

  const authState = authUser ? DB.auth.buildAuthState(authUser) : null;
  const myRole = authState ? authState.role : "buyer";
  const role = params.role || myRole;
  const isOwnRole = role === myRole;

  useEffect(() => { setSection("overview"); }, [role]);

  if (!authChecked) {
    return <div style={{ padding: "100px 0", textAlign: "center" }}><Icon name="loader-circle" size={28} className="spin" style={{ color: "var(--ink-400)" }} /></div>;
  }
  if (window.supabaseClient && !authUser) return null;

  const buyerNav = [
    ["overview", "Overview", "layout-dashboard"],
    ["rfqs", "My RFQs", "file-text"],
    ["saved", "Saved & wishlist", "heart"],
    ["inquiries", "Inquiries & chat", "messages-square"],
    ["settings", "Profile settings", "settings"],
  ];
  const supplierNav = [
    ["overview", "Overview", "layout-dashboard"],
    ["products", "Products", "package"],
    ["store", "Store page", "store"],
    ["inbox", "Inquiry inbox", "inbox"],
    ["analytics", "Analytics", "bar-chart-3"],
    ["settings", "Profile settings", "settings"],
  ];
  const menu = role === "supplier" ? supplierNav : buyerNav;

  const displayName = isOwnRole && authState ? (role === "supplier" ? (authState.company || authState.name) : authState.name) : (role === "supplier" ? "Savannah Steel Works" : "Amina Okoye");
  const displaySub = isOwnRole && authState ? (authState.company || authState.email) : "Rift Valley Co.";
  const displayInitials = isOwnRole && authState ? authState.initials : (role === "supplier" ? "SW" : "AO");

  const signOut = async () => {
    if (window.supabaseClient && DB.auth) { try { await DB.auth.signOut(); } catch (e) {} }
    nav("home");
  };

  return (
    <div className="route-anim dash-layout" style={{ display: "grid", gridTemplateColumns: "230px minmax(0,1fr)", minHeight: "calc(100vh - var(--nav-h))" }}>
      {/* sidebar */}
      <aside className="dash-side" style={{ background: "#fff", borderRight: "1px solid var(--border)", padding: "20px 14px" }}>
        <div style={{ padding: "0 8px 14px", borderBottom: "1px solid var(--border)", marginBottom: 12 }}>
          <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase" }}>{role} account</div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 10 }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--navy-800)", color: "var(--gold-400)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>{displayInitials}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{displayName}</div>
              {role === "supplier" ? <TierBadge tier="premium" /> : <span className="muted" style={{ fontSize: 12, display: "block", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{displaySub}</span>}
            </div>
          </div>
        </div>
        {menu.map(([id, label, icon]) => (
          <button key={id} onClick={() => setSection(id)} style={{
            display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 12px", borderRadius: 9,
            fontWeight: 600, fontSize: 14, marginBottom: 2, textAlign: "left",
            color: section === id ? "var(--navy-800)" : "var(--ink-600)", background: section === id ? "var(--navy-50)" : "transparent",
          }}>
            <Icon name={icon} size={18} style={{ color: section === id ? "var(--gold-700)" : "var(--ink-400)" }} /> {label}
          </button>
        ))}
        <button onClick={signOut} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 12px", borderRadius: 9, fontWeight: 600, fontSize: 14, color: "var(--ink-500)", marginTop: 8 }}>
          <Icon name="log-out" size={18} style={{ color: "var(--ink-400)" }} /> Sign out
        </button>
        {/* role switcher (demo aid) */}
        <div style={{ marginTop: 16, padding: "10px 8px", background: "var(--navy-50)", borderRadius: 10, fontSize: 12 }}>
          <div className="muted" style={{ marginBottom: 6 }}>Preview as</div>
          <div style={{ display: "flex", gap: 6 }}>
            <button className={role === "buyer" ? "btn btn-navy btn-sm" : "btn btn-ghost btn-sm"} style={{ flex: 1, padding: "6px 0", fontSize: 12 }} onClick={() => nav("dashboard", { role: "buyer" })}>Buyer</button>
            <button className={role === "supplier" ? "btn btn-navy btn-sm" : "btn btn-ghost btn-sm"} style={{ flex: 1, padding: "6px 0", fontSize: 12 }} onClick={() => nav("dashboard", { role: "supplier" })}>Supplier</button>
          </div>
        </div>
      </aside>

      {/* content */}
      <div style={{ padding: "28px 32px 64px", background: "var(--paper)" }} className="dash-content">
        {role === "buyer"
          ? <BuyerSection section={section} nav={nav} showToast={showToast} authUser={authUser} authState={authState} isOwnRole={isOwnRole} />
          : <SupplierSection section={section} nav={nav} showToast={showToast} authUser={authUser} authState={authState} isOwnRole={isOwnRole} />}
      </div>
    </div>
  );
}

function DashHead({ title, sub, action }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 22, flexWrap: "wrap", gap: 12 }}>
      <div><h1 style={{ fontSize: 24 }}>{title}</h1>{sub && <p className="muted" style={{ marginTop: 5 }}>{sub}</p>}</div>
      {action}
    </div>
  );
}
function KPI({ label, value, delta, icon }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span className="muted" style={{ fontSize: 13 }}>{label}</span>
        <Icon name={icon} size={18} style={{ color: "var(--ink-400)" }} />
      </div>
      <div style={{ fontSize: 28, fontWeight: 800, color: "var(--navy-800)", marginTop: 8 }}>{value}</div>
      {delta && <div style={{ fontSize: 12.5, color: "var(--green-600)", fontWeight: 600, marginTop: 2, display: "flex", alignItems: "center", gap: 3 }}><Icon name="trending-up" size={13} /> {delta}</div>}
    </div>
  );
}

/* ---------------- BUYER ---------------- */
function BuyerSection({ section, nav, showToast, authUser, authState, isOwnRole }) {
  const [rfqs, setRfqs] = useState(null);

  useEffect(() => {
    if (!isOwnRole || !window.supabaseClient || !DB.auth || !DB.dashboard) return;
    DB.auth.ensureBuyerRecord(authUser)
      .then(buyer => DB.dashboard.getBuyerRFQs(buyer.id))
      .then(setRfqs)
      .catch(() => {});
  }, [isOwnRole, authUser]);

  const myRfqs = rfqs !== null ? rfqs : AM.RFQS;
  const firstName = isOwnRole && authState ? authState.name.split(" ")[0] : "Amina";

  if (section === "overview") return (
    <>
      <DashHead title={"Welcome back, " + firstName} sub="Here's what's happening with your sourcing." action={<button className="btn btn-gold" onClick={() => nav("rfq")}><Icon name="plus" size={16} /> Post RFQ</button>} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 14, marginBottom: 24 }}>
        <KPI label="Active RFQs" value={String(myRfqs.filter(r => r.status === "open").length)} icon="file-text" />
        <KPI label="Quotes received" value={rfqs !== null ? String(myRfqs.reduce((sum, r) => sum + (r.quotes || 0), 0)) : "19"} delta={rfqs === null ? "+7 this week" : null} icon="inbox" />
        <KPI label="Saved suppliers" value="12" icon="heart" />
        <KPI label="Open inquiries" value="5" icon="messages-square" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1fr)", gap: 18 }}>
        <div className="card" style={{ padding: 20 }}>
          <h3 style={{ fontSize: 16, marginBottom: 14 }}>Recent quotes</h3>
          {myRfqs.length === 0 && <p className="muted" style={{ padding: "12px 0" }}>No RFQs posted yet.</p>}
          {myRfqs.slice(0, 3).map(r => (
            <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderTop: "1px solid var(--border)" }}>
              <CatIcon cat={AM.catById[r.cat]} size={18} />
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.title}</div><div className="muted" style={{ fontSize: 12.5 }}>{r.quotes} quotes · deadline {r.deadline}</div></div>
              <button className="btn btn-ghost btn-sm" onClick={() => nav("rfq")}>View</button>
            </div>
          ))}
        </div>
        <div className="card" style={{ padding: 20 }}>
          <h3 style={{ fontSize: 16, marginBottom: 14 }}>Saved suppliers</h3>
          {AM.SUPPLIERS.slice(0, 3).map(s => (
            <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderTop: "1px solid var(--border)", cursor: "pointer" }} onClick={() => nav("store", { slug: s.slug })}>
              <div style={{ width: 34, height: 34, borderRadius: 8, background: s.color + "1a", color: s.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 13 }}>{s.name.split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.name}</div><div className="muted" style={{ fontSize: 12 }}><Stars value={s.rating} size={11} /> {s.rating}</div></div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
  if (section === "rfqs") return (
    <>
      <DashHead title="My RFQs" sub="Requests for quotation you've posted" action={<button className="btn btn-gold" onClick={() => nav("rfq")}><Icon name="plus" size={16} /> New RFQ</button>} />
      <div className="card" style={{ overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead><tr style={{ background: "var(--navy-50)", textAlign: "left" }}>{["RFQ", "Quantity", "Quotes", "Deadline", "Status"].map(h => <th key={h} style={{ padding: "12px 16px", fontSize: 12.5, fontWeight: 700, color: "var(--ink-500)" }}>{h}</th>)}</tr></thead>
          <tbody>
            {myRfqs.length === 0 && <tr><td colSpan={5} className="muted" style={{ padding: "20px 16px", textAlign: "center" }}>You haven't posted any RFQs yet.</td></tr>}
            {myRfqs.slice(0, 4).map(r => (
              <tr key={r.id} style={{ borderTop: "1px solid var(--border)" }}>
                <td style={{ padding: "13px 16px", fontWeight: 600 }}>{r.title}</td>
                <td style={{ padding: "13px 16px" }}>{r.qty}</td>
                <td style={{ padding: "13px 16px" }}><b>{r.quotes}</b></td>
                <td style={{ padding: "13px 16px" }}>{r.deadline}</td>
                <td style={{ padding: "13px 16px" }}><span className={"badge " + (r.status === "open" ? "badge-green" : r.status === "awarded" ? "badge-blue" : "badge-gray")}>{r.status.charAt(0).toUpperCase() + r.status.slice(1)}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
  if (section === "saved") return (
    <>
      <DashHead title="Saved & wishlist" sub="Suppliers and products you've bookmarked" />
      <h3 style={{ fontSize: 15, margin: "0 0 12px" }}>Wishlisted products</h3>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 16, marginBottom: 28 }}>
        {AM.PRODUCTS.slice(0, 3).map(p => <ProductCard key={p.id} product={p} nav={nav} />)}
      </div>
      <h3 style={{ fontSize: 15, margin: "0 0 12px" }}>Saved suppliers</h3>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 16 }}>
        {AM.SUPPLIERS.slice(0, 3).map(s => <SupplierCard key={s.id} supplier={s} nav={nav} />)}
      </div>
    </>
  );
  if (section === "inquiries") return <ChatPane showToast={showToast} />;
  return <SettingsPane role="buyer" showToast={showToast} />;
}

/* ---------------- SUPPLIER ---------------- */
function SupplierSection({ section, nav, showToast, authUser, authState, isOwnRole }) {
  const seedProducts = AM.PRODUCTS.filter(p => p.supplier === "s1");
  const [products, setProducts] = useState(seedProducts);
  const [inquiries, setInquiries] = useState(null);
  const [supplierName, setSupplierName] = useState(null);

  useEffect(() => {
    if (!isOwnRole || !window.supabaseClient || !DB.auth || !DB.storefront || !DB.dashboard) return;
    DB.auth.ensureSupplierRecord(authUser).then(sup => {
      setSupplierName(sup.name);
      DB.storefront.getProductsBySupplier(sup.id).then(setProducts).catch(() => {});
      DB.dashboard.getSupplierInquiries(sup.id).then(setInquiries).catch(() => {});
    }).catch(() => {});
  }, [isOwnRole, authUser]);

  const staticRecent = [
    { who: "Rift Valley Construction", subj: "Y16 rebar — 80 MT", status: "New", time: "2h" },
    { who: "Coastal Builders", subj: "IBR roofing — 4,000 m", status: "Replied", time: "5h" },
    { who: "Kampala Infra", subj: "Galvanized sheet pricing", status: "New", time: "1d" },
  ];
  const recentList = (inquiries || staticRecent).slice(0, 3);

  if (section === "overview") return (
    <>
      <DashHead title={isOwnRole && supplierName ? supplierName : "Savannah Steel Works"} sub={isOwnRole ? "Manage your storefront and listings" : "Premium supplier · Mombasa, Kenya"} action={<button className="btn btn-gold" onClick={() => showToast("Add product")}><Icon name="plus" size={16} /> Add product</button>} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 14, marginBottom: 24 }}>
        <KPI label="Profile views" value="8,420" delta="+12% this week" icon="eye" />
        <KPI label="Product views" value="31,200" delta="+8%" icon="bar-chart-3" />
        <KPI label="Inquiries received" value={inquiries !== null ? String(inquiries.length) : "214"} delta={inquiries === null ? "+18 new" : null} icon="inbox" />
        <KPI label="Response rate" value="98%" icon="zap" />
      </div>
      <div className="card" style={{ padding: 20 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <h3 style={{ fontSize: 16 }}>Recent inquiries</h3>
          <a onClick={() => {}} style={{ cursor: "pointer", color: "var(--navy-600)", fontWeight: 600, fontSize: 13.5 }}>View inbox</a>
        </div>
        {recentList.length === 0 && <p className="muted" style={{ padding: "12px 0" }}>No inquiries yet.</p>}
        {recentList.map((it, i) => (
          <div key={it.id || i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderTop: "1px solid var(--border)" }}>
            <div style={{ width: 34, height: 34, borderRadius: "50%", background: "var(--navy-50)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12, color: "var(--navy-600)" }}>{it.who.split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
            <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{it.who}</div><div className="muted" style={{ fontSize: 12.5 }}>{it.subj}</div></div>
            <span className={it.status === "New" ? "badge badge-blue" : "badge badge-green"}>{it.status}</span>
            <span className="muted" style={{ fontSize: 12 }}>{it.time}</span>
          </div>
        ))}
      </div>
    </>
  );
  if (section === "products") return <ProductManager products={products} showToast={showToast} />;
  if (section === "store") return <StoreManager nav={nav} showToast={showToast} />;
  if (section === "inbox") return <ChatPane supplier inquiries={inquiries} showToast={showToast} />;
  if (section === "analytics") return (
    <>
      <DashHead title="Analytics" sub="Last 30 days" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 14, marginBottom: 22 }}>
        <KPI label="Profile views" value="8,420" delta="+12%" icon="eye" />
        <KPI label="Product views" value="31,200" delta="+8%" icon="mouse-pointer-click" />
        <KPI label="Inquiries" value="214" delta="+9%" icon="inbox" />
        <KPI label="Conversion" value="6.8%" delta="+1.2pt" icon="target" />
      </div>
      <div className="card" style={{ padding: 24 }}>
        <h3 style={{ fontSize: 16, marginBottom: 18 }}>Product views (30 days)</h3>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height: 180 }}>
          {[42, 55, 48, 70, 62, 80, 75, 90, 84, 96, 88, 100].map((h, i) => (
            <div key={i} style={{ flex: 1, height: h + "%", background: "linear-gradient(var(--gold-400), var(--gold-600))", borderRadius: "5px 5px 0 0", minWidth: 8 }} title={h + "00 views"} />
          ))}
        </div>
        <div className="muted" style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, marginTop: 8 }}><span>30 days ago</span><span>Today</span></div>
      </div>
    </>
  );
  return <SettingsPane role="supplier" showToast={showToast} />;
}

Object.assign(window, { DashboardPage, DashHead, KPI, BuyerSection, SupplierSection });
