import { system, world, ItemStack } from '@minecraft/server';
import { ActionFormData, MessageFormData, ModalFormData } from "@minecraft/server-ui"
import { cachedPlayers } from '../lag/pvp.js';


const SCOREBOARD_NAMES = [
  "Money",
  "player_kills",
  "player_deaths",
  "h",
  "min",
  "sec",
  "BlockdropLvl",
  "BlockdropPoint"
];

world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
  if (!initialSpawn) return;

  system.run(async () => {
    const name = player.name;

    for (const sb of SCOREBOARD_NAMES) {
      await player.runCommandAsync(`scoreboard players add "${name}" ${sb} 0`);
    }
  });
});

system.runInterval(() => {
  const moneyObj = world.scoreboard.getObjective("Money");
  if (!moneyObj) return;

  for (const player of cachedPlayers) {
    try {
      const inv = player.getComponent("minecraft:inventory")?.container;
      if (!inv) continue;

      let total = 0;

      for (let i = 0; i < inv.size; i++) {
        const item = inv.getItem(i);
        if (item?.typeId === "pa:money") {
          total += item.amount;
          inv.setItem(i, undefined); // Remove money item
        }
      }

      if (total > 0) {
        const id = player.scoreboardIdentity;
        const current = moneyObj.getScore(id) ?? 0;
        moneyObj.setScore(id, current + total);

        // Show Actionbar
        player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§a§l+§r§a$${total}"}]}`);
        
      }
    } catch (err) {
      console.warn(`[pa:money] Error for ${player.name}: ${err}`);
    }
  }
}, 200); // Every 5 seconds


// --- Rank Settings (with all toggleable abilities) ---
const rankEffects = {
  Miner: [{ key: "Miner_hasteV_toggle", label: "Haste V" }],
  Healer: [{ key: "Healer_regenerationV_toggle", label: "Regeneration V" }],
  Warrior: [
    { key: "Warrior_strengthIV_toggle", label: "Strength IV" },
    { key: "Warrior_resistanceIII_toggle", label: "Resistance III" },
  ],
  VIP: [
    { key: "VIP_particles_toggle", label: "VIP Particle Effects" },
  ],
  VIPPlus: [
    { key: "VIPPlus_hasteIV_toggle", label: "Haste IV" },
    { key: "VIPPlus_resistanceIII_toggle", label: "Resistance III" },
    { key: "VIPPlus_particles_toggle", label: "VIP+ Particle Effects" },
    { key: "VIPPlus_VIP_particles_toggle", label: "VIP Particle Effects" },
  ],
  Elite: [
    { key: "Elite_regenerationV_toggle", label: "Regeneration V" },
    { key: "Elite_strengthIV_toggle", label: "Strength IV" },
    { key: "Elite_resistanceIII_toggle", label: "Resistance III" },
    { key: "Elite_hasteIV_toggle", label: "Haste IV" },
    { key: "Elite_particles_toggle", label: "Elite Particle Effects" },
    { key: "Elite_VIP_particles_toggle", label: "VIP Particle Effects" },
    { key: "Elite_VIPPlus_particles_toggle", label: "VIP+ Particle Effects" },
  ],
  ElitePlus: [
    { key: "ElitePlus_regenerationV_toggle", label: "Regeneration V" },
    { key: "ElitePlus_strengthIV_toggle", label: "Strength IV" },
    { key: "ElitePlus_resistanceIII_toggle", label: "Resistance III" },
    { key: "ElitePlus_hasteIV_toggle", label: "Haste IV" },
    { key: "ElitePlus_mine3x3_toggle", label: "3×3×3 Mining" },
    { key: "ElitePlus_particles_toggle", label: "Elite+ Particle Effects" },
    { key: "ElitePlus_VIP_particles_toggle", label: "VIP Particle Effects" },
    { key: "ElitePlus_VIPPlus_particles_toggle", label: "VIP+ Particle Effects" },
    { key: "ElitePlus_Elite_particles_toggle", label: "Elite Particle Effects" },
  ],
  God: [
    { key: "God_regenerationV_toggle", label: "Regeneration V" },
    { key: "God_strengthIV_toggle", label: "Strength IV" },
    { key: "God_resistanceIII_toggle", label: "Resistance III" },
    { key: "God_hasteIV_toggle", label: "Haste IV" },
    { key: "God_mine3x3_toggle", label: "3×3×3 Mining" },
    { key: "Flying_ability", label: "Flying Ability §c[ Unavailable ]" },
    { key: "God_particles_toggle", label: "God Particle Effects" },
    { key: "God_spiral_particles_toggle", label: "Spiral Particle Effects" },
    { key: "God_VIP_particles_toggle", label: "VIP Particle Effects" },
    { key: "God_VIPPlus_particles_toggle", label: "VIP+ Particle Effects" },
    { key: "God_Elite_particles_toggle", label: "Elite Particle Effects" },
    { key: "God_ElitePlus_particles_toggle", label: "Elite+ Particle Effects" },
  ]
};

