# ------------------------------------------------------------
# HDRI Helper – v2.12.7 – PRESERVE SETTINGS ON REBUILD
# Author: Jonathan & Grok
# Version: 2.12.7
# ------------------------------------------------------------

bl_info = {
    "name": "HDRI Helper",
    "author": "Jonathan & Grok",
    "version": (2, 12, 7),
    "blender": (5, 2, 0),
    "category": "World",
    "description": "Pro HDRI tool with white-balance picker",
}

import bpy
import os
import gpu
from bpy.props import StringProperty, BoolProperty, PointerProperty, FloatVectorProperty
from bpy.types import Operator, Panel, PropertyGroup

# Set True to keep diagnostic prints while investigating Blender 5.3 draw issues.
DEBUG = False


def _log(msg):
    if DEBUG:
        print(f"[HDRI] {msg}")


class HDRIWorldProps(PropertyGroup):
    hdri_path: StringProperty(name="HDRI Path")
    use_background: BoolProperty(
        name="Use Separate Background HDRI",
        default=False,
        update=lambda self, context: rebuild_world_nodes(context.scene.world)
    )
    background_hdri: PointerProperty(
        name="Background HDRI",
        type=bpy.types.World,
        update=lambda self, context: rebuild_world_nodes(context.scene.world)
    )
    main_node_group: PointerProperty(type=bpy.types.NodeTree)
    last_sampled_color: FloatVectorProperty(
        name="Last Sampled",
        subtype='COLOR',
        size=3,
        default=(1.0, 1.0, 1.0),
        min=0.0,
        max=100.0
    )
    wb_picked_main: BoolProperty(default=False)
    wb_picked_bg: BoolProperty(default=False)


def is_hdri_world(world):
    """True only for worlds created by this addon."""
    if not world or not hasattr(world, "hdri_props"):
        return False
    props = world.hdri_props
    return bool(props.main_node_group or props.hdri_path)


def mix_sock(sockets, name, sock_type='RGBA'):
    """Return the Mix socket of the requested type (avoids float/vector name collisions)."""
    for s in sockets:
        if s.name == name and s.type == sock_type:
            return s
    raise RuntimeError(f"Mix socket {name}/{sock_type} not found")


# ─────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────
def title_case_hdri_name(filepath: str) -> str:
    name = bpy.path.display_name_from_filepath(filepath)
    name = name.replace("_", " ")
    parts = name.split()
    result = []
    for part in parts:
        if part.upper() in {"1K", "2K", "4K", "8K", "16K"}:
            result.append(part.upper())
        else:
            result.append(part.capitalize())
    return " ".join(result)


def compute_wb_gains(rgb):
    """Classic equal-RGB gains, max-normalized."""
    r, g, b = [max(c, 1e-4) for c in rgb]
    gains = [1.0 / r, 1.0 / g, 1.0 / b]
    max_gain = max(gains)
    if max_gain > 0:
        gains = [g / max_gain for g in gains]
    return tuple(gains)


