@extends('layouts.admin')

@section('title', 'Shift #' . $session->id)
@section('page-title', 'Shift Details')

@push('admin-styles')
    .detail-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        overflow: hidden;
    }
    .detail-card-header {
        padding: 16px 24px;
        font-size: .72rem;
        font-weight: 700;
        letter-spacing: 2px;
        text-transform: uppercase;
        color: #fff;
    }
    .detail-card-body { padding: 24px; }

    .detail-field {
        padding: 14px 18px;
        border-radius: 12px;
        background: #f8f9fb;
        border-left: 4px solid #e5e7eb;
        margin-bottom: 12px;
    }
    .detail-field-label {
        font-size: .65rem;
        font-weight: 700;
        letter-spacing: 2px;
        text-transform: uppercase;
        color: #8896a8;
        margin-bottom: 4px;
    }
    .detail-field-value {
        font-size: 1rem;
        font-weight: 700;
        color: #1a1a2e;
    }
    .detail-field-teal   { border-left-color: #007870; }
    .detail-field-maroon { border-left-color: #780045; }
    .detail-field-red    { border-left-color: #F54927; }
    .detail-field-blue   { border-left-color: #1a73e8; }
    .detail-field-amber  { border-left-color: #d97706; }
    .detail-field-green  { border-left-color: #16a34a; }

    /* ── OEE Speedometer ── */
    .speedo-wrapper {
        position: relative;
        width: 100%;
        max-width: 500px;
        height: 280px;
        margin: 0 auto;
    }
    .speedo-svg { width: 100%; height: 100%; overflow: visible; }
    .speedo-track { fill: none; stroke: #e8ecf1; stroke-width: 14; stroke-linecap: round; }
    .speedo-fill {
        fill: none;
        stroke-width: 14;
        stroke-linecap: round;
        transition: stroke-dashoffset .6s ease;
        filter: drop-shadow(0 0 6px rgba(0,120,112,.3));
    }
    .speedo-tick { stroke: #c0c8d4; stroke-width: 1.5; }
    .speedo-tick-major { stroke: #8896a8; stroke-width: 2.5; }
    .speedo-tick-label { fill: #6b7a8d; font-size: 7.5px; font-weight: 600; text-anchor: middle; }
    .speedo-needle {
        fill: #F54927;
        filter: drop-shadow(0 2px 4px rgba(245,73,39,.35));
        transition: transform .6s cubic-bezier(.4, 0, .2, 1);
        transform-origin: 110px 110px;
    }
    .speedo-needle-cap {
        fill: #fff;
        stroke: #F54927;
        stroke-width: 2;
        filter: drop-shadow(0 1px 3px rgba(0,0,0,.15));
    }
    .speedo-center {
        position: absolute;
        top: 60%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
    }
    .speedo-center .val { font-size: 2.5rem; font-weight: 900; color: #007870; line-height: 1; }
    .speedo-center .val span { font-size: 1.1rem; }
    .speedo-center .lbl { font-size: .7rem; color: #8896a8; letter-spacing: 3px; text-transform: uppercase; margin-top: 2px; }
    .speedo-glow {
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        pointer-events: none;
        border-radius: 50% 50% 0 0;
        opacity: 0;
        transition: opacity .5s ease;
    }
    .speedo-glow.active {
        opacity: 1;
        animation: speedoGlow 2s ease-in-out infinite alternate;
    }
    @keyframes speedoGlow {
        0%   { box-shadow: inset 0 -10px 30px rgba(0,120,112,.08); }
        100% { box-shadow: inset 0 -10px 30px rgba(0,120,112,.2); }
    }

    /* ── Activity Timeline ── */
    .activity-timeline {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
        gap: 12px;
    }
    .tl-item { position: relative; }
    .tl-dot {
        position: absolute;
        top: 8px; right: 8px;
        width: 28px; height: 28px;
        border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        font-weight: 800; font-size: .68rem;
        border: 2px solid #fff;
        box-shadow: 0 2px 6px rgba(0,0,0,.13);
        color: #fff;
        z-index: 1;
    }
    .tl-dot-start   { background: #007870; }
    .tl-dot-product { background: #1a73e8; }
    .tl-dot-pause   { background: #d97706; }
    .tl-dot-resume  { background: #16a34a; }
    .tl-dot-stop    { background: #dc2626; }
    .tl-card {
        padding: 11px 42px 11px 14px;
        border-radius: 10px;
        border-left: 3px solid;
        height: 100%;
        box-sizing: border-box;
    }
    .tl-card-start   { background: #f0fdfb; border-left-color: #007870; }
    .tl-card-product { background: #eff6ff; border-left-color: #1a73e8; }
    .tl-card-pause   { background: #fffbeb; border-left-color: #d97706; }
    .tl-card-resume  { background: #f0fdf4; border-left-color: #16a34a; }
    .tl-card-stop    { background: #fef2f2; border-left-color: #dc2626; }
    .tl-title { font-weight: 700; font-size: .88rem; color: #1a1a2e; }
    .tl-sub   { font-size: .78rem; color: #6b7a8d; margin-top: 3px; }
    .tl-time  { font-size: .72rem; font-family: 'Courier New', monospace; color: #8896a8; margin-top: 3px; }
    .tl-stats-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
    .tl-stats-sep { color: #cbd5e1; font-size: .7rem; }
    .tl-badge {
        display: inline-block;
        font-size: .62rem;
        font-weight: 700;
        letter-spacing: 1.5px;
        text-transform: uppercase;
        padding: 2px 8px;
        border-radius: 20px;
        margin-bottom: 4px;
    }
    .tl-badge-start   { background: #d1faf5; color: #007870; }
    .tl-badge-product { background: #dbeafe; color: #1a73e8; }
    .tl-badge-pause   { background: #fef3c7; color: #d97706; }
    .tl-badge-resume  { background: #dcfce7; color: #16a34a; }
    .tl-badge-stop    { background: #fee2e2; color: #dc2626; }

    /* Pause timeline */
    .pause-timeline-item {
        padding: 14px 18px;
        border-radius: 12px;
        background: #fffbeb;
        border-left: 4px solid #d97706;
        margin-bottom: 10px;
    }
    .pause-timeline-item .pause-reason {
        font-weight: 600;
        color: #92400e;
    }
    .pause-timeline-item .pause-time {
        font-size: .8rem;
        color: #a16207;
    }
    .pause-timeline-item .pause-duration {
        font-family: 'Courier New', monospace;
        font-weight: 700;
        color: #d97706;
    }

    .status-badge-lg {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 20px;
        border-radius: 12px;
        font-weight: 700;
        font-size: .85rem;
    }
    .status-running { background: rgba(16,185,129,.1); color: #059669; }
    .status-paused  { background: rgba(217,119,6,.1); color: #d97706; }
    .status-stopped { background: rgba(239,68,68,.1); color: #dc2626; }

    .btn-back {
        background: #f0f2f5;
        color: #1a1a2e;
        border: none;
        border-radius: 10px;
        padding: 8px 18px;
        font-weight: 600;
        font-size: .85rem;
        text-decoration: none;
        transition: all .2s ease;
    }
    .btn-back:hover { background: #e5e7eb; color: #1a1a2e; }

    .live-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: #dc2626;
        color: #fff;
        font-size: .7rem;
        font-weight: 700;
        letter-spacing: 2px;
        padding: 5px 14px;
        border-radius: 20px;
        text-transform: uppercase;
    }
    .live-dot {
        width: 8px; height: 8px;
        border-radius: 50%;
        background: #fff;
        animation: livePulse 1s ease-in-out infinite;
    }
    @keyframes livePulse {
        0%, 100% { opacity: 1; }
        50% { opacity: .3; }
    }
    .oee-stats { display: flex; justify-content: center; gap: 12px; margin-top: 14px; }
    .oee-stat {
        padding: 8px 16px; border-radius: 10px; text-align: center; min-width: 70px;
    }
    .oee-stat-teal  { background: linear-gradient(135deg, #e6f7f5, #ccf0ec); }
    .oee-stat-maroon { background: linear-gradient(135deg, #f5e6ee, #ecc); }
    .oee-stat-green { background: linear-gradient(135deg, #ecfdf5, #d1fae5); }
    .oee-stat-val { font-weight: 800; font-size: .9rem; line-height: 1; }
    .oee-stat-lbl { font-size: .55rem; color: #8896a8; text-transform: uppercase; letter-spacing: 1px; margin-top: 2px; }

    /* ── Pause Info (replaces meter when paused) ── */
    .pause-info-admin {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 280px;
        padding: 20px;
    }
    .pause-info-admin .pause-icon-big {
        font-size: 3rem;
        color: #d97706;
        animation: pauseBounce 1.5s ease-in-out infinite;
    }
    @keyframes pauseBounce {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.1); }
    }
    .pause-info-admin .pause-product {
        font-size: 1.4rem;
        font-weight: 800;
        color: #1a1a2e;
        margin-top: 12px;
        letter-spacing: 1px;
    }
    .pause-info-admin .pause-label {
        font-size: .65rem;
        color: #8896a8;
        letter-spacing: 3px;
        text-transform: uppercase;
        margin-top: 14px;
    }
    .pause-info-admin .pause-reason-text {
        font-size: .85rem;
        font-weight: 700;
        color: #dc2626;
        margin-top: 4px;
    }
    .pause-info-admin .pause-run-time {
        font-family: 'Courier New', monospace;
        font-size: 2.2rem;
        font-weight: 800;
        color: #d97706;
        margin-top: 4px;
        letter-spacing: 3px;
    }
@endpush

@section('content')
{{-- Top bar --}}
<div class="d-flex justify-content-between align-items-center mb-4">
    <a href="{{ route('admin.sessions.index') }}" class="btn-back">
        <i class="bi bi-arrow-left me-2"></i>Back to Sessions
    </a>
    <div class="d-flex align-items-center gap-2">
        @if($session->status !== 'stopped')
            <span class="live-badge"><span class="live-dot"></span> Live</span>
        @endif
        <span class="status-badge-lg" id="statusBadge"
              @if($session->status === 'running') style="background:rgba(16,185,129,.1); color:#059669;">
                <i class="bi bi-play-fill"></i> Running
              @elseif($session->status === 'paused') style="background:rgba(217,119,6,.1); color:#d97706;">
                <i class="bi bi-pause-fill"></i> Paused
              @else style="background:rgba(239,68,68,.1); color:#dc2626;">
                <i class="bi bi-stop-fill"></i> Stopped
              @endif
        </span>
    </div>
</div>

<div class="row g-4">
    {{-- LEFT: OEE Big Meter + Activity Timeline --}}
    <div class="col-lg-6">
        <div class="detail-card">
            <div class="detail-card-header" style="background: linear-gradient(135deg, #007870, #00a396);">
                <i class="bi bi-speedometer2 me-2"></i>OEE Performance
            </div>
            <div class="detail-card-body">
                {{-- Speedometer (hidden when paused) --}}
                <div id="speedoWrap" @if($session->status === 'paused') class="d-none" @endif>
                    <div class="speedo-wrapper">
                        <svg class="speedo-svg" viewBox="0 0 220 140">
                            <defs>
                                <linearGradient id="oeeGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" stop-color="#F54927" />
                                    <stop offset="30%" stop-color="#f59e0b" />
                                    <stop offset="60%" stop-color="#22c55e" />
                                    <stop offset="100%" stop-color="#007870" />
                                </linearGradient>
                            </defs>
                            <path class="speedo-track" id="speedoTrack"
                                  d="M 25 115 A 90 90 0 0 1 195 115" />
                            <path class="speedo-fill" id="oeeRing" stroke="url(#oeeGradient)"
                                  d="M 25 115 A 90 90 0 0 1 195 115" />
                            <g id="speedoTicks"></g>
                            <polygon class="speedo-needle" id="speedoNeedle"
                                     points="110,30 105,108 110,112 115,108"
                                     style="transform: rotate(-90deg);" />
                            <circle class="speedo-needle-cap" cx="110" cy="110" r="6" />
                        </svg>
                        <div class="speedo-glow" id="speedoGlow"></div>
                        <div class="speedo-center">
                            <div class="val" id="oeeValue">{{ $session->status === 'stopped' ? $oee : ($activeSegment ? $activeSegmentOee : $oee) }}<span>%</span></div>
                            <div class="lbl">OEE</div>
                        </div>
                    </div>
                    <div class="oee-stats">
                        <div class="oee-stat oee-stat-teal">
                            <div class="oee-stat-val" id="liveCases" style="color:#007870;">{{ $activeSegment ? $activeSegment->case_number : ($session->case_number ?? '0') }}</div>
                            <div class="oee-stat-lbl">{{ str_starts_with($session->product_name, 'Preform') ? 'Total Bottle' : 'Total Case' }}</div>
                        </div>
                        <div class="oee-stat oee-stat-maroon">
                            <div class="oee-stat-val" id="liveFillRate" style="color:#780045;">{{ $activeSegment ? $activeSegment->filling_rate : $session->filling_rate }}/hr</div>
                            <div class="oee-stat-lbl">Rate</div>
                        </div>
                        <div class="oee-stat oee-stat-green">
                            <div class="oee-stat-val" id="liveRunTime" style="color:#16a34a;">
                                @if($activeSegment && $session->status !== 'stopped')
                                    {{ $activeSegmentRunTime }}
                                @elseif($session->total_duration > 0)
                                    {{ gmdate('H:i:s', $session->total_duration - $session->total_pause_duration) }}
                                @else
                                    0:00
                                @endif
                            </div>
                            <div class="oee-stat-lbl">Run Time</div>
                        </div>
                    </div>
                </div>

                {{-- Pause Info (shown when paused, replaces speedometer) --}}
                <div class="pause-info-admin @if($session->status !== 'paused') d-none @endif" id="pauseInfo">
                    <div class="pause-icon-big"><i class="bi bi-pause-circle-fill"></i></div>
                    <div class="pause-product" id="pauseInfoProduct">{{ $session->product_name }}</div>
                    <div class="pause-label">PAUSE REASON</div>
                    <div class="pause-reason-text" id="pauseInfoReason">{{ $pauseReason ?? '—' }}</div>
                    <div class="pause-label">RUN TIME</div>
                    <div class="pause-run-time" id="pauseInfoTime">
                        @if($activeSegment && $session->status !== 'stopped')
                            {{ $activeSegmentRunTime }}
                        @else
                            00:00:00
                        @endif
                    </div>
                </div>
            </div>
        </div>

        {{-- Activity Timeline --}}
        <div class="detail-card mt-4">
            <div class="detail-card-header" style="background: linear-gradient(135deg, #1a1a2e, #2d2d4e);">
                <i class="bi bi-activity me-2"></i>Activity Timeline
                <span style="opacity:.7; font-size:.65rem; margin-left:8px;">({{ count($timeline) }} events)</span>
            </div>
            <div class="detail-card-body">
                <div class="activity-timeline">
                    @foreach($timeline as $i => $event)
                        @php
                            $serial = $i + 1;
                            $typeClass = match($event['type']) {
                                'start'          => 'start',
                                'product_change' => 'product',
                                'pause'          => 'pause',
                                'resume'         => 'resume',
                                'stop'           => 'stop',
                                default          => 'start',
                            };
                            $icon = match($event['type']) {
                                'start'          => 'bi-play-fill',
                                'product_change' => 'bi-arrow-repeat',
                                'pause'          => 'bi-pause-fill',
                                'resume'         => 'bi-play-fill',
                                'stop'           => 'bi-stop-fill',
                                default          => 'bi-circle-fill',
                            };
                            $badgeLabel = match($event['type']) {
                                'start'          => 'Shift Started',
                                'product_change' => 'Product Changed',
                                'pause'          => 'Paused',
                                'resume'         => 'Resumed',
                                'stop'           => 'Shift Stopped',
                                default          => '',
                            };
                        @endphp
                        <div class="tl-item">
                            <div class="tl-dot tl-dot-{{ $typeClass }}">
                                {{ $serial }}
                            </div>
                            <div class="tl-card tl-card-{{ $typeClass }}">
                                <span class="tl-badge tl-badge-{{ $typeClass }}">
                                    <i class="bi {{ $icon }} me-1"></i>{{ $badgeLabel }}
                                </span>

                                @php
                                    $evRun   = $event['run_seconds'] ?? 0;
                                    $evCases = $event['case_number'] ?? 0;
                                    $evDur   = $event['duration'] ?? 0;
                                @endphp

                                {{-- Title row --}}
                                @if($event['type'] === 'start' || $event['type'] === 'product_change')
                                    <div class="tl-title">{{ $event['product'] }}</div>
                                    <div class="tl-sub">Rate: {{ $event['filling_rate'] }}/hr</div>
                                @elseif($event['type'] === 'pause')
                                    <div class="tl-title">{{ $event['reason'] }}</div>
                                @elseif($event['type'] === 'resume')
                                    <div class="tl-title">Machine Resumed</div>
                                @elseif($event['type'] === 'stop')
                                    <div class="tl-title">{{ $event['reason'] ?? 'Shift ended' }}</div>
                                @endif

                                {{-- Stats row for run events --}}
                                @if(in_array($event['type'], ['start','product_change','resume']) && ($evRun > 0 || $evCases > 0))
                                    <div class="tl-sub tl-stats-row">
                                        @if($evRun > 0)
                                            <span><i class="bi bi-stopwatch me-1"></i>Duration: {{ gmdate('H:i:s', $evRun) }}</span>
                                        @endif
                                        @if($evRun > 0 && $evCases > 0)
                                            <span class="tl-stats-sep"> · </span>
                                        @endif
                                        @if($evCases > 0)
                                            @php $evProduct = $event['product'] ?? $session->product_name; @endphp
                                            <span><i class="bi bi-box-seam me-1"></i>{{ $evCases }} {{ str_starts_with($evProduct, 'Preform') ? 'Bottles' : 'Cases' }}</span>
                                        @endif
                                    </div>
                                @endif

                                {{-- Duration row for pause events --}}
                                @if($event['type'] === 'pause' && $evDur > 0)
                                    <div class="tl-sub"><i class="bi bi-hourglass-split me-1"></i>Duration: {{ gmdate('H:i:s', $evDur) }}</div>
                                @endif

                                <div class="tl-time">
                                    <i class="bi bi-clock me-1"></i>{{ $event['time']->format('d M Y, h:i:s A') }}
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    {{-- RIGHT: Session Details --}}
    <div class="col-lg-6">
        <div class="detail-card mb-4">
            <div class="detail-card-header" style="background: linear-gradient(135deg, #780045, #a0005e);">
                <i class="bi bi-info-circle-fill me-2"></i>Shift Information
            </div>
            <div class="detail-card-body">
                <div class="row g-3">
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-teal">
                            <div class="detail-field-label">Current Product</div>
                            <div class="detail-field-value" id="liveProductName">{{ $session->product_name }}</div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-blue">
                            <div class="detail-field-label">Incharge Name</div>
                            <div class="detail-field-value">{{ $session->incharge_name }}</div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-maroon">
                            <div class="detail-field-label">Operator</div>
                            <div class="detail-field-value">{{ $session->operator->name ?? '—' }}</div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-green">
                            <div class="detail-field-label">{{ str_starts_with($session->product_name, 'Preform') ? 'Bottle Number' : 'Case Number' }}</div>
                            <div class="detail-field-value">
                                @if($session->case_number_history && str_contains($session->case_number_history, '+'))
                                    {{ $session->case_number_history }} = {{ $session->case_number }}
                                @else
                                    {{ $session->case_number ?? '—' }}
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        @php
                            $oeeColor = $oee >= 100 ? '#16a34a' : ($oee >= 60 ? '#d97706' : '#dc2626');
                        @endphp
                        <div class="detail-field detail-field-maroon">
                            <div class="detail-field-label">OEE</div>
                            <div class="detail-field-value" id="liveOeeField" style="color:{{ $oeeColor }}; font-size:1.3rem;">
                                {{ $session->status === 'stopped' ? $oee : ($activeSegment ? $activeSegmentOee : $oee) }}%
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-teal">
                            <div class="detail-field-label">Start Time</div>
                            <div class="detail-field-value">
                                @if($session->start_time)
                                    {{ $session->start_time->format('d M Y, h:i:s A') }}
                                @else
                                    —
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="detail-field detail-field-red">
                            <div class="detail-field-label">Stop Time</div>
                            <div class="detail-field-value">
                                @if($session->stop_time)
                                    {{ $session->stop_time->format('d M Y, h:i:s A') }}
                                @else
                                    —
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="detail-field detail-field-blue">
                            <div class="detail-field-label">Total Duration</div>
                            <div class="detail-field-value" id="liveTotalDuration" style="font-family:'Courier New',monospace;">
                                {{ $session->total_duration > 0 ? gmdate('H:i:s', $session->total_duration) : '—' }}
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="detail-field detail-field-green">
                            <div class="detail-field-label">Actual Run Time</div>
                            <div class="detail-field-value" id="liveActualRunTime" style="font-family:'Courier New',monospace; color:#16a34a;">
                                @if($session->total_duration > 0)
                                    {{ gmdate('H:i:s', $session->total_duration - $session->total_pause_duration) }}
                                @else
                                    —
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="detail-field detail-field-amber">
                            <div class="detail-field-label">Total Pause Time</div>
                            <div class="detail-field-value" id="livePauseTime" style="font-family:'Courier New',monospace; color:#d97706;">
                                {{ $session->total_pause_duration > 0 ? gmdate('H:i:s', $session->total_pause_duration) : '00:00:00' }}
                            </div>
                        </div>
                    </div>
                    @if($session->stop_reason)
                    <div class="col-12">
                        <div class="detail-field detail-field-red">
                            <div class="detail-field-label">Stop Reason</div>
                            <div class="detail-field-value">{{ $session->stop_reason }}</div>
                        </div>
                    </div>
                    @endif
                </div>
            </div>
        </div>

        {{-- Product Segments --}}
        @if($session->segments->count() > 1)
        <div class="detail-card mb-4">
            <div class="detail-card-header" style="background: linear-gradient(135deg, #1a73e8, #4a9af5);">
                <i class="bi bi-layers-fill me-2"></i>Product Segments ({{ $session->segments->count() }})
            </div>
            <div class="detail-card-body">
                @foreach($session->segments as $segment)
                    <div class="detail-field detail-field-teal mb-3">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="detail-field-label">{{ $segment->product_name }}</div>
                                <div class="detail-field-value">
                                    {{ str_starts_with($segment->product_name, 'Preform') ? 'Bottles' : 'Cases' }}: {{ $segment->case_number ?? 0 }}
                                    @if($segment->case_number_history && str_contains($segment->case_number_history, '+'))
                                        ({{ $segment->case_number_history }})
                                    @endif
                                </div>
                                <small class="text-muted">
                                    {{ $segment->started_at->format('h:i:s A') }}
                                    @if($segment->ended_at)
                                        – {{ $segment->ended_at->format('h:i:s A') }}
                                    @else
                                        – Active
                                    @endif
                                </small>
                            </div>
                            <div class="text-end">
                                <div style="font-family:'Courier New'; font-weight:700; color:#007870;">
                                    @if($segment->is_active && $session->status !== 'stopped')
                                        <span id="segRunTime{{ $segment->id }}">—</span>
                                    @else
                                        {{ gmdate('H:i:s', $segment->run_seconds) }}
                                    @endif
                                </div>
                                <div style="font-weight:700; color:{{ ($segmentOees[$segment->id] ?? 0) >= 100 ? '#16a34a' : (($segmentOees[$segment->id] ?? 0) >= 60 ? '#d97706' : '#dc2626') }};">
                                    OEE: {{ $segmentOees[$segment->id] ?? 0 }}%
                                </div>
                                <small class="text-muted">Rate: {{ $segment->filling_rate }}/hr</small>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
        @endif

        {{-- Pause History --}}
        @if($session->pauses->count() > 0)
        <div class="detail-card mb-4">
            <div class="detail-card-header" style="background: linear-gradient(135deg, #d97706, #f59e0b);">
                <i class="bi bi-pause-circle-fill me-2"></i>Pause History ({{ $session->pauses->count() }} times)
            </div>
            <div class="detail-card-body">
                @foreach($session->pauses as $pause)
                    <div class="pause-timeline-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="pause-reason">
                                    <i class="bi bi-chat-quote me-1"></i>{{ $pause->pause_reason }}
                                </div>
                                <div class="pause-time mt-1">
                                    <i class="bi bi-clock me-1"></i>
                                    {{ $pause->pause_time ? $pause->pause_time->format('h:i:s A') : '—' }}
                                    @if($pause->resume_time)
                                        <i class="bi bi-arrow-right mx-1"></i>
                                        {{ $pause->resume_time->format('h:i:s A') }}
                                    @endif
                                </div>
                            </div>
                            <div class="pause-duration">
                                {{ $pause->duration > 0 ? gmdate('H:i:s', $pause->duration) : 'Active' }}
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
        @endif
    </div>
</div>

{{-- Speedometer setup (runs for both live and stopped) --}}
@push('admin-scripts')
<script>
(function() {
    // ── Speedometer Setup ──
    const SPEEDO_MAX = 100;
    const SPEEDO_CX = 110, SPEEDO_CY = 110, SPEEDO_R = 90;
    const SPEEDO_START_ANGLE = -180;
    const SPEEDO_END_ANGLE = 0;

    const $oeeRing = document.getElementById('oeeRing');
    const $speedoNeedle = document.getElementById('speedoNeedle');
    const $speedoGlow = document.getElementById('speedoGlow');
    const $oeeValue = document.getElementById('oeeValue');

    const SPEEDO_ARC_LENGTH = (function() {
        const track = document.getElementById('speedoTrack');
        return track ? track.getTotalLength() : 282.74;
    })();

    // Generate ticks & labels
    (function buildTicks() {
        const g = document.getElementById('speedoTicks');
        if (!g) return;
        const steps = 10; // 10 segments → ticks at 0,10,20,...,100
        for (let i = 0; i <= steps; i++) {
            const val = Math.round((SPEEDO_MAX / steps) * i);
            const angleDeg = SPEEDO_START_ANGLE + ((SPEEDO_END_ANGLE - SPEEDO_START_ANGLE) * i / steps);
            const angleRad = angleDeg * Math.PI / 180;
            const isMajor = i % 2 === 0; // major at 0,20,40,60,80,100
            const innerR = isMajor ? SPEEDO_R - 18 : SPEEDO_R - 12;
            const outerR = SPEEDO_R - 4;

            const x1 = SPEEDO_CX + innerR * Math.cos(angleRad);
            const y1 = SPEEDO_CY + innerR * Math.sin(angleRad);
            const x2 = SPEEDO_CX + outerR * Math.cos(angleRad);
            const y2 = SPEEDO_CY + outerR * Math.sin(angleRad);

            const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            line.setAttribute('x1', x1); line.setAttribute('y1', y1);
            line.setAttribute('x2', x2); line.setAttribute('y2', y2);
            line.setAttribute('class', isMajor ? 'speedo-tick-major' : 'speedo-tick');
            g.appendChild(line);

            if (isMajor) {
                const labelR = SPEEDO_R - 26;
                const lx = SPEEDO_CX + labelR * Math.cos(angleRad);
                const ly = SPEEDO_CY + labelR * Math.sin(angleRad);
                const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                text.setAttribute('x', lx); text.setAttribute('y', ly + 3);
                text.setAttribute('class', 'speedo-tick-label');
                text.textContent = val;
                g.appendChild(text);
            }
        }
    })();

    // Init arc dash
    $oeeRing.style.strokeDasharray = SPEEDO_ARC_LENGTH;
    $oeeRing.style.strokeDashoffset = SPEEDO_ARC_LENGTH;

    function setOeeDisplay(oee) {
        const pct = Math.round(oee * 10) / 10;
        $oeeValue.innerHTML = pct + '<span>%</span>';
        const ratio = Math.min(pct, SPEEDO_MAX) / SPEEDO_MAX;
        const offset = SPEEDO_ARC_LENGTH - (SPEEDO_ARC_LENGTH * ratio);
        $oeeRing.style.strokeDashoffset = offset;
        const needleAngle = SPEEDO_START_ANGLE + (SPEEDO_END_ANGLE - SPEEDO_START_ANGLE) * ratio;
        $speedoNeedle.style.transform = 'rotate(' + (needleAngle + 90) + 'deg)';
        $speedoGlow.classList.toggle('active', pct > 0);
    }

    // Set initial OEE from server
    setOeeDisplay({{ $session->status === 'stopped' ? $oee : ($activeSegment ? $activeSegmentOee : $oee) }});

    @if($session->status !== 'stopped')
    // ── Live Polling ──
    const LIVE_URL = '{{ route("admin.sessions.live", $session) }}';
    const $liveCases     = document.getElementById('liveCases');
    const $liveRunTime   = document.getElementById('liveRunTime');
    const $liveTotalDur  = document.getElementById('liveTotalDuration');
    const $liveActualRun = document.getElementById('liveActualRunTime');
    const $livePauseTime = document.getElementById('livePauseTime');
    const $statusBadge   = document.getElementById('statusBadge');
    const $liveFillRate  = document.getElementById('liveFillRate');
    const $liveProductName = document.getElementById('liveProductName');
    const $liveOeeField  = document.getElementById('liveOeeField');
    const $speedoWrap    = document.getElementById('speedoWrap');
    const $pauseInfo     = document.getElementById('pauseInfo');
    const $pauseInfoProduct = document.getElementById('pauseInfoProduct');
    const $pauseInfoReason  = document.getElementById('pauseInfoReason');
    const $pauseInfoTime    = document.getElementById('pauseInfoTime');

    async function poll() {
        try {
            const res = await fetch(LIVE_URL);
            const d = await res.json();

            // Use segment OEE if active segment exists, otherwise overall
            const displayOee = d.active_segment ? d.active_segment.oee : d.oee;

            // Toggle speedometer vs pause info based on status
            if (d.status === 'paused') {
                $speedoWrap.classList.add('d-none');
                $pauseInfo.classList.remove('d-none');
                if ($pauseInfoProduct) $pauseInfoProduct.textContent = d.product_name || '—';
                if ($pauseInfoReason) $pauseInfoReason.textContent = d.pause_reason || '—';
                if ($pauseInfoTime && d.active_segment) $pauseInfoTime.textContent = d.active_segment.run_time;
            } else {
                $speedoWrap.classList.remove('d-none');
                $pauseInfo.classList.add('d-none');
                // Update speedometer with segment OEE
                setOeeDisplay(displayOee);
            }

            // Update stats with active segment data
            if (d.active_segment) {
                $liveCases.textContent = d.active_segment.case_number || '0';
                $liveRunTime.textContent = d.active_segment.run_time;
                if ($liveFillRate) $liveFillRate.textContent = d.active_segment.filling_rate + '/hr';
            } else {
                $liveCases.textContent = d.case_number || '0';
                $liveRunTime.textContent = d.run_time;
                if ($liveFillRate) $liveFillRate.textContent = d.filling_rate + '/hr';
            }

            // Session-level times
            if ($liveTotalDur) $liveTotalDur.textContent = d.total_time;
            if ($liveActualRun) $liveActualRun.textContent = d.run_time;
            if ($livePauseTime) $livePauseTime.textContent = d.pause_time;

            // Update product name when product changes
            if (d.product_name && $liveProductName) {
                $liveProductName.textContent = d.product_name;
            }

            // Update OEE field (right side)
            if ($liveOeeField) {
                $liveOeeField.textContent = displayOee + '%';
                $liveOeeField.style.color = displayOee >= 100 ? '#16a34a' : (displayOee >= 60 ? '#d97706' : '#dc2626');
            }

            // Update status badge
            if (d.status === 'stopped') {
                $statusBadge.style.background = 'rgba(239,68,68,.1)';
                $statusBadge.style.color = '#dc2626';
                $statusBadge.innerHTML = '<i class="bi bi-stop-fill"></i> Stopped';
                clearInterval(liveInterval);
                setTimeout(() => location.reload(), 1500);
            } else if (d.status === 'paused') {
                $statusBadge.style.background = 'rgba(217,119,6,.1)';
                $statusBadge.style.color = '#d97706';
                $statusBadge.innerHTML = '<i class="bi bi-pause-fill"></i> Paused';
            } else {
                $statusBadge.style.background = 'rgba(16,185,129,.1)';
                $statusBadge.style.color = '#059669';
                $statusBadge.innerHTML = '<i class="bi bi-play-fill"></i> Running';
            }
        } catch(e) {}
    }

    const liveInterval = setInterval(poll, 2000);
    poll();
    @endif
})();
</script>
@endpush
@endsection
