/* Assets — a design-asset library. Upload images/video with a category, keywords
   and target platforms, then browse a gallery filtered by tag / keyword / platform
   and sorted by recency or usage. Assets are stored locally (data URLs) and their
   use count increments when reused. Exposed as window.AssetsView. */
(function () {
  const S = window.CroprStore;
  const D = window.CROPR_DATA;
  const CATS = D.ASSET_CATEGORIES;
  const PLATS = D.PLATFORMS;
  const catLabel = (id) => (CATS.find((c) => c.id === id) || {}).label || id;

  function PlatformPicker({ selected, onToggle }) {
    return (
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {PLATS.map((p) => {
          const on = selected.includes(p.id);
          return (
            <button key={p.id} type="button" onClick={() => onToggle(p.id)}
              style={{ display: "inline-flex", alignItems: "center", gap: 6, border: `1px solid ${on ? "var(--leap-teal)" : "var(--border-strong)"}`, background: on ? "var(--accent-weak)" : "transparent", color: on ? "var(--accent)" : "var(--fg2)", borderRadius: 999, padding: "4px 10px 4px 5px", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>
              <PlatformLogo platform={p.id} size={16} style={{ borderRadius: 4 }} />{p.label}
            </button>
          );
        })}
      </div>
    );
  }

  function Thumb({ a, height = 150 }) {
    const box = { width: "100%", height, background: "var(--gradient-core)", display: "grid", placeItems: "center", overflow: "hidden" };
    if (a.url && a.kind === "video") return <div style={box}><video src={a.url} muted playsInline style={{ width: "100%", height: "100%", objectFit: "cover" }} /></div>;
    if (a.url) return <div style={box}><img src={a.url} alt={a.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} /></div>;
    return <div style={box}><Icon name={a.kind === "video" ? "video" : "image"} size={26} color="#fff" /></div>;
  }

  function UploadForm({ onToast, onDone }) {
    const fileRef = React.useRef(null);
    const [file, setFile] = React.useState(null);
    const [name, setName] = React.useState("");
    const [category, setCategory] = React.useState("photo");
    const [keywords, setKeywords] = React.useState("");
    const [plats, setPlats] = React.useState([]);
    const readFile = async (f) => {
      if (!f) return;
      const m = await window.LeapUpload.readAndHost(f); // hosts the upload (live)
      if (m) { setFile({ url: m.url, kind: m.kind, fname: f.name }); setName((n) => n || m.name); }
    };
    const onInput = (e) => { readFile((e.target.files || [])[0]); e.target.value = ""; };
    const togglePlat = (id) => setPlats((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
    const reset = () => { setFile(null); setName(""); setKeywords(""); setPlats([]); setCategory("photo"); };
    const save = () => {
      if (!file) { onToast("Choose a file first", "error"); return; }
      S.addAsset({ name: name || file.fname, url: file.url, kind: file.kind,
        category, keywords: keywords.split(",").map((s) => s.trim()).filter(Boolean), platforms: plats });
      reset(); onToast("Asset added to the library"); onDone && onDone();
    };
    return (
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "200px 1fr", gap: 18, alignItems: "start" }} className="asset-upload-grid">
          <div onClick={() => fileRef.current && fileRef.current.click()}
            onDragOver={(e) => { e.preventDefault(); }} onDrop={(e) => { e.preventDefault(); readFile((e.dataTransfer.files || [])[0]); }}
            style={{ height: 150, borderRadius: 14, border: "1.5px dashed var(--border-strong)", cursor: "pointer", overflow: "hidden", display: "grid", placeItems: "center", background: "var(--bg-subtle)" }}>
            {file ? <Thumb a={file} height={150} /> : (
              <div style={{ textAlign: "center", color: "var(--fg3)", padding: 12 }}>
                <Icon name="image-plus" size={24} color="var(--fg4)" />
                <div style={{ fontSize: 12, fontWeight: 600, marginTop: 6 }}>Drop or click to choose</div>
                <div style={{ fontSize: 11, color: "var(--fg4)" }}>PNG, JPG, GIF, SVG, MP4</div>
              </div>
            )}
          </div>
          <input ref={fileRef} type="file" accept="image/*,video/*" style={{ display: "none" }} onChange={onInput} />
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 160px", gap: 12 }}>
              <Field label="Name"><TextInput value={name} onChange={setName} placeholder="e.g. Spring launch hero" /></Field>
              <Field label="Category"><Select value={category} onChange={setCategory} options={CATS.map((c) => ({ value: c.id, label: c.label }))} /></Field>
            </div>
            <Field label="Keywords" hint="Comma-separated — used for search & filtering.">
              <TextInput value={keywords} onChange={setKeywords} placeholder="launch, hero, blue, product" />
            </Field>
            <Field label="Platforms" hint="Which channels this asset is sized/meant for.">
              <PlatformPicker selected={plats} onToggle={togglePlat} />
            </Field>
            <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
              <Button variant="primary" icon="plus" onClick={save}>Add to library</Button>
              {file && <Button variant="ghost" onClick={reset}>Clear</Button>}
            </div>
          </div>
        </div>
      </div>
    );
  }

  function AssetCard({ a, onToast }) {
    const [editing, setEditing] = React.useState(false);
    const [name, setName] = React.useState(a.name);
    const [category, setCategory] = React.useState(a.category);
    const [keywords, setKeywords] = React.useState((a.keywords || []).join(", "));
    const [plats, setPlats] = React.useState(a.platforms || []);
    const saveEdit = () => { S.updateAsset(a.id, { name, category, keywords: keywords.split(",").map((s) => s.trim()).filter(Boolean), platforms: plats }); setEditing(false); onToast("Asset updated"); };
    const togglePlat = (id) => setPlats((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
    const activeClient = S.getActiveClient();
    const isLogo = !!(activeClient && activeClient.logoUrl && activeClient.logoUrl === a.url);
    const canLogo = a.kind !== "video";
    const setAsLogo = () => {
      const cid = S.getActiveClientId();
      if (!cid) { onToast("Switch to a client account to set its logo", "error"); return; }
      if (isLogo) { S.updateClient(cid, { logoUrl: "" }); onToast("Removed the account logo"); return; }
      S.updateClient(cid, { logoUrl: a.url }); onToast(`Set “${a.name}” as the account logo`);
    };
    return (
      <Card pad={0} style={{ overflow: "hidden", outline: isLogo ? "2px solid var(--accent)" : "none" }}>
        <div style={{ position: "relative" }}>
          <Thumb a={a} />
          <span style={{ position: "absolute", top: 8, left: 8, fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em", fontFamily: "var(--font-mono)", background: "rgba(11,59,66,.75)", color: "#fff", padding: "3px 7px", borderRadius: 999 }}>{catLabel(a.category)}</span>
          {isLogo && <span style={{ position: "absolute", bottom: 8, left: 8, fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em", fontFamily: "var(--font-mono)", background: "var(--accent)", color: "#fff", padding: "3px 8px", borderRadius: 999, display: "inline-flex", gap: 4, alignItems: "center" }}><Icon name="badge-check" size={12} color="#fff" />Account logo</span>}
          <span style={{ position: "absolute", top: 8, right: 8, fontSize: 11, fontWeight: 700, background: "rgba(255,255,255,.92)", color: "var(--fg1)", padding: "3px 8px", borderRadius: 999, display: "inline-flex", gap: 4, alignItems: "center" }}><Icon name="repeat" size={12} color="var(--fg2)" />{a.uses || 0}</span>
        </div>
        <div style={{ padding: 12 }}>
          {editing ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <TextInput value={name} onChange={setName} placeholder="Name" />
              <Select value={category} onChange={setCategory} options={CATS.map((c) => ({ value: c.id, label: c.label }))} />
              <TextInput value={keywords} onChange={setKeywords} placeholder="keywords, comma-separated" />
              <PlatformPicker selected={plats} onToggle={togglePlat} />
              <div style={{ display: "flex", gap: 6 }}>
                <Button size="sm" variant="primary" icon="check" onClick={saveEdit}>Save</Button>
                <Button size="sm" variant="ghost" onClick={() => setEditing(false)}>Cancel</Button>
              </div>
            </div>
          ) : (
            <React.Fragment>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 5, margin: "7px 0", minHeight: 20 }}>
                {(a.platforms || []).map((p) => <PlatformLogo key={p} platform={p} size={18} style={{ borderRadius: 5 }} />)}
                {!(a.platforms || []).length && <span style={{ fontSize: 11, color: "var(--fg4)" }}>Any platform</span>}
              </div>
              {!!(a.keywords || []).length && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginBottom: 10 }}>
                  {a.keywords.slice(0, 5).map((k) => <span key={k} style={{ fontSize: 10.5, color: "var(--fg3)", background: "var(--bg-muted)", padding: "2px 7px", borderRadius: 999 }}>{k}</span>)}
                </div>
              )}
              <div style={{ display: "flex", gap: 6 }}>
                <Button size="sm" variant="primary" icon="check-check" onClick={() => { S.useAsset(a.id); onToast(`“${a.name}” marked as used`); }}>Use</Button>
                {canLogo && <Button size="sm" variant={isLogo ? "primary" : "secondary"} icon="badge-check" title={isLogo ? "Current account logo — click to remove" : "Set as account logo"} onClick={setAsLogo} />}
                <Button size="sm" variant="secondary" icon="pencil" onClick={() => setEditing(true)} />
                <Button size="sm" variant="danger" icon="trash-2" onClick={() => { if (confirm("Delete “" + a.name + "”?")) { S.removeAsset(a.id); onToast("Asset deleted"); } }} />
              </div>
            </React.Fragment>
          )}
        </div>
      </Card>
    );
  }

  function AssetsView({ onToast }) {
    const assets = S.getAssets();
    const [q, setQ] = React.useState("");
    const [cat, setCat] = React.useState("all");
    const [plats, setPlats] = React.useState([]);
    const [sort, setSort] = React.useState("recent");
    const [showUpload, setShowUpload] = React.useState(false);
    const togglePlat = (id) => setPlats((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);

    const ql = q.trim().toLowerCase();
    let list = assets.filter((a) => {
      if (cat !== "all" && a.category !== cat) return false;
      if (plats.length && !plats.some((p) => (a.platforms || []).includes(p))) return false;
      if (ql) { const hay = (a.name + " " + (a.keywords || []).join(" ")).toLowerCase(); if (!hay.includes(ql)) return false; }
      return true;
    });
    list = list.slice().sort((x, y) =>
      sort === "most" ? (y.uses || 0) - (x.uses || 0) :
      sort === "least" ? (x.uses || 0) - (y.uses || 0) :
      new Date(y.createdAt) - new Date(x.createdAt));

    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.01em" }}>Asset library</div>
            <div style={{ fontSize: 12.5, color: "var(--fg3)", marginTop: 2 }}>Reusable logos, photos, templates and video for this account. Set an image as the account logo from any card.</div>
          </div>
          <Button variant="primary" icon="upload-cloud" onClick={() => setShowUpload(true)}>Add to library</Button>
        </div>

        <Modal open={showUpload} title="Upload an asset" subtitle="Add an image or video to your library." width={680} onClose={() => setShowUpload(false)}>
          <UploadForm onToast={onToast} onDone={() => setShowUpload(false)} />
        </Modal>

        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", marginBottom: 14 }}>
          <div style={{ position: "relative", flex: 1, minWidth: 200 }}>
            <Icon name="search" size={16} color="var(--fg4)" style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)" }} />
            <TextInput value={q} onChange={setQ} placeholder="Search name or keywords…" style={{ paddingLeft: 34 }} />
          </div>
          <Select value={cat} onChange={setCat} style={{ width: 160 }} options={[{ value: "all", label: "All categories" }].concat(CATS.map((c) => ({ value: c.id, label: c.label })))} />
          <Segmented value={sort} onChange={setSort} options={[{ value: "recent", label: "Recent" }, { value: "most", label: "Most used" }, { value: "least", label: "Least used" }]} />
        </div>
        <div style={{ marginBottom: 20 }}><PlatformPicker selected={plats} onToggle={togglePlat} /></div>

        {list.length === 0 ? (
          <Card pad={44} style={{ textAlign: "center" }}>
            <Icon name={assets.length ? "search-x" : "image"} size={30} color="var(--fg4)" />
            <div style={{ fontSize: 15, fontWeight: 700, marginTop: 10 }}>{assets.length ? "No assets match these filters" : "Your asset library is empty"}</div>
            <div style={{ fontSize: 13, color: "var(--fg3)", marginTop: 4 }}>{assets.length ? "Try clearing the search, category or platform filters." : "Upload logos, photos, templates and other design assets to reuse in your posts."}</div>
          </Card>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(230px,1fr))", gap: 16 }}>
            {list.map((a) => <AssetCard key={a.id} a={a} onToast={onToast} />)}
          </div>
        )}
        <div style={{ fontSize: 11.5, color: "var(--fg4)", marginTop: 16, display: "flex", gap: 6, alignItems: "center" }}>
          <Icon name="info" size={14} color="var(--fg4)" />Assets are stored locally in your browser. In production they'd sync to your media library (e.g. OneDrive / cloud storage).
        </div>
      </div>
    );
  }
  window.AssetsView = AssetsView;
})();