# ─────────────────────────────────────────────────────────────
# Node group
# ─────────────────────────────────────────────────────────────
def create_hdri_node_group(name_suffix=""):
    ng_name = f"HDRI Controls — {name_suffix}" if name_suffix else "HDRI Controls"
    ng = bpy.data.node_groups.new(ng_name, 'ShaderNodeTree')
    ng.use_fake_user = True

    iface = ng.interface
    iface.new_socket(name="Output", in_out='OUTPUT', socket_type='NodeSocketShader')
    strength = iface.new_socket(name="Strength", in_out='INPUT', socket_type='NodeSocketFloat')
    influence = iface.new_socket(name="Influence", in_out='INPUT', socket_type='NodeSocketFloat')
    wb = iface.new_socket(name="White Balance", in_out='INPUT', socket_type='NodeSocketColor')
    hue = iface.new_socket(name="Hue", in_out='INPUT', socket_type='NodeSocketFloat')
    sat = iface.new_socket(name="Saturation", in_out='INPUT', socket_type='NodeSocketFloat')
    val = iface.new_socket(name="Value", in_out='INPUT', socket_type='NodeSocketFloat')
    temp = iface.new_socket(name="Temperature", in_out='INPUT', socket_type='NodeSocketFloat')
    tint = iface.new_socket(name="Tint", in_out='INPUT', socket_type='NodeSocketFloat')
    rot = iface.new_socket(name="Rotation", in_out='INPUT', socket_type='NodeSocketVector')

    strength.default_value = 1.0; strength.min_value = 0.0; strength.max_value = 10.0; strength.subtype = 'FACTOR'
    influence.default_value = 1.0; influence.min_value = 0.0; influence.max_value = 1.0; influence.subtype = 'FACTOR'
    wb.default_value = (1.0, 1.0, 1.0, 1.0)
    hue.default_value = 0.5; hue.min_value = 0.0; hue.max_value = 1.0; hue.subtype = 'FACTOR'
    sat.default_value = 1.0; sat.min_value = 0.0; sat.max_value = 2.0; sat.subtype = 'FACTOR'
    val.default_value = 1.0; val.min_value = 0.0; val.max_value = 2.0; val.subtype = 'FACTOR'
    temp.default_value = 6500.0; temp.min_value = 1500.0; temp.max_value = 12000.0; temp.subtype = 'FACTOR'
    tint.default_value = 0.0; tint.min_value = -1.0; tint.max_value = 1.0; tint.subtype = 'FACTOR'
    rot.default_value = (0.0, 0.0, 0.0); rot.subtype = 'EULER'

    nodes = ng.nodes
    links = ng.links

    # Coordinate / texture
    tex_coord = nodes.new('ShaderNodeTexCoord')
    tex_coord.location = (-1800, 0)
    mapping = nodes.new('ShaderNodeMapping')
    mapping.location = (-1600, 0)
    tex = nodes.new('ShaderNodeTexEnvironment')
    tex.name = "HDRI Texture"
    tex.location = (-1400, 0)
    tex.interpolation = 'Smart'
    tex.projection = 'EQUIRECTANGULAR'

    # White Balance multiply (always full; Influence is applied later as master blend)
    wb_mix = nodes.new('ShaderNodeMix')
    wb_mix.data_type = 'RGBA'
    wb_mix.blend_type = 'MULTIPLY'
    wb_mix.location = (-1200, 0)
    wb_mix.inputs['Factor'].default_value = 1.0
    wb_mix.name = "White Balance Mix"

    # Existing HSV
    hsv = nodes.new('ShaderNodeHueSaturation')
    hsv.location = (-1000, 0)
    hsv.inputs['Fac'].default_value = 1.0

    # Temperature white balance (relative to 6500K)
    temp_offset = nodes.new('ShaderNodeMath')
    temp_offset.operation = 'SUBTRACT'
    temp_offset.location = (-800, 350)
    temp_offset.inputs[1].default_value = 6500.0

    temp_sens = nodes.new('ShaderNodeMath')
    temp_sens.operation = 'MULTIPLY'
    temp_sens.location = (-600, 350)
    temp_sens.inputs[1].default_value = 5.0

    temp_restore = nodes.new('ShaderNodeMath')
    temp_restore.operation = 'ADD'
    temp_restore.location = (-400, 350)
    temp_restore.inputs[1].default_value = 6500.0

    bb_temp = nodes.new('ShaderNodeBlackbody')
    bb_temp.location = (-200, 250)
    bb_neutral = nodes.new('ShaderNodeBlackbody')
    bb_neutral.location = (-800, 50)
    bb_neutral.inputs['Temperature'].default_value = 6500.0

    divide = nodes.new('ShaderNodeVectorMath')
    divide.operation = 'DIVIDE'
    divide.location = (-200, 150)

    temp_color_mult = nodes.new('ShaderNodeMix')
    temp_color_mult.data_type = 'RGBA'
    temp_color_mult.blend_type = 'MULTIPLY'
    temp_color_mult.location = (0, 0)
    temp_color_mult.inputs['Factor'].default_value = 1.0

    # Tint
    tint_scale = nodes.new('ShaderNodeMath')
    tint_scale.operation = 'MULTIPLY'
    tint_scale.location = (-400, -200)
    tint_scale.inputs[1].default_value = 0.3

    green_adj = nodes.new('ShaderNodeMath')
    green_adj.operation = 'SUBTRACT'
    green_adj.location = (-200, -200)
    green_adj.inputs[0].default_value = 1.0

    tint_color = nodes.new('ShaderNodeCombineColor')
    tint_color.location = (0, -200)
    tint_color.inputs['Red'].default_value = 1.0
    tint_color.inputs['Blue'].default_value = 1.0

    tint_mult = nodes.new('ShaderNodeMix')
    tint_mult.data_type = 'RGBA'
    tint_mult.blend_type = 'MULTIPLY'
    tint_mult.location = (200, 0)
    tint_mult.inputs['Factor'].default_value = 1.0

    # Master Influence blend: 0 = original color, 1 = full WB+Temp+Tint correction
    # HSV stays outside so artistic hue/sat/value always apply.
    influence_mix = nodes.new('ShaderNodeMix')
    influence_mix.data_type = 'RGBA'
    influence_mix.blend_type = 'MIX'
    influence_mix.location = (350, 0)
    influence_mix.name = "Influence Mix"

    # Background + outputs
    bg = nodes.new('ShaderNodeBackground')
    bg.location = (550, 0)
    group_in = nodes.new('NodeGroupInput')
    group_in.location = (-2000, 0)
    group_out = nodes.new('NodeGroupOutput')
    group_out.location = (750, 0)

    # Links
    links.new(group_in.outputs['Rotation'], mapping.inputs['Rotation'])
    links.new(tex_coord.outputs['Generated'], mapping.inputs['Vector'])
    links.new(mapping.outputs['Vector'], tex.inputs['Vector'])

    # HSV always applied (artistic, outside Influence)
    links.new(tex.outputs['Color'], hsv.inputs['Color'])
    links.new(group_in.outputs['Hue'], hsv.inputs['Hue'])
    links.new(group_in.outputs['Saturation'], hsv.inputs['Saturation'])
    links.new(group_in.outputs['Value'], hsv.inputs['Value'])

    # White Balance only on the corrected path
    links.new(hsv.outputs['Color'], mix_sock(wb_mix.inputs, 'A'))
    links.new(group_in.outputs['White Balance'], mix_sock(wb_mix.inputs, 'B'))

    # Temperature
    links.new(group_in.outputs['Temperature'], temp_offset.inputs[0])
    links.new(temp_offset.outputs['Value'], temp_sens.inputs[0])
    links.new(temp_sens.outputs['Value'], temp_restore.inputs[0])
    links.new(temp_restore.outputs['Value'], bb_temp.inputs['Temperature'])
    links.new(bb_temp.outputs['Color'], divide.inputs[0])
    links.new(bb_neutral.outputs['Color'], divide.inputs[1])
    links.new(mix_sock(wb_mix.outputs, 'Result'), mix_sock(temp_color_mult.inputs, 'A'))
    links.new(divide.outputs['Vector'], mix_sock(temp_color_mult.inputs, 'B'))

    # Tint
    links.new(group_in.outputs['Tint'], tint_scale.inputs[0])
    links.new(tint_scale.outputs['Value'], green_adj.inputs[1])
    links.new(green_adj.outputs['Value'], tint_color.inputs['Green'])
    links.new(mix_sock(temp_color_mult.outputs, 'Result'), mix_sock(tint_mult.inputs, 'A'))
    links.new(tint_color.outputs['Color'], mix_sock(tint_mult.inputs, 'B'))

    # Master Influence: blend original (post-HSV) with fully corrected
    links.new(hsv.outputs['Color'], mix_sock(influence_mix.inputs, 'A'))
    links.new(mix_sock(tint_mult.outputs, 'Result'), mix_sock(influence_mix.inputs, 'B'))
    links.new(group_in.outputs['Influence'], mix_sock(influence_mix.inputs, 'Factor', 'VALUE'))

    # Final
    links.new(mix_sock(influence_mix.outputs, 'Result'), bg.inputs['Color'])
    links.new(group_in.outputs['Strength'], bg.inputs['Strength'])
    links.new(bg.outputs['Background'], group_out.inputs['Output'])

    return ng


