// ===================================
// 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 lastLat = null;
let lastLng = null;

let targetMarker = null;
let targetLat = null;
let targetLng = null;

let stationMarkers = [];

/* ==========================================================
   共有機能（リンク / QR / 共有シート）
========================================================== */

let shareURL = "";

// モーダル制御
function closeShare() {
  document.getElementById("shareModal").style.display = "none";
}
function closeQR() {
  document.getElementById("qrModal").style.display = "none";
}

// 共有メニューを開く
const shareBtn = document.getElementById("shareBtn");
if (shareBtn) {
  shareBtn.addEventListener("click", async () => {

    // パスワード取得
    const { data } = await supa
      .from("groups")
      .select("password")
      .eq("group_name", currentGroup)
      .maybeSingle();

    const pass = data.password;

    shareURL =
      `https://www.yatex.org/gitbucket/KoekiGameDesign/2025-shino/pages/join_group.html`
      + `?group=${encodeURIComponent(currentGroup)}`
      + `&pass=${encodeURIComponent(pass)}`;

    document.getElementById("shareModal").style.display = "flex";
  });
}

/* 🔗 リンクでシェア */
const shareLinkBtn = document.getElementById("shareLinkBtn");
if (shareLinkBtn) {
  shareLinkBtn.addEventListener("click", async () => {

    // Safari・iPhone 全対応
    if (navigator.share) {
      navigator.share({
        title: "グループ招待",
        text: "参加はこちら！",
        url: shareURL
      });
      return;
    }

    // 通常コピー
    try {
      await navigator.clipboard.writeText(shareURL);
      alert("コピーしました！");
    } catch {
      alert("コピーできませんでした。");
    }
  });
}

/* 📱 QRコードでシェア */
const shareQRBtn = document.getElementById("shareQRBtn");
if (shareQRBtn) {
  shareQRBtn.addEventListener("click", () => {
    document.getElementById("qrModal").style.display = "flex";
    document.getElementById("qrcode").innerHTML = "";

    new QRCode(document.getElementById("qrcode"), {
      text: shareURL,
      width: 200,
      height: 200
    });
  });
}
// ===================================
// 自分の状態（移動中 / 遅れます / 寄り道中 / 到着）
// ===================================
let myStatus = localStorage.getItem("myStatus") || "移動中";

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() {
  document.querySelectorAll(".stBtn").forEach((btn) => {
    btn.addEventListener("click", () =>
      updateStatus(btn.dataset.status)
    );
  });
}

// ===================================
// エレベーター情報（CSV 読み込み）
// ===================================
let elevatorInfo = new Map();

// elevators.csv は map4.js / map4.html と同じフォルダ想定
fetch("./elevators.csv")
  .then((res) => res.text())
  .then((text) => {
    const lines = text.split("\n").slice(1); // 1行目ヘッダ除外

    lines.forEach((line) => {
      if (!line.trim()) return;
      const [station, hasEV] = line.split(",");
      elevatorInfo.set(station.trim(), hasEV.trim() === "1");
    });

    console.log("EVデータ読み込み成功:", elevatorInfo);
  });

const elevatorIcon = L.icon({
  iconUrl: "./marker-icon-red.png",   // ← map4.js と同じ場所の画像
  shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
});

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

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

// ===================================
// 名前ラベル付きピン作成
// ===================================
function createLabeledMarker(lat, lng, name, isSelf) {
  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 html = `
    <div style="position: relative; width: 80px; height: 70px;">
      <div style="
        position:absolute; top:0; left:50%; transform:translateX(-50%);
        width:78px; height:28px; padding:2px 4px;
        background:white; border:1px solid #666; border-radius:6px;
        font-size:12px; text-align:center; white-space:nowrap;
        overflow:hidden; text-overflow:ellipsis;
      ">
        ${name}
      </div>
      <img src="${pinUrl}" style="
        position:absolute; bottom:0; left:50%; transform:translateX(-50%);
        width:25px; height:41px;
      ">
    </div>`;

  return L.marker([lat, lng], {
    icon: L.divIcon({
      html,
      className: "",
      iconSize: [80, 70],
      iconAnchor: [40, 41],
    }),
  });
}

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

  if (selfMarker) map.removeLayer(selfMarker);

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

// ===================================
// 自分の位置を Supabase に保存
// ===================================
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,
  });
}

// ===================================
// 待ち合わせピンアイコン
// ===================================
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],
});

