// MA-Trip — Spots feature inspired by Roamy.
// Save places ("spots") from URL/search/map-pick, group by trip destination,
// then let the AI generator distribute them across trip days.

/* ─────────────── URL parsing ─────────────── */

function parseSpotUrl(raw) {
  if (!raw || typeof raw !== "string") return null;
  const url = raw.trim();
  let m = url.match(/@(-?\d+\.\d+),(-?\d+\.\d+)/);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "gmaps" };
  m = url.match(/[?&]q=(-?\d+\.\d+),(-?\d+\.\d+)/);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "gmaps" };
  m = url.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "gmaps" };
  m = url.match(/[?&](?:ll|center|destination)=(-?\d+\.\d+),(-?\d+\.\d+)/);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "maps" };
  m = url.match(/[?&]daddr=(-?\d+\.\d+),(-?\d+\.\d+)/);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "apple-maps" };
  m = url.match(/^geo:(-?\d+\.\d+),(-?\d+\.\d+)/i);
  if (m) return { lat: parseFloat(m[1]), lng: parseFloat(m[2]), source: "geo" };
  // bare "lat,lng" text
  m = url.match(/^(-?\d{1,3}\.\d+),\s*(-?\d{1,3}\.\d+)$/);
  if (m) {
    const lat = parseFloat(m[1]), lng = parseFloat(m[2]);
    if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
      return { lat, lng, source: "coords" };
    }
  }
  return null;
}

function isShortUrl(u) {
  if (!u) return false;
  return /maps\.app\.goo\.gl|goo\.gl\/maps|share\.google/i.test(u);
}

function extractPlaceNameFromUrl(url) {
  const m = url.match(/\/maps\/place\/([^/@?]+)/);
  if (m) {
    try { return decodeURIComponent(m[1].replace(/\+/g, " ")); } catch (e) { return m[1]; }
  }
  return "";
}

window.parseSpotUrl = parseSpotUrl;
window.isShortUrl = isShortUrl;
window.extractPlaceNameFromUrl = extractPlaceNameFromUrl;

/* ─────────────── Categories ─────────────── */

const SPOT_CATEGORIES = [
  { key: "food",   label: "אוכל",     icon: "🍜", color: "#ff9500" },
  { key: "view",   label: "תצפית",    icon: "🏔️", color: "#34c759" },
  { key: "beach",  label: "חוף",      icon: "🏖️", color: "#32ade6" },
  { key: "market", label: "שוק",      icon: "🛍️", color: "#af52de" },
  { key: "todo",   label: "אטרקציה",  icon: "🎯", color: "#ff3b30" },
  { key: "sunset", label: "שקיעה",    icon: "🌅", color: "#ff2d55" },
  { key: "temple", label: "מקדש",     icon: "🛕", color: "#ffcc00" },
  { key: "other",  label: "אחר",      icon: "📍", color: "#8e8e93" },
];
window.SPOT_CATEGORIES = SPOT_CATEGORIES;

function spotCatMeta(key) {
  return SPOT_CATEGORIES.find(c => c.key === key) || SPOT_CATEGORIES[SPOT_CATEGORIES.length - 1];
}
window.spotCatMeta = spotCatMeta;

/* ─────────────── Spots Screen ─────────────── */