def generate_panoramic_preview(world, filepath):
    """Generate a 256x256 full-panorama squished thumbnail with AgX Base Contrast tone mapping."""
    preview_img = None
    temp_scene = None
    temp_path = None
    try:
        img = bpy.data.images.load(filepath, check_existing=True)
        if not img or img.size[0] == 0 or img.size[1] == 0:
            return

        target_size = 256
        preview_name = f"preview_{world.name}"

        if preview_name in bpy.data.images:
            bpy.data.images.remove(bpy.data.images[preview_name])

        preview_img = img.copy()
        preview_img.name = preview_name
        preview_img.scale(target_size, target_size)

        temp_scene = bpy.data.scenes.new(name="_HDRI_Preview_Temp")
        temp_scene.view_settings.view_transform = 'AgX'
        temp_scene.view_settings.look = 'AgX - Base Contrast'
        temp_scene.view_settings.exposure = 0.0
        temp_scene.view_settings.gamma = 1.0

        temp_path = bpy.app.tempdir + f"/hdri_preview_{world.name}.png"
        preview_img.save_render(filepath=temp_path, scene=temp_scene)

        world.asset_mark()
        with bpy.context.temp_override(id=world):
            bpy.ops.ed.lib_id_load_custom_preview(filepath=temp_path)

    except Exception as e:
        print(f"HDRI Helper: Preview generation failed: {e}")
    finally:
        if temp_path and os.path.exists(temp_path):
            try:
                os.remove(temp_path)
            except Exception:
                pass
        if preview_img and preview_img.name in bpy.data.images:
            try:
                bpy.data.images.remove(preview_img)
            except Exception:
                pass
        if temp_scene and temp_scene.name in bpy.data.scenes:
            try:
                bpy.data.scenes.remove(temp_scene)
            except Exception:
                pass


