// ===================================
// 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 map;
let selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};

let lastLat = null;
let lastLng = null;

const DEFAULT_LAT = 35.681236;
const DEFAULT_LNG = 139.767125;

// ===================================
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;
}

// ==================================================
// ラベル付きピンを作成（常時名前表示）
// ==================================================
function createLabeledMarker(lat, lng, name, isSelf) {
  const icon = L.divIcon({
    className: "",
    html: `
      <div style="position: relative; transform: translate(-20px, -55px);">
         <img src="${
           isSelf
             ? "https://maps.gstatic.com/mapfiles/kml/paddle/blu-stars.png"
             : "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png"
         }" style="width:40px;">
         <div class="marker-label">${name}</div>
      </div>
    `,
    iconSize: [40, 55],
    iconAnchor: [20, 55],
  });

  return L.marker([lat, lng], { icon });
}

// ===================================
function getPosition() {
  return new Promise((res, rej) => {
    navigator.geolocation.getCurrentPosition(
      pos => res(pos.coords),
      rej,
      { 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);
}

// ===================================
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,
  });
}

// ===================================
function renderSelfMarker() {
  if (selfMarker) map.removeLayer(selfMarker);

  selfMarker = createLabeledMarker(lastLat, lastLng, currentUser, true);
  selfMarker.addTo(map);

  selfMarker.on("click", (e) => {
    map.panTo(e.latlng, { animate: true, duration: 0.4 });
  });
}

// ===================================
function showMemberList(latestByDevice) {
  const list = document.getElementById("memberList");
  list.innerHTML = "";

  Object.values(latestByDevice).forEach((row) => {
    const li = document.createElement("li");

    const updated = new Date(row.updated_at);
    const diff = (Date.now() - updated) / 1000;
    const isOnline = diff < 30;

    li.classList.add(isOnline ? "online" : "offline");

    const icon = document.createElement("div");
    icon.className = "member-icon";
    li.append(icon);

    li.append(row.user_name);

    li.onclick = () => {
      if (row.device_id === deviceId) {
        selfMarker.fire("click");
      } else {
        const mk = otherMarkers.find(m => m._deviceId === row.device_id);
        if (mk) mk.fire("click");
      }
    };

    list.appendChild(li);
  });
}

// ===================================
async function showOtherUsers() {
  const { data } = await supa
    .from("locations")
    .select("*")
    .eq("group_name", currentGroup)
    .order("updated_at", { ascending: false });

  latestByDevice = {};
  if (!Array.isArray(data)) return;

  for (const r of data) {
    if (!latestByDevice[r.device_id]) latestByDevice[r.device_id] = r;
  }

  showMemberList(latestByDevice);

  otherMarkers.forEach(m => map.removeLayer(m));
  otherMarkers = [];

  Object.values(latestByDevice).forEach((row) => {
    if (row.device_id === deviceId) return;

    const mk = createLabeledMarker(row.lat, row.lng, row.user_name, false);
    mk._deviceId = row.device_id;

    mk.on("click", (e) => {
      map.panTo(e.latlng, { animate: true, duration: 0.4 });
    });

    mk.addTo(map);
    otherMarkers.push(mk);
  });
}

// ===================================
async function main() {
  loadParams();

  let lat = DEFAULT_LAT, lng = DEFAULT_LNG;
  try {
    const p = await getPosition();
    lat = p.latitude;
    lng = p.longitude;
  } catch {}

  lastLat = lat;
  lastLng = lng;

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

  setInterval(async () => {
    try {
      const p = await getPosition();
      lastLat = p.latitude;
      lastLng = p.longitude;
      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
    } catch {}
  }, 8000);

  setInterval(showOtherUsers, 2000);

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

  setTimeout(() => map.invalidateSize(), 500);
}

window.addEventListener("DOMContentLoaded", main);