// ===================================
// 地図初期化
// ===================================
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) {
      if (!confirm("待ち合わせ場所を置き直しますか？")) 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 loadSharedTarget() {
  const { data, error } = await supa
    .from("shared_target")
    .select("*")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (error) {
    console.error("shared_target 読み込みエラー:", error);
    return;
  }

  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 =
    "待ち合わせ場所が共有されました！";

  showDistanceToTarget();
}

// ===================================
// 距離計算（修正版）
// ===================================
function distanceMeters(lat1, lng1, lat2, lng2) {
  const R = 6371000;
  const toRad = (deg) => (deg * Math.PI) / 180;

  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);  // ← ここが大事！

  const a =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(lat1)) *
      Math.cos(toRad(lat2)) *
      Math.sin(dLng / 2) ** 2;

  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

// ===================================
// 待ち合わせ距離表示
// ===================================
function showDistanceToTarget() {
  if (targetLat === null || lastLat === null) return;

  const d = distanceMeters(lastLat, lastLng, targetLat, targetLng);
  const km = (d / 1000).toFixed(2);

  document.getElementById("targetInfo").innerHTML =
    `待ち合わせ場所まで 約 <b>${km}</b> km`;
}

// ===================================
// メンバー状態カラー
// ===================================
function getStatusColor(s) {
  return {
    "移動中": "#4caf50",
    "遅れます": "#ff9800",
    "寄り道中": "#2196f3",
    "到着": "#9c27b0",
  }[s] || "#ccc";
}

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

  const members = Object.values(latestByDevice);

  members.forEach((member) => {
    const online =
      member.updated_at &&
      (Date.now() - new Date(member.updated_at)) / 1000 < 6;

    const li = document.createElement("li");
    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 = member.status || "移動中";

    li.innerHTML = `
      <div class="member-icon" style="background:${bgColor}; color:white;">
        ${initial}
      </div>
      <div class="member-name">${crown}${member.user_name}</div>
      <div class="member-status" style="margin-left:auto;">
        <span style="
          padding:2px 6px;
          border-radius:8px;
          color:white;
          font-size:13px;
          background:${getStatusColor(status)};
        ">
          ${status}
        </span>
      </div>
    `;

    // メンバーをタップでその位置へ移動
    li.addEventListener("click", () => {
      const r = latestByDevice[member.device_id];
      if (!r) return;
      map.setView([r.lat, r.lng], 17, { animate: true });
    });

    list.appendChild(li);
  });
}

// ===================================
// 他ユーザーのピン表示
// ===================================
async function showOtherUsers() {
  const { data, error } = await supa
    .from("locations")
    .select("*")
    .eq("group_name", currentGroup)
    .order("updated_at", { ascending: false });

  if (error) {
    console.error("locations 読み込みエラー:", error);
    return;
  }

  // デバイスごとに最新のみ残す
  latestByDevice = {};
  (data || []).forEach((r) => {
    if (!latestByDevice[r.device_id]) latestByDevice[r.device_id] = r;
  });

  // ホスト自動交代
  await checkHostAuto();

  // メンバー一覧更新
  showMemberList(latestByDevice);

  // ピン消去
  otherMarkers.forEach((m) => map.removeLayer(m));
  otherMarkers = [];

  // ピン描画
  Object.values(latestByDevice).forEach((r) => {
    if (r.device_id === deviceId) return;

    const mk = createLabeledMarker(r.lat, r.lng, r.user_name, false);
    mk.addTo(map);
    otherMarkers.push(mk);
  });

  checkAllArrived();
}

// ===================================
// 待ち合わせ到着判定
// ===================================
async function checkAllArrived() {
  if (targetLat === null) return;

  const users = Object.values(latestByDevice);
  if (users.length === 0) return;

  const ok = users.every((u) => {
    const d = distanceMeters(u.lat, u.lng, targetLat, targetLng);
    return d < 120; // 120m以内
  });

  if (!ok) return;

  document.getElementById("targetInfo").innerHTML = `
    🎉 全員が待ち合わせ場所に到着しました！ 🎉<br>
    <small>ホストは新しい待ち合わせを設定できます。</small>
  `;

  targetLat = null;
  targetLng = null;

  if (targetMarker) {
    map.removeLayer(targetMarker);
    targetMarker = null;
  }

  await supa.from("shared_target").delete().eq("group_name", currentGroup);
}

// ===================================
// 時刻フォーマット
// ===================================
function formatTime(t) {
  const d = new Date(t);
  return `${String(d.getHours()).padStart(2, "0")}:${String(
    d.getMinutes()
  ).padStart(2, "0")}`;
}

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

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

  if (error) {
    console.error("messages 読み込みエラー:", error);
    return;
  }

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