def _snapshot_group_inputs(group_node):
    """Return {socket_name: value} for a group node's inputs."""
    if not group_node:
        return {}
    snap = {}
    for inp in group_node.inputs:
        try:
            v = inp.default_value
            snap[inp.name] = tuple(v) if hasattr(v, "__len__") else v
        except Exception:
            pass
    return snap


def _restore_group_inputs(group_node, snap):
    """Write previously snapshotted values back onto a group node."""
    if not group_node or not snap:
        return
    for inp in group_node.inputs:
        if inp.name in snap:
            try:
                inp.default_value = snap[inp.name]
            except Exception:
                pass


def rebuild_world_nodes(world):
    if not world or not world.node_tree:
        return
    tree = world.node_tree

    # Snapshot instance values before clear so user tweaks survive the rebuild
    main_snap = _snapshot_group_inputs(find_group(world, 'MAIN'))
    bg_snap = _snapshot_group_inputs(find_group(world, 'BACKGROUND'))

    tree.nodes.clear()

    output = tree.nodes.new('ShaderNodeOutputWorld')
    output.location = (600, 0)

    main_group = tree.nodes.new('ShaderNodeGroup')
    main_group.node_tree = world.hdri_props.main_node_group
    main_group.location = (-200, 200)
    main_group["hdri_main"] = True
    _restore_group_inputs(main_group, main_snap)

    if world.hdri_props.use_background and world.hdri_props.background_hdri:
        bg_group = tree.nodes.new('ShaderNodeGroup')
        bg_group.node_tree = world.hdri_props.background_hdri.hdri_props.main_node_group
        bg_group.location = (-200, -200)
        bg_group["hdri_background"] = True
        _restore_group_inputs(bg_group, bg_snap)

        lp = tree.nodes.new('ShaderNodeLightPath')
        mix = tree.nodes.new('ShaderNodeMixShader')
        lp.location = (200, 0)
        mix.location = (400, 0)

        tree.links.new(main_group.outputs[0], mix.inputs[1])
        tree.links.new(bg_group.outputs[0], mix.inputs[2])
        tree.links.new(lp.outputs['Is Camera Ray'], mix.inputs[0])
        tree.links.new(mix.outputs[0], output.inputs[0])
    else:
        tree.links.new(main_group.outputs[0], output.inputs[0])


