import { db, auth } from './config';
import { doc, getDoc, setDoc, getDocs, collection, serverTimestamp } from 'firebase/firestore';
import { getRegionPrefix } from '$lib/utils/geohash.js';
import { reverseGeocode } from '$lib/utils/geocode.js';
import { pickStampIcon } from '$lib/utils/stampIcons.js';
import { stampsStore } from '$lib/stores/stampsStore.js';

// same pastel formula as messagePin()'s randomPastel() in pins.js, so stamp
// colors feel consistent with the pin palette - random per stamp (doesn't
// need to be deterministic, unlike the icon below)
function randomStampColor() {
    const hue = Math.floor(Math.random() * 360);
    return `hsl(${hue}, 60%, 72%)`;
}

// --- "passport stamps" ------------------------------------------------------
// Each user/device (anonymous Firebase UID, see userStore.js) earns one
// stamp per distinct geohash-4 region (~20-40km, roughly city-sized - see
// getRegionPrefix in geohash.js) they've ever posted a message from. Stamps
// live at users/{uid}/stamps/{geohash4} - using the geohash-4 prefix itself
// as the document ID means "does this user already have a stamp for this
// region" is a single getDoc by ID, and re-posting from the same region can
// never create a duplicate stamp.
//
// Called from addMessage() (messages.js) after a message successfully posts.
export async function checkAndAwardStamp(lat, lng) {
    const uid = auth.currentUser?.uid;
    if (!uid) return; // not signed in yet - shouldn't happen since initAuth() runs on app load, but bail safely

    const geohash4 = getRegionPrefix(lat, lng);
    const ref = doc(db, 'users', uid, 'stamps', geohash4);

    const existing = await getDoc(ref);
    if (existing.exists()) return; // already have a stamp for this region

    // --- reverse geocode: turn these coordinates into a place name ---------
    // reverseGeocode() (geocode.js) calls the Google Geocoding API and
    // returns { city, country } - falling back to 'Unknown'/'Unknown' if the
    // lookup fails, so a failed geocode still earns a (generically-labeled)
    // stamp rather than blocking.
    const { city, country } = await reverseGeocode(lat, lng);

    // --- deterministic icon, random color -----------------------------------
    // pickStampIcon hashes "City, Country" so the same place always gets the
    // same icon; the color is a fresh random pastel per stamp.
    const icon = pickStampIcon(city, country);

    const stamp = {
        geohash4,
        city,
        country,
        iconId: icon.id,
        color: randomStampColor(),
        earnedAt: serverTimestamp()
    };

    await setDoc(ref, stamp);

    // keep stampsStore (drives the bottom-nav/desktop stamp-book icons) in
    // sync immediately, without a full getStamps() refetch
    stampsStore.update(stamps => [...stamps, stamp]);
}

// fetch every stamp this user has earned, for the stamp book page - also
// refreshes stampsStore so the nav icons reflect the latest count
export async function getStamps() {
    const uid = auth.currentUser?.uid;
    if (!uid) return [];

    try {
        const snapshot = await getDocs(collection(db, 'users', uid, 'stamps'));
        const stamps = snapshot.docs.map(d => d.data());
        stampsStore.set(stamps);
        return stamps;
    } catch (err) {
        console.error('[stamps] failed to fetch stamps:', err);
        return [];
    }
}
