/* ============================================================
   AfricaMart — Buyer & Supplier dashboards
   ============================================================ */
function DashboardPage({ nav, params, showToast }) {
  const role = params.role || "buyer";
  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 [section, setSection] = useState("overview");
  useEffect(() => { setSection("overview"); }, [role]);

  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 }}>{role === "supplier" ? "SW" : "AO"}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{role === "supplier" ? "Savannah Steel" : "Amina Okoye"}</div>
              {role === "supplier" ? <TierBadge tier="premium" /> : <span className="muted" style={{ fontSize: 12 }}>Rift Valley Co.</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={() => { nav("home"); }} 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} /> : <SupplierSection section={section} nav={nav} showToast={showToast} />}
      </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 }) {
  if (section === "overview") return (
    <>
      <DashHead title="Welcome back, Amina" 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="3" icon="file-text" />
        <KPI label="Quotes received" value="19" delta="+7 this week" 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>
          {AM.RFQS.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>
            {AM.RFQS.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 badge-green">Open</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 }) {
  const myProducts = AM.PRODUCTS.filter(p => p.supplier === "s1");
  if (section === "overview") return (
    <>
      <DashHead title="Savannah Steel Works" sub="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="214" delta="+18 new" 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>
        {[["Rift Valley Construction", "Y16 rebar — 80 MT", "New", "2h"], ["Coastal Builders", "IBR roofing — 4,000 m", "Replied", "5h"], ["Kampala Infra", "Galvanized sheet pricing", "New", "1d"]].map(([who, what, st, t], i) => (
          <div key={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)" }}>{who.split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
            <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{who}</div><div className="muted" style={{ fontSize: 12.5 }}>{what}</div></div>
            <span className={st === "New" ? "badge badge-blue" : "badge badge-green"}>{st}</span>
            <span className="muted" style={{ fontSize: 12 }}>{t}</span>
          </div>
        ))}
      </div>
    </>
  );
  if (section === "products") return <ProductManager products={myProducts} showToast={showToast} />;
  if (section === "store") return <StoreManager nav={nav} showToast={showToast} />;
  if (section === "inbox") return <ChatPane supplier 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 });
