<template>
    <div style="display:flex; flex-direction:column; align-items:center;">
        <!-- Node Card (n8n Aesthetic) -->
        <div 
            :id="`node-${node.id}`"
            :class="['af-node', `af-node--${node.type}`, { 'is-selected': selectedNodeId === node.id, 'has-active-tooltip': openTooltipNodeId === node.id }]"
            @click.stop="$emit('select', node)"
        >
            <div class="af-node-hdr">
                <!-- Icon Badge -->
                <div class="af-node-icon-badge" :class="`af-icon--${node.type}`">
                    <!-- Trigger -->
                    <svg v-if="node.type === 'trigger'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
                    </svg>
                    <!-- Incoming Webhook Trigger -->
                    <svg v-else-if="node.type === 'incoming_webhook'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" />
                    </svg>
                    <!-- Condition or A/B Split -->
                    <svg v-else-if="node.type === 'condition' || node.type === 'ab_split'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
                    </svg>
                    <!-- Email -->
                    <svg v-else-if="node.type === 'email'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" />
                    </svg>
                    <!-- Campaign Email -->
                    <svg v-else-if="node.type === 'campaign_email'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.113 12.09a2 2 0 01-.218.83L15 20l-2.68-2.68A2 2 0 0111.91 16.5H5a2 2 0 01-2-2v-5a2 2 0 012-2h6.91a2 2 0 011.41.59L15 4l3.895 7.08a2 2 0 01.218.83v.18zM19.5 12h.008v.008H19.5V12z" />
                    </svg>
                    <!-- Webhook / HTTP Request -->
                    <svg v-else-if="node.type === 'webhook'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M14.25 9.75L16.5 12l-2.25 2.25m-4.5 0L7.5 12l2.25-2.25M6 20.25h12A2.25 2.25 0 0020.25 18V6A2.25 2.25 0 0018 3.75H6A2.25 2.25 0 003.75 6v12A2.25 2.25 0 006 20.25z" />
                    </svg>

                    <!-- Wait -->
                    <svg v-else-if="node.type === 'wait'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <!-- Tag (apply_tag / remove_tag) -->
                    <svg v-else-if="node.type === 'apply_tag' || node.type === 'remove_tag'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z" />
                    </svg>
                    <!-- Update Property -->
                    <svg v-else-if="node.type === 'update_field'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                    </svg>
                    <!-- List Membership (apply_list / remove_list) -->
                    <svg v-else-if="node.type === 'apply_list' || node.type === 'remove_list'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <!-- End -->
                    <svg v-else xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                    </svg>
                </div>

                <!-- Title & Category Pill -->
                <div class="af-node-title-wrap">
                    <div class="af-node-title-row">
                        <span class="af-node-title">{{ node.title || defaultTitle(node.type) }}</span>
                    </div>
                    <div class="af-node-cat-row">
                        <span class="af-node-cat-badge" :class="`af-cat--${nodeCategory(node.type).toLowerCase()}`">{{ nodeCategory(node.type) }}</span>
                    </div>
                </div>

                <!-- Actions -->
                <div class="af-node-actions">
                    <span v-if="node.type === 'trigger'" class="af-node-status-dot" title="Active Trigger"></span>
                </div>
            </div>

            <!-- Bottom Summary Pill -->
            <div class="af-node-sub-box">
                <span class="af-node-sub-text">{{ defaultSub(node) }}</span>
            </div>

            <!-- Node Stats & Tooltip Footer -->
            <div v-if="nodeStatus && nodeStatus[node.id]" class="af-node-status-footer">
                <div class="af-status-indicators">
                    <!-- Spinner if processing -->
                    <span v-if="nodeStatus[node.id].processingCount > 0" class="af-status-badge is-processing" title="Processing contacts">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-refresh-ccw-icon lucide-refresh-ccw animate-spin"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>
                        {{ nodeStatus[node.id].processingCount }}
                    </span>
                    
                    <!-- Success count -->
                    <span v-if="nodeStatus[node.id].successCount > 0" class="af-status-badge is-success" title="Success count">
                        ✓ {{ nodeStatus[node.id].successCount }}
                    </span>
                    
                    <!-- Error count -->
                    <span v-if="nodeStatus[node.id].errorCount > 0" class="af-status-badge is-error" title="Error count">
                        ⚠ {{ nodeStatus[node.id].errorCount }}
                    </span>
                </div>
                
                <!-- Info Button with click-toggle tooltip -->
                <div class="af-tooltip-wrapper">
                    <button class="af-info-btn" type="button" @click.stop="openTooltipNodeId = (openTooltipNodeId === node.id ? null : node.id)">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-info-icon lucide-info"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
                    </button>
                    <div class="af-tooltip-panel" v-if="openTooltipNodeId === node.id">
                        <div class="af-tooltip-hdr" style="display:flex; justify-content:space-between; align-items:center; border-bottom: 1px solid #334155; padding-bottom: 6px; margin-bottom: 8px;">
                            <span class="af-tooltip-title" style="margin:0; padding:0;">Step Execution Logs</span>
                            <button class="af-tooltip-close" type="button" @click.stop="openTooltipNodeId = null">&times;</button>
                        </div>
                        <div class="af-tooltip-stats">
                            <span class="stat-item is-success">✓ {{ nodeStatus[node.id].successCount }} success</span>
                            <span class="stat-item is-processing">{{ nodeStatus[node.id].processingCount }} pending</span>
                            <span class="stat-item is-error">⚠ {{ nodeStatus[node.id].errorCount }} errors</span>
                        </div>
                        <div class="af-tooltip-logs">
                            <div v-for="log in nodeStatus[node.id].logs.slice(0, 5)" :key="log.id" class="af-tooltip-log-item" :class="`is-${log.event_type === 'enrolled' ? 'success' : log.event_type.replace('node_', '')}`">
                                <div class="log-header">
                                    <span class="log-email">{{ log.contact ? log.contact.email : 'Unknown' }}</span>
                                    <span class="log-time">{{ formatLogTime(log.created_at) }}</span>
                                </div>
                                <div class="log-body">{{ log.reason }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── BRANCHES OR NEXT NODE ── -->
        <template v-if="node.type === 'condition' || node.type === 'ab_split'">
            <div class="af-branch-root">
                <div class="af-branch-hline"></div>
                <div class="af-branch-cols">
                    <!-- Left Branch (No / Path A) -->
                    <div class="af-branch-col af-branch-col--no">
                        <div class="af-branch-vline-top"></div>
                        <div class="af-branch-pill af-branch-pill--no">{{ node.type === 'ab_split' ? 'Path A (50%)' : 'No' }}</div>
                        <div class="af-branch-vline"></div>
                        <div class="af-branch-box af-branch-box--no">
                            <template v-if="getBranchNode(node.id, 'no')">
                                <FunnelNode 
                                    :node="getBranchNode(node.id, 'no')"
                                    :nodes="nodes"
                                    :edges="edges"
                                    :selectedNodeId="selectedNodeId"
                                    :nodeStatus="nodeStatus"
                                    @select="$emit('select', $event)"
                                    @delete="$emit('delete', $event)"
                                    @add-click="$emit('add-click', $event)"
                                />
                            </template>
                            <template v-else>
                                <button class="af-add-action-btn" @click.stop="$emit('add-click', { sourceId: node.id, branch: 'no' })">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                                    </svg>
                                    Add Action
                                </button>
                            </template>
                        </div>
                    </div>

                    <!-- Right Branch (Yes / Path B) -->
                    <div class="af-branch-col af-branch-col--yes">
                        <div class="af-branch-vline-top"></div>
                        <div class="af-branch-pill af-branch-pill--yes">{{ node.type === 'ab_split' ? 'Path B (50%)' : 'Yes' }}</div>
                        <div class="af-branch-vline"></div>
                        <div class="af-branch-box af-branch-box--yes">
                            <template v-if="getBranchNode(node.id, 'yes')">
                                <FunnelNode 
                                    :node="getBranchNode(node.id, 'yes')"
                                    :nodes="nodes"
                                    :edges="edges"
                                    :selectedNodeId="selectedNodeId"
                                    :nodeStatus="nodeStatus"
                                    @select="$emit('select', $event)"
                                    @delete="$emit('delete', $event)"
                                    @add-click="$emit('add-click', $event)"
                                />
                            </template>
                            <template v-else>
                                <button class="af-add-action-btn" @click.stop="$emit('add-click', { sourceId: node.id, branch: 'yes' })">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                                    </svg>
                                    Add Action
                                </button>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </template>

        <!-- Sequential Node -->
        <template v-else-if="node.type !== 'end'">
            <div class="af-connector">
                <div class="af-connector-line"></div>
                <button class="af-add-circle" @click.stop="$emit('add-click', { sourceId: node.id })" title="Add step">+</button>
                <div class="af-connector-line"></div>
            </div>

            <template v-if="getNextNode(node.id)">
                <FunnelNode 
                    :node="getNextNode(node.id)"
                    :nodes="nodes"
                    :edges="edges"
                    :selectedNodeId="selectedNodeId"
                    :nodeStatus="nodeStatus"
                    @select="$emit('select', $event)"
                    @delete="$emit('delete', $event)"
                    @add-click="$emit('add-click', $event)"
                />
            </template>
        </template>
    </div>
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
    node: Object,
    nodes: Array,
    edges: Array,
    selectedNodeId: String,
    nodeStatus: Object,
});