# ─────────────────────────────────────────────────────────────
# Operators
# ─────────────────────────────────────────────────────────────
class WORLD_OT_import_hdri_as_asset(Operator):
    bl_idname = "world.import_hdri_as_asset"
    bl_label = "Add World Assets"
    bl_options = {'REGISTER', 'UNDO'}
    bl_description = "Import EXR or HDR files as world assets with controls and preview thumbnails"

    files: bpy.props.CollectionProperty(type=bpy.types.OperatorFileListElement)
    directory: StringProperty(subtype='DIR_PATH')
    filter_glob: StringProperty(default="*.exr;*.hdr", options={'HIDDEN'})

    def execute(self, context):
        if not self.files:
            self.report({'WARNING'}, "No files selected")
            return {'CANCELLED'}

        valid_files = []
        for f in self.files:
            if f.name.lower().endswith(('.exr', '.hdr')):
                path = os.path.join(self.directory, f.name)
                if not any(getattr(w, "hdri_props", None) and w.hdri_props.hdri_path == path for w in bpy.data.worlds):
                    valid_files.append(path)

        total = len(valid_files)
        if total == 0:
            self.report({'INFO'}, "No new HDRIs")
            return {'CANCELLED'}

        wm = context.window_manager
        wm.progress_begin(0, total)
        context.window.cursor_set("WAIT")
        try:
            for i, path in enumerate(valid_files):
                self.create_hdri_world(path)
                wm.progress_update(i + 1)
            self.report({'INFO'}, f"Imported {total} HDRI(s)")
            return {'FINISHED'}
        finally:
            wm.progress_end()
            context.window.cursor_set("DEFAULT")

    def invoke(self, context, event):
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

    def create_hdri_world(self, filepath):
        clean_name = title_case_hdri_name(filepath)
        world = bpy.data.worlds.new(clean_name)
        # Blender 5.x creates the node tree automatically

        ng = create_hdri_node_group(clean_name)
        world.hdri_props.main_node_group = ng

        tree = world.node_tree
        tree.nodes.clear()
        output = tree.nodes.new('ShaderNodeOutputWorld')
        output.location = (300, 0)
        group_node = tree.nodes.new('ShaderNodeGroup')
        group_node.node_tree = ng
        group_node["hdri_main"] = True
        tree.links.new(group_node.outputs[0], output.inputs[0])

        img = bpy.data.images.load(filepath, check_existing=True)
        ng.nodes["HDRI Texture"].image = img
        world.hdri_props.hdri_path = filepath
        generate_panoramic_preview(world, filepath)

        world.asset_mark()
        world.asset_data.author = "HDRI Helper"
        world.asset_data.description = f"HDRI: {os.path.basename(filepath)}"
        world.asset_data.tags.new("HDRI")
        world.asset_data.tags.new("World")


def find_group(world, target):
    """Return the main or background HDRI group node on a world, or None."""
    if not world or not world.node_tree:
        return None
    key = "hdri_main" if target == 'MAIN' else "hdri_background"
    nodes = world.node_tree.nodes
    node = next((n for n in nodes if n.get(key)), None)
    if not node and target == 'MAIN':
        node = next((n for n in nodes if n.type == 'GROUP'), None)
    return node


def find_view3d_under_mouse(context, event):
    """Return True if the mouse is over a 3D Viewport window region."""
    win = context.window
    if not win:
        return False
    for area in win.screen.areas:
        if area.type != 'VIEW_3D':
            continue
        for region in area.regions:
            if region.type != 'WINDOW':
                continue
            x = event.mouse_x - region.x
            y = event.mouse_y - region.y
            if 0 <= x < region.width and 0 <= y < region.height:
                return True
    return False


