/* ============================================================
   AfricaMart — Dashboard sub-panes
   ============================================================ */

/* ---------- Messaging / chat ---------- */
function ChatPane({ supplier, showToast, inquiries }) {
  const mockThreads = supplier
    ? [
        { id: 1, who: "Rift Valley Construction", country: "KE", subj: "Y16 rebar — 80 MT", status: "New", last: "Can you confirm mill cert availability?", time: "2h" },
        { id: 2, who: "Coastal Builders", country: "KE", subj: "IBR roofing — 4,000 m", status: "Replied", last: "Thanks, the quote looks good. Lead time?", time: "5h" },
        { id: 3, who: "Kampala Infra Group", country: "UG", subj: "Galvanized sheet pricing", status: "Closed", last: "Order placed — thank you!", time: "3d" },
      ]
    : [
        { id: 1, who: "Savannah Steel Works", country: "KE", subj: "Y12 rebar inquiry", status: "Replied", last: "We can offer $635/MT for 10+ MT. Lead time 2 weeks.", time: "1h" },
        { id: 2, who: "Addis Agro Exports", country: "ET", subj: "Yirgacheffe samples", status: "New", last: "Samples shipped — tracking attached.", time: "6h" },
        { id: 3, who: "Lagos Polymer", country: "NG", subj: "HDPE PN16 quote", status: "Closed", last: "Great, we'll proceed with the PO.", time: "2d" },
      ];
  const threads = inquiries || mockThreads;
  const role = supplier ? "supplier" : "buyer";
  const live = !!inquiries && !!window.supabaseClient && !!(DB.dashboard && DB.dashboard.getInquiryMessages);
  const [active, setActive] = useState(threads[0] ? threads[0].id : null);
  const [msg, setMsg] = useState("");
  const [messages, setMessages] = useState(null);
  const [sending, setSending] = useState(false);

  useEffect(() => {
    if (threads.length && !threads.some(x => x.id === active)) setActive(threads[0].id);
  }, [threads]);

  useEffect(() => {
    if (!live || active == null) { setMessages(null); return; }
    const t = threads.find(x => x.id === active);
    setMessages(null);
    DB.dashboard.getInquiryMessages(active).then(rows => {
      const first = t ? [{ id: "first", senderRole: "buyer", body: t.firstMessage }] : [];
      setMessages([...first, ...rows]);
    }).catch(() => setMessages([]));
  }, [active, live]);

  const stColor = s => s === "New" ? "badge-blue" : s === "Replied" ? "badge-amber" : "badge-gray";

  if (threads.length === 0) {
    return (
      <>
        <DashHead title={supplier ? "Inquiry inbox" : "Inquiries & chat"} sub="Thread-based messaging · email notifications on" />
        <div className="card" style={{ padding: 48, textAlign: "center" }}>
          <Icon name="inbox" size={28} style={{ color: "var(--ink-300)" }} />
          <p className="muted" style={{ marginTop: 10 }}>No inquiries yet.</p>
        </div>
      </>
    );
  }

  const t = threads.find(x => x.id === active) || threads[0];

  const send = async () => {
    const body = msg.trim();
    if (!body) return;
    if (!live) {
      setMsg("");
      showToast("Message sent");
      return;
    }
    setSending(true);
    try {
      const sent = await DB.dashboard.sendInquiryMessage(active, role, body);
      setMessages(prev => [...(prev || []), sent]);
      setMsg("");
    } catch (e) {
      showToast("Could not send message — please try again");
    } finally {
      setSending(false);
    }
  };

  return (
    <>
      <DashHead title={supplier ? "Inquiry inbox" : "Inquiries & chat"} sub="Thread-based messaging · email notifications on" />
      <div className="card chat-grid" style={{ display: "grid", gridTemplateColumns: "300px 1fr", overflow: "hidden", height: 520, padding: 0 }}>
        <div style={{ borderRight: "1px solid var(--border)", overflow: "auto" }} className="thin-scroll">
          {threads.map(th => (
            <button key={th.id} onClick={() => setActive(th.id)} style={{ display: "block", width: "100%", textAlign: "left", padding: "14px 16px", borderBottom: "1px solid var(--border)", background: active === th.id ? "var(--navy-50)" : "#fff" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                <Flag code={th.country} size={13} />
                <span style={{ fontWeight: 700, fontSize: 13.5, flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{th.who}</span>
                <span className="muted" style={{ fontSize: 11 }}>{th.time}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4, color: "var(--ink-700)" }}>{th.subj}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{th.last}</div>
              <span className={"badge " + stColor(th.status)} style={{ marginTop: 7 }}>{th.status}</span>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 10 }}>
            <Flag code={t.country} size={15} />
            <div><div style={{ fontWeight: 700, fontSize: 14.5 }}>{t.who}</div><div className="muted" style={{ fontSize: 12.5 }}>{t.subj}</div></div>
            <span className={"badge " + stColor(t.status)} style={{ marginLeft: "auto" }}>{t.status}</span>
          </div>
          <div style={{ flex: 1, overflow: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 12, background: "var(--paper)" }} className="thin-scroll">
            {live && messages === null && <div className="muted" style={{ textAlign: "center" }}><Icon name="loader-circle" size={18} className="spin" /></div>}
            {live && messages !== null && messages.map(m => (
              <Bubble key={m.id} side={m.senderRole === role ? "me" : "them"}>{m.body}</Bubble>
            ))}
            {!live && (
              <>
                <Bubble side="them">Hi, we're interested in your products. {t.last}</Bubble>
                <Bubble side="me">{supplier ? "Thanks for reaching out — happy to help. Let me pull together the details for you." : "Hello, thanks for the quick reply. Could you confirm the delivery terms?"}</Bubble>
                <Bubble side="them">Sure — we deliver DAP to most East-African destinations. I'll attach the spec sheet and certs.</Bubble>
              </>
            )}
          </div>
          <div style={{ padding: 14, borderTop: "1px solid var(--border)", display: "flex", gap: 10 }}>
            <input className="input" value={msg} onChange={e => setMsg(e.target.value)} placeholder="Type a message…" onKeyDown={e => { if (e.key === "Enter" && msg && !sending) send(); }} />
            <button className="btn btn-gold" disabled={sending} onClick={() => msg && send()}><Icon name={sending ? "loader-circle" : "send"} size={16} className={sending ? "spin" : ""} /></button>
          </div>
        </div>
      </div>
    </>
  );
}
function Bubble({ side, children }) {
  const me = side === "me";
  return (
    <div style={{ alignSelf: me ? "flex-end" : "flex-start", maxWidth: "72%", background: me ? "var(--navy-800)" : "#fff", color: me ? "#fff" : "var(--ink-900)", padding: "10px 14px", borderRadius: me ? "14px 14px 4px 14px" : "14px 14px 14px 4px", fontSize: 14, lineHeight: 1.5, border: me ? "none" : "1px solid var(--border)", boxShadow: "var(--sh-sm)" }}>
      {children}
    </div>
  );
}

/* ---------- Product manager (supplier) ---------- */
const PRODUCT_STATUS_BADGE = { active: "badge-green", pending: "badge-amber", flagged: "badge-blue", inactive: "badge-gray" };

function ProductManager({ products, setProducts, supplierId, isOwnRole, showToast }) {
  const [adding, setAdding] = useState(false);
  const [editing, setEditing] = useState(null);
  const live = isOwnRole && !!window.supabaseClient && !!supplierId;

  const remove = async (p) => {
    if (!window.confirm('Remove "' + p.name + '" from your catalog?')) return;
    if (!live) { showToast("Product removed"); return; }
    try {
      await DB.dashboard.deactivateProduct(p.id);
      setProducts(prev => prev.filter(x => x.id !== p.id));
      showToast("Product removed");
    } catch (e) {
      showToast("Could not remove product — please try again");
    }
  };

  return (
    <>
      <DashHead title="Products" sub={products.length + " products listed"} action={<button className="btn btn-gold" onClick={() => setAdding(true)}><Icon name="plus" size={16} /> Add product</button>} />
      <div className="card" style={{ overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead><tr style={{ background: "var(--navy-50)", textAlign: "left" }}>{["Product", "SKU", "Price", "MOQ", "Views", "Status", ""].map(h => <th key={h} style={{ padding: "12px 16px", fontSize: 12.5, fontWeight: 700, color: "var(--ink-500)" }}>{h}</th>)}</tr></thead>
          <tbody>
            {products.length === 0 && <tr><td colSpan={7} className="muted" style={{ padding: "20px 16px", textAlign: "center" }}>No products yet — click "Add product" to list your first item.</td></tr>}
            {products.map(p => (
              <tr key={p.id} style={{ borderTop: "1px solid var(--border)" }}>
                <td style={{ padding: "12px 16px", fontWeight: 600, maxWidth: 240 }}>{p.name}</td>
                <td style={{ padding: "12px 16px" }} className="mono muted">{p.sku}</td>
                <td style={{ padding: "12px 16px", fontWeight: 600 }}>{p.priceUSD != null ? fmtPrice(p.priceUSD) + "/" + (p.unit || "") : "—"}</td>
                <td style={{ padding: "12px 16px" }}>{p.moq != null ? p.moq + " " + (p.moqUnit || "") : "—"}</td>
                <td style={{ padding: "12px 16px" }}>{(p.views || 0).toLocaleString()}</td>
                <td style={{ padding: "12px 16px" }}><span className={"badge " + (PRODUCT_STATUS_BADGE[p.status] || "badge-green")}>{p.status ? p.status.charAt(0).toUpperCase() + p.status.slice(1) : "Active"}</span></td>
                <td style={{ padding: "12px 16px", textAlign: "right" }}>
                  <button style={{ padding: 6 }} onClick={() => setEditing(p)}><Icon name="pencil" size={16} style={{ color: "var(--ink-500)" }} /></button>
                  <button style={{ padding: 6 }} onClick={() => remove(p)}><Icon name="trash-2" size={16} style={{ color: "var(--ink-500)" }} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {(adding || editing) && (
        <AddProductModal
          product={editing}
          supplierId={supplierId}
          live={live}
          onClose={() => { setAdding(false); setEditing(null); }}
          onSaved={p => {
            if (editing) setProducts(prev => prev.map(x => x.id === p.id ? p : x));
            else setProducts(prev => [p, ...prev]);
          }}
          showToast={showToast}
        />
      )}
    </>
  );
}

function AddProductModal({ onClose, showToast, product, supplierId, live, onSaved }) {
  const isEdit = !!product;
  const [f, setF] = useState({
    name:     product ? product.name || "" : "",
    sku:      product ? product.sku || "" : "",
    category: product ? product.cat || "" : "",
    price:    product && product.priceUSD != null ? String(product.priceUSD) : "",
    unit:     product ? product.unit || "" : "",
    moq:      product && product.moq != null ? String(product.moq) : "",
  });
  const set = k => e => setF(prev => ({ ...prev, [k]: e.target.value }));
  const [desc, setDesc] = useState(product ? product.desc || "" : "");
  const [generating, setGenerating] = useState(false);
  const [tags, setTags] = useState(product ? product.tags || [] : []);
  const [tagging, setTagging] = useState(false);
  const [saving, setSaving] = useState(false);
  const canAI = window.AMAI && AMAI.available();

  const genDesc = async () => {
    if (!f.name) { showToast("Add a product name first"); return; }
    setGenerating(true);
    try {
      const text = await AMAI.generateDescription({ name: f.name, category: f.category, price: f.price, unit: f.unit, moq: f.moq });
      setDesc(text);
      showToast("AI description generated");
    } catch (e) { showToast("AI is unavailable right now — please try again"); }
    setGenerating(false);
  };
  const genTags = async () => {
    if (!f.name) { showToast("Add a product name first"); return; }
    setTagging(true);
    try {
      const t = await AMAI.suggestTags({ name: f.name, category: f.category });
      setTags(t);
      showToast("AI suggested " + t.length + " tags");
    } catch (e) { showToast("AI is unavailable right now — please try again"); }
    setTagging(false);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!live) { onClose(); showToast(isEdit ? "Product updated" : "Product published"); return; }
    setSaving(true);
    try {
      const fields = { ...f, desc, tags };
      const saved = isEdit
        ? await DB.dashboard.updateProduct(product.id, fields)
        : await DB.dashboard.createProduct(supplierId, fields);
      onSaved(saved);
      onClose();
      showToast(isEdit ? "Product updated" : "Product published");
    } catch (err) {
      console.error("[products] save failed", err);
      showToast("Could not save product — please try again");
    }
    setSaving(false);
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(13,27,42,.55)", backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <form onClick={e => e.stopPropagation()} onSubmit={submit} style={{ background: "#fff", borderRadius: 16, width: "min(620px,100%)", maxHeight: "92vh", overflow: "auto", boxShadow: "var(--sh-lg)" }} className="route-anim thin-scroll">
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", position: "sticky", top: 0, background: "#fff", zIndex: 1 }}>
          <h3 style={{ fontSize: 19 }}>{isEdit ? "Edit product" : "Add product"}</h3>
          <button type="button" onClick={onClose} style={{ marginLeft: "auto" }}><Icon name="x" size={22} style={{ color: "var(--ink-500)" }} /></button>
        </div>
        <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 16 }}>
          <ImageEnhancer onApply={() => {}} />
          <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
            <div><label className="field-label">Product name</label><input className="input" value={f.name} onChange={set("name")} required placeholder="e.g. Deformed steel rebar Y12" /></div>
            <div><label className="field-label">SKU</label><input className="input" value={f.sku} onChange={set("sku")} placeholder="SSW-RB-Y12" /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 0.7fr 1fr", gap: 14 }}>
            <div><label className="field-label">Category</label><select className="select" value={f.category} onChange={set("category")} required><option value="" disabled>Select…</option>{AM.CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
            <div><label className="field-label">Price (USD)</label><input className="input" type="number" min="0" step="0.01" value={f.price} onChange={set("price")} placeholder="640" /></div>
            <div><label className="field-label">Unit</label><input className="input" value={f.unit} onChange={set("unit")} placeholder="MT" /></div>
            <div><label className="field-label">MOQ</label><input className="input" type="number" min="0" step="1" value={f.moq} onChange={set("moq")} placeholder="5" /></div>
          </div>
          <div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
              <label className="field-label" style={{ margin: 0 }}>Description</label>
              {canAI && (
                <button type="button" onClick={genDesc} disabled={generating} className="ai-chip" style={{ cursor: "pointer", border: "none" }}>
                  <Icon name={generating ? "loader-circle" : "sparkles"} size={12} className={generating ? "spin" : ""} /> {generating ? "Generating…" : "Generate with AI"}
                </button>
              )}
            </div>
            <textarea className="textarea" rows="5" value={desc} onChange={e => setDesc(e.target.value)} placeholder="Describe your product, or let AI write SEO-optimized copy for you…" />
            <div className="muted" style={{ fontSize: 12, marginTop: 5, display: "flex", alignItems: "center", gap: 5 }}><Icon name="info" size={13} /> AI writes keyword-rich, SEO-friendly descriptions to help buyers find you.</div>
          </div>
          <div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
              <label className="field-label" style={{ margin: 0 }}>Search tags</label>
              {canAI && (
                <button type="button" onClick={genTags} disabled={tagging} className="ai-chip" style={{ cursor: "pointer", border: "none" }}>
                  <Icon name={tagging ? "loader-circle" : "sparkles"} size={12} className={tagging ? "spin" : ""} /> {tagging ? "Suggesting…" : "Suggest tags with AI"}
                </button>
              )}
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", minHeight: 30, alignItems: "center" }}>
              {tags.length === 0 && <span className="muted" style={{ fontSize: 12.5 }}>No tags yet — let AI suggest keywords buyers search for.</span>}
              {tags.map(t => (
                <span key={t} className="badge badge-gray" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>{t}
                  <button type="button" onClick={() => setTags(tags.filter(x => x !== t))} style={{ display: "inline-flex" }}><Icon name="x" size={11} style={{ color: "var(--ink-400)" }} /></button>
                </span>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding: "16px 24px", borderTop: "1px solid var(--border)", display: "flex", gap: 12, justifyContent: "flex-end", position: "sticky", bottom: 0, background: "#fff" }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn btn-gold" disabled={saving}>
            <Icon name={saving ? "loader-circle" : "check"} size={16} className={saving ? "spin" : ""} /> {isEdit ? "Save changes" : "Publish product"}
          </button>
        </div>
      </form>
    </div>
  );
}

/* ---------- Premium storefront upsell ---------- */
function PremiumUpsell({ nav, showToast, compact, slug }) {
  const [showPlans, setShowPlans] = useState(false);
  const benefits = ["Your own brand & domain — no AfricaMart branding", "Editorial, premium design that converts", "Priority placement in search & category pages", "Advanced analytics & lead insights"];
  return (
    <>
      <div className="card prem-upsell" style={{ padding: 0, overflow: "hidden", marginBottom: compact ? 18 : 24, display: "grid", gridTemplateColumns: compact ? "1fr" : "1.5fr 1fr" }}>
        <div style={{ background: "linear-gradient(125deg, var(--navy-800), var(--navy-600))", color: "#fff", padding: 26, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", top: -50, right: -30, width: 200, height: 200, borderRadius: "50%", background: "radial-gradient(circle, rgba(232,184,75,.22), transparent 70%)" }} />
          <span className="badge badge-premium" style={{ position: "relative" }}><Icon name="crown" size={12} /> Premium storefront</span>
          <h3 style={{ fontSize: 22, marginTop: 14, color: "#fff", lineHeight: 1.2, position: "relative" }}>Turn your store into a standalone brand site</h3>
          <p style={{ color: "var(--navy-200)", fontSize: 14, marginTop: 8, lineHeight: 1.55, maxWidth: 440, position: "relative" }}>Upgrade from your Verified storefront to a white-label Premium site — your branding, your domain, zero marketplace chrome.</p>
          <div style={{ display: "flex", gap: 10, marginTop: 20, flexWrap: "wrap", position: "relative" }}>
            <button className="btn btn-gold" onClick={() => nav("store", { slug, variant: "premium" })}><Icon name="eye" size={16} /> Preview premium store</button>
            <button className="btn btn-ghost-light" onClick={() => setShowPlans(true)}>Compare plans</button>
          </div>
        </div>
        <div style={{ padding: 26, display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {benefits.map(b => (
              <div key={b} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <Icon name="check-circle-2" size={17} style={{ color: "var(--green-600)", flexShrink: 0, marginTop: 1 }} />
                <span style={{ fontSize: 13.5, color: "var(--ink-700)", lineHeight: 1.4 }}>{b}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 10 }}>
            <div><span style={{ fontSize: 26, fontWeight: 800, color: "var(--navy-800)" }}>$149</span><span className="muted" style={{ fontSize: 13 }}>/ month</span></div>
            <button className="btn btn-navy" style={{ marginLeft: "auto" }} onClick={() => showToast("Upgrade flow — premium storefront")}>Upgrade now</button>
          </div>
        </div>
      </div>
      {showPlans && <PlanComparison onClose={() => setShowPlans(false)} nav={nav} showToast={showToast} slug={slug} />}
    </>
  );
}

function PlanComparison({ onClose, nav, showToast, slug }) {
  const rows = [
    ["Marketplace listing & search", true, true, true],
    ["Product / service catalog", "Up to 10", "Unlimited", "Unlimited"],
    ["Inquiry inbox & messaging", true, true, true],
    ["Verified badge", false, true, true],
    ["AfricaMart-branded storefront", false, true, true],
    ["White-label storefront (own brand)", false, false, true],
    ["Custom domain", false, false, true],
    ["Editorial premium design", false, false, true],
    ["Priority search placement", false, false, true],
    ["Advanced analytics", false, true, "Advanced"],
    ["Dedicated account manager", false, false, true],
  ];
  const plans = [["Free", "$0"], ["Verified", "$39/mo"], ["Premium", "$149/mo"]];
  const cell = v => v === true ? <Icon name="check" size={16} style={{ color: "var(--green-600)" }} /> : v === false ? <Icon name="minus" size={15} style={{ color: "var(--ink-300)" }} /> : <span style={{ fontSize: 12.5, fontWeight: 600 }}>{v}</span>;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(13,27,42,.55)", backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={e => e.stopPropagation()} className="route-anim thin-scroll" style={{ background: "#fff", borderRadius: 16, width: "min(680px,100%)", maxHeight: "90vh", overflow: "auto", boxShadow: "var(--sh-lg)" }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", position: "sticky", top: 0, background: "#fff", zIndex: 1 }}>
          <h3 style={{ fontSize: 19 }}>Storefront plans</h3>
          <button onClick={onClose} style={{ marginLeft: "auto" }}><Icon name="x" size={22} style={{ color: "var(--ink-500)" }} /></button>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
          <thead>
            <tr>
              <th style={{ textAlign: "left", padding: "14px 16px" }} />
              {plans.map(([name, price], i) => (
                <th key={name} style={{ padding: "14px 12px", textAlign: "center", background: i === 2 ? "var(--gold-50)" : "transparent", borderTopLeftRadius: i === 2 ? 10 : 0, borderTopRightRadius: i === 2 ? 10 : 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", gap: 5 }}>{i === 2 && <Icon name="crown" size={13} style={{ color: "var(--gold-600)" }} />}{name}</div>
                  <div className="muted" style={{ fontSize: 12, fontWeight: 600, marginTop: 2 }}>{price}</div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, ri) => (
              <tr key={ri} style={{ borderTop: "1px solid var(--border)" }}>
                <td style={{ padding: "11px 16px", color: "var(--ink-700)" }}>{r[0]}</td>
                {[1, 2, 3].map(ci => <td key={ci} style={{ padding: "11px 12px", textAlign: "center", background: ci === 3 ? "var(--gold-50)" : "transparent" }}>{cell(r[ci])}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{ padding: "18px 24px", borderTop: "1px solid var(--border)", display: "flex", gap: 12, justifyContent: "flex-end", flexWrap: "wrap" }}>
          <button className="btn btn-ghost" onClick={() => { onClose(); nav("store", { slug, variant: "premium" }); }}><Icon name="eye" size={16} /> Preview premium</button>
          <button className="btn btn-gold" onClick={() => { onClose(); showToast("Upgrade flow — premium storefront"); }}><Icon name="crown" size={16} /> Upgrade to Premium</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Store manager (supplier) ---------- */
/* ---------- small chip-list editor (payment methods, incoterms, etc.) ---------- */
function ChipInput({ items, onAdd, onRemove, placeholder }) {
  const [val, setVal] = useState("");
  const add = () => {
    const v = val.trim();
    if (!v || items.includes(v)) { setVal(""); return; }
    onAdd(v);
    setVal("");
  };
  return (
    <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
      {items.map(it => (
        <span key={it} className="badge badge-gray" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          {it}
          <button type="button" onClick={() => onRemove(it)} style={{ display: "inline-flex" }}><Icon name="x" size={11} /></button>
        </span>
      ))}
      <input className="input" style={{ width: 170, height: 30, fontSize: 12.5, padding: "0 10px" }} placeholder={placeholder} value={val}
        onChange={e => setVal(e.target.value)}
        onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
      <button type="button" className="badge badge-gray" style={{ cursor: "pointer", border: "1px dashed var(--border-strong)" }} onClick={add}><Icon name="plus" size={12} /> Add</button>
    </div>
  );
}

/* ---------- export-markets editor (country picker → chips) ---------- */
function MarketsInput({ codes, onAdd, onRemove }) {
  const [sel, setSel] = useState("");
  const available = AM.COUNTRIES.filter(c => !codes.includes(c.code));
  return (
    <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
      {codes.filter(code => AM.countryByCode[code]).map(code => (
        <span key={code} className="badge badge-gray" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <Flag code={code} size={12} /> {AM.countryByCode[code].name}
          <button type="button" onClick={() => onRemove(code)} style={{ display: "inline-flex" }}><Icon name="x" size={11} /></button>
        </span>
      ))}
      <select className="select" style={{ height: 30, fontSize: 12.5, width: 170 }} value={sel} onChange={e => setSel(e.target.value)}>
        <option value="">Select country…</option>
        {available.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
      </select>
      <button type="button" className="badge badge-gray" style={{ cursor: "pointer", border: "1px dashed var(--border-strong)" }} onClick={() => { if (sel) { onAdd(sel); setSel(""); } }}><Icon name="plus" size={12} /> Add</button>
    </div>
  );
}

const CAP_DEFAULTS = { capacity: "", staff: "", leadTime: "", sample: "", oem: false, payment: [], incoterms: [], markets: [], why: [] };

const FALLBACK_STORE_SEED = { slug: "", name: "", color: "#5a6b7a", bio: "", certs: [], capabilities: {} };

function StoreManager({ nav, showToast, supplierId, isOwnRole }) {
  const seed = (supplierId && AM.supplierById[supplierId]) || FALLBACK_STORE_SEED;
  const [s, setS] = useState(seed);
  const [bio, setBio] = useState(seed.bio);
  const [certs, setCerts] = useState(seed.certs);
  const [newCert, setNewCert] = useState("");
  const [caps, setCaps] = useState({ ...CAP_DEFAULTS, ...(seed.capabilities || {}) });
  const [saving, setSaving] = useState(false);
  const live = isOwnRole && !!window.supabaseClient && !!supplierId && !!DB.dashboard;

  useEffect(() => {
    if (!live) return;
    DB.dashboard.getSupplierProfile(supplierId).then(row => {
      if (!row) return;
      setS(prev => ({ ...prev, ...row }));
      setBio(row.bio || "");
      setCerts(row.certs || []);
      setCaps({ ...CAP_DEFAULTS, ...(row.capabilities || {}) });
    }).catch(() => {});
  }, [live, supplierId]);

  const addCert = () => {
    const v = newCert.trim();
    if (!v || certs.includes(v)) { setNewCert(""); return; }
    setCerts(prev => [...prev, v]);
    setNewCert("");
  };
  const removeCert = c => setCerts(prev => prev.filter(x => x !== c));

  const updateCap = (key, value) => setCaps(prev => ({ ...prev, [key]: value }));
  const addToCap = (key, value) => setCaps(prev => ({ ...prev, [key]: [...prev[key], value] }));
  const removeFromCap = (key, value) => setCaps(prev => ({ ...prev, [key]: prev[key].filter(x => x !== value) }));

  const save = async () => {
    if (!live) { showToast("Store page saved"); return; }
    setSaving(true);
    try {
      await DB.dashboard.saveSupplierStore(supplierId, {
        bio, certs,
        capabilities: { ...caps, why: caps.why.map(w => w.trim()).filter(Boolean) },
      });
      showToast("Store page saved");
    } catch (err) {
      console.error("[store] save failed", err);
      showToast("Could not save store page — please try again");
    }
    setSaving(false);
  };

  return (
    <>
      <DashHead title="Store page" sub={"africamart.co/supplier/" + s.slug} action={<button className="btn btn-ghost" onClick={() => nav("store", { slug: s.slug })}><Icon name="external-link" size={16} /> View store</button>} />
      {/* current plan + upgrade */}
      <div className="card" style={{ padding: 18, marginBottom: 18, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
        <div style={{ width: 42, height: 42, borderRadius: 10, background: "var(--gold-100)", color: "var(--gold-700)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="badge-check" size={22} /></div>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontWeight: 700, fontSize: 15 }}>Your storefront plan: <span style={{ color: "var(--gold-700)" }}>Verified</span></div>
          <div className="muted" style={{ fontSize: 13 }}>AfricaMart-branded storefront · upgrade to Premium for a white-label brand site.</div>
        </div>
        <button className="btn btn-navy" onClick={() => nav("store", { slug: s.slug, variant: "premium" })}><Icon name="eye" size={15} /> Preview premium</button>
      </div>
      <PremiumUpsell nav={nav} showToast={showToast} slug={s.slug} />
      <div className="card" style={{ overflow: "hidden", marginBottom: 18 }}>
        <div style={{ height: 130, background: "linear-gradient(120deg, " + s.color + "dd, var(--navy-800))", position: "relative" }}>
          <button className="btn btn-ghost-light btn-sm" style={{ position: "absolute", right: 14, bottom: 14 }} onClick={() => showToast("Banner upload")}><Icon name="image" size={14} /> Change banner</button>
        </div>
        <div style={{ padding: 20, display: "flex", gap: 16, alignItems: "center" }}>
          <div style={{ width: 64, height: 64, borderRadius: 14, background: s.color + "22", color: s.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 22, marginTop: -44, border: "3px solid #fff" }}>{(s.name || "").split(" ").map(w => w[0]).slice(0, 2).join("")}</div>
          <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 16 }}>{s.name}</div><div className="muted" style={{ fontSize: 13 }}>Logo · 512×512 recommended</div></div>
          <button className="btn btn-ghost btn-sm" onClick={() => showToast("Logo upload")}><Icon name="upload" size={14} /> Change logo</button>
        </div>
      </div>
      <div className="card" style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16, marginBottom: 18 }}>
        <div><label className="field-label">Company description</label><textarea className="textarea" rows="3" value={bio || ""} onChange={e => setBio(e.target.value)} /></div>
        <div><label className="field-label">Certifications</label>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
            {certs.map(c => (
              <span key={c} className="badge badge-green" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                <Icon name="award" size={12} /> {c}
                <button type="button" onClick={() => removeCert(c)} style={{ display: "inline-flex" }}><Icon name="x" size={11} /></button>
              </span>
            ))}
            <input className="input" style={{ width: 170, height: 30, fontSize: 12.5, padding: "0 10px" }} placeholder="Add certification…" value={newCert}
              onChange={e => setNewCert(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); addCert(); } }} />
            <button type="button" className="badge badge-gray" style={{ cursor: "pointer", border: "1px dashed var(--border-strong)" }} onClick={addCert}><Icon name="plus" size={12} /> Add</button>
          </div>
        </div>
      </div>
      <div className="card" style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <h3 style={{ fontSize: 16 }}>Trade capabilities</h3>
          <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>Shown in your storefront's "Trade capabilities" section and trust ribbon.</p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div><label className="field-label">Production capacity</label><input className="input" placeholder="e.g. 60,000 MT / year" value={caps.capacity} onChange={e => updateCap("capacity", e.target.value)} /></div>
          <div><label className="field-label">Staff size</label><input className="input" placeholder="e.g. 200–500" value={caps.staff} onChange={e => updateCap("staff", e.target.value)} /></div>
          <div><label className="field-label">Lead time</label><input className="input" placeholder="e.g. 2–4 weeks" value={caps.leadTime} onChange={e => updateCap("leadTime", e.target.value)} /></div>
          <div><label className="field-label">Sample policy</label><input className="input" placeholder="e.g. Free samples · freight on buyer" value={caps.sample} onChange={e => updateCap("sample", e.target.value)} /></div>
        </div>
        <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--ink-600)" }}>
          <input type="checkbox" checked={caps.oem} onChange={e => updateCap("oem", e.target.checked)} style={{ width: 15, height: 15, accentColor: "var(--navy-700)" }} /> OEM / ODM customization available
        </label>
        <div><label className="field-label">Payment methods</label>
          <ChipInput items={caps.payment} placeholder="e.g. T/T" onAdd={v => addToCap("payment", v)} onRemove={v => removeFromCap("payment", v)} />
        </div>
        <div><label className="field-label">Shipping / Incoterms</label>
          <ChipInput items={caps.incoterms} placeholder="e.g. FOB Mombasa" onAdd={v => addToCap("incoterms", v)} onRemove={v => removeFromCap("incoterms", v)} />
        </div>
        <div><label className="field-label">Main export markets</label>
          <MarketsInput codes={caps.markets} onAdd={v => addToCap("markets", v)} onRemove={v => removeFromCap("markets", v)} />
        </div>
        <div><label className="field-label">Why buyers choose you (one per line)</label>
          <textarea className="textarea" rows="4" placeholder={"e.g. ISO-certified mill with in-house QC lab\nMill test certs with every shipment"} value={caps.why.join("\n")} onChange={e => updateCap("why", e.target.value.split("\n"))} />
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <button className="btn btn-gold" onClick={save} disabled={saving}>{saving ? <Icon name="loader-circle" size={16} className="spin" /> : null} Save changes</button>
        </div>
      </div>
    </>
  );
}

/* ---------- Verification (supplier KYC) ---------- */
const KYC_DOC_TYPES = ["Trade license", "Business registration", "Tax ID / VAT certificate"];

function VerificationPane({ supplierId, showToast }) {
  const [verification, setVerification] = useState(null);
  const [loading, setLoading] = useState(true);
  const [docs, setDocs] = useState({});
  const [uploading, setUploading] = useState({});
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!supplierId || !DB.dashboard) { setLoading(false); return; }
    DB.dashboard.getSupplierVerification(supplierId).then(v => {
      setVerification(v);
      if (v && v.docs) {
        const map = {};
        v.docs.forEach(path => {
          const base = (path.split("/").pop() || "").toLowerCase();
          const label = KYC_DOC_TYPES.find(l => base.startsWith(l.toLowerCase().replace(/[^a-z0-9]+/g, "-")));
          if (label) map[label] = path;
        });
        setDocs(map);
      }
    }).catch(() => {}).finally(() => setLoading(false));
  }, [supplierId]);

  const upload = label => async e => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (!supplierId) { showToast("Still loading your account — please wait and try again", "alert-triangle"); return; }
    setUploading(u => ({ ...u, [label]: true }));
    try {
      const path = await DB.dashboard.uploadKycDoc(supplierId, label, file);
      setDocs(d => ({ ...d, [label]: path }));
      showToast(label + " uploaded");
    } catch (err) {
      console.error("[verification] upload failed", err);
      showToast("Upload failed — please try again", "alert-triangle");
    }
    setUploading(u => ({ ...u, [label]: false }));
  };

  const submit = async () => {
    setSubmitting(true);
    try {
      const row = await DB.dashboard.submitVerification(KYC_DOC_TYPES.map(l => docs[l]));
      setVerification(row);
      showToast("Submitted for verification");
    } catch (err) {
      console.error("[verification] submit failed", err);
      showToast("Submit failed — please try again", "alert-triangle");
    }
    setSubmitting(false);
  };

  if (loading) return <div style={{ padding: "60px 0", textAlign: "center" }}><Icon name="loader-circle" size={28} className="spin" style={{ color: "var(--ink-400)" }} /></div>;

  const status = verification ? verification.status : null;
  const statusBadge = status === "approved" ? <span className="badge badge-green"><Icon name="badge-check" size={12} /> Verified</span>
    : status === "rejected" ? <span className="badge" style={{ background: "var(--red-50)", color: "var(--red-600)" }}><Icon name="x-circle" size={12} /> Rejected — please resubmit</span>
    : (status === "pending" || status === "review") ? <span className="badge badge-amber"><Icon name="clock" size={12} /> Pending review</span>
    : <span className="badge badge-gray">Not submitted</span>;

  const allUploaded = KYC_DOC_TYPES.every(l => docs[l]);

  return (
    <>
      <DashHead title="Verification" sub="Upload your business documents to get a Verified badge" action={statusBadge} />
      {status === "rejected" && verification.notes && (
        <div className="card" style={{ padding: 16, marginBottom: 18, borderLeft: "3px solid var(--red-600)" }}>
          <div style={{ fontWeight: 700, fontSize: 13.5, marginBottom: 4 }}>Reviewer notes</div>
          <div className="muted" style={{ fontSize: 13.5 }}>{verification.notes}</div>
        </div>
      )}
      <div className="card" style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16, maxWidth: 640 }}>
        {KYC_DOC_TYPES.map(label => (
          <div key={label}>
            <label className="field-label">{label}</label>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <label className="btn btn-ghost btn-sm" style={{ cursor: "pointer" }}>
                <Icon name={uploading[label] ? "loader-circle" : "upload"} size={14} className={uploading[label] ? "spin" : ""} /> {docs[label] ? "Replace file" : "Upload file"}
                <input type="file" accept=".pdf,.jpg,.jpeg,.png" style={{ display: "none" }} onChange={upload(label)} disabled={!!uploading[label]} />
              </label>
              {docs[label] && <span className="badge badge-green" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="check" size={12} /> Uploaded</span>}
            </div>
          </div>
        ))}
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 4 }}>
          <button className="btn btn-gold" disabled={!allUploaded || submitting} onClick={submit}>
            {submitting ? <Icon name="loader-circle" size={16} className="spin" /> : <Icon name="send" size={16} />} Submit for verification
          </button>
        </div>
      </div>
    </>
  );
}

/* ---------- Settings ---------- */
function SettingsPane({ role, showToast, authUser, isOwnRole }) {
  const isSupplier = role === "supplier";
  const [ids, setIds] = useState({ profileId: null, entityId: null });
  const [saving, setSaving] = useState(false);
  const [f, setF] = useState({
    name:                isSupplier ? "Savannah Steel Works" : "Rift Valley Construction Ltd",
    type:                "Manufacturer",
    countryCode:         "KE",
    phone:               "+254 712 000 000",
    addressLine:         "Industrial Area, Nakuru",
    deliveryCountryCode: "KE",
    defaultCurrency:     "USD",
    emailNotifications:  true,
  });
  const set = k => e => setF(prev => ({ ...prev, [k]: e.target.value }));

  useEffect(() => {
    if (!isOwnRole || !window.supabaseClient || !authUser || !DB.dashboard) return;
    (async () => {
      try {
        const entity = isSupplier
          ? await DB.auth.ensureSupplierRecord(authUser)
          : await DB.auth.ensureBuyerRecord(authUser);
        const { profile, entity: row } = await DB.dashboard.getSettings(role, authUser.id, entity.id);
        setIds({ profileId: authUser.id, entityId: entity.id });
        setF(prev => ({
          ...prev,
          name:                (row && row.name) || prev.name,
          type:                (row && row.type) || prev.type,
          countryCode:         (row && row.country_code) || (profile && profile.country_code) || prev.countryCode,
          phone:               (profile && profile.phone) || (row && row.phone) || prev.phone,
          addressLine:         (row && row.address_line) || prev.addressLine,
          deliveryCountryCode: (row && row.delivery_country_code) || prev.deliveryCountryCode,
          defaultCurrency:     (row && row.default_currency) || prev.defaultCurrency,
          emailNotifications:  profile && profile.email_notifications != null ? profile.email_notifications : prev.emailNotifications,
        }));
      } catch (e) {}
    })();
  }, [isOwnRole, authUser]);

  const save = async () => {
    if (!isOwnRole || !window.supabaseClient || !ids.entityId) { showToast("Settings saved"); return; }
    setSaving(true);
    try {
      if (isSupplier) await DB.dashboard.saveSupplierSettings(ids.profileId, ids.entityId, f);
      else await DB.dashboard.saveBuyerSettings(ids.profileId, ids.entityId, f);
      showToast("Settings saved");
    } catch (err) {
      console.error("[settings] save failed", err);
      showToast("Could not save settings — please try again");
    }
    setSaving(false);
  };

  return (
    <>
      <DashHead title="Profile settings" sub="Manage your account and preferences" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, maxWidth: 880 }}>
        <div className="card" style={{ padding: 22 }}>
          <h3 style={{ fontSize: 16, marginBottom: 16 }}>Company info</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div><label className="field-label">Company name</label><input className="input" value={f.name} onChange={set("name")} /></div>
            {isSupplier && (
              <div><label className="field-label">Business type</label><select className="select" value={f.type} onChange={set("type")}>{["Manufacturer", "Exporter", "Distributor", "Wholesaler", "Trading company"].map(t => <option key={t} value={t}>{t}</option>)}</select></div>
            )}
            <div><label className="field-label">Country</label><select className="select" value={f.countryCode} onChange={set("countryCode")}>{AM.COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}</select></div>
            <div><label className="field-label">Phone</label><input className="input" value={f.phone} onChange={set("phone")} /></div>
          </div>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <h3 style={{ fontSize: 16, marginBottom: 16 }}>{role === "buyer" ? "Shipping address" : "Preferences"}</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {role === "buyer"
              ? <><div><label className="field-label">Address line</label><input className="input" value={f.addressLine} onChange={set("addressLine")} /></div>
                  <div><label className="field-label">Default delivery country</label><select className="select" value={f.deliveryCountryCode} onChange={set("deliveryCountryCode")}>{AM.COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}</select></div></>
              : <><div><label className="field-label">Default currency</label><select className="select" value={f.defaultCurrency} onChange={set("defaultCurrency")}>{Object.keys(AM.CURRENCIES).map(c => <option key={c} value={c}>{c}</option>)}</select></div>
                  <div><label className="field-label">Subscription plan</label><div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 4 }}><TierBadge tier="premium" /><a style={{ cursor: "pointer", fontSize: 13, color: "var(--navy-600)", fontWeight: 600 }}>Manage plan</a></div></div></>}
            <label style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 14, marginTop: 4 }}><input type="checkbox" checked={f.emailNotifications} onChange={e => setF(prev => ({ ...prev, emailNotifications: e.target.checked }))} style={{ width: 15, height: 15, accentColor: "var(--navy-700)" }} /> Email notifications on new messages</label>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 18 }}><button className="btn btn-gold" onClick={save} disabled={saving}>{saving ? <Icon name="loader-circle" size={16} className="spin" /> : null} Save changes</button></div>
    </>
  );
}

Object.assign(window, { ChatPane, Bubble, ProductManager, AddProductModal, StoreManager, VerificationPane, SettingsPane });