// ===================================
// チャット送信
// ===================================
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, error } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (error || !group) return;

  currentHostName = group.host_name;

  // 6秒以内 → オンライン
  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;
  } else {
    isHost = currentUser === currentHostName;
  }

  // UI更新
  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel) {
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
  }

  const disbandBtn = document.getElementById("disbandBtn");
  if (disbandBtn) {
    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, error } = await supa
    .from("groups")
    .select("is_active")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (error) {
    console.error("groups 読み込みエラー:", error);
    return;
  }

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

// ===================================
// 駅検索（Overpass API）
// ===================================
async function fetchStationsAround(lat, lng) {
  const query = `
    [out:json];
    node["railway"="station"](around:5000,${lat},${lng});
    out;
  `;

  const res = await fetch(
    "https://overpass-api.de/api/interpreter?data=" +
      encodeURIComponent(query)
  );

  return (await res.json()).elements || [];
}

// ===================================
// 最寄り駅のピン（EV対応・駅名ゆれ吸収・「○○駅」表示）
// ===================================
async function loadStations() {
  if (!map || lastLat === null) return;

  const box = document.getElementById("nearestBox");

  // 駅データ取得
  const stations = await fetchStationsAround(lastLat, lastLng);

  // 既存ピン削除
  stationMarkers.forEach((m) => map.removeLayer(m));
  stationMarkers = [];

  if (!stations || stations.length === 0) {
    box.textContent = "駅が見つかりませんでした。";
    return;
  }

  let nearest = null;
  let nearestDist = Infinity;

  // ---------------------
  // ★ forEach の正しい開始
  // ---------------------
  stations.forEach((st) => {
    let name = st.tags?.name || "駅名不明";

    // 「駅」を削除して比較用にする
    const cleanName = name.replace(/駅$/, "");

    const d = distanceMeters(lastLat, lastLng, st.lat, st.lon);

    // 最寄り駅更新
    if (d < nearestDist) {
      nearest = {
        name: cleanName,
        lat: st.lat,
        lng: st.lon,
      };
      nearestDist = d;
    }

 // エレベーター有無でピンを切り替え（1つだけ立てる）
const isEV = elevatorInfo.get(cleanName);
const icon = isEV ? elevatorIcon : null; // null → Leaflet標準ピン(青)

const mk = L.marker([st.lat, st.lon], icon ? { icon } : {}).addTo(map);
mk.bindPopup(isEV ? `${cleanName}駅（エレベーターあり）` : `${cleanName}駅`);
stationMarkers.push(mk);

  }); 
  // ---------------------
  // ★ forEach 正しく閉じる
  // ---------------------

  // 最寄り駅の EV判定
  const evText = elevatorInfo.get(nearest.name)
    ? "（エレベーターあり）"
    : "（エレベーターなし）";

  // 最寄り駅表示
  box.textContent =
  `最寄り駅：${nearest.name}${evText}駅（約 ${(nearestDist / 1000).toFixed(2)} km）`;

}
// ===================================
// メイン処理
// ===================================
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();

  // 駅表示（EV 対応）
  loadStations();

  // ------------------------------
  // ▼ 定期更新 ▼
  // ------------------------------

  // GPS更新
  setInterval(async () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;

      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
      showDistanceToTarget();
    } catch {}
  }, 2500);

  // 他ユーザー位置
  setInterval(showOtherUsers, 1500);

  // 待ち合わせ再取得
  setInterval(loadSharedTarget, 9000);

  // チャット更新
  setInterval(loadMessages, 2500);

  // ホスト自動交代
  setInterval(checkHostAuto, 4000);

  // グループ解散チェック
  setInterval(checkGroupActive, 4000);

  // 駅の再検索
  setInterval(loadStations, 15000);

  // ------------------------------
  // ▼ ボタン ▼
  // ------------------------------
  const exitBtn = document.getElementById("exitBtn");
  if (exitBtn) exitBtn.onclick = () => (location.href = "index.html");

  const disbandBtn = document.getElementById("disbandBtn");
  if (disbandBtn) disbandBtn.onclick = disbandGroup;

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

  // マップサイズ調整（スマホ対策）
  setTimeout(() => map.invalidateSize(), 500);
}

// ===================================
// DOMContentLoaded（起動）
// ===================================
window.addEventListener("DOMContentLoaded", async () => {
  const p = new URLSearchParams(location.search);
  const g = p.get("group");
  const u = p.get("user");

  // グループ存在チェック
  const { data, error } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", g)
    .maybeSingle();

  if (error) {
    alert("グループ情報の取得に失敗しました");
    location.href = "index.html";
    return;
  }

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

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

  // 設定反映
  currentGroup = g;
  currentUser = u;
  currentHostName = data.host_name;
  isHost = currentUser === currentHostName;

  // ホスト表示更新
  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel) {
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
  }

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

  // アプリ開始
  main();
});
