// Tools Index — search, filter, and full CRUD with per-tool markdown links.
const {
  useState: useStateT,
  useMemo: useMemoT,
  useEffect: useEffectT,
} = React;

function tokT() { return sessionStorage.getItem("kol_tok") || ""; }
function jsonHeadersT() {
  return { "Authorization": "Bearer " + tokT(), "Content-Type": "application/json" };
}

function slugifyT(s) {
  return String(s || "").toLowerCase().trim()
    .replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-")
    || ("tool-" + Date.now());
}

// ── Tool card ─────────────────────────────────────────────────────────────────

function ToolCard({ tool, onEdit, onDelete }) {
  const linksHtml = useMemoT(() => {
    if (!tool.links || !window.marked) return "";
    return window.marked.parse(tool.links.trim());
  }, [tool.links]);

  return (
    <div className="tool">
      <div className="tool-head">
        <h4>{tool.name}</h4>
        <span className={`tool-cost${tool.cost === "paid" ? " paid" : ""}`}>{tool.cost}</span>
      </div>
      {linksHtml ? (
        <div className="tool-links" dangerouslySetInnerHTML={{ __html: linksHtml }} />
      ) : null}
      <p>{tool.desc}</p>
      <div className="tool-tags">
        <span className="tool-tag">{tool.category}</span>
        {(tool.tags || []).map(tag => <span key={tag} className="tool-tag">{tag}</span>)}
      </div>
      <div className="tool-actions">
        <button
          className="btn ghost"
          style={{ fontSize: 12, padding: "4px 9px" }}
          onClick={() => onEdit(tool)}
        >Edit</button>
        <button
          className="btn ghost"
          style={{ fontSize: 12, padding: "4px 9px", color: "var(--danger)", borderColor: "color-mix(in oklab, var(--danger), transparent 60%)" }}
          onClick={() => onDelete(tool)}
        >Delete</button>
      </div>
    </div>
  );
}

// ── Tool editor ───────────────────────────────────────────────────────────────

function ToolEditor({ tool, onSave, onCancel }) {
  const isNew = !tool || !tool.id;
  const [draft, setDraft] = useStateT({
    name:     tool?.name     || "",
    category: tool?.category || "",
    cost:     tool?.cost     || "free",
    desc:     tool?.desc     || "",
    links:    tool?.links    || "",
    tags:     (tool?.tags || []).join(", "),
  });

  function handleSave() {
    if (!draft.name.trim()) return;
    onSave({
      id:       tool?.id || slugifyT(draft.name),
      name:     draft.name.trim(),
      category: draft.category.trim(),
      cost:     draft.cost,
      desc:     draft.desc.trim(),
      links:    draft.links.trim(),
      tags:     draft.tags.split(",").map(s => s.trim()).filter(Boolean),
    });
  }

  const linkPreview = useMemoT(() => {
    if (!draft.links || !window.marked) return "";
    return window.marked.parse(draft.links.trim());
  }, [draft.links]);

  return (
    <div className="session-editor" style={{ marginBottom: 24 }}>
      <h3>{isNew ? "New tool" : `Editing: ${tool.name}`}</h3>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 10 }}>
        <div className="field">
          <label>Name</label>
          <input value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} placeholder="Tool name" />
        </div>
        <div className="field">
          <label>Category</label>
          <input value={draft.category} onChange={e => setDraft({ ...draft, category: e.target.value })} placeholder="e.g. Geolocation" />
        </div>
        <div className="field">
          <label>Cost</label>
          <div className="segment" style={{ marginTop: 2 }}>
            <button type="button" className={draft.cost === "free" ? "active" : ""} onClick={() => setDraft({ ...draft, cost: "free" })}>Free</button>
            <button type="button" className={draft.cost === "paid" ? "active" : ""} onClick={() => setDraft({ ...draft, cost: "paid" })}>Paid</button>
          </div>
        </div>
      </div>
      <div className="field">
        <label>Description</label>
        <input value={draft.desc} onChange={e => setDraft({ ...draft, desc: e.target.value })} placeholder="One-sentence description" />
      </div>
      <div className="field">
        <label>Links — Markdown (e.g. [Guide](https://…) | [Download](https://…) | [YouTube](https://…))</label>
        <input
          value={draft.links}
          onChange={e => setDraft({ ...draft, links: e.target.value })}
          placeholder="[Guide](https://…) | [Download](https://…)"
          style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}
        />
        {linkPreview ? (
          <div className="tool-links" style={{ marginTop: 6, padding: "6px 10px", background: "var(--bg-sunk)", borderRadius: "var(--radius-sm)" }}
            dangerouslySetInnerHTML={{ __html: linkPreview }}
          />
        ) : null}
      </div>
      <div className="field">
        <label>Tags (comma-separated)</label>
        <input value={draft.tags} onChange={e => setDraft({ ...draft, tags: e.target.value })} placeholder="e.g. cli, geo, browser" />
      </div>
      <div className="row">
        <button className="btn" onClick={handleSave}>Save</button>
        <button className="btn ghost" onClick={onCancel}>Cancel</button>
      </div>
    </div>
  );
}

