Newer
Older
2025-shino / map4.js
// ===================================
// Supabase 設定
// ===================================
const SUPABASE_URL = "https://ogtlmtnjkpsxsqzqlacj.supabase.co";
const SUPABASE_KEY =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9ndGxtdG5qa3BzeHNxenFsYWNqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjMyOTU3NjUsImV4cCI6MjA3ODg3MTc2NX0.JnCE7oUQwrSgGqiu-QRbwnaLBZrO8JX1_RUb37VIMFI";

const supa = window.supabase.createClient(SUPABASE_URL, SUPABASE_KEY);

// ===================================
// グローバル変数
// ===================================
let deviceId = localStorage.getItem("deviceId");
if (!deviceId) {
  deviceId = crypto.randomUUID();
  localStorage.setItem("deviceId", deviceId);
}

let currentGroup = "";
let currentUser = "";
let isHost = false;
let currentHostName = "";

let map;
let selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let allMembers = [];

let lastLat = null;
let lastLng = null;

let targetMarker = null;
let stationMarkers = [];
let targetLat = null;
let targetLng = null;

// --------------------------------------
// ステータス:デフォルトは「移動中」
// --------------------------------------
let myStatus = localStorage.getItem("myStatus") || "移動中";

// ===================================
// ステータスを Supabase に保存
// ===================================
async function updateStatus(newStatus) {
  myStatus = newStatus;
  localStorage.setItem("myStatus", newStatus);

  await supa
    .from("locations")
    .update({ status: newStatus })
    .eq("group_name", currentGroup)
    .eq("device_id", deviceId);

  showOtherUsers(); // メンバーリスト更新
}

// ===================================
// ステータスボタン設定
// ===================================
function setupStatusButtons() {
  const buttons = document.querySelectorAll(".stBtn");
  buttons.forEach((btn) => {
    btn.addEventListener("click", () => {
      const newStatus = btn.dataset.status;
      updateStatus(newStatus);
    });
  });
}

// ===================================
// 待ち合わせピン
// ===================================
const meetIcon = L.icon({
  iconUrl:
    "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-violet.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});

// ===================================
// URL パラメータ読み込み
// ===================================
function loadParams() {
  const p = new URLSearchParams(location.search);
  currentGroup = p.get("group");
  currentUser = p.get("user");

  document.getElementById("groupName").textContent = currentGroup;
  document.getElementById("userName").textContent = currentUser;

  localStorage.setItem("group", currentGroup);
  localStorage.setItem("userName", currentUser);
}

// ===================================
// 現在位置取得
// ===================================
function getPosition() {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      (pos) => resolve(pos.coords),
      (err) => reject(err),
      { enableHighAccuracy: true }
    );
  });
}

// ===================================
// 地図初期化
// ===================================
function initMap(lat, lng) {
  map = L.map("map").setView([lat, lng], 16);

  L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
  }).addTo(map);

  // ホストだけ待ち合わせを設定
  map.on("click", async (e) => {
    if (!isHost) return;

    const newLat = e.latlng.lat;
    const newLng = e.latlng.lng;

    if (targetLat !== null) {
      const ok = confirm("待ち合わせ場所を置き直しますか?");
      if (!ok) return;
    }

    targetLat = newLat;
    targetLng = newLng;

    if (targetMarker) map.removeLayer(targetMarker);
    targetMarker = L.marker([targetLat, targetLng], { icon: meetIcon }).addTo(map);

    await supa.from("shared_target").upsert({
      group_name: currentGroup,
      lat: targetLat,
      lng: targetLng,
    });

    document.getElementById("targetInfo").textContent =
      "待ち合わせ場所を設定しました!";
  });
}

// ===================================
// 自分の位置保存(ステータスも一緒に)
// ===================================
async function saveMyLocation(lat, lng) {
  await supa
    .from("locations")
    .delete()
    .eq("group_name", currentGroup)
    .eq("device_id", deviceId);

  await supa.from("locations").insert({
    group_name: currentGroup,
    user_name: currentUser,
    device_id: deviceId,
    lat,
    lng,
    status: myStatus,  // ★ 追加:ステータス保存
  });
}