const openTooltipNodeId = ref(null);

// Relative time formatting for logs
function formatLogTime(isoString) {
    const date = new Date(isoString);
    const now = new Date();
    const diffMs = now - date;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHr = Math.floor(diffMin / 60);
    
    if (diffSec < 60) return 'just now';
    if (diffMin < 60) return `${diffMin}m ago`;
    if (diffHr < 24) return `${diffHr}h ago`;
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}

const emit = defineEmits(['select', 'delete', 'add-click']);

function getNextNode(id) {
    const edge = props.edges.find(e => e.source === id && !e.branch);
    if (!edge) return null;
    return props.nodes.find(n => n.id === edge.target);
}

function getBranchNode(id, branchName) {
    const edge = props.edges.find(e => e.source === id && e.branch === branchName);
    if (!edge) return null;
    return props.nodes.find(n => n.id === edge.target);
}

function defaultTitle(type) {
    const titles = {
        trigger: 'Trigger Event',
        incoming_webhook: 'Incoming Webhook',
        condition: 'If / Else Condition',
        email: 'Send Email',
        campaign_email: 'Campaign Email',
        wait: 'Wait / Delay Execution',
        webhook: 'Outgoing Webhook',

        ab_split: 'A/B Split Test',
        apply_tag: 'Apply Contact Tag',
        remove_tag: 'Remove Contact Tag',
        apply_list: 'Subscribe to List',
        remove_list: 'Unsubscribe from List',
        update_field: 'Update Contact Property',
        end: 'End Funnel',
    };
    return titles[type] || type;
}