const particleTags = ["gwim:VIP", "gwim:VIPPlus", "gwim:Elite", "gwim:ElitePlus", "gwim:God"];



// === Particle Systems ===
const ELITE_MAIN = "minecraft:endrod";
const ELITE_SECONDARY = "minecraft:enchanting_table_particle";
const ELITE_RADIUS = 1.8;
const ELITE_COUNT = 8;

const GOD_PARTICLE_SPIRAL        = "minecraft:example_spiral";
const GOD_PARTICLE_COMBOCURVE    = "minecraft:example_combocurve";
const GOD_PARTICLE_TRIAL_SIGNAL  = "minecraft:trial_spawner_detection";

const VIP_PARTICLE_TYPE = "minecraft:basic_portal_particle";
const VIP_PARTICLE_POINTS = 8;
const VIP_PARTICLE_SPREAD = 1.4;

let vipTick = 0;

system.runInterval(() => {

  vipTick++;

  for (const player of cachedPlayers) {
  if (!player || !player.isValid()) continue;
    applyRankEffects(player);
    const { x, y, z } = player.location;
    const dim = player.dimension;
    const sinTick = Math.sin(vipTick * 0.1);
    const cosTick = Math.cos(vipTick * 0.1);
    const crownY = y + 2.3;
    const vipPlusCrownY = y + 2.1 + sinTick * 0.1;

    const spiralParticles = (radius, count, yOffset = 1.1) => {
      for (let i = 0; i < count; i++) {
        const angle = (2 * Math.PI * i) / count + vipTick * 0.05;
        const px = x + Math.cos(angle) * radius;
        const py = y + yOffset + Math.sin(vipTick * 0.1 + i) * 0.4;
        const pz = z + Math.sin(angle) * radius;
        dim.spawnParticle(ELITE_MAIN, { x: px, y: py, z: pz });

        if (i % 2 === 0) {
          const sx = x + Math.cos(angle) * 0.4;
          const sz = z + Math.sin(angle) * 0.4;
          const sy = y + 1.7;
          dim.spawnParticle(ELITE_SECONDARY, { x: sx, y: sy, z: sz });
        }
      }
    };

    const ringParticles = (type, spread, points) => {
      for (let i = 0; i < points; i++) {
        const angle = (2 * Math.PI * i) / points + vipTick * 0.08;
        const px = x + Math.cos(angle) * spread;
        const py = y + 1.3;
        const pz = z + Math.sin(angle) * spread;
        dim.spawnParticle(type, { x: px, y: py, z: pz });
      }
    };

    const randomFlame = (type) => {
      const flameX = x - 1.5 + Math.random() * 3;
      const flameZ = z - 1.5 + Math.random() * 3;
      const flameY = y + 0.2 + Math.random() * 1.0;
      dim.spawnParticle(type, { x: flameX, y: flameY, z: flameZ });
    };

    const crownParticles = (type, count = 3, radius = 0.4, yOffset = 2.3) => {
      for (let i = 0; i < count; i++) {
        const angle = (2 * Math.PI * i) / count + vipTick * 0.1;
        const cx = x + Math.cos(angle) * radius;
        const cz = z + Math.sin(angle) * radius;
        dim.spawnParticle(type, { x: cx, y: yOffset, z: cz });
      }
    };

    if (player.hasTag("gwim:ElitePlus") && player.getDynamicProperty("ElitePlus_Elite_particles_toggle") === true) {
  if (vipTick % 2 === 0) spiralParticles(ELITE_RADIUS, ELITE_COUNT);
  if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0) {
    randomFlame("minecraft:blue_flame_particle");
  }
  continue; // 🔧
}

if (player.hasTag("gwim:God") && player.getDynamicProperty("God_Elite_particles_toggle") === true) {
  if (vipTick % 2 === 0) spiralParticles(ELITE_RADIUS, ELITE_COUNT);
  if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0) {
    randomFlame("minecraft:blue_flame_particle");
  }
  continue; // 🔧
}

    // Elite_particles_toggle - spiral only
    if (player.hasTag("gwim:Elite") && player.getDynamicProperty("Elite_particles_toggle") === true) {
  if (vipTick % 2 === 0) spiralParticles(ELITE_RADIUS, ELITE_COUNT);
  if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0) {
    randomFlame("minecraft:blue_flame_particle");
  }
  continue; // 🔧
}

