/* Daily Picks — 10 produits Amazon.ca + 10 fournisseurs wholesale par jour
   Génère via /api/daily-picks (Gemini + KV cache 24h) */

const fmtCAD = (n) => {
  const v = Number(n);
  if (!isFinite(v)) return "—";
  return new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);
};

const ScoreDots = ({ n = 0, max = 5 }) => (
  <div style={{ display: "inline-flex", gap: 2 }}>
    {Array.from({ length: max }).map((_, i) => (
      <span key={i} style={{
        width: 6, height: 6, borderRadius: "50%",
        background: i < n ? "var(--accent)" : "var(--bg-3)",
      }}/>
    ))}
  </div>
);

const SupplierCard = ({ s, onAdd }) => (
  <div className="card" style={{ padding: 14, display: "flex", flexDirection: "column", gap: 8, minWidth: 0 }}>
    <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.3, wordBreak: "break-word" }}>{s.name}</div>
        <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>
          {s.city || s.country || "—"} · {s.category || "Multi"}
        </div>
      </div>
      <ScoreDots n={Number(s.score) || 0} />
    </div>
    {Array.isArray(s.brands) && s.brands.length > 0 && (
      <div className="row" style={{ flexWrap: "wrap", gap: 4 }}>
        {s.brands.slice(0, 4).map((b, i) => (
          <span key={i} className="badge" style={{ fontSize: 10.5, padding: "2px 6px" }}>{b}</span>
        ))}
      </div>
    )}
    <div style={{ fontSize: 11.5, color: "var(--text-muted)", lineHeight: 1.5 }}>{s.why || "—"}</div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 4, fontSize: 11, color: "var(--text-dim)" }}>
      <div><span style={{ color: "var(--text-faint)" }}>MOQ </span>{s.moq || "—"}</div>
      <div><span style={{ color: "var(--text-faint)" }}>Terms </span>{s.terms || "—"}</div>
    </div>
    <div className="row" style={{ gap: 6, marginTop: 4, flexWrap: "wrap" }}>
      {s.website && (
        <a className="btn" data-variant="ghost" data-size="sm" href={s.website} target="_blank" rel="noopener noreferrer">
          <Icon name="external" size={11}/> Site
        </a>
      )}
      {s.email && (
        <a className="btn" data-variant="ghost" data-size="sm" href={`mailto:${s.email}`}>
          <Icon name="mail" size={11}/> Email
        </a>
      )}
      {onAdd && (
        <button className="btn" data-variant="primary" data-size="sm" onClick={() => onAdd(s)}>
          <Icon name="plus" size={11}/> Ajouter
        </button>
      )}
    </div>
  </div>
);

const ProductCard = ({ p, onAdd }) => {
  const margin = Number(p.fbaMargin) || 0;
  const marginColor = margin >= 35 ? "var(--green)" : margin >= 25 ? "var(--amber)" : "var(--red)";
  return (
    <div className="card" style={{ padding: 14, display: "flex", flexDirection: "column", gap: 8, minWidth: 0 }}>
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 13.5, lineHeight: 1.3, wordBreak: "break-word" }}>{p.name || p.title}</div>
          <div style={{ fontSize: 11, color: "var(--text-dim)", marginTop: 2 }}>
            {p.brand || "—"} · {p.category || "—"}
          </div>
        </div>
        <span className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>{p.asin || "—"}</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, fontSize: 11 }}>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>RETAIL</div>
          <div className="mono" style={{ fontWeight: 600 }}>{fmtCAD(p.retailPrice)}</div>
        </div>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>WHOLESALE</div>
          <div className="mono" style={{ fontWeight: 600 }}>{fmtCAD(p.wholesalePrice)}</div>
        </div>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>MARGE</div>
          <div className="mono" style={{ fontWeight: 700, color: marginColor }}>{margin}%</div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, fontSize: 11, color: "var(--text-dim)" }}>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>BSR <span style={{ color: "var(--text-faint)", fontSize: 9 }}>· Keepa</span></div>
          <div className="mono">
            {window.KeepaCell && p.asin
              ? <window.KeepaCell asin={p.asin} fields={["bsr_current"]} auto={true} compact={true} fallback={p.bsr ? Number(p.bsr).toLocaleString("fr-CA") : "—"} />
              : (p.bsr ? Number(p.bsr).toLocaleString("fr-CA") : "—")}
          </div>
        </div>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>VENDEURS</div>
          <div className="mono">{p.sellers || "—"}</div>
        </div>
        <div>
          <div style={{ color: "var(--text-faint)", fontSize: 10 }}>VENTES/MOIS</div>
          <div className="mono">{p.monthlySales ? (String(p.monthlySales).startsWith("~") ? p.monthlySales : `~${p.monthlySales}`) : "—"}</div>
        </div>
      </div>
      <div style={{ fontSize: 11.5, color: "var(--text-muted)", lineHeight: 1.5 }}>{p.why || "—"}</div>
      <div className="row" style={{ gap: 6, marginTop: 4, flexWrap: "wrap" }}>
        {p.asin && (
          <a className="btn" data-variant="ghost" data-size="sm"
             href={`https://www.amazon.ca/dp/${p.asin}`} target="_blank" rel="noopener noreferrer">
            <Icon name="external" size={11}/> Amazon.ca
          </a>
        )}
        {onAdd && (
          <button className="btn" data-variant="primary" data-size="sm" onClick={() => onAdd(p)}>
            <Icon name="plus" size={11}/> Ajouter à la library
          </button>
        )}
      </div>
    </div>
  );
};