def _deferred_apply_wb(rgb, target, prev=None, prev_picked=None):
    """Apply white-balance gains after the modal operator has fully exited.
    On failure, restore the values that were saved before the invoke-time reset.
    """
    try:
        world = bpy.context.scene.world
        if not is_hdri_world(world):
            _log("deferred apply: no HDRI world")
            raise RuntimeError("no HDRI world")
        group_node = find_group(world, target)
        if not group_node:
            _log("deferred apply: no group node")
            raise RuntimeError("no group node")

        props = world.hdri_props
        props.last_sampled_color = tuple(min(max(c, 0.0), 100.0) for c in rgb[:3])
        gains = compute_wb_gains(rgb)
        for inp in group_node.inputs:
            if inp.name == "White Balance":
                inp.default_value = (*gains, 1.0)
        if target == 'MAIN':
            props.wb_picked_main = True
        else:
            props.wb_picked_bg = True
        _log(f"deferred apply done for {target} → {gains}")
    except Exception as e:
        _log(f"deferred apply failed: {e}")
        # Restore the pre-pick values so a failed timer doesn't leave the reset state
        try:
            world = bpy.context.scene.world
            if is_hdri_world(world) and prev is not None:
                group_node = find_group(world, target)
                if group_node:
                    for inp in group_node.inputs:
                        if inp.name in prev:
                            inp.default_value = prev[inp.name]
                if prev_picked is not None:
                    if target == 'MAIN':
                        world.hdri_props.wb_picked_main = prev_picked
                    else:
                        world.hdri_props.wb_picked_bg = prev_picked
                _log("restored previous values after deferred failure")
        except Exception as e2:
            _log(f"restore after deferred failure also failed: {e2}")
    return None  # one-shot timer