// ── Main Tools component ──────────────────────────────────────────────────────

function Tools({ search, setSearch }) {
  const [tools, setTools] = useStateT(() => window.TOOLS || []);
  const [loading, setLoading] = useStateT(true);
  const [cat, setCat] = useStateT("All");
  const [cost, setCost] = useStateT("Any");
  const [editing, setEditing] = useStateT(null); // null | "new" | tool object

  useEffectT(() => { loadFromApi(); }, []);

  async function loadFromApi() {
    setLoading(true);
    try {
      const resp = await fetch("/api/tools");
      if (!resp.ok) throw new Error(resp.status);
      const { tools: apiTools, seeded } = await resp.json();

      if (!seeded) {
        // Seed DB from bundled data.js tools
        const bundled = window.TOOLS || [];
        for (const tool of bundled) {
          await fetch("/api/tools", {
            method: "POST",
            headers: jsonHeadersT(),
            body: JSON.stringify({ tool }),
          });
        }
        const r2 = await fetch("/api/tools");
        if (r2.ok) {
          const data = await r2.json();
          const loaded = data.tools || [];
          setTools(loaded);
          window.TOOLS = loaded;
        }
      } else {
        setTools(apiTools);
        window.TOOLS = apiTools;
      }
    } catch {
      setTools(window.TOOLS || []);
    }
    setLoading(false);
  }

  const categories = useMemoT(() => {
    const s = new Set(tools.map(t => t.category).filter(Boolean));
    return ["All", ...[...s].sort()];
  }, [tools]);

  const filtered = useMemoT(() => {
    const q = (search || "").trim().toLowerCase();
    return tools.filter(t => {
      if (cat !== "All" && t.category !== cat) return false;
      if (cost !== "Any" && t.cost !== cost) return false;
      if (!q) return true;
      const hay = [t.name, t.category, t.desc, t.links || "", ...(t.tags || [])].join(" ").toLowerCase();
      return hay.includes(q);
    });
  }, [tools, search, cat, cost]);

  async function handleSave(saved) {
    const isNew = !tools.find(t => t.id === saved.id);
    setTools(prev => {
      const next = isNew ? [...prev, saved] : prev.map(t => t.id === saved.id ? saved : t);
      window.TOOLS = next;
      return next;
    });
    setEditing(null);
    fetch("/api/tools", {
      method: "POST",
      headers: jsonHeadersT(),
      body: JSON.stringify({ tool: saved }),
    }).catch(console.error);
  }

  async function handleDelete(tool) {
    const ok = await window.requestDelete(`tool "${tool.name}"`);
    if (!ok) return;
    setTools(prev => {
      const next = prev.filter(t => t.id !== tool.id);
      window.TOOLS = next;
      return next;
    });
    fetch("/api/tools/" + encodeURIComponent(tool.id), {
      method: "DELETE",
      headers: jsonHeadersT(),
    }).catch(console.error);
  }

  return (
    <>
      <div className="crumbs">
        <a href="#/">Home</a><span>/</span>
        <span style={{ color: "var(--ink)" }}>All Tools</span>
      </div>
      <header className="tools-head">
        <h1>All Tools</h1>
        <p>A working list of the tools we actually reach for. Filter by what fits your machine, your budget, and the kind of question you are trying to answer.</p>
      </header>

      <div style={{ marginBottom: 20 }}>
        {editing === null && (
          <button className="btn" onClick={() => setEditing("new")}>+ New tool</button>
        )}
      </div>

      {editing !== null && (
        <ToolEditor
          tool={editing === "new" ? null : editing}
          onSave={handleSave}
          onCancel={() => setEditing(null)}
        />
      )}

      <div className="tools-controls">
        <div className="tools-search">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
            <circle cx="7" cy="7" r="5"></circle>
            <path d="m11 11 3 3"></path>
          </svg>
          <input
            placeholder="Search tools by name, tag, or purpose…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            autoFocus
          />
        </div>
        <div className="pill-row">
          {["Any", "free", "paid"].map(c => (
            <button key={c} className={`pill ${cost === c ? "active" : ""}`} onClick={() => setCost(c)}>
              {c === "Any" ? "Any cost" : c}
            </button>
          ))}
        </div>
      </div>

      <div className="pill-row" style={{ marginBottom: 4 }}>
        {categories.map(c => (
          <button key={c} className={`pill ${cat === c ? "active" : ""}`} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", margin: "18px 0 0" }}>
        {loading ? "Loading…" : `Showing ${filtered.length} of ${tools.length}`}
      </div>

      {!loading && filtered.length === 0 ? (
        <div className="empty">No tools match those filters</div>
      ) : (
        <div className="tools-grid">
          {filtered.map(t => (
            <ToolCard
              key={t.id || t.name}
              tool={t}
              onEdit={tool => setEditing(tool)}
              onDelete={handleDelete}
            />
          ))}
        </div>
      )}
    </>
  );
}

window.KOL_PAGES.Tools = Tools;
