<template>
    <!-- Connector + Delay Pill -->
    <div class="sb-connector">
        <div class="sb-connector-line" style="height:12px"></div>
        <div class="sb-connector-dot"></div>
    </div>
    <div class="sb-delay-pill" @click="$emit('open-delay', index)">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" 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>
        <span v-if="step.delay.amount === 0">Send immediately</span>
        <span v-else>Wait {{ step.delay.amount }} {{ step.delay.unit }} then send</span>
    </div>
    <div class="sb-connector">
        <div class="sb-connector-dot"></div>
        <div class="sb-connector-line" style="height:12px"></div>
    </div>

    <!-- Email Step -->
    <div class="sb-email-step" :class="{ 'is-selected': isSelected }" @click="$emit('select', index)">
        <div class="sb-step-badge">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" 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>
            Email &middot; {{ stepLabel }}
        </div>
        <div class="sb-step-subject">
            <input type="text" v-model="step.subject" @change="$emit('save')" @click.stop placeholder="Enter email subject...">
        </div>
        <div class="sb-step-meta">From: {{ step.from_name || 'Emma at CRMfic' }} &middot; {{ stepStat && stepStat.sent > 0 ? 'Sent' : 'Not sent yet' }}</div>

        <!-- Performance summary -->
        <div v-if="stepStat" class="sb-step-perf">
            <span>{{ stepStat.sent }} sent</span>
            <span v-if="stepStat.sent > 0">&middot; {{ Math.round((stepStat.opens / stepStat.sent) * 100) }}% open</span>
            <span v-if="stepStat.sent > 0">&middot; {{ Math.round((stepStat.clicks / stepStat.sent) * 100) }}% click</span>
        </div>

        <!-- Node Stats & Tooltip Footer -->
        <div v-if="nodeStatus && nodeStatus[step.id]" class="af-node-status-footer sb-node-status-footer">
            <div class="af-status-indicators">
                <span v-if="nodeStatus[step.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[step.id].processingCount }}
                </span>
                <span v-if="nodeStatus[step.id].successCount > 0" class="af-status-badge is-success" title="Success count">
                    ✓ {{ nodeStatus[step.id].successCount }}
                </span>
                <span v-if="nodeStatus[step.id].errorCount > 0" class="af-status-badge is-error" title="Error count">
                    ⚠ {{ nodeStatus[step.id].errorCount }}
                </span>
            </div>

            <div class="af-tooltip-wrapper">
                <button class="af-info-btn" type="button" @click.stop="$emit('toggle-tooltip', step.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 === step.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="$emit('toggle-tooltip', null)">&times;</button>
                    </div>
                    <div class="af-tooltip-stats">
                        <span class="stat-item is-success" style="color:#22c55e">✓ {{ nodeStatus[step.id].successCount }} success</span>
                        <span class="stat-item is-processing" style="color:#3b82f6">{{ nodeStatus[step.id].processingCount }} pending</span>
                        <span class="stat-item is-error" style="color:#ef4444">⚠ {{ nodeStatus[step.id].errorCount }} errors</span>
                    </div>
                    <div class="af-tooltip-logs" style="max-height: 200px; overflow-y: auto;">
                        <div v-for="log in nodeStatus[step.id].logs.filter(l => l.event_type !== 'sent' && l.event_type !== 'node_processing').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" style="font-weight:600">{{ log.contact ? log.contact.email : 'Unknown' }}</span>
                                <span class="log-time" style="color:#94a3b8; font-size:10px">{{ formatLogTime(log.created_at) }}</span>
                            </div>
                            <div v-if="log.reason" class="log-body" style="font-size:11px; margin-top:2px; color:#cbd5e1">{{ log.reason }}</div>
                        </div>
                        <div v-if="!nodeStatus[step.id].logs || nodeStatus[step.id].logs.length === 0" style="font-size:11px; color:#94a3b8; text-align:center; padding:8px 0;">
                            No recent activity logs.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

const props = defineProps({
    step:              { type: Object,  required: true },
    index:             { type: Number,  required: true },
    stepLabel:         { type: String,  default: '' },
    isSelected:        { type: Boolean, default: false },
    openTooltipNodeId: { default: null },
    nodeStatus:        { type: Object,  default: () => ({}) },
    stepStats:         { type: Object,  default: () => ({}) },
});

defineEmits(['select', 'remove', 'save', 'open-delay', 'toggle-tooltip']);

const stepStat = computed(() => props.stepStats?.[props.step.id] ?? null);

function formatLogTime(isoString) {
    if (!isoString) return '';
    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);
    const diffDay = Math.floor(diffHr / 24);

    if (diffSec < 60) return 'Just now';
    if (diffMin < 60) return `${diffMin}m ago`;
    if (diffHr < 24) return `${diffHr}h ago`;
    if (diffDay < 7) return `${diffDay}d ago`;
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
</script>

<style scoped>
.sb-node-status-footer {
    margin: 12px -20px -16px -20px;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
}
.sb-step-perf {
    margin-top: 8px;
    font-size: 11px;
    color: var(--text-muted, #9ca3af);
    display: flex;
    gap: 4px;
}
</style>