if (player.hasTag("gwim:God") && player.getDynamicProperty("God_ElitePlus_particles_toggle") === true) {
  if (vipTick % 2 === 0) spiralParticles(ELITE_RADIUS, ELITE_COUNT);
  crownParticles("minecraft:blue_flame_particle", 3, 0.4, crownY);
  continue; // 🔧
}


    // ElitePlus_particles_toggle - spiral + crown
    if (player.hasTag("gwim:ElitePlus") && player.getDynamicProperty("ElitePlus_particles_toggle") === true) {
  if (vipTick % 2 === 0) spiralParticles(ELITE_RADIUS, ELITE_COUNT);
  crownParticles("minecraft:blue_flame_particle", 3, 0.4, crownY);
  continue; // 🔧
}

    // VIP_particles_toggle
if (
  player.hasTag("gwim:VIP") &&
  player.getDynamicProperty("VIP_particles_toggle") === true
) {
  if (vipTick % 2 === 0)
    ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);

  if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0)
    randomFlame("minecraft:basic_flame_particle");

  continue; // 🔧
}



if (
  player.hasTag("gwim:VIPPlus") &&
  player.getDynamicProperty("VIPPlus_VIP_particles_toggle") === true
) {
  if (vipTick % 2 === 0)
    ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);

  if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0)
    randomFlame("minecraft:basic_flame_particle");

  continue; // 🔧
}

// VIPPlus_particles_toggle
if (
  player.hasTag("gwim:VIPPlus") &&
  player.getDynamicProperty("VIPPlus_particles_toggle") === true
) {
  if (vipTick % 2 === 0)
    ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);

  if (vipTick % 2 === 0)
    crownParticles("minecraft:basic_flame_particle", 5, 0.7, y + 2.1 + Math.sin(vipTick * 0.1) * 0.1);

  continue; // 🔧
}
    
  

    // Elite
if (player.hasTag("gwim:Elite")) {
  if (player.getDynamicProperty("Elite_VIP_particles_toggle") === true) {
    if (vipTick % 2 === 0)
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
    if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0)
      randomFlame("minecraft:basic_flame_particle");
    continue; // 🔧
  }

  if (player.getDynamicProperty("Elite_VIPPlus_particles_toggle") === true) {
    if (vipTick % 2 === 0) {
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
      crownParticles("minecraft:basic_flame_particle", 5, 0.7, y + 2.1 + sinTick * 0.1);
    }
    continue; // 🔧
  }
}

// ElitePlus
if (player.hasTag("gwim:ElitePlus")) {
  if (player.getDynamicProperty("ElitePlus_VIP_particles_toggle") === true) {
    if (vipTick % 2 === 0)
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
    if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0)
      randomFlame("minecraft:basic_flame_particle");
    continue; // 🔧
  }

  if (player.getDynamicProperty("ElitePlus_VIPPlus_particles_toggle") === true) {
    if (vipTick % 2 === 0) {
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
      crownParticles("minecraft:basic_flame_particle", 5, 0.7, y + 2.1 + sinTick * 0.1);
    }
    continue; // 🔧
  }
}

// God
if (player.hasTag("gwim:God")) {
  if (player.getDynamicProperty("God_VIP_particles_toggle") === true) {
    if (vipTick % 2 === 0)
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
    if (vipTick % (5 + Math.floor(Math.random() * 6)) === 0)
      randomFlame("minecraft:basic_flame_particle");
    continue; // 🔧
  }

  if (player.getDynamicProperty("God_VIPPlus_particles_toggle") === true) {
    if (vipTick % 2 === 0) {
      ringParticles(VIP_PARTICLE_TYPE, VIP_PARTICLE_SPREAD, VIP_PARTICLE_POINTS);
      crownParticles("minecraft:basic_flame_particle", 5, 0.7, y + 2.1 + sinTick * 0.1);
    }
    continue; // 🔧
  }
}