const DailyPicks = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [refreshing, setRefreshing] = React.useState(false);
  const [tab, setTab] = React.useState("products");        // products | suppliers
  const [view, setView] = React.useState("today");          // today | history
  const [history, setHistory] = React.useState(null);       // { dates, totalAsins, totalDays }
  const [selectedDate, setSelectedDate] = React.useState(null);

  // Charge un batch (aujourd'hui par défaut, ou date précise, ou force regen)
  const load = async (opts = {}) => {
    const { force = false, date = null } = opts;
    if (force) setRefreshing(true); else setLoading(true);
    setError(null);
    try {
      const qs = new URLSearchParams();
      if (date) qs.set("date", date);
      if (force) qs.set("_t", Date.now());
      const url = `/api/daily-picks-batch${qs.toString() ? "?" + qs.toString() : ""}`;
      const opt = force ? { method: "POST" } : {};
      const d = await fetch(url, opt).then(r => r.json());
      if (!d || d.ok === false) {
        setError(d?.error || "Erreur chargement du batch");
      } else {
        setData(d);
        if (date) setSelectedDate(date);
      }
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const loadHistory = async () => {
    try {
      const h = await fetch("/api/daily-picks-history").then(r => r.json());
      if (h && h.ok) setHistory(h);
    } catch (_) { /* silent */ }
  };

  React.useEffect(() => { load({}); loadHistory(); }, []);

  const products = (data?.products || []);
  const suppliers = (data?.suppliers || []);

  const addProduct = (p) => {
    if (!window.KCC_PRODUCTS) window.KCC_PRODUCTS = [];
    window.KCC_PRODUCTS.push({
      asin: p.asin, name: p.name, brand: p.brand, category: p.category,
      retail: p.retailPrice, wholesale: p.wholesalePrice, status: "evaluating",
      added: new Date().toISOString(), source: "daily-picks",
    });
    window.dispatchEvent(new CustomEvent("kcc:notify", { detail: { message: `Ajouté à la library : ${p.name}` } }));
  };
  const addSupplier = (s) => {
    if (!window.KCC_SUPPLIERS) window.KCC_SUPPLIERS = [];
    window.KCC_SUPPLIERS.push({
      name: s.name, website: s.website, email: s.email, phone: s.phone,
      country: s.country, city: s.city, brands: s.brands, category: s.category,
      moq: s.moq, terms: s.terms, added: new Date().toISOString(), source: "daily-picks",
    });
    window.dispatchEvent(new CustomEvent("kcc:notify", { detail: { message: `Ajouté à l'annuaire : ${s.name}` } }));
  };

  const cumulativeLabel = history
    ? `${history.totalAsins} ASIN cumulés · ${history.totalDays} jours`
    : "";

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">
            Picks du jour {data?.date && <span style={{ fontSize: 13, color: "var(--text-dim)", fontWeight: 400, marginLeft: 8 }}>· {data.date}</span>}
          </div>
          <div className="page-sub">
            {data
              ? `${products.length} produits · ${suppliers.length} fournisseurs · ${data.source === "keepa_best_sellers" ? "Keepa Best Sellers" : "Keepa live"}${data.tokens_left != null ? ` · ${data.tokens_left} tokens restants` : ""}${cumulativeLabel ? " · " + cumulativeLabel : ""}`
              : "10 nouveaux produits Amazon.ca par jour via Keepa, cumulatif."}
          </div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <button className="btn" data-variant="ghost" onClick={() => { setView("today"); setSelectedDate(null); load({}); }}>
            <Icon name="calendar" size={13}/> Aujourd'hui
          </button>
          <button className="btn" data-variant="ghost" onClick={() => { setView("history"); loadHistory(); }}>
            <Icon name="layers" size={13}/> Historique{history ? ` (${history.totalDays})` : ""}
          </button>
          <button className="btn" data-variant="ghost" onClick={() => load({ force: !selectedDate, date: selectedDate })} disabled={refreshing}>
            <Icon name={refreshing ? "loader" : "refresh"} size={13}/>
            {refreshing ? "Génération…" : selectedDate ? "Recharger" : "Régénérer"}
          </button>
        </div>
      </div>

      {view === "history" && (
        <div className="card" style={{ padding: 14, marginBottom: 12 }}>
          <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8 }}>
            Historique des batches {history && `· ${history.totalAsins} ASIN uniques cumulés sur ${history.totalDays} jours`}
          </div>
          {!history && <div style={{ fontSize: 12, color: "var(--text-dim)" }}>Chargement…</div>}
          {history && history.dates.length === 0 && (
            <div style={{ fontSize: 12, color: "var(--text-dim)" }}>Aucun batch encore. Génère le premier en revenant à "Aujourd'hui".</div>
          )}
          {history && history.dates.length > 0 && (
            <div className="row" style={{ flexWrap: "wrap", gap: 6 }}>
              {history.dates.map(d => (
                <button key={d} className="btn" data-variant={selectedDate === d ? "primary" : "ghost"} data-size="sm"
                  onClick={() => { setView("today"); load({ date: d }); }}>
                  {d}
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Tabs */}
      <div className="row" style={{ gap: 4, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: 2, alignSelf: "flex-start", marginBottom: 12 }}>
        <button onClick={() => setTab("products")} style={{
          height: 26, padding: "0 12px", borderRadius: 4, fontSize: 12,
          background: tab === "products" ? "var(--bg-4)" : "transparent",
          color: tab === "products" ? "var(--text)" : "var(--text-dim)",
          fontWeight: tab === "products" ? 600 : 400, whiteSpace: "nowrap",
        }}>Produits · {products.length}</button>
        <button onClick={() => setTab("suppliers")} style={{
          height: 26, padding: "0 12px", borderRadius: 4, fontSize: 12,
          background: tab === "suppliers" ? "var(--bg-4)" : "transparent",
          color: tab === "suppliers" ? "var(--text)" : "var(--text-dim)",
          fontWeight: tab === "suppliers" ? 600 : 400, whiteSpace: "nowrap",
        }}>Fournisseurs · {suppliers.length}</button>
      </div>

      {loading && (
        <div className="card" style={{ padding: 32, textAlign: "center", color: "var(--text-dim)" }}>
          <Icon name="loader" size={18}/> Chargement des picks du jour…
        </div>
      )}

      {error && (
        <div className="card" style={{ padding: 20, borderColor: "var(--red)", color: "var(--red)" }}>
          <div style={{ fontWeight: 600, marginBottom: 6 }}>Erreur de génération</div>
          <div style={{ fontSize: 12 }}>{error}</div>
          <button className="btn" data-variant="ghost" data-size="sm" onClick={() => load(true)} style={{ marginTop: 10 }}>
            Réessayer
          </button>
        </div>
      )}

      {!loading && !error && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
          {tab === "products" && products.map((p, i) => <ProductCard key={i} p={p} onAdd={addProduct}/>)}
          {tab === "suppliers" && suppliers.map((s, i) => <SupplierCard key={i} s={s} onAdd={addSupplier}/>)}
        </div>
      )}

      {!loading && !error && tab === "products" && products.length === 0 && (
        <div className="card" style={{ padding: 24, textAlign: "center", color: "var(--text-dim)", fontSize: 13 }}>
          Aucun produit aujourd'hui. Cliquez sur Rafraîchir.
        </div>
      )}
      {!loading && !error && tab === "suppliers" && suppliers.length === 0 && (
        <div className="card" style={{ padding: 24, textAlign: "center", color: "var(--text-dim)", fontSize: 13 }}>
          Aucun fournisseur aujourd'hui. Cliquez sur Rafraîchir.
        </div>
      )}
    </div>
  );
};

window.DailyPicks = DailyPicks;
