/* ============================================================
   AfricaMart — RFQ Board
   ============================================================ */
function RFQPage({ nav, showToast }) {
  const [posting, setPosting] = useState(false);
  const [cat, setCat] = useState("");
  const list = AM.RFQS.filter(r => !cat || r.cat === cat);

  return (
    <div className="route-anim">
      {/* header band */}
      <div style={{ background: "var(--navy-800)", color: "#fff" }}>
        <div className="wrap" style={{ padding: "40px 24px", display: "flex", gap: 24, alignItems: "center", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div>
            <Breadcrumb trail={[["Home", () => nav("home")], ["RFQ Board"]]} />
            <h1 style={{ fontSize: 32, marginTop: 12, color: "#fff" }}>Request for Quotation board</h1>
            <p style={{ color: "var(--navy-200)", marginTop: 8, maxWidth: 540, lineHeight: 1.55 }}>Post what you need and let verified suppliers across Africa come to you with their best offers.</p>
          </div>
          <button className="btn btn-gold btn-lg" onClick={() => setPosting(true)}><Icon name="plus" size={18} /> Post an RFQ</button>
        </div>
      </div>

      <div className="wrap" style={{ padding: "28px 24px 64px" }}>
        {/* AI matching — live */}
        <div style={{ border: "1px solid var(--gold-300)", background: "var(--gold-50)", borderRadius: 12, padding: "14px 18px", display: "flex", alignItems: "center", gap: 12, marginBottom: 22, flexWrap: "wrap" }}>
          <span className="ai-chip"><Icon name="sparkles" size={13} /> AI RFQ Matching</span>
          <span style={{ fontSize: 14 }}>Post an RFQ and our AI instantly routes it to the <b>best-match suppliers</b> by category, location and track record.</span>
          <span className="badge badge-green" style={{ marginLeft: "auto" }}><Icon name="zap" size={11} /> Live</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18, flexWrap: "wrap" }}>
          <b style={{ fontSize: 16 }}>{list.length} open RFQs</b>
          <select className="select" value={cat} onChange={e => setCat(e.target.value)} style={{ width: "auto", marginLeft: "auto", fontWeight: 600 }}>
            <option value="">All categories</option>
            {AM.CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {list.map(r => {
            const ct = AM.catById[r.cat];
            const co = AM.countryByCode[r.country];
            return (
              <div key={r.id} className="card rfq-card" style={{ padding: 22, display: "flex", gap: 20, alignItems: "flex-start" }}>
                <CatIcon cat={ct} size={24} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                    <h3 style={{ fontSize: 17 }}>{r.title}</h3>
                    <span className="badge badge-green">Open</span>
                  </div>
                  <p className="muted" style={{ fontSize: 14, marginTop: 6, lineHeight: 1.55 }}>{r.desc}</p>
                  <div style={{ display: "flex", gap: 18, marginTop: 12, flexWrap: "wrap", fontSize: 13, color: "var(--ink-600)" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="package" size={15} style={{ color: "var(--ink-400)" }} /> {r.qty}</span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Flag code={r.country} size={13} /> {co.name}</span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="building-2" size={15} style={{ color: "var(--ink-400)" }} /> {r.buyer}</span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="calendar" size={15} style={{ color: "var(--ink-400)" }} /> Deadline {r.deadline}</span>
                  </div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0, display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
                  <div className="muted" style={{ fontSize: 12 }}>{r.posted}</div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{r.quotes} quotes</div>
                  <button className="btn btn-navy btn-sm" onClick={() => showToast("Quote submitted for review")}>Respond</button>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {posting && <RFQModal onClose={() => setPosting(false)} showToast={showToast} nav={nav} />}
    </div>
  );
}

function RFQModal({ onClose, showToast, nav }) {
  const [f, setF] = useState({ product: "", category: "", quantity: "", destination: "", details: "" });
  const set = k => e => setF(prev => ({ ...prev, [k]: e.target.value }));
  const [match, setMatch] = useState({ status: "idle" });
  const runMatch = async () => {
    if (!f.product && !f.category) { showToast("Add a product or category first"); return; }
    setMatch({ status: "loading" });
    try {
      const data = await AMAI.matchSuppliers(f);
      setMatch({ status: data.matches.length ? "done" : "empty", data });
    } catch (e) { setMatch({ status: "error" }); }
  };
  const canAI = window.AMAI && AMAI.available();
  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={e => { e.preventDefault(); onClose(); showToast("RFQ posted — suppliers notified"); }}
        className="route-anim thin-scroll" style={{ background: "#fff", borderRadius: 16, width: "min(560px,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 }}>Post a request for quotation</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 }}>
          <div><label className="field-label">Product needed</label><input className="input" value={f.product} onChange={set("product")} placeholder="e.g. Deformed steel rebar Y16" required /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 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.name}>{c.name}</option>)}</select></div>
            <div><label className="field-label">Quantity</label><input className="input" value={f.quantity} onChange={set("quantity")} placeholder="e.g. 80 MT" required /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div><label className="field-label">Destination country</label><select className="select" value={f.destination} onChange={set("destination")} required><option value="" disabled>Select…</option>{AM.COUNTRIES.map(c => <option key={c.code} value={c.name}>{c.name}</option>)}</select></div>
            <div><label className="field-label">Deadline</label><input className="input" type="date" required /></div>
          </div>
          <div><label className="field-label">Details</label><textarea className="textarea" rows="3" value={f.details} onChange={set("details")} placeholder="Specs, standards, delivery terms…" /></div>

          {/* AI matching */}
          {canAI && (
            <div style={{ border: "1px solid var(--gold-300)", background: "var(--gold-50)", borderRadius: 12, padding: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span className="ai-chip"><Icon name="sparkles" size={12} /> AI</span>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>Preview your best-match suppliers</span>
                <button type="button" onClick={runMatch} disabled={match.status === "loading"} className="btn btn-navy btn-sm" style={{ marginLeft: "auto" }}>
                  <Icon name={match.status === "loading" ? "loader-circle" : "wand-sparkles"} size={14} className={match.status === "loading" ? "spin" : ""} /> {match.status === "loading" ? "Matching…" : "Find matches"}
                </button>
              </div>
              {match.status === "error" && <div className="muted" style={{ fontSize: 13, marginTop: 10, display: "flex", gap: 6, alignItems: "center" }}><Icon name="info" size={13} /> AI matching is unavailable right now.</div>}
              {match.status === "empty" && <div className="muted" style={{ fontSize: 13, marginTop: 10 }}>No strong supplier match yet — your RFQ will still reach the full network.</div>}
              {match.status === "done" && (
                <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
                  {match.data.note && <div style={{ fontSize: 13, color: "var(--ink-700)", lineHeight: 1.5 }}>{match.data.note}</div>}
                  {match.data.matches.map((m, i) => (
                    <div key={i} onClick={() => { onClose(); nav("store", { slug: m.rec.slug }); }} style={{ display: "flex", alignItems: "center", gap: 12, background: "#fff", border: "1px solid var(--border)", borderRadius: 10, padding: "10px 12px", cursor: "pointer" }}>
                      <span style={{ width: 40, flexShrink: 0, textAlign: "center", fontWeight: 800, fontSize: 13.5, color: "var(--gold-700)" }}>{m.score}<span style={{ fontSize: 9 }}>%</span></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 13.5, display: "flex", alignItems: "center", gap: 6 }}><Flag code={m.rec.country} size={12} /> {m.rec.name}</div>
                        <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{m.reason}</div>
                      </div>
                      <Icon name="arrow-right" size={15} style={{ color: "var(--ink-400)", flexShrink: 0 }} />
                    </div>
                  ))}
                </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"><Icon name="send" size={16} /> Post RFQ</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { RFQPage, RFQModal });