// ─── GOD: Custom Particles ─────────────────────
if (player.hasTag("gwim:God")) {

  // ComboCurve + Trial Signal (if enabled)
  if (player.getDynamicProperty("God_particles_toggle") === true) {
    if (vipTick % 30 === 0) {
      dim.spawnParticle(GOD_PARTICLE_COMBOCURVE, {
        x: x,
        y: y - 1,
        z: z
      });
    }

    if (vipTick % 20 === 0) {
      dim.spawnParticle(GOD_PARTICLE_TRIAL_SIGNAL, {
        x: x - 0.5,
        y: y,
        z: z - 0.5
      });
    }
  }

  // Spiral only (if enabled separately)
  if (player.getDynamicProperty("God_spiral_particles_toggle") === true) {
    if (vipTick % 50 === 0) {
      dim.spawnParticle(GOD_PARTICLE_SPIRAL, {
        x: x,
        y: y - 1,
        z: z
      });
    }
  }
}
}
}, 1);


system.runInterval(() => {
  for (const player of cachedPlayers) {
    const tagSet = new Set(player.getTags());

    // --- Determine active rank ---
    const activeTag = getRankTag(player, tagSet);
    const activeRank = activeTag ? activeTag.replace("gwim:", "") : null;

    // --- Clear toggles from ranks player does NOT have ---
    for (const rankTag of particleTags) {
      if (rankTag === activeTag) continue; // skip current rank
      const rankName = rankTag.slice(5);
      const effects = rankEffects[rankName];
      if (!effects) continue;

      for (const { key } of effects) {
        // Only clear if property exists to avoid unnecessary writes
        if (player.getDynamicProperty(key) !== undefined) {
          player.setDynamicProperty(key, undefined);
        }
      }
    }

    if (!activeRank) continue;

    // --- Particle toggles ---
    const effects = rankEffects[activeRank];
    if (!effects) continue;

    const particleKeys = effects
      .filter(e => e.key.includes("particles_toggle"))
      .map(e => e.key);

    if (particleKeys.length > 0) {
      let firstEnabledIndex = -1;
      for (let i = 0; i < particleKeys.length; i++) {
        if (player.getDynamicProperty(particleKeys[i]) === true) {
          firstEnabledIndex = i;
          break;
        }
      }

      for (let i = 0; i < particleKeys.length; i++) {
        const shouldEnable = i === firstEnabledIndex;
        if (player.getDynamicProperty(particleKeys[i]) !== shouldEnable) {
          player.setDynamicProperty(particleKeys[i], shouldEnable);
        }
      }
    }
  }
}, 40); // every 2 seconds