class WORLD_OT_pick_white_balance(Operator):
    bl_idname = "world.pick_white_balance"
    bl_label = "Pick Neutral"
    bl_options = {'REGISTER', 'UNDO'}
    bl_description = "Click a point in the 3D Viewport that should be neutral"

    RESET_VALUES = {
        "White Balance": (1.0, 1.0, 1.0, 1.0),
        "Temperature": 6500.0,
        "Tint": 0.0,
        "Influence": 1.0,
        "Hue": 0.5,
        "Saturation": 1.0,
        "Value": 1.0,
    }

    target: bpy.props.EnumProperty(
        items=[
            ('MAIN', "Main", "Main lighting HDRI"),
            ('BACKGROUND', "Background", "Background HDRI"),
        ],
        default='MAIN'
    )

    def modal(self, context, event):
        # Do not tag_redraw here — it has been linked to draw-engine crashes
        # in Blender 5.3 after the operator finishes.

        if event.type == 'LEFTMOUSE' and event.value == 'PRESS':
            if not find_view3d_under_mouse(context, event):
                self.report({'WARNING'}, "Click inside a 3D Viewport (Esc or right-click to cancel)")
                return {'RUNNING_MODAL'}
            try:
                fb = gpu.state.active_framebuffer_get()
                if not fb:
                    raise ValueError("No active framebuffer")
                # 1x1 read — safer while isolating the 5.3 draw crash
                buf = fb.read_color(event.mouse_x, event.mouse_y, 1, 1, 3, 0, 'FLOAT')
                raw = buf.to_list() if hasattr(buf, "to_list") else list(buf)
                while isinstance(raw, (list, tuple)) and len(raw) == 1 and isinstance(raw[0], (list, tuple)):
                    raw = raw[0]
                if not (isinstance(raw, (list, tuple)) and len(raw) >= 3):
                    raise ValueError(f"Unexpected sample shape: {raw}")
                rgb = (float(raw[0]), float(raw[1]), float(raw[2]))
                _log(f"sampled → {rgb}")
                # Defer the node write so it happens after this operator
                # has fully returned and the draw engine is idle.
                # Pass previous values so a failed timer can restore them.
                bpy.app.timers.register(
                    lambda r=rgb, t=self.target, p=dict(self._prev), pk=self._prev_picked:
                        _deferred_apply_wb(r, t, p, pk),
                    first_interval=0.05,
                )
                self.report({'INFO'}, "Sample captured — applying…")
            except Exception as e:
                _log(f"sample failed: {e}")
                self.report({'WARNING'}, f"Sample failed: {e}")
                self.restore_previous(context)

            context.window.cursor_modal_restore()
            return {'FINISHED'}

        elif event.type in {'RIGHTMOUSE', 'ESC'}:
            self.restore_previous(context)
            context.window.cursor_modal_restore()
            return {'CANCELLED'}

        return {'RUNNING_MODAL'}

    def invoke(self, context, event):
        self._prev = {}
        self._prev_picked = False
        world = context.scene.world
        if is_hdri_world(world):
            group_node = find_group(world, self.target)
            if group_node:
                for inp in group_node.inputs:
                    if inp.name in self.RESET_VALUES:
                        v = inp.default_value
                        self._prev[inp.name] = tuple(v) if hasattr(v, "__len__") else v
            if self.target == 'MAIN':
                self._prev_picked = world.hdri_props.wb_picked_main
            else:
                self._prev_picked = world.hdri_props.wb_picked_bg

        self.reset_target(context)
        _log("Pick Neutral started — click a neutral in the 3D Viewport")
        context.window.cursor_modal_set('EYEDROPPER')
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def restore_previous(self, context):
        world = context.scene.world
        if not is_hdri_world(world):
            return
        group_node = find_group(world, self.target)
        if group_node:
            for inp in group_node.inputs:
                if inp.name in self._prev:
                    inp.default_value = self._prev[inp.name]
        if self.target == 'MAIN':
            world.hdri_props.wb_picked_main = self._prev_picked
        else:
            world.hdri_props.wb_picked_bg = self._prev_picked

    def reset_target(self, context):
        world = context.scene.world
        if not is_hdri_world(world):
            return
        group_node = find_group(world, self.target)
        if group_node:
            for inp in group_node.inputs:
                if inp.name in self.RESET_VALUES:
                    inp.default_value = self.RESET_VALUES[inp.name]
            if self.target == 'MAIN':
                world.hdri_props.wb_picked_main = False
            else:
                world.hdri_props.wb_picked_bg = False


class WORLD_OT_reset_white_balance(Operator):
    bl_idname = "world.reset_white_balance"
    bl_label = "Reset All Color"
    bl_options = {'REGISTER', 'UNDO'}
    bl_description = "Reset white balance, hue, saturation, value, temperature, tint and influence to defaults"

    target: bpy.props.EnumProperty(
        items=[
            ('MAIN', "Main", ""),
            ('BACKGROUND', "Background", ""),
        ],
        default='MAIN'
    )

    def execute(self, context):
        world = context.scene.world
        if not is_hdri_world(world):
            return {'CANCELLED'}

        group_node = find_group(world, self.target)

        if group_node:
            for inp in group_node.inputs:
                if inp.name == "White Balance":
                    inp.default_value = (1.0, 1.0, 1.0, 1.0)
                elif inp.name == "Temperature":
                    inp.default_value = 6500.0
                elif inp.name == "Tint":
                    inp.default_value = 0.0
                elif inp.name == "Influence":
                    inp.default_value = 1.0
                elif inp.name == "Hue":
                    inp.default_value = 0.5
                elif inp.name == "Saturation":
                    inp.default_value = 1.0
                elif inp.name == "Value":
                    inp.default_value = 1.0

        if self.target == 'MAIN':
            world.hdri_props.wb_picked_main = False
        else:
            world.hdri_props.wb_picked_bg = False

        return {'FINISHED'}


