/* global React, Ic, Retailer, fluxActions, useFlux, fmtMoney, timeAgo, DiscountThumb, Copyable, Seg, CATEGORIES */
const { useState: useBS, useMemo: useBM } = React;

// ─────────────────────────────────────────────────────────────
// Browse — list/grid of discounts with search, filters, sort
// ─────────────────────────────────────────────────────────────
function Browse({ go }) {
  const s = useFlux();
  const [q, setQ] = useBS("");
  const [cat, setCat] = useBS("All");
  const [sort, setSort] = useBS("newest");
  const [view, setView] = useBS("grid");

  const cats = useBM(() => ["All", ...Array.from(new Set(s.discounts.map((d) => d.category)))], [s.discounts]);

  const list = useBM(() => {
    let r = s.discounts.filter((d) => d.status !== "archived");
    if (cat !== "All") r = r.filter((d) => d.category === cat);
    if (q.trim()) {
      const t = q.toLowerCase();
      r = r.filter((d) => (d.title + " " + d.retailer + " " + (d.code || "")).toLowerCase().includes(t));
    }
    r = [...r];
    if (sort === "newest") r.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    if (sort === "discount") r.sort((a, b) => b.discount_pct - a.discount_pct);
    if (sort === "price") r.sort((a, b) => a.price_sale - b.price_sale);
    return r;
  }, [s.discounts, q, cat, sort]);

  return (
    <div className="view-pad fade-in">
      <div className="sec-head">
        <h2>Discounts</h2>
        <span className="desc">{list.length} live · {s.discounts.length} total in database</span>
        <span className="spacer" />
        <Seg value={view} onChange={setView} options={[{ value: "grid", label: "", icon: Ic.grid }, { value: "table", label: "", icon: Ic.list }]} />
        <button className="btn primary" onClick={() => go("add")}><Ic.plus className="ico" />Add discount</button>
      </div>

      {/* controls */}
      <div className="card" style={{ padding: 12, marginBottom: 16, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 220 }}>
          <Ic.search style={{ width: 15, height: 15, position: "absolute", left: 11, top: 10, color: "var(--text-3)" }} />
          <input className="input" placeholder="Search title, retailer, code…" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 34 }} />
        </div>
        <div className="chip-row">
          {cats.slice(0, 8).map((c) => (
            <div key={c} className={`chip ${cat === c ? "on" : ""}`} onClick={() => setCat(c)}>{c}</div>
          ))}
        </div>
        <select className="input" style={{ width: 168 }} value={sort} onChange={(e) => setSort(e.target.value)}>
          <option value="newest">Sort · Newest</option>
          <option value="discount">Sort · Biggest % off</option>
          <option value="price">Sort · Lowest price</option>
        </select>
      </div>

      {list.length === 0 ? (
        <div className="empty"><Ic.tag className="ic" /><div className="t">No discounts match</div><div className="d">Try clearing filters, or post one via the API.</div></div>
      ) : view === "grid" ? (
        <div className="grid-cards">
          {list.map((d) => <DiscountCard key={d.id} d={d} onClick={() => go("detail", d.id)} />)}
        </div>
      ) : (
        <DiscountTable list={list} go={go} />
      )}
    </div>
  );
}