function defaultSub(node) {
    if (node.type === 'trigger') {
        // Wait, we need to access settings from the parent page. 
        // In FunnelNode, the node object represents the nodes inside form.settings.nodes.
        // But the trigger settings (like type, list_id, tag_id) are defined on node.config or the main settings.
        // Let's check how the trigger config is stored in node.config!
        // In our DB settings: {"id":"n_8c3dd0882c35","type":"trigger","title":"New Automation","sub":"New User Sign Up","config":[]}
        // So the trigger config is not in node.config, it is in campaign.settings.trigger.
        // But since we don't have access to the main campaign.settings in FunnelNode (it only receives nodes and edges props),
        // we can check if the trigger details are passed in node.config or falls back to node.sub.
        // Let's write a safe fallback that checks both!
        if (node.sub) return node.sub;
        return 'Automation Trigger';
    }
    if (node.type === 'incoming_webhook') {
        return node.sub || 'HTTP POST Webhook Trigger';
    }
    if (node.type === 'wait') {
        const val = node.config?.value !== undefined ? node.config.value : 1;
        const unit = node.config?.unit || 'days';
        return `Wait ${val} ${unit}`;
    }
    if (node.type === 'email') {
        if (node.sub && node.sub.startsWith('Design:')) return node.sub;
        return `Subject: ${node.config?.subject || 'Hey there!'}`;
    }
    if (node.type === 'campaign_email') {
        if (node.sub && node.sub.startsWith('Campaign:')) return node.sub;
        return 'Select a Campaign...';
    }
    if (node.type === 'webhook') {
        return `${node.config?.method || 'POST'} ${node.config?.url || 'https://api.external.endpoint'}`;
    }

    if (node.type === 'ab_split') {
        return `Split ${node.config?.split_percentage || 50}% / ${100 - (node.config?.split_percentage || 50)}%`;
    }
    if (node.type === 'update_field') {
        return `Set ${node.config?.field_name || 'contact_type'} = ${node.config?.value || 'lead'}`;
    }
    if (node.type === 'condition') {
        return `Evaluate conditions & split flow`;
    }
    if (node.type === 'apply_tag') {
        return node.sub && node.sub.startsWith('Apply:') ? node.sub : 'Attach tag to profile';
    }
    if (node.type === 'remove_tag') {
        return node.sub && node.sub.startsWith('Remove:') ? node.sub : 'Remove tag from profile';
    }
    if (node.type === 'apply_list') {
        return node.sub && node.sub.startsWith('Subscribe:') ? node.sub : 'Subscribe contact to list';
    }
    if (node.type === 'remove_list') {
        return node.sub && node.sub.startsWith('Unsubscribe:') ? node.sub : 'Unsubscribe contact from list';
    }
    if (node.type === 'end') {
        return `Terminate workflow branch`;
    }
    return node.sub || 'Automation Step';
}

function nodeCategory(type) {
    if (type === 'trigger' || type === 'incoming_webhook') return 'Trigger';
    if (type === 'condition' || type === 'ab_split' || type === 'wait') return 'Logic';

    if (type === 'end') return 'End';
    return 'Action';
}
</script>
