(() => {
  "use strict";
  const bridge = window.chrome && window.chrome.webview ? window.chrome.webview : null;
  function post(msg) { if (bridge) bridge.postMessage(msg); }
  function ask(type) { post({ type }); }
  function toast(text) {
    const t = document.getElementById("toast");
    t.textContent = text;
    t.classList.add("show");
    setTimeout(() => t.classList.remove("show"), 2200);
  }
  function esc(s) {
    return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  }
  let allItems = [];

  const FMT = {
    hour: "the last hour",
    day: "the last 24 hours",
    week: "the last 7 days",
    month: "the last 4 weeks",
    all: "all time"
  };
  let since = "all";

  function onHostMessage(e) {
    let msg;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch { return; }
    if (!msg || !msg.type) return;
    if (msg.type === "history.data") { allItems = msg.items || []; render(); }
    else if (msg.type === "clear.browsing.done") { toast("Cleared"); ask("history.get"); }
  }
  if (bridge) bridge.addEventListener("message", onHostMessage);
  window.addEventListener("message", onHostMessage);
  ask("history.get");

  // Lucide clock (stroke icon, currentColor) — no emoji.
  const CLOCK_SVG = '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';

  function dayLabel(d) {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const day = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    const diff = Math.round((today - day) / 86400000);
    if (diff === 0) return "Today";
    if (diff === 1) return "Yesterday";
    return d.toLocaleDateString(undefined, {
      weekday: "long", day: "numeric", month: "long",
      year: d.getFullYear() !== now.getFullYear() ? "numeric" : undefined,
    });
  }

  function render() {
    const list = document.getElementById("historyList");
    const q = (document.getElementById("searchBox").value || "").trim().toLowerCase();
    const items = allItems.filter((h) => !q || (h.title || "").toLowerCase().includes(q) || h.url.toLowerCase().includes(q));
    if (!items.length) {
      list.innerHTML = `<div class="empty">${allItems.length ? "No history matches your search" : "No history yet — pages you visit will appear here"}</div>`;
      return;
    }
    // Group by day — only days that actually have visits (store order is newest first).
    const groups = [];
    const byDay = new Map();
    items.forEach((h) => {
      let d = null;
      try { d = new Date(h.visited); } catch { d = null; }
      if (!d || isNaN(d)) d = null;
      const key = d ? d.toDateString() : "unknown";
      if (!byDay.has(key)) { byDay.set(key, { day: d, items: [] }); groups.push(key); }
      byDay.get(key).items.push(h);
    });
    list.innerHTML = "";
    groups.forEach((key) => {
      const g = byDay.get(key);
      const head = document.createElement("div");
      head.className = "day-head";
      head.textContent = g.day ? dayLabel(g.day) : "Other";
      list.appendChild(head);
      g.items.forEach((h) => {
        const row = document.createElement("div");
        row.className = "list-item";
        row.style.cssText = "cursor:pointer";
        let time = "";
        try {
          const d = new Date(h.visited);
          if (!isNaN(d)) time = d.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
        } catch { }
        row.innerHTML = `
        <span style="display:inline-flex;opacity:.7;flex-shrink:0">${CLOCK_SVG}</span>
        <div style="min-width:0;flex:1">
          <div class="li-title">${esc(h.title || h.url)}</div>
          <div class="li-sub">${esc(h.url)}</div>
        </div>
        <span style="font-size:11px;color:var(--muted);flex-shrink:0">${time}</span>`;
        row.addEventListener("click", () => post({ type: "nav.url", url: h.url }));
        list.appendChild(row);
      });
    });
  }

  // ---------- Clear browsing data dialog ----------
  const dlg = document.getElementById("dlgOverlay");
  const chips = Array.from(document.querySelectorAll("#timeChips .chip"));

  function updateSummary() {
    const checked = Array.from(document.querySelectorAll(".tick-row input:checked")).map((i) => i.dataset.kind);
    document.getElementById("dlgSummary").textContent =
      `Clearing ${checked.length ? checked.join(", ") : "nothing"} from ${FMT[since]}.`;
  }
  chips.forEach((c) => c.addEventListener("click", () => {
    chips.forEach((x) => x.classList.remove("active"));
    c.classList.add("active");
    since = c.dataset.since;
    updateSummary();
  }));
  document.querySelectorAll(".tick-row input").forEach((i) => i.addEventListener("change", updateSummary));

  function openClearDlg() {
    // Sensible defaults every time: history ticked, rest off, time = everything.
    document.querySelectorAll(".tick-row input").forEach((i) => { i.checked = i.dataset.kind === "history"; });
    chips.forEach((c) => c.classList.toggle("active", c.dataset.since === "all"));
    since = "all";
    updateSummary();
    dlg.classList.remove("hidden");
  }
  document.getElementById("clearBtn").addEventListener("click", openClearDlg);
  document.getElementById("dlgCancel").addEventListener("click", () => dlg.classList.add("hidden"));
  dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.classList.add("hidden"); });
  document.getElementById("dlgOk").addEventListener("click", () => {
    const kinds = Array.from(document.querySelectorAll(".tick-row input:checked")).map((i) => i.dataset.kind);
    if (!kinds.length) { dlg.classList.add("hidden"); return; }
    const data = { since };
    kinds.forEach((k) => (data[k] = true));
    post({ type: "clear.browsing", data });
    dlg.classList.add("hidden");
  });

  document.getElementById("searchBox").addEventListener("input", render);
})();