function SpotsScreen() {
  const { useStore, A, CircleIcon, Pill, QuickNav, I } = window;
  const { spots, trip, currentSpotsList, currentSpotsListId, lists } = useStore(s => ({
    spots: s.spots || [],
    trip: s.trip,
    currentSpotsList: s.currentSpotsList,
    currentSpotsListId: s.currentSpotsListId,
    lists: s.lists || [],
  }));
  const dests = (trip.destinations || []).map(d => window.destName(d));
  const destFilter = currentSpotsList || "all";
  const listFilter = currentSpotsListId || null;
  const filtered = spots.filter(sp => {
    if (listFilter && !((sp.lists || []).includes(listFilter))) return false;
    if (destFilter !== "all" && sp.dest !== destFilter) return false;
    return true;
  });
  const grouped = SPOT_CATEGORIES.map(c => ({
    ...c,
    items: filtered.filter(sp => (sp.cat || "other") === c.key),
  })).filter(g => g.items.length > 0);

  return (
    <div dir="rtl" style={{ background: "var(--canvas)", color: "var(--ink)", minHeight: "100%", position: "relative", paddingBottom: 120 }}>
      <div style={{ padding: "4px 20px 12px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <CircleIcon size={36} data-nav="back" style={{ cursor: "pointer" }}>{I.back(18)}</CircleIcon>
        <div style={{ fontSize: 16, fontWeight: 600 }}>מקומות שמורים</div>
        <CircleIcon size={36} className="lg-coral" onClick={() => A.addSpotFromAnywhere()} style={{ cursor: "pointer" }}>{I.plus(20, "#fff")}</CircleIcon>
      </div>

      {QuickNav ? <QuickNav current="spots" /> : null}

      <div style={{ padding: "8px 20px 18px" }}>
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-.02em", lineHeight: 1.1 }}>
          שמרי מקומות.
        </div>
        <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-.02em", lineHeight: 1.1, color: "var(--coral)" }}>
          נדאג למסלול.
        </div>
        <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 10, lineHeight: 1.5 }}>
          הדביקי קישור מ-Google Maps, חפשי בשם, או בחרי על המפה. בלחיצה אחת המסלול ייבנה אוטומטית לפי הימים והיעדים שלך.
        </div>
      </div>

      <div style={{ padding: "0 20px 16px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
        <button onClick={() => A.addSpotFromLink()} className="lg-light" style={{
          borderRadius: 14, padding: "14px 8px", border: "none", cursor: "pointer",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 6, fontFamily: "inherit",
        }}>
          <span style={{ fontSize: 22 }}>🔗</span>
          <span style={{ fontSize: 12, fontWeight: 500 }}>הדבקת קישור</span>
        </button>
        <button onClick={() => A.addSpotBySearch()} className="lg-light" style={{
          borderRadius: 14, padding: "14px 8px", border: "none", cursor: "pointer",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 6, fontFamily: "inherit",
        }}>
          <span style={{ fontSize: 22 }}>🔍</span>
          <span style={{ fontSize: 12, fontWeight: 500 }}>חיפוש שם</span>
        </button>
        <button onClick={() => A.addSpotFromMap()} className="lg-light" style={{
          borderRadius: 14, padding: "14px 8px", border: "none", cursor: "pointer",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 6, fontFamily: "inherit",
        }}>
          <span style={{ fontSize: 22 }}>🗺️</span>
          <span style={{ fontSize: 12, fontWeight: 500 }}>בחירה על מפה</span>
        </button>
      </div>

      {spots.length > 0 && trip.days > 0 && (
        <div className="lg-coral" style={{
          margin: "0 20px 18px", borderRadius: 16, padding: "14px 16px",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".04em", opacity: .9 }}>AI ITINERARY</div>
            <div style={{ fontSize: 15, fontWeight: 600, marginTop: 2 }}>
              בני מסלול אוטומטי מ-{spots.length} מקומות
            </div>
          </div>
          <button onClick={() => A.confirmGenerateItinerary()} style={{
            padding: "10px 16px", borderRadius: 9999,
            background: "rgba(255,255,255,.22)", color: "#fff",
            border: "0.5px solid rgba(255,255,255,.4)", fontSize: 13, fontWeight: 600,
            cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap",
          }}>בנה מסלול</button>
        </div>
      )}

      {/* Lists row */}
      <div className="no-scrollbar" style={{ display: "flex", gap: 8, overflowX: "auto", padding: "0 20px 10px" }}>
        <div onClick={() => A.setSpotsListById(null)} className={`lg-chip ${!listFilter ? "is-active" : ""}`} style={{
          flexShrink: 0, padding: "8px 16px", borderRadius: 9999,
          fontSize: 13, fontWeight: 500, cursor: "pointer",
        }}>📋 כל הרשימות</div>
        {lists.map(l => {
          const count = spots.filter(sp => (sp.lists || []).includes(l.id)).length;
          const active = listFilter === l.id;
          return (
            <div key={l.id}
              onClick={() => active ? A.askListActions(l.id) : A.setSpotsListById(l.id)}
              onContextMenu={(e) => { e.preventDefault(); A.askListActions(l.id); }}
              className={`lg-chip ${active ? "is-active" : ""}`}
              style={{
                flexShrink: 0, padding: "8px 16px", borderRadius: 9999,
                fontSize: 13, fontWeight: 500, cursor: "pointer",
              }}>{l.name} ({count})</div>
          );
        })}
        <div onClick={() => A.addList()} className="lg-chip" style={{
          flexShrink: 0, padding: "8px 14px", borderRadius: 9999,
          fontSize: 13, fontWeight: 500, cursor: "pointer", color: "var(--coral)",
        }}>＋ רשימה</div>
      </div>

      {dests.length > 0 && (
        <div className="no-scrollbar" style={{ display: "flex", gap: 8, overflowX: "auto", padding: "0 20px 14px" }}>
          <div onClick={() => A.setSpotsList(null)} className={`lg-chip ${destFilter === "all" ? "is-active" : ""}`} style={{
            flexShrink: 0, padding: "8px 16px", borderRadius: 9999,
            fontSize: 13, fontWeight: 500, cursor: "pointer",
          }}>הכל ({spots.length})</div>
          {dests.map(d => {
            const count = spots.filter(sp => sp.dest === d).length;
            const active = destFilter === d;
            return (
              <div key={d} onClick={() => A.setSpotsList(d)} className={`lg-chip ${active ? "is-active" : ""}`} style={{
                flexShrink: 0, padding: "8px 16px", borderRadius: 9999,
                fontSize: 13, fontWeight: 500, cursor: "pointer",
              }}>{d} ({count})</div>
            );
          })}
        </div>
      )}

      {filtered.length === 0 && (
        <div className="lg-bento" style={{
          margin: "0 20px", padding: "32px 22px",
          textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 14,
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: 9999,
            background: "linear-gradient(135deg, #4ec5c2, #1a6e8f)",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "#fff", fontSize: 28,
            boxShadow: "0 10px 24px -6px rgba(26,110,143,.45)",
          }} aria-hidden="true">📍</div>
          <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.02em" }}>אין מקומות עדיין</div>
          <div style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.55, maxWidth: 280 }}>
            הדביקי קישור Google Maps, חפשי שם, או בחרי על המפה. הכל יופיע במפה ובמחולל המסלול.
          </div>
          <button onClick={() => window.A.addSpotFromAnywhere && window.A.addSpotFromAnywhere()} className="lg-coral" type="button" style={{
            padding: "10px 18px", borderRadius: 9999, fontFamily: "inherit",
            fontSize: 14, fontWeight: 600, border: "none", cursor: "pointer", color: "#fff",
            marginTop: 4,
          }}>+ הוסיפי מקום ראשון</button>
        </div>
      )}

      {grouped.map(group => (
        <div key={group.key} style={{ padding: "0 20px 18px" }}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            marginBottom: 10, paddingBottom: 6,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 18 }}>{group.icon}</span>
              <span style={{ fontSize: 16, fontWeight: 600 }}>{group.label}</span>
              <span style={{ fontSize: 12, color: "var(--muted)", fontFamily: "var(--mono)" }}>{group.items.length}</span>
            </div>
          </div>
          <div style={{
            borderRadius: 14, background: "var(--canvas)",
            border: "1px solid var(--hairline)", overflow: "hidden",
          }}>
            {group.items.map((sp, i) => (
              <div key={sp.id} onClick={() => A.askSpotActions(sp.id)} style={{
                padding: "12px 14px", display: "flex", alignItems: "center", gap: 12,
                borderBottom: i < group.items.length - 1 ? "1px solid var(--hairline-soft)" : "none",
                cursor: "pointer",
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: group.color + "22", color: group.color,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 18, flexShrink: 0,
                }}>{group.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-.01em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {sp.title}
                  </div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {sp.dest ? <span>{sp.dest} · </span> : null}{sp.sub || sp.address || ""}
                  </div>
                </div>
                {sp.lat != null && (
                  <div style={{ fontSize: 10, fontFamily: "var(--mono)", color: "var(--muted-soft)" }}>📍</div>
                )}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

window.SpotsScreen = SpotsScreen;
