<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>PTM ステータス</title>
<script type="application/json" id="claude-artifacts-manifest">{"permissions": ["notifications", "menu-bar"]}</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+JP:wght@400;500;700&display=swap" rel="stylesheet">
<style>
/* VOICE: サイト（pixelstomotors.com）と同じ。静かで、知らせることだけが目に入る
   IDEA: ハコブくんが「いま知らせること」を読み上げる見張り番
   PICTURE: ハコブくんの顔と、その日の一言。下に見張っている3つ
   COLOUR and TYPE: 地 #f7f7f7・面 #fff・字 #242424。青 #2f6fdf は届いた相談（主役）だけ、赤は費用と止まり。Inter + Noto Sans JP
   LAYOUT: 縦1列。ハコブくんの一言 → 見張り3つ → サイトの数字 → 操作 */
:root{color-scheme:light;--ink:#242424;--ink2:#555;--ink3:#888;--bg:#f7f7f7;--panel:#fff;--blue:#2f6fdf;--red:#C8322B;--sans:Inter,'Noto Sans JP',sans-serif}
*{box-sizing:border-box;min-width:0}
body{margin:0;background:var(--bg);color:var(--ink);font:400 14px/1.6 var(--sans);overflow-x:clip}
.top{app-region:drag;height:36px}
main{padding:0 16px 20px;max-width:560px;margin:0 auto;display:grid;gap:12px}
.panel{background:var(--panel);border-radius:16px;padding:20px}
.say{display:grid;grid-template-columns:112px minmax(0,1fr);gap:16px;align-items:center}
.say{padding-bottom:0;align-items:end}.say img{width:112px;height:auto;display:block;border-radius:0 0 0 0}.say>div{padding-bottom:20px}
.say h1{margin:0;font:700 18px/1.45 var(--sans)}
.say p{margin:4px 0 0;color:var(--ink3);font-size:13px}
.watch{padding:8px 20px}
.row{display:grid;grid-template-columns:12px minmax(0,1fr) auto;gap:4px 10px;align-items:baseline;padding:12px 0}
.row+.row{box-shadow:0 -1px 0 #f2f2f2} /* line-ok 行の区切り（1px） */
.dot{width:7px;height:7px;border-radius:50%;background:#9a9a9a;transform:translateY(-1px)}
.dot.blue{background:var(--blue)}.dot.red{background:var(--red)}
.row b{font-weight:500}
.row .val{color:var(--ink2);text-align:right;white-space:nowrap}
.row .sub{white-space:pre-line;grid-column:2/-1;color:var(--ink3);font-size:13px}
.row.blue .val{color:var(--blue);font-weight:600}.row.red .val{color:var(--red);font-weight:600}
.row button{grid-column:2/-1;justify-self:start;margin-top:4px}
h2{margin:0 0 12px;font:600 13px/1.4 var(--sans);color:var(--ink3)}
.nums{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.num span{display:block;color:var(--ink3);font-size:12px;line-height:1.4}
.num strong{display:block;font:600 28px/1.2 Inter,sans-serif;font-variant-numeric:tabular-nums;margin-top:4px}
.num.blue strong{color:var(--blue)}
.num em{white-space:pre-line;font-style:normal;color:var(--ink3);font-size:12px}
.acts{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
button{font:500 14px/1 var(--sans);min-height:36px;padding:0 16px;border-radius:4px;border:0;background:var(--ink);color:#fff;cursor:pointer}
button.light{background:#f0f0f0;color:var(--ink)}
button:focus-visible{outline:2px solid var(--blue);outline-offset:2px}
.note{color:var(--ink3);font-size:12px;margin:0}
#err{display:none;color:var(--red);font-size:13px;margin:0}
</style>
</head>
<body>
<div class="top"></div>
<main>
  <section class="panel say">
    <img id="face" alt="">
    <div><h1 id="say">読み込んでいます</h1><p id="fresh"></p></div>
  </section>

  <section class="panel watch" aria-label="見張っていること">
    <div class="row" id="r-inq"><i class="dot"></i><b>サイトへの相談</b><span class="val">–</span><span class="sub"></span></div>
    <div class="row" id="r-pod"><i class="dot"></i><b>Runpod の Pod</b><span class="val">–</span><span class="sub"></span></div>
    <div class="row" id="r-inbox"><i class="dot"></i><b>依頼箱</b><span class="val">–</span><span class="sub"></span></div>
  </section>

  <section class="panel">
    <h2>サイトの主な数字（今日）</h2>
    <div class="nums">
      <div class="num" id="n-refs"><span>AI から来た人</span><strong>–</strong><em></em></div>
      <div class="num" id="n-reads"><span>AI が読んだ数</span><strong>–</strong><em></em></div>
      <div class="num" id="n-name"><span>サイト名の検索</span><strong>–</strong><em></em></div>
    </div>
  </section>

  <section class="acts" id="acts"></section>
  <p class="note" id="note"></p>
  <p id="err" role="status"></p>
</main>

<script>
{
const $ = (id) => document.getElementById(id);
const SERVER = "PTMの計測";
const jst = (ms) => new Date(ms + 9 * 3600e3).toISOString().slice(0, 10);
const today = jst(Date.now());
const d0 = new Date(today + "T00:00:00Z");
const dow = (d0.getUTCDay() + 6) % 7;
const weekMon = jst(Date.UTC(d0.getUTCFullYear(), d0.getUTCMonth(), d0.getUTCDate() - dow) - 9 * 3600e3);
const kpiSince = jst(Date.parse(weekMon + "T00:00:00Z") - 7 * 86400e3 - 9 * 3600e3);
const hm = (iso) => new Date(iso).toLocaleString("ja-JP", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" });
const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 60 ? `${m}分前` : m < 1440 ? `${Math.round(m / 60)}時間前` : `${Math.round(m / 1440)}日前`; };

let desktop = null, mcp = null;
const S = { inq: null, pod: null, inbox: null, kpi: null };
const seen = (() => { try { return JSON.parse(localStorage.getItem("ptm-status-v2") || "{}"); } catch { return {}; } })();
const save = () => { try { localStorage.setItem("ptm-status-v2", JSON.stringify(seen)); } catch {} };

/* ---------- ハコブくん：解説動画と同じ絵（face/make_video_faces.py が 動画/_制作ベース/hakobu.py の Hakobu().frame で描いた上半身。base・joy・trouble） ---------- */
const FACES = {"base": "（PNG の data URI・59,098字。face/make_video_faces.py の出力 faces.json の base）", "joy": "（PNG の data URI・59,242字。face/make_video_faces.py の出力 faces.json の joy）", "worry": "（PNG の data URI・59,902字。face/make_video_faces.py の出力 faces.json の worry）", "dock": "（PNG の data URI・143,594字。face/make_video_faces.py の出力 faces.json の dock）", "tray": "（PNG の data URI・1,130字。face/make_video_faces.py の出力 faces.json の tray）"};
function setFace(mood) { const el = $("face"); if (el.dataset.mood !== mood) { el.src = FACES[mood]; el.dataset.mood = mood; } }
function drawIcon(size, template) { return Promise.resolve(template ? FACES.tray : FACES.dock); }

/* ---------- 見張りの判定（state: blue=知らせ / red=費用・止まり / ok） ---------- */
function judge() {
  const out = {};
  const q = S.inq;
  if (q?.err) out.inq = { state: "ok", val: q.err, sub: "" };
  else if (q) {
    const fresh = q.latestAt && Date.parse(q.latestAt) > Date.now() - 3 * 86400e3;
    out.inq = { state: fresh ? "blue" : "ok", val: q.latestAt ? (fresh ? `届きました（${ago(q.latestAt)}）` : "新しい相談なし") : "まだ届いていない",
      sub: q.recent?.[0] ? `最新：${hm(q.recent[0].at)}・${q.recent[0].topic}` : "", btn: fresh ? ["メールを確かめた", () => { seen.inqAck = q.latestAt; save(); refreshView(); }] : null };
    if (fresh && seen.inqAck === q.latestAt) { out.inq.state = "ok"; out.inq.val = `確かめ済み（${ago(q.latestAt)}）`; out.inq.btn = null; }
  }
  const p = S.pod;
  if (p?.err) out.pod = { state: "ok", val: p.err, sub: "" };
  else if (p) {
    const run = p.pods.filter((x) => ["RUNNING", "STARTING", "PROVISIONING"].includes(x.status));
    const stop = p.pods.filter((x) => ["EXITED", "ERROR"].includes(x.status));
    const cost = run.reduce((a, x) => a + (x.costPerHr || 0), 0);
    out.pod = run.length || stop.length
      ? { state: "red", val: run.length ? `${run.length}台が動いています` : `${stop.length}台が停止のまま`,
          sub: [run.length ? `$${cost.toFixed(2)}/時・最長 ${Math.max(...run.map((x) => x.runningHours || 0))}時間` : "", stop.length ? `停止のまま削除していない ${stop.length}台（ディスク料金）` : ""].filter(Boolean).join("\n"),
          link: "https://console.runpod.io/pods" }
      : { state: "ok", val: "Pod なし", sub: "" };
  }
  const b = S.inbox;
  if (b?.err) out.inbox = { state: "ok", val: b.err, sub: "" };
  else if (b && !b.found) out.inbox = { state: "ok", val: "まだつながっていない", sub: "Mac の依頼箱から状態を送る仕組みを作る予定" };
  else if (b) {
    const stuck = (b.columns || []).filter((c) => c.current && Date.now() - Date.parse(c.current.lastProgressAt || c.current.startedAt) > 60 * 60e3);
    const busy = (b.columns || []).filter((c) => c.current);
    const quiet = b.ageMinutes > 30;
    out.inbox = { state: stuck.length || quiet ? "red" : "ok",
      val: quiet ? `${b.ageMinutes}分 便りなし` : stuck.length ? `${stuck.map((c) => c.name).join("・")}が止まっています` : busy.length ? `${busy.length}列が動いています` : "待機中",
      sub: busy.map((c) => `${c.name}：依頼${c.current.id}（${ago(c.current.lastProgressAt || c.current.startedAt)}に進んだ）`).join("\n") };
  }
  return out;
}

function paintRow(id, r) {
  const el = $(id); if (!r) return;
  el.className = "row " + (r.state === "ok" ? "" : r.state);
  el.querySelector(".dot").className = "dot " + (r.state === "ok" ? "" : r.state);
  el.querySelector(".val").textContent = r.val;
  if (r.sub !== undefined) el.querySelector(".sub").textContent = r.sub;
  el.querySelector("button")?.remove();
  if (r.btn) { const b = document.createElement("button"); b.className = "light"; b.textContent = r.btn[0]; b.onclick = r.btn[1]; el.append(b); }
}

function refreshView() {
  const J = judge();
  paintRow("r-inq", J.inq); paintRow("r-pod", J.pod); paintRow("r-inbox", J.inbox);
  const top = [J.inq?.state === "blue" && "サイトに相談が届いています", J.pod?.state === "red" && "Runpod の Pod を確かめてください", J.inbox?.state === "red" && "依頼箱が進んでいません"].filter(Boolean);
  $("say").textContent = top[0] || "いま知らせることはありません";
  setFace(J.inq?.state === "blue" ? "joy" : top.length ? "worry" : "base");
  const k = S.kpi;
  if (k) {
    $("n-refs").querySelector("strong").textContent = k.refs; $("n-refs").classList.toggle("blue", k.refs > 0);
    $("n-refs").querySelector("em").textContent = `今週 ${k.wRefs ?? "–"}\n先週 ${k.pRefs ?? "–"}`;
    $("n-reads").querySelector("strong").textContent = k.reads;
    $("n-reads").querySelector("em").textContent = `今週 ${k.wReads ?? "–"}\n先週 ${k.pReads ?? "–"}`;
    $("n-name").querySelector("strong").textContent = k.name ?? "–";
    $("n-name").querySelector("em").textContent = k.nameWeek ? `${k.nameWeek.slice(5).replace("-", "/")} の週` : "記録なし";
  }
  $("fresh").textContent = `${new Date().toLocaleTimeString("ja-JP", { hour: "2-digit", minute: "2-digit" })} に確かめました`;
  setTray(J, top);
  desktop?.app?.dock.setBadge(top.length ? String(top.length) : "").catch(() => {});
}

/* ---------- 通知（同じことは1回だけ） ---------- */
async function notify(key, body) {
  if (seen.n?.[key]) return;
  seen.n = seen.n || {}; seen.n[key] = Date.now();
  for (const [k, t] of Object.entries(seen.n)) if (Date.now() - t > 14 * 86400e3) delete seen.n[k];
  save();
  if (!seen.primed) return; // 初めて開いたときは、今ある状態を覚えるだけで鳴らさない
  if (desktop?.notification && (await perm("notifications")) === "granted") desktop.notification.show({ body: body.slice(0, 300) }).catch(() => {});
}
function checkNotify() {
  const q = S.inq; if (q?.latestAt) notify("inq:" + q.latestAt, `サイトに相談が届きました（${q.recent?.[0]?.topic || ""}）。メールを確かめてください`);
  const p = S.pod;
  if (p?.pods) {
    for (const x of p.pods) if (x.status === "RUNNING" && (x.runningHours || 0) >= 3) notify(`pod:${x.id}:${x.startedAt}`, `Runpod の Pod「${x.name}」が${x.runningHours}時間動いています（$${x.costPerHr}/時）`);
    const stop = p.pods.filter((x) => ["EXITED", "ERROR"].includes(x.status));
    if (stop.length) notify("podstop:" + today, `停止したまま削除していない Pod が${stop.length}台あります。ディスクの料金がかかり続けます`);
  }
  const b = S.inbox;
  if (b?.found) {
    for (const c of b.columns || []) if (c.current && Date.now() - Date.parse(c.current.lastProgressAt || c.current.startedAt) > 60 * 60e3) notify(`stuck:${c.name}:${c.current.id}:${c.current.lastProgressAt}`, `依頼箱の${c.name}の列（依頼${c.current.id}）が1時間進んでいません`);
    if (b.ageMinutes > 30) notify("quiet:" + b.receivedAt, `依頼箱から${b.ageMinutes}分便りがありません。依頼箱か Mac が止まっているかもしれません`);
  }
  const k = S.kpi; if (k && k.refs > 0) notify(`ref:${today}:${k.refs}`, `AI のサービスのリンクから人が来ました（今日 ${k.refs}人）`);
  if (S.inq && S.pod && S.inbox && S.kpi && !seen.primed) { seen.primed = true; save(); }
}

/* ---------- メニューバー ---------- */
async function perm(name) { return desktop?.permissions ? desktop.permissions.state(name).catch(() => "unavailable") : "unavailable"; }
async function setTray(J, top) {
  if (!desktop?.tray || (await perm("menu-bar")) !== "granted") return;
  const line = (label, r) => ({ label: `${r?.state === "ok" || !r ? "　" : "●"} ${label}：${r?.val ?? "–"}`, enabled: false });
  desktop.tray.set({
    icon: await drawIcon(36, true),
    title: top.length ? top[0].replace(/を確かめてください|が届いています|が進んでいません/, "").slice(0, 14) : "",
    toolTip: top[0] || "いま知らせることはありません",
    menu: [
      line("相談", J.inq), line("Runpod", J.pod), line("依頼箱", J.inbox),
      { label: `　AI のリンクから来た人（今日）：${S.kpi?.refs ?? "–"}`, enabled: false },
      { type: "separator" },
      { label: "今すぐ確かめる", click: () => refreshAll() },
      { label: "画面を開く", click: () => desktop.window.show().catch(() => {}) },
      { label: "Runpod を開く", href: "https://console.runpod.io/pods" },
      { label: "pixelstomotors.com を開く", href: "https://pixelstomotors.com/" }
    ]
  }).catch((e) => showErr(`メニューバーに出せませんでした：${e.message}`));
}
function showErr(t) { $("err").textContent = t; $("err").style.display = t ? "block" : "none"; }

/* ---------- データ ---------- */
const errText = (e) => ({ server_not_connected: "コネクタ「PTMの計測」がない", needs_reauth: "コネクタをつなぎ直す", tool_error: "まだ使えない", not_in_manifest: "許可がない", approval_required: "許可がない" }[e?.code] || "読めなかった");
const WATCH = [
  ["inquiries", () => ({ since: new Date(Date.now() - 7 * 86400e3).toISOString() }), 5, (p) => (S.inq = p)],
  ["runpod_pods", () => ({}), 10, (p) => (S.pod = p.ok === false ? { err: `読めなかった（${p.status}）` } : p)],
  ["inbox_status", () => ({}), 5, (p) => (S.inbox = p)],
  ["kpi", () => ({ since: kpiSince }), 15, (p) => {
    const t = (p.byDay || []).find((d) => d.day === today) || {};
    const w = p.byWeek || [], ns = (p.nameSearch || []).filter((x) => x && x.clicks != null);
    S.kpi = { refs: t.aiReferrals || 0, reads: t.aiReads || 0, wRefs: w.at(-1)?.aiReferrals, pRefs: w.at(-2)?.aiReferrals, wReads: w.at(-1)?.aiReads, pReads: w.at(-2)?.aiReads, name: ns.at(-1)?.clicks, nameWeek: ns.at(-1)?.week };
  }],
];
const ERR_KEY = { inquiries: "inq", runpod_pods: "pod", inbox_status: "inbox" };
function onData(tool, set) {
  return (ev) => {
    if (ev.type === "data") set(ev.result.payload || {});
    else if (ERR_KEY[tool]) S[ERR_KEY[tool]] = { err: errText(ev.error) };
    if (ev.type === "error" && ["server_not_connected", "needs_reauth"].includes(ev.error?.code)) showErr("コネクタ「PTMの計測」を claude.ai の設定 → コネクタで確かめてください。");
    refreshView(); checkNotify();
  };
}
async function refreshAll() {
  for (const [tool, input, , set] of WATCH) {
    try { const r = await mcp.callTool(SERVER, tool, input(), { cache: { refresh: true } }); set(r.payload || {}); }
    catch (e) { if (ERR_KEY[tool]) S[ERR_KEY[tool]] = { err: errText(e) }; }
  }
  refreshView(); checkNotify();
}

function addBtn(label, fn, light) {
  const b = document.createElement("button"); b.textContent = label; if (light) b.className = "light"; b.onclick = fn; $("acts").append(b); return b;
}

async function setupDesktop() {
  desktop = await claude.use("desktop");
  if (!desktop?.tray) {
    if ((await desktop?.install?.state().catch(() => "unavailable")) === "available") addBtn("アプリとして入れる", () => desktop.install.request().catch(() => {}));
    else $("note").textContent = "メニューバーと通知は、Claude のデスクトップアプリで「アプリとして入れる」と使えます。";
    return;
  }
  drawIcon(512, false).then((u) => desktop.app.dock.setIcon(u)).catch(() => {});
  desktop.window.setOptions({ titleBarStyle: "hiddenInset", dragHeight: 36, width: 400, height: 640 }).catch(() => {});
  const s = await desktop.permissions.state().catch(() => ({}));
  if (s["menu-bar"] !== "granted" || s.notifications !== "granted") {
    const b = addBtn("メニューバーと通知を使う", async () => {
      const r = await desktop.permissions.request(["menu-bar", "notifications"]).catch(() => ({}));
      if (r["menu-bar"] === "denied" || r.notifications === "denied") addBtn("許可を変える", () => desktop.permissions.manage().catch(() => {}), true);
      else b.remove();
      refreshView();
    });
  }
  addBtn("今すぐ確かめる", () => refreshAll(), true);
}

setFace("base");
refreshView();
(async () => {
  setupDesktop().catch(() => {});
  mcp = await claude.use("mcp");
  if (!mcp) { $("say").textContent = "この表示ではコネクタを使えません"; showErr("claude.ai か Claude のデスクトップアプリで開いてください。"); return; }
  for (const [tool, input, min, set] of WATCH) {
    mcp.watchTool(SERVER, tool, input(), onData(tool, set), { cache: { staleTime: 60e3, gcTime: 24 * 3600e3 }, refetchInterval: min * 60e3 });
  }
})();
}
</script>
</body>
</html>