// ===================================
// 自分のピン表示
// ===================================
function renderSelfMarker() {
  if (!map || lastLat === null || lastLng === null) return;

  if (selfMarker) map.removeLayer(selfMarker);

  selfMarker = createLabeledMarker(lastLat, lastLng, currentUser, true, myStatus);
  selfMarker.addTo(map);
}
// ===================================
// ピン生成(ステータス色ラベル)
// ===================================
function createLabeledMarker(lat, lng, name, isSelf, status) {
  const pinUrl = isSelf
    ? "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png"
    : "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-gold.png";

  // ステータスによって色分け
  const statusColor = {
    "移動中": "#4caf50",
    "遅れます": "#ff9800",
    "寄り道中": "#2196f3",
    "到着": "#9c27b0",
  }[status || "移動中"];

  const html = `
    <div class="pin-box">
      <img src="${pinUrl}" class="pin-img">
      <div class="pin-label">${name}</div>
      <div class="pin-status" style="
        background:${statusColor};
        color:white;
        padding:1px 6px;
        margin-top:2px;
        border-radius:8px;
        font-size:10px;
      ">${status}</div>
    </div>
  `;

  return L.marker([lat, lng], {
    icon: L.divIcon({
      className: "custom-pin",
      html: html,
      iconSize: [40, 60],
      iconAnchor: [20, 60],
    }),
  });
}

// ===================================
// メンバー一覧(ステータス追加)
// ===================================
function showMemberList(latestByDevice) {
  const list = document.getElementById("memberList");
  list.innerHTML = "";

  Object.values(latestByDevice).forEach((row) => {
    if (!allMembers.some((m) => m.device_id === row.device_id)) {
      allMembers.push({
        device_id: row.device_id,
        user_name: row.user_name,
      });
    }
  });

  allMembers.forEach((member) => {
    const row = latestByDevice[member.device_id];
    const li = document.createElement("li");

    const online =
      row && row.updated_at
        ? (Date.now() - new Date(row.updated_at)) / 1000 < 6
        : false;

    li.classList.toggle("online", online);
    li.classList.toggle("offline", !online);

    const crown = member.user_name === currentHostName ? "👑 " : "";
    const initial = member.user_name.charAt(0);
    const bgColor = member.device_id === deviceId ? "#4CAF50" : "#FFD700";
    const status = row?.status || "移動中";

    li.innerHTML = `
      <div class="member-icon"
        style="background:${bgColor}; color:white; font-weight:bold;">
        ${initial}
      </div>

      <div class="member-name">${crown}${member.user_name}</div>

      <div class="member-status"
        style="margin-left:auto; font-size:13px;">
        <span style="
          padding:2px 6px;
          border-radius:8px;
          background:${getStatusColor(status)};
          color:white;
          font-weight:bold;
        ">
          ${status}
        </span>
      </div>
    `;

    li.addEventListener("click", () => {
      const latestRow = latestByDevice[member.device_id];
      if (!latestRow) return;
      map.setView([latestRow.lat, latestRow.lng], 17, { animate: true });
    });

    list.appendChild(li);
  });
}

function getStatusColor(s) {
  return {
    "移動中": "#4caf50",
    "遅れます": "#ff9800",
    "寄り道中": "#2196f3",
    "到着": "#9c27b0",
  }[s] || "#ccc";
}

// ===================================
// 共有待ち合わせ読み込み
// ===================================
async function loadSharedTarget() {
  const { data } = await supa
    .from("shared_target")
    .select("*")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (!data) return;

  targetLat = data.lat;
  targetLng = data.lng;

  if (targetMarker) map.removeLayer(targetMarker);

  targetMarker = L.marker([targetLat, targetLng], { icon: meetIcon }).addTo(map);

  document.getElementById("targetInfo").textContent =
    "待ち合わせ場所が共有されました!";
}

// ===================================
// チャット読み込み
// ===================================
async function loadMessages() {
  const chatList = document.getElementById("chatList");

  const { data } = await supa
    .from("messages")
    .select("*")
    .eq("group_name", currentGroup)
    .order("created_at", { ascending: true });

  chatList.innerHTML = data
    .map((m) => {
      const isMe = m.user_name === currentUser;
      const side = isMe ? "chat-right" : "chat-left";

      return `
        <div class="chat-line ${side}">
          <div class="chat-bubble">
            ${isMe ? "" : `<strong>${m.user_name}</strong><br>`}
            ${m.message}
          </div>
          <span class="chat-time">${formatTime(m.created_at)}</span>
        </div>
      `;
    })
    .join("");

  chatList.scrollTop = chatList.scrollHeight;
}