# ─────────────────────────────────────────────────────────────
# Panel
# ─────────────────────────────────────────────────────────────
class WORLD_PT_hdri_helper(Panel):
    bl_label = "HDRI Helper"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "world"

    def draw(self, context):
        layout = self.layout
        col = layout.column(align=True)
        col.scale_y = 1.5
        col.operator("world.import_hdri_as_asset", text="Add World Assets", icon='WORLD')

        if is_hdri_world(context.scene.world):
            world = context.scene.world
            props = world.hdri_props

            # Main lighting
            box = layout.box()
            box.label(text=f"Lighting HDRI: {world.name}", icon='WORLD')
            main_group = next((n for n in world.node_tree.nodes if n.get("hdri_main")), None)
            if not main_group:
                # Fallback for worlds created with earlier versions
                main_group = next((n for n in world.node_tree.nodes if n.type == 'GROUP'), None)

            if main_group:
                # Strength first
                for inp in main_group.inputs:
                    if inp.name == "Strength":
                        box.prop(inp, "default_value", text=inp.name)
                        break

                # White Balance controls
                row = box.row(align=True)
                row.operator("world.pick_white_balance", text="Pick Neutral", icon='EYEDROPPER').target = 'MAIN'
                row.label(text="", icon='CHECKMARK' if props.wb_picked_main else 'BLANK1')
                row.operator("world.reset_white_balance", text="Reset All Color", icon='LOOP_BACK').target = 'MAIN'

                # Influence
                for inp in main_group.inputs:
                    if inp.name == "Influence":
                        box.prop(inp, "default_value", text="Influence")
                        break

                # Side-by-side swatches with compact left-justified labels
                row = box.row()
                col = row.column()
                col.label(text="Last Sample")
                col.prop(props, "last_sampled_color", text="")
                col = row.column()
                col.label(text="White Balance")
                for inp in main_group.inputs:
                    if inp.name == "White Balance":
                        col.prop(inp, "default_value", text="")
                        break

                # Remaining controls (skip the ones we already drew)
                for inp in main_group.inputs:
                    if inp.name not in {"Output", "Strength", "Influence", "White Balance"}:
                        box.prop(inp, "default_value", text=inp.name)

            layout.prop(props, "use_background")

            if props.use_background:
                box = layout.box()
                box.label(text="Background HDRI", icon='WORLD')
                row = box.row()
                row.prop(props, "background_hdri", text="")
                row.operator("world.import_hdri_as_asset", text="", icon='FILE_FOLDER')

                if props.background_hdri:
                    bg_group = next((n for n in world.node_tree.nodes if n.get("hdri_background")), None)
                    if bg_group:
                        for inp in bg_group.inputs:
                            if inp.name == "Strength":
                                box.prop(inp, "default_value", text=inp.name)
                                break

                        row = box.row(align=True)
                        row.operator("world.pick_white_balance", text="Pick Neutral", icon='EYEDROPPER').target = 'BACKGROUND'
                        row.label(text="", icon='CHECKMARK' if props.wb_picked_bg else 'BLANK1')
                        row.operator("world.reset_white_balance", text="Reset All Color", icon='LOOP_BACK').target = 'BACKGROUND'

                        for inp in bg_group.inputs:
                            if inp.name == "Influence":
                                box.prop(inp, "default_value", text="Influence")
                                break

                        row = box.row()
                        col = row.column()
                        col.label(text="Last Sample")
                        col.prop(props, "last_sampled_color", text="")
                        col = row.column()
                        col.label(text="White Balance")
                        for inp in bg_group.inputs:
                            if inp.name == "White Balance":
                                col.prop(inp, "default_value", text="")
                                break

                        for inp in bg_group.inputs:
                            if inp.name not in {"Output", "Strength", "Influence", "White Balance"}:
                                box.prop(inp, "default_value", text=inp.name)


classes = (
    HDRIWorldProps,
    WORLD_OT_import_hdri_as_asset,
    WORLD_OT_pick_white_balance,
    WORLD_OT_reset_white_balance,
    WORLD_PT_hdri_helper,
)

def register():
    for c in classes:
        bpy.utils.register_class(c)
    bpy.types.World.hdri_props = PointerProperty(type=HDRIWorldProps)

def unregister():
    del bpy.types.World.hdri_props
    for c in reversed(classes):
        bpy.utils.unregister_class(c)

if __name__ == "__main__":
    register()