function DiscountCard({ d, onClick }) {
  return (
    <div className="dcard" onClick={onClick}>
      <div className="media">
        <DiscountThumb d={d} />
        {d.discount_pct > 0 && <div className="off">−{d.discount_pct}%</div>}
      </div>
      <div className="body">
        <div className="title" style={{ display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{d.title}</div>
        <div className="meta"><Retailer name={d.retailer} /></div>
        <div className="prices">
          <span className="sale" style={{ color: "var(--green)" }}>{fmtMoney(d.price_sale, d.currency)}</span>
          {d.price_original ? <span className="orig">{fmtMoney(d.price_original, d.currency)}</span> : null}
          <span className="spacer" style={{ flex: 1 }} />
          {d.code ? <span className="pill indigo" style={{ fontFamily: "var(--mono)" }}>{d.code}</span> : null}
        </div>
        <div className="meta" style={{ justifyContent: "space-between" }}>
          <span>{d.category}</span>
          <span>{timeAgo(d.created_at)}</span>
        </div>
      </div>
    </div>
  );
}

function DiscountTable({ list, go }) {
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <table className="tbl">
        <thead><tr><th>Product</th><th>Retailer</th><th>Category</th><th>Was</th><th>Now</th><th>Off</th><th>Code</th><th>Added</th></tr></thead>
        <tbody>
          {list.map((d) => (
            <tr key={d.id} style={{ cursor: "pointer" }} onClick={() => go("detail", d.id)}>
              <td>{d.title}</td>
              <td><Retailer name={d.retailer} /></td>
              <td>{d.category}</td>
              <td className="mono" style={{ textDecoration: d.price_original ? "line-through" : "none", color: "var(--text-3)" }}>{d.price_original ? fmtMoney(d.price_original, d.currency) : "—"}</td>
              <td className="mono" style={{ color: "var(--green)", fontWeight: 600 }}>{fmtMoney(d.price_sale, d.currency)}</td>
              <td><span className="pill indigo">{d.discount_pct}%</span></td>
              <td className="mono-sm">{d.code || "—"}</td>
              <td className="muted">{timeAgo(d.created_at)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Detail
// ─────────────────────────────────────────────────────────────
function Detail({ id, go }) {
  const s = useFlux();
  const d = s.discounts.find((x) => x.id === id);
  if (!d) return <div className="view-pad"><div className="empty"><Ic.tag className="ic" /><div className="t">Discount not found</div></div></div>;
  const deliveries = s.deliveries.filter((x) => x.discountId === d.id);

  return (
    <div className="view-pad fade-in" style={{ maxWidth: 1040 }}>
      <button className="btn ghost sm" style={{ marginBottom: 16 }} onClick={() => go("discounts")}><Ic.chevLeft className="ico" />All discounts</button>

      <div style={{ display: "grid", gridTemplateColumns: "420px 1fr", gap: 26, alignItems: "start" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ position: "relative", height: 300 }}>
            <DiscountThumb d={d} className="" />
            {!d.image && <div className="thumb" style={{ position: "absolute", inset: 0 }}>product shot</div>}
            {d.discount_pct > 0 && <div className="off" style={{ fontSize: 14 }}>−{d.discount_pct}%</div>}
          </div>
        </div>

        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <Retailer name={d.retailer} />
            <span className="pill">{d.category}</span>
            {d.status === "active" ? <span className="pill green dot">ACTIVE</span> : <span className="pill yellow dot">{d.status.toUpperCase()}</span>}
          </div>
          <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 16px", lineHeight: 1.2 }}>{d.title}</h1>

          <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 18 }}>
            <span style={{ fontSize: 34, fontWeight: 700, color: "var(--green)", letterSpacing: "-0.02em" }}>{fmtMoney(d.price_sale, d.currency)}</span>
            {d.price_original ? <span style={{ fontSize: 18, color: "var(--text-3)", textDecoration: "line-through" }}>{fmtMoney(d.price_original, d.currency)}</span> : null}
            {d.price_original ? <span className="pill indigo dot">Save {fmtMoney(d.price_original - d.price_sale, d.currency)}</span> : null}
          </div>

          {d.description ? <p style={{ color: "var(--text-2)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 18px" }}>{d.description}</p> : null}

          {d.code ? (
            <div className="keyval" style={{ marginBottom: 18 }}>
              <span className="muted">CODE</span>
              <span style={{ color: "var(--text)", fontWeight: 600, fontSize: 13 }}>{d.code}</span>
              <Copyable text={d.code} iconOnly className="btn ghost sm" />
            </div>
          ) : null}

          <div style={{ display: "flex", gap: 10, marginBottom: 22 }}>
            <a className="btn primary" href={d.url} target="_blank" rel="noreferrer"><Ic.external className="ico" />Open deal</a>
            <button className="btn" onClick={() => go("edit", d.id)}><Ic.edit className="ico" />Edit</button>
          </div>

          <div className="card" style={{ padding: 16 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 22px", fontSize: 12.5 }}>
              <Meta label="Source" value={<span className="mono-sm">{d.source}</span>} />
              <Meta label="Discount ID" value={<span className="mono-sm">{d.id}</span>} />
              <Meta label="Added" value={`${timeAgo(d.created_at)} · ${new Date(d.created_at).toLocaleString("en-AU")}`} />
              <Meta label="Updated" value={timeAgo(d.updated_at)} />
              <Meta label="Currency" value={d.currency} />
              <Meta label="Expires" value={d.expires_at ? new Date(d.expires_at).toLocaleDateString("en-AU") : "—"} />
              <Meta label="URL" value={<a href={d.url} target="_blank" rel="noreferrer" className="mono-sm" style={{ color: "var(--indigo)", wordBreak: "break-all" }}>{d.url}</a>} full />
            </div>
          </div>
        </div>
      </div>

      {/* webhook deliveries for this discount */}
      <div style={{ marginTop: 26 }}>
        <div className="sec-head"><h2>Webhook deliveries</h2><span className="desc">Discord pushes triggered by this discount</span></div>
        {deliveries.length === 0 ? (
          <div className="card" style={{ padding: 20, color: "var(--text-3)", fontSize: 13 }}>No webhook deliveries recorded for this discount.</div>
        ) : (
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <table className="tbl">
              <thead><tr><th>Webhook</th><th>Event</th><th>Status</th><th>When</th></tr></thead>
              <tbody>
                {deliveries.map((x) => (
                  <tr key={x.id}>
                    <td>{x.webhookName}</td>
                    <td><span className="pill">{x.event}</span></td>
                    <td><window.DeliveryPill status={x.status} code={x.code} /></td>
                    <td className="muted">{timeAgo(x.ts)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function Meta({ label, value, full }) {
  return (
    <div style={{ gridColumn: full ? "1 / -1" : "auto" }}>
      <div className="field-label" style={{ marginBottom: 3 }}>{label}</div>
      <div style={{ color: "var(--text)" }}>{value}</div>
    </div>
  );
}

Object.assign(window, { Browse, Detail });