function formatTime(t) {
  const d = new Date(t);
  return `${String(d.getHours()).padStart(2, "0")}:${String(
    d.getMinutes()
  ).padStart(2, "0")}`;
}

// ===================================
// チャット送信
// ===================================
async function sendMessage() {
  const input = document.getElementById("chatInput");
  const text = input.value.trim();
  if (!text) return;

  await supa.from("messages").insert({
    group_name: currentGroup,
    user_name: currentUser,
    message: text,
  });

  input.value = "";
  loadMessages();
}

// ===================================
// ホスト自動交代
// ===================================
async function checkHostAuto() {
  const { data: group } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (!group) return;

  currentHostName = group.host_name;

  const onlineUsers = Object.values(latestByDevice).filter(
    (u) => (Date.now() - new Date(u.updated_at)) / 1000 < 6
  );

  const hostOnline = onlineUsers.some((u) => u.user_name === currentHostName);

  if (!hostOnline && onlineUsers.length > 0) {
    const newHost = onlineUsers.sort(
      (a, b) => new Date(b.updated_at) - new Date(a.updated_at)
    )[0];

    await supa
      .from("groups")
      .update({ host_name: newHost.user_name })
      .eq("group_name", currentGroup);

    currentHostName = newHost.user_name;
    isHost = currentUser === currentHostName;
  }

  document.getElementById("hostStatus").textContent = isHost
    ? "あなたはホストです"
    : "一般メンバーです";

  document.getElementById("disbandBtn").style.display = isHost
    ? "inline-block"
    : "none";
}

// ===================================
// グループ解散
// ===================================
async function disbandGroup() {
  if (!isHost) return alert("ホストのみ解散できます");

  const ok = confirm("このグループを解散しますか?");
  if (!ok) return;

  await supa
    .from("groups")
    .update({ is_active: false })
    .eq("group_name", currentGroup);

  location.href = `archive.html?group=${encodeURIComponent(currentGroup)}`;
}

// ===================================
// グループ状態確認
// ===================================
async function checkGroupActive() {
  const { data } = await supa
    .from("groups")
    .select("is_active")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (!data || data.is_active === false) {
    alert("このグループは解散されました。");
    location.href = `archive.html?group=${encodeURIComponent(currentGroup)}`;
  }
}

// ===================================
// メイン
// ===================================
async function main() {
  loadParams();

  setupStatusButtons();

  let lat = 35.681236,
    lng = 139.767125; // 皇居

  try {
    const pos = await getPosition();
    lat = pos.latitude;
    lng = pos.longitude;
  } catch {}

  lastLat = lat;
  lastLng = lng;

  initMap(lat, lng);
  renderSelfMarker();
  await saveMyLocation(lat, lng);

  await showOtherUsers();
  loadSharedTarget();
  loadMessages();

  // 定期更新
  setInterval(async () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;
      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
    } catch {}
  }, 2500);

  setInterval(showOtherUsers, 1500);
  setInterval(loadSharedTarget, 9000);
  setInterval(loadMessages, 2500);
  setInterval(checkHostAuto, 4000);
  setInterval(checkGroupActive, 4000);

  document.getElementById("exitBtn").onclick = () =>
    (location.href = "index.html");
  document.getElementById("disbandBtn").onclick = disbandGroup;

  document.getElementById("chatSend").onclick = sendMessage;
  document.getElementById("chatInput").addEventListener("keydown", (e) => {
    if (e.key === "Enter") sendMessage();
  });
}

// ===================================
// DOMContentLoaded
// ===================================
window.addEventListener("DOMContentLoaded", async () => {
  const p = new URLSearchParams(location.search);
  const groupName = p.get("group");
  const user = p.get("user");

  const { data: group } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", groupName)
    .maybeSingle();

  if (!group) {
    alert("グループが存在しません");
    location.href = "index.html";
    return;
  }

  if (group.is_active === false) {
    alert("このグループは解散されています");
    location.href = `archive.html?group=${groupName}`;
    return;
  }

  currentHostName = group.host_name;
  isHost = currentHostName === user;

  main();
});