// Personal settings UI
export function personalSettings(player) {
  const tag = getRankTag(player);
  if (!tag) return player.sendMessage("§cNo rank options for your current rank");

  const rankName = tag.replace("gwim:", "");
  const effects = rankEffects[rankName];
  if (!effects?.length) return player.sendMessage("§cNo toggleable settings.");

  const form = new ModalFormData()
    .title("§lRank Settings")
    .slider(
  `§8━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
  `§7You are ranked: ${getRankDisplayName(rankName)}\n` +
  `§8Customize which special abilities you want active below.\n` +
  `§7Only active in specific zones.\n` +
  `§c§l- You can only toggle §oonly one§r§c§l particle effect at a time!\n` +
  `§8━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`,
  0, 0, 1, 0
);

  effects.forEach(({ label, key }) => {
    const state = player.getDynamicProperty(key);
    form.toggle(label, state === undefined ? true : state);
  });

  form.show(player).then(res => {
  if (res.canceled) return;

  // Save all toggles normally first
  effects.forEach((effect, i) => {
    player.setDynamicProperty(effect.key, res.formValues[i + 1]);
  });

  // Now enforce only one particle effect toggle ON
  const particleKeys = effects
    .filter(e => e.key.includes("particles_toggle"))
    .map(e => e.key);

  const firstEnabledIndex = particleKeys.findIndex(key => player.getDynamicProperty(key) === true);

  particleKeys.forEach((key, i) => {
    player.setDynamicProperty(key, i === firstEnabledIndex);
  });
  
  

  player.sendMessage("§eRank settings saved.");
  player.playSound("random.pop");
}); // close .then
}    // ✅ ← close personalSettings function

function getRankTag(player) {
  return player.getTags().find(tag =>
    tag.startsWith("gwim:") &&
    ["Miner", "Healer", "Warrior", "VIP", "VIPPlus", "Elite", "ElitePlus", "God"].includes(tag.slice(5)) // â† add "VIP" here
  );
}

// Rank display
function getRankDisplayName(rank) {
  switch (rank) {
    case "VIP": return "§e§lVIP";
    case "VIPPlus": return "§e§lVIP+";
    case "Elite": return "§b§lElite";
    case "ElitePlus": return "§b§lElite+";
    case "God": return "§d§l||GOD||";
    case "Miner": return "§a§lMiner";
    case "Healer": return "§4§lHealer";
    case "Warrior": return "§c§lWarrior";
    default: return `§7§l${rank}`;
  }
}

// Apply effects
function applyRankEffects(player) {
  try {
    const tag = getRankTag(player);
    if (!tag) return;
    const rank = tag.replace("gwim:", "");

    const { x, y, z } = player.location;
    const dim = player.dimension.id;
    const inZone = isInEffectZone(x, y, z, dim);
    const inMinerZone = isInMinerZone(x, y, z);

    const apply = (effectId, amp) => {
      player.addEffect(effectId, 40, { amplifier: amp, showParticles: false });
    };

    const isOn = key => {
      const prop = player.getDynamicProperty(key);
      return prop === undefined || prop === true;
    };

    switch (rank) {
      case "Miner":
        if (inMinerZone && isOn("Miner_hasteV_toggle")) apply("haste", 4);
        break;

      case "Healer":
        if (inZone && isOn("Healer_regenerationV_toggle")) apply("regeneration", 4);
        break;

      case "Warrior":
        if (inZone) {
          if (isOn("Warrior_strengthIV_toggle")) apply("strength", 3);
          if (isOn("Warrior_resistanceIII_toggle")) apply("resistance", 2);
        }
        break;

      case "VIPPlus":
        if (inZone && isOn("VIPPlus_resistanceIII_toggle")) apply("resistance", 2);
        if (inMinerZone && isOn("VIPPlus_hasteIV_toggle")) apply("haste", 3);
        break;

      case "Elite":
      case "ElitePlus":
      case "God":
        if (inZone) {
          if (isOn(`${rank}_regenerationV_toggle`)) apply("regeneration", 4);
          if (isOn(`${rank}_strengthIV_toggle`)) apply("strength", 3);
          if (isOn(`${rank}_resistanceIII_toggle`)) apply("resistance", 2);
        }
        if (inMinerZone && isOn(`${rank}_hasteIV_toggle`)) apply("haste", 3);
        break;
    }
  } catch (err) {
    console.warn(`Rank effect error: ${err}`);
  }
}

// Zones
function isInMinerZone(x, y, z) {
  return (
    isWithin(x, y, z, 3944, 4, -4000, 300) ||
    isWithin(x, y, z, 3000, 6, -3000, 400) ||
    isWithin(x, y, z, -3978, 12, -3884, 20) ||
    isWithin(x, y, z, 4028, 5, 4000, 150)
  );
}

function isInEffectZone(x, y, z, dimId) {
  return (
    isWithin(x, y, z, 1047, -10, -1009, 200) ||
    isWithin(x, y, z, -1000, 20, 1000, 400) ||
    dimId === "minecraft:the_end"
  );
}

function isWithin(px, py, pz, cx, cy, cz, radius) {
  const dx = px - cx, dy = py - cy, dz = pz - cz;
  return dx * dx + dy * dy + dz * dz <= radius * radius;
}

// Init default toggles
world.afterEvents.playerJoin.subscribe(e => {
  const p = e.player;
  system.runTimeout(() => {
    const tag = getRankTag(p);
    if (!tag) return;
    const effects = rankEffects[tag.replace("gwim:", "")];
    if (!effects) return;
    for (const { key } of effects) {
      if (p.getDynamicProperty(key) === undefined) {
        if (key === "Flying_ability") {
          p.setDynamicProperty(key, false);
        } else {
          p.setDynamicProperty(key, true);
        }
      }
    }
  }, 5);
});



const RADIUS = 1; // 1 block in each direction = 3x3 area

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { block, brokenBlockPermutation, player } = event;

  const isElite = player.hasTag("gwim:ElitePlus");
  const isGod = player.hasTag("gwim:God");

  // Exit if player has neither tag
  if (!isElite && !isGod) return;

  // Check correct toggle based on rank
  if (
    (isElite && player.getDynamicProperty("ElitePlus_mine3x3_toggle") !== true) ||
    (isGod && player.getDynamicProperty("God_mine3x3_toggle") !== true)
  ) return;

  const dim = player.dimension;
  const targetType = brokenBlockPermutation.type.id;

  for (let dx = -RADIUS; dx <= RADIUS; dx++) {
    for (let dy = -RADIUS; dy <= RADIUS; dy++) {
      for (let dz = -RADIUS; dz <= RADIUS; dz++) {
        const x = block.x + dx;
        const y = block.y + dy;
        const z = block.z + dz;

        const b = dim.getBlock({ x, y, z });
        if (b && b.typeId === targetType) {
          player.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air destroy`);
        }
      }
    }
  }
});