// this is a shared state between game canvas and UI screens

// svelte stores are like global variables 
// they update evey component that reads them
// so I can place my color states here so they are updated everywhere


// a writable is a box that holds a value 
// any svelte component can read from within it 
// autoupdated when value changes 
// its like the dollar sign notation 

// -- so these are the global variables ----

import { writable, derived } from 'svelte/store';
import { LEVELS } from '../game/levelData.js';

// world starts gray so unlockedColors start as an empty array (there is none)
export const unlockedColors = writable([]);

// the current level number 
export const currentLevel = writable(1);

// opacity of color being unlccked: 0.0 is gray, 1.0 is full color
// this increases per fragment collected
export const colorOpacity = writable(0.0);

// the hex color for the current level 
export const levelColor = writable('#888888');

// how many fragment have been collected 
export const fragmentsCollected = writable(0);

//player lives
export const lives = writable(3);

// true once every level's color has been unlocked (game beaten)
export const gameCompleted = derived(
    unlockedColors,
    $colors => LEVELS.every(level => $colors.includes(level.color))
);

// --- these are the global functions -----

// for collecting a fragment 
// we update the number of fragments collected and the color opacity
export function onFragmentCollection(totalFragments, hexColor){
    fragmentsCollected.update(n => {
        const newCount = n + 1;
        // opacity is a fraction of the number of fragments collected
        colorOpacity.set(newCount / totalFragments);
        return newCount;
    });
    levelColor.set(hexColor);
}

// starting a level over
export function resetLevel(levelNum, hexColor){
    currentLevel.set(levelNum);
    levelColor.set(hexColor);
    colorOpacity.set(0.0); // back to gray
    fragmentsCollected.set(0); 
    lives.set(3); // reset lives 
}

// compleating a level!
export function completeLevel(hexColor){
    unlockedColors.update(arr => {
        if (!arr.includes(hexColor)) return [...arr, hexColor];
        return arr; // we don't want duplicate colors so only add if not already existed 
        // bascially person can play game again but color has been gained anyway 
    });
}



