<?php $__env->startSection('title', 'Machine Performance'); ?>
<?php $__env->startSection('no-padding', true); ?>

<?php $__env->startPush('styles'); ?>
<style>
    :root {
        --clr-red: #F54927;
        --clr-maroon: #780045;
        --clr-teal: #007870;
        --bg-body: #f0f2f5;
        --text-dim: #7a8599;
        --text-soft: #4a5568;
        --text-bright: #1a1f2e;
    }

    body {
        background: var(--bg-body) !important;
        font-family: 'Alan Sans', 'Segoe UI', system-ui, -apple-system, sans-serif;
        min-height: 100vh;
    }

    /* ── Running Background Animation ── */
    .running-bg-overlay {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        pointer-events: none;
        z-index: 0;
        opacity: 0;
        transition: opacity .8s ease;
    }
    .running-bg-overlay.active {
        opacity: 1;
    }
    .running-bg-overlay .bg-glow {
        position: absolute;
        border-radius: 50%;
        filter: blur(80px);
    }
    .running-bg-overlay .bg-glow-1 {
        width: 400px; height: 400px;
        top: -100px; right: -50px;
        background: rgba(22,163,74,.12);
        animation: bgFloat1 6s ease-in-out infinite;
    }
    .running-bg-overlay .bg-glow-2 {
        width: 350px; height: 350px;
        bottom: -80px; left: -60px;
        background: rgba(0,120,112,.10);
        animation: bgFloat2 8s ease-in-out infinite;
    }
    .running-bg-overlay .bg-glow-3 {
        width: 250px; height: 250px;
        top: 40%; left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(5,150,105,.08);
        animation: bgFloat3 5s ease-in-out infinite;
    }
    .running-bg-overlay .bg-particles {
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        overflow: hidden;
    }
    .running-bg-overlay .bg-particle {
        position: absolute;
        width: 4px; height: 4px;
        border-radius: 50%;
        background: rgba(22,163,74,.25);
        animation: particleRise linear infinite;
    }
    .running-bg-overlay .bg-particle:nth-child(1) { left: 10%; animation-duration: 7s; animation-delay: 0s; width: 3px; height: 3px; }
    .running-bg-overlay .bg-particle:nth-child(2) { left: 25%; animation-duration: 9s; animation-delay: 1s; width: 5px; height: 5px; }
    .running-bg-overlay .bg-particle:nth-child(3) { left: 40%; animation-duration: 6s; animation-delay: 2s; }
    .running-bg-overlay .bg-particle:nth-child(4) { left: 55%; animation-duration: 8s; animation-delay: 0.5s; width: 3px; height: 3px; }
    .running-bg-overlay .bg-particle:nth-child(5) { left: 70%; animation-duration: 10s; animation-delay: 3s; width: 6px; height: 6px; }
    .running-bg-overlay .bg-particle:nth-child(6) { left: 85%; animation-duration: 7s; animation-delay: 1.5s; }
    .running-bg-overlay .bg-particle:nth-child(7) { left: 50%; animation-duration: 11s; animation-delay: 4s; width: 3px; height: 3px; }
    .running-bg-overlay .bg-particle:nth-child(8) { left: 15%; animation-duration: 8s; animation-delay: 2.5s; width: 5px; height: 5px; }

    @keyframes bgFloat1 {
        0%, 100% { transform: translate(0, 0) scale(1); }
        50%      { transform: translate(-30px, 20px) scale(1.1); }
    }
    @keyframes bgFloat2 {
        0%, 100% { transform: translate(0, 0) scale(1); }
        50%      { transform: translate(40px, -25px) scale(1.15); }
    }
    @keyframes bgFloat3 {
        0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: .6; }
        50%      { transform: translate(-50%, -50%) scale(1.3); opacity: 1; }
    }
    @keyframes particleRise {
        0%   { bottom: -10px; opacity: 0; }
        10%  { opacity: 1; }
        90%  { opacity: 1; }
        100% { bottom: 105%; opacity: 0; }
    }

    /* ── Animated Gradient Title ── */
    .machine-title {
        font-size: clamp(1.1rem, 3.5vw, 2rem);
        font-weight: 900;
        letter-spacing: 4px;
        text-transform: uppercase;
        background: linear-gradient(270deg, var(--clr-red), var(--clr-maroon), var(--clr-teal), var(--clr-red));
        background-size: 600% 600%;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        animation: gradientShift 6s ease infinite;
        line-height: 1.3;
    }
    @keyframes gradientShift {
        0%   { background-position: 0% 50%; }
        50%  { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }

    .glow-divider {
        height: 2px;
        background: linear-gradient(90deg, transparent, var(--clr-teal), var(--clr-maroon), var(--clr-red), transparent);
        border: none;
        opacity: .5;
        margin: 8px 0 0;
    }

    /* ── Panel Card ── */
    .panel {
        background: #ffffff;
        border: none;
        border-radius: 18px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0,0,0,.06);
        transition: all .3s ease;
    }
    .panel:hover { box-shadow: 0 6px 24px rgba(0,0,0,.1); transform: translateY(-1px); }
    .panel-header {
        padding: 14px 20px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .panel-header-title {
        color: #fff;
        font-size: .7rem;
        font-weight: 700;
        letter-spacing: 2px;
        text-transform: uppercase;
        text-shadow: 0 1px 2px rgba(0,0,0,.15);
    }
    .panel-header-icon {
        width: 26px; height: 26px;
        border-radius: 8px;
        display: flex; align-items: center; justify-content: center;
        font-size: .75rem;
        color: #fff;
        background: rgba(255,255,255,.25);
    }
    .panel-body { padding: 20px; }

    /* Panel header color variants */
    .panel-teal .panel-header   { background: linear-gradient(135deg, #007870, #00a396); }
    .panel-red .panel-header    { background: linear-gradient(135deg, #F54927, #ff6b4a); }
    .panel-purple .panel-header { background: linear-gradient(135deg, #780045, #a0005e); }
    .panel-blue .panel-header   { background: linear-gradient(135deg, #1a73e8, #4a9af5); }

    /* ── 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: var(--clr-red);
        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: var(--clr-red);
        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: var(--clr-teal); line-height: 1; }
    .speedo-center .val span { font-size: 1.1rem; }
    .speedo-center .lbl { font-size: .7rem; color: var(--text-dim); 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); }
    }
    /* ── Pause Info (replaces meter) ── */
    .pause-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 280px;
        padding: 20px;
    }
    .pause-info-icon {
        font-size: 3rem;
        color: #d97706;
        animation: pauseBounce 1.5s ease-in-out infinite;
    }
    .pause-info-product {
        font-size: 1.4rem;
        font-weight: 800;
        color: var(--text-bright);
        margin-top: 12px;
        letter-spacing: 1px;
    }
    .pause-info-label {
        font-size: .65rem;
        color: var(--text-dim);
        letter-spacing: 3px;
        text-transform: uppercase;
        margin-top: 14px;
    }
    .pause-info-time {
        font-family: 'Courier New', monospace;
        font-size: 2.2rem;
        font-weight: 800;
        color: #d97706;
        margin-top: 4px;
        letter-spacing: 3px;
    }

    .oee-stats { display: flex; justify-content: center; gap: 12px; margin-top: 14px; }
    .oee-stat {
        text-align: center;
        padding: 6px 12px;
        border-radius: 10px;
    }
    .oee-stat-teal  { background: linear-gradient(135deg, #e6f7f5, #ccf0ec); }
    .oee-stat-maroon { background: linear-gradient(135deg, #f5e6ee, #ecc); }
    .oee-stat-red   { background: linear-gradient(135deg, #fde8e4, #fdd); }
    .oee-stat-val { font-weight: 800; font-size: .9rem; line-height: 1; }
    .oee-stat-lbl { font-size: .55rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: 1px; margin-top: 2px; }

    /* ── Digital Clock ── */
    .clock-wrap {
        border-radius: 14px;
        padding: 20px;
        text-align: center;
    }
    .clock-time {
        font-family: 'Courier New', monospace;
        font-size: clamp(1.8rem, 4vw, 2.6rem);
        font-weight: 700;
        color: var(--text-bright);
        letter-spacing: 4px;
    }
    .clock-sep { animation: blink 1s step-end infinite; color: var(--clr-red); }
    @keyframes blink { 0%,100% { opacity:1; } 50% { opacity:.2; } }
    .clock-ampm { font-size: 1rem; color: var(--clr-teal); font-weight: 800; letter-spacing: 2px; margin-top: 2px; }
    .clock-date { color: var(--text-dim); font-size: .72rem; letter-spacing: 1px; margin-top: 4px; }
    .clock-start-time { font-size: .72rem; color: var(--clr-teal); letter-spacing: .5px; margin-top: 6px; border-top: 1px solid rgba(255,255,255,.08); padding-top: 6px; }

    /* ── Action Buttons ── */
    .btn-machine {
        display: flex;
        align-items: center;
        gap: 10px;
        width: 100%;
        padding: 10px 14px;
        border: none;
        border-radius: 12px;
        color: #fff;
        font-weight: 700;
        font-size: .75rem;
        letter-spacing: .5px;
        text-transform: uppercase;
        cursor: pointer;
        transition: all .3s ease;
        position: relative;
        overflow: hidden;
        box-shadow: 0 3px 10px rgba(0,0,0,.12);
    }
    .btn-machine::before {
        content: '';
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        background: linear-gradient(135deg, rgba(255,255,255,.15), transparent);
        pointer-events: none;
    }
    .btn-machine:hover { transform: translateY(-3px); box-shadow: 0 8px 28px rgba(0,0,0,.18); }
    .btn-machine:active { transform: translateY(0); box-shadow: 0 2px 8px rgba(0,0,0,.12); }
    .btn-machine:disabled { opacity: .35; cursor: not-allowed; transform: none !important; box-shadow: 0 2px 8px rgba(0,0,0,.08) !important; }
    .btn-machine .btn-icon {
        width: 34px; height: 34px;
        border-radius: 10px;
        display: flex; align-items: center; justify-content: center;
        font-size: 1rem;
        flex-shrink: 0;
        background: rgba(255,255,255,.2);
        backdrop-filter: blur(4px);
    }
    .btn-machine .btn-label { font-size: .68rem; color: rgba(255,255,255,.75); font-weight: 500; text-transform: none; letter-spacing: 0; }

    .btn-machine.production { background: linear-gradient(135deg, #1a73e8, #4a9af5); }
    .btn-machine.production:hover { box-shadow: 0 8px 28px rgba(26,115,232,.35); }
    .btn-machine.run { background: linear-gradient(135deg, #16a34a, #22c55e); }
    .btn-machine.run:hover { box-shadow: 0 8px 28px rgba(22,163,74,.35); }
    .btn-machine.pause-btn { background: linear-gradient(135deg, #d97706, #f59e0b); }
    .btn-machine.pause-btn:hover { box-shadow: 0 8px 28px rgba(217,119,6,.35); }
    .btn-machine.resume-btn { background: linear-gradient(135deg, #2563eb, #60a5fa); }
    .btn-machine.resume-btn:hover { box-shadow: 0 8px 28px rgba(37,99,235,.35); }
    .btn-machine.stop { background: linear-gradient(135deg, #dc2626, #f54927); }
    .btn-machine.stop:hover { box-shadow: 0 8px 28px rgba(220,38,38,.35); }
    .btn-machine.case { background: linear-gradient(135deg, #007870, #00a396); }
    .btn-machine.case:hover { box-shadow: 0 8px 28px rgba(0,120,112,.35); }

    /* ── Monitor ── */
    .monitor-field {
        padding: 12px 16px;
        border-radius: 12px;
        border-left: 4px solid;
        background: #f7f8fa;
        transition: all .2s;
    }
    .monitor-field:hover { background: #f0f2f5; }
    .monitor-field-teal   { border-color: var(--clr-teal); }
    .monitor-field-maroon { border-color: var(--clr-maroon); }
    .monitor-field-red    { border-color: var(--clr-red); }
    .monitor-field-blue   { border-color: #1a73e8; }
    .monitor-field-amber  { border-color: #d97706; }
    .monitor-label { color: var(--text-dim); font-size: .65rem; font-weight: 700; letter-spacing: 2px; text-transform: uppercase; }
    .monitor-val { color: var(--text-bright); font-size: 1.05rem; font-weight: 700; margin-top: 2px; }

    /* Segment history in live monitor */
    .segment-history { margin-top: 4px; }
    .segment-history-title {
        font-size: .6rem; font-weight: 700; letter-spacing: 2px;
        text-transform: uppercase; color: #1a73e8; margin-bottom: 6px;
    }
    .segment-item {
        display: flex; justify-content: space-between; align-items: center;
        padding: 8px 12px; border-radius: 8px; background: #f0f4ff;
        border-left: 3px solid #1a73e8; margin-bottom: 6px; font-size: .78rem;
    }
    .segment-item-product { font-weight: 700; color: #1a1a2e; }
    .segment-item-cases { font-weight: 600; color: #007870; }
    .segment-item-time { font-size: .68rem; color: #8896a8; font-family: 'Courier New', monospace; }
    .running-timer {
        font-family: 'Courier New', monospace;
        font-size: 1.5rem;
        font-weight: 700;
        color: #16a34a;
    }

    /* ── Status Bar ── */
    .status-bar {
        border-radius: 16px;
        padding: 18px 24px;
        font-weight: 700;
        font-size: 1rem;
        letter-spacing: .5px;
        position: relative;
        overflow: hidden;
        display: flex;
        align-items: center;
    }

    .status-bar-idle {
        background: linear-gradient(135deg, #e0e7ff, #c7d2fe, #ddd6fe);
        color: #4338ca;
        border: 2px solid rgba(99,102,241,.2);
        box-shadow: 0 4px 20px rgba(99,102,241,.1);
    }
    .status-bar-idle .status-icon-wrap {
        width: 36px; height: 36px;
        border-radius: 10px;
        background: linear-gradient(135deg, #6366f1, #818cf8);
        display: flex; align-items: center; justify-content: center;
        margin-right: 14px;
        color: #fff;
        font-size: .9rem;
        flex-shrink: 0;
        animation: idleBounce 2s ease-in-out infinite;
    }
    @keyframes idleBounce {
        0%,100% { transform: translateY(0); }
        50%     { transform: translateY(-3px); }
    }

    .status-bar-running {
        background: linear-gradient(270deg, #16a34a, #22c55e, #059669, #16a34a);
        background-size: 400% 100%;
        animation: runFlow 3s linear infinite;
        color: #fff;
        border: none;
        box-shadow: 0 6px 28px rgba(22,163,74,.3), inset 0 0 40px rgba(255,255,255,.05);
    }
    @keyframes runFlow {
        0%   { background-position: 0% 50%; }
        100% { background-position: 400% 50%; }
    }
    .status-bar-running::before {
        content: '';
        position: absolute;
        top: 0; left: -100%;
        width: 40%; height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,.3), transparent);
        animation: runShimmer 2s linear infinite;
    }
    @keyframes runShimmer {
        0%   { left: -40%; }
        100% { left: 140%; }
    }
    .status-bar-running::after {
        content: '';
        position: absolute;
        bottom: 0; left: 0;
        height: 4px;
        width: 100%;
        background: linear-gradient(90deg, rgba(255,255,255,.1), rgba(255,255,255,.8), rgba(255,255,255,.1));
        background-size: 30% 100%;
        animation: progressSweep 1.2s linear infinite;
    }
    @keyframes progressSweep {
        0%   { background-position: -30% 0; }
        100% { background-position: 130% 0; }
    }
    .status-bar-running .pulse-dot {
        animation: gearSpin 2s linear infinite;
    }
    .status-bar-running .pulse-dot::after {
        content: '\F3E5';
        font-family: 'bootstrap-icons';
        width: auto; height: auto;
        border-radius: 0;
        background: none;
        box-shadow: none;
        color: #fff;
        font-size: 1.1rem;
    }
    @keyframes gearSpin {
        0%   { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* Paused status */
    .status-bar-paused {
        background: linear-gradient(270deg, #d97706, #f59e0b, #fbbf24, #d97706);
        background-size: 400% 100%;
        animation: pauseFlow 4s linear infinite;
        color: #fff;
        border: none;
        box-shadow: 0 6px 28px rgba(217,119,6,.3);
    }
    @keyframes pauseFlow {
        0%   { background-position: 0% 50%; }
        100% { background-position: 400% 50%; }
    }
    .status-bar-paused::before {
        content: '';
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        background: radial-gradient(ellipse at 30% 50%, rgba(255,255,255,.15), transparent 70%);
        animation: pausePulse 2s ease-in-out infinite;
    }
    @keyframes pausePulse {
        0%,100% { opacity: .5; }
        50%     { opacity: 1; }
    }
    .pause-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 36px; height: 36px;
        border-radius: 10px;
        background: rgba(255,255,255,.25);
        margin-right: 14px;
        flex-shrink: 0;
        animation: pauseBounce 1.5s ease-in-out infinite;
    }
    @keyframes pauseBounce {
        0%,100% { transform: scale(1); }
        50%     { transform: scale(1.1); }
    }

    .status-bar-stopped {
        background: linear-gradient(135deg, #dc2626, #ef4444, #f87171);
        color: #fff;
        border: none;
        box-shadow: 0 6px 28px rgba(220,38,38,.25);
    }
    .status-bar-stopped::before {
        content: '';
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        background: radial-gradient(ellipse at 30% 50%, rgba(255,255,255,.1), transparent 70%);
        animation: stopPulse 2s ease-in-out infinite;
    }
    @keyframes stopPulse {
        0%,100% { opacity: .5; }
        50%     { opacity: 1; }
    }

    .pulse-dot {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 36px; height: 36px;
        border-radius: 10px;
        margin-right: 14px;
        background: rgba(255,255,255,.25);
        flex-shrink: 0;
        animation: pulseDot 1.5s ease-in-out infinite;
    }
    .pulse-dot::after {
        content: '';
        width: 10px; height: 10px;
        border-radius: 50%;
        background: #fff;
        box-shadow: 0 0 10px rgba(255,255,255,.8);
    }
    @keyframes pulseDot {
        0%,100% { opacity: 1; transform: scale(1); }
        50%     { opacity: .6; transform: scale(.92); }
    }

    .stop-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 36px; height: 36px;
        border-radius: 10px;
        background: rgba(255,255,255,.25);
        margin-right: 14px;
        flex-shrink: 0;
    }
    .stop-icon::after {
        content: '';
        width: 10px; height: 10px;
        border-radius: 3px;
        background: #fff;
        box-shadow: 0 0 10px rgba(255,255,255,.8);
    }

    /* ── Activity Timeline ── */
    .timeline-section { margin-top: 16px; }
    .timeline-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
    }
    .timeline-header-icon {
        width: 32px; height: 32px;
        border-radius: 10px;
        background: linear-gradient(135deg, #780045, #a0005e);
        display: flex; align-items: center; justify-content: center;
        color: #fff;
        font-size: .8rem;
    }
    .timeline-header-title {
        font-weight: 800;
        font-size: .8rem;
        letter-spacing: 2px;
        text-transform: uppercase;
        color: var(--text-bright);
    }
    /* activity-timeline grid (mirrors admin panel) */
    .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,.18);
        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-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; }
    .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; }
    .timeline-empty {
        color: var(--text-dim);
        font-size: .85rem;
        font-style: italic;
        padding: 12px 0;
        grid-column: 1 / -1;
    }

    /* ── Light Modal ── */
    .modal-light .modal-content {
        background: #ffffff;
        border: none;
        border-radius: 22px;
        color: var(--text-bright);
        box-shadow: 0 20px 60px rgba(0,0,0,.18);
        overflow: hidden;
    }
    .modal-light .modal-header {
        border-bottom: none;
        padding: 20px 24px 12px;
        background: linear-gradient(135deg, #007870, #00a396);
        color: #fff;
    }
    .modal-light .modal-header .modal-title { color: #fff; }
    .modal-light .modal-header .modal-title i { color: rgba(255,255,255,.7) !important; }
    .modal-light .modal-body   { padding: 24px; }
    .modal-light .modal-footer { border-top: 1px solid rgba(0,0,0,.06); padding: 16px 24px; }
    .modal-light .btn-close { filter: invert(1); opacity: .6; }
    .modal-light .form-control, .modal-light .form-select {
        background: #f7f8fa;
        border: 2px solid #e8ecf1;
        border-radius: 12px;
        color: var(--text-bright);
        padding: 12px 16px;
        font-weight: 500;
        transition: all .2s;
    }
    .modal-light .form-control:focus, .modal-light .form-select:focus {
        background: #fff;
        border-color: var(--clr-teal);
        color: var(--text-bright);
        box-shadow: 0 0 0 4px rgba(0,120,112,.1);
    }
    .modal-light .form-label {
        color: var(--text-soft);
        font-weight: 700;
        font-size: .7rem;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 6px;
    }
    .modal-light .modal-title { font-weight: 800; font-size: 1rem; }

    /* Stop modal red header */
    .modal-stop .modal-header {
        background: linear-gradient(135deg, #dc2626, #f54927);
    }
    /* Pause modal amber header */
    .modal-pause .modal-header {
        background: linear-gradient(135deg, #d97706, #f59e0b);
    }

    /* ── Toast ── */
    .toast-container { position: fixed; top: 80px; right: 20px; z-index: 9999; }

    /* ── Responsive ── */
    @media (max-width: 991.98px) {
        .main-grid { grid-template-columns: 1fr !important; }
        .buttons-col { display: grid !important; grid-template-columns: 1fr 1fr; gap: 10px; }
        .btn-machine { padding: 10px 12px; }
        .btn-machine .btn-icon { width: 32px; height: 32px; font-size: .9rem; }
        .activity-timeline { grid-template-columns: 1fr 1fr; }
    }
    @media (max-width: 575.98px) {
        .speedo-wrapper { width: 100%; max-width: 100%; height: 250px; }
        .speedo-center .val { font-size: 2rem; }
        .speedo-center .val span { font-size: .85rem; }
        .clock-time { font-size: 1.6rem !important; letter-spacing: 2px; }
        .monitor-val { font-size: .95rem; }
        .running-timer { font-size: 1.2rem; }
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>

<div class="running-bg-overlay" id="runningBgOverlay">
    <div class="bg-glow bg-glow-1"></div>
    <div class="bg-glow bg-glow-2"></div>
    <div class="bg-glow bg-glow-3"></div>
    <div class="bg-particles">
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
        <div class="bg-particle"></div>
    </div>
</div>

<div class="container-fluid px-3 px-lg-4" style="max-width:1600px; margin:0 auto; position:relative; z-index:1;">

    
    <div class="text-center pt-2 pb-1">
        <h1 class="machine-title mb-0">Golden Ark Machine Performance</h1>
        <hr class="glow-divider mx-auto" style="max-width:500px;">
    </div>

    
    <div class="main-grid" style="display:grid; grid-template-columns: 1fr 300px 1fr; gap:16px; margin-top:14px;">

        
        <div class="d-flex flex-column gap-3">
            
            <div class="panel panel-teal">
                <div class="panel-header">
                    <div class="panel-header-icon"><i class="bi bi-pie-chart-fill"></i></div>
                    <span class="panel-header-title">OEE Meter</span>
                </div>
                <div class="panel-body text-center">
                    <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>
                            <!-- Track arc (background) -->
                            <path class="speedo-track" id="speedoTrack"
                                  d="M 25 115 A 90 90 0 0 1 195 115" />
                            <!-- Filled arc -->
                            <path class="speedo-fill" id="oeeRing" stroke="url(#oeeGradient)"
                                  d="M 25 115 A 90 90 0 0 1 195 115" />
                            <!-- Tick marks & labels -->
                            <g id="speedoTicks"></g>
                            <!-- Needle -->
                            <polygon class="speedo-needle" id="speedoNeedle"
                                     points="110,30 105,108 110,112 115,108"
                                     style="transform: rotate(-90deg);" />
                            <!-- Center cap -->
                            <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">0<span>%</span></div>
                            <div class="lbl">OEE</div>
                        </div>
                    </div>
                    <div class="pause-info d-none" id="pauseInfo">
                        <div class="pause-info-icon"><i class="bi bi-pause-circle-fill"></i></div>
                        <div class="pause-info-product" id="pauseInfoProduct">—</div>
                        <div class="pause-info-label">PAUSE REASON</div>
                        <div class="pause-info-product" id="pauseInfoReason" style="font-size:.85rem; color:var(--clr-red);">—</div>
                        <div class="pause-info-label">RUN TIME</div>
                        <div class="pause-info-time" id="pauseInfoTime">00:00:00</div>
                    </div>
                    <div class="oee-stats">
                        <div class="oee-stat oee-stat-teal">
                            <div class="oee-stat-val" id="statCases" style="color:var(--clr-teal);">0</div>
                            <div class="oee-stat-lbl">Total Case</div>
                        </div>
                        <div class="oee-stat oee-stat-maroon">
                            <div class="oee-stat-val" id="statRate" style="color:var(--clr-maroon);">0/hr</div>
                            <div class="oee-stat-lbl">Rate</div>
                        </div>
                        <div class="oee-stat oee-stat-red">
                            <div class="oee-stat-val" id="statRunTime" style="color:var(--clr-red);">0:00</div>
                            <div class="oee-stat-lbl">Run Time</div>
                        </div>
                    </div>
                </div>
            </div>

            
            <div class="panel panel-red flex-grow-1">
                <div class="panel-header">
                    <div class="panel-header-icon"><i class="bi bi-clock-fill"></i></div>
                    <span class="panel-header-title">Current Time</span>
                </div>
                <div class="panel-body d-flex align-items-center justify-content-center" style="min-height:140px;">
                    <div class="clock-wrap w-100">
                        <div class="clock-time">
                            <span id="clockHours">00</span><span class="clock-sep">:</span><span id="clockMinutes">00</span><span class="clock-sep">:</span><span id="clockSeconds">00</span>
                        </div>
                        <div class="clock-ampm" id="clockAmPm"></div>
                        <div class="clock-date" id="clockDate"></div>
                        <div id="clockStartTime" class="clock-start-time d-none"></div>
                    </div>
                </div>
            </div>
        </div>

        
        <div class="buttons-col d-flex flex-column gap-3">
            <button class="btn-machine production" id="btnProductionEntry" data-bs-toggle="modal" data-bs-target="#productionModal">
                <div class="btn-icon"><i class="bi bi-box-seam"></i></div>
                <div>
                    <div>Production Entry</div>
                    <div class="btn-label">Set product & incharge</div>
                </div>
            </button>
            <button class="btn-machine run" id="btnRun">
                <div class="btn-icon"><i class="bi bi-play-fill"></i></div>
                <div>
                    <div>Run Machine</div>
                    <div class="btn-label">Start production timer</div>
                </div>
            </button>
            <button class="btn-machine pause-btn" id="btnPause" disabled>
                <div class="btn-icon"><i class="bi bi-pause-fill"></i></div>
                <div>
                    <div>Pause Machine</div>
                    <div class="btn-label">Pause with reason</div>
                </div>
            </button>
            <button class="btn-machine resume-btn d-none" id="btnResume">
                <div class="btn-icon"><i class="bi bi-skip-forward-fill"></i></div>
                <div>
                    <div>Resume Machine</div>
                    <div class="btn-label">Continue production</div>
                </div>
            </button>
            <button class="btn-machine case" id="btnCaseEntry" data-bs-toggle="modal" data-bs-target="#caseModal">
                <div class="btn-icon"><i class="bi bi-upc-scan"></i></div>
                <div>
                    <div>Case Number</div>
                    <div class="btn-label">Update case reference</div>
                </div>
            </button>
            <div class="mt-auto pt-2">
                <button class="btn-machine stop w-100" id="btnStop" disabled>
                    <div class="btn-icon"><i class="bi bi-stop-fill"></i></div>
                    <div>
                        <div>End of Shift</div>
                        <div class="btn-label">Stop & generate report</div>
                    </div>
                </button>
            </div>
        </div>

        
        <div class="panel panel-blue d-flex flex-column">
            <div class="panel-header justify-content-between">
                <div class="d-flex align-items-center gap-2">
                    <div class="panel-header-icon"><i class="bi bi-display-fill"></i></div>
                    <span class="panel-header-title">Live Monitor</span>
                </div>
                <div class="running-timer" id="runningTimer" style="color:#fff; text-shadow:0 0 10px rgba(255,255,255,.3);">00:00:00</div>
            </div>
            <div class="panel-body flex-grow-1 d-flex flex-column">
                <div class="d-flex flex-column gap-3 flex-grow-1 mb-3">
                    <div class="monitor-field monitor-field-teal">
                        <div class="monitor-label">Product Name</div>
                        <div class="monitor-val" id="monitorProduct">—</div>
                    </div>
                    <div class="monitor-field monitor-field-maroon">
                        <div class="monitor-label">Incharge Name</div>
                        <div class="monitor-val" id="monitorIncharge">—</div>
                    </div>
                    <div class="monitor-field monitor-field-red">
                        <div class="monitor-label">Total Production Case Number</div>
                        <div class="monitor-val" id="monitorCase">—</div>
                    </div>
                    <div class="monitor-field monitor-field-blue">
                        <div class="monitor-label">Pause Duration</div>
                        <div class="monitor-val" id="monitorPauseDuration">00:00:00</div>
                    </div>
                    <div id="monitorProductImageWrap" style="display:none; text-align:center; padding:8px 0;">
                        <img id="monitorProductImage" src="" alt="Product" style="max-height:220px; max-width:100%; object-fit:contain; border-radius:10px; filter:drop-shadow(0 2px 8px rgba(0,0,0,.10));">
                    </div>
                    <div id="segmentHistoryWrap" class="segment-history d-none">
                        <div class="segment-history-title"><i class="bi bi-layers me-1"></i>Production History</div>
                        <div id="segmentHistoryList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="timeline-section" id="timelineSection">
        <div class="timeline-header">
            <div class="timeline-header-icon"><i class="bi bi-clock-history"></i></div>
            <span class="timeline-header-title">Activity Timeline</span>
        </div>
        <div class="activity-timeline" id="timelineTrack">
            <div class="timeline-empty">No activity yet. Start a session to see the timeline.</div>
        </div>
    </div>

    
    <div style="margin-top:16px;">
        <div class="status-bar status-bar-idle" id="statusIdle">
            <div class="status-icon-wrap"><i class="bi bi-hourglass-split"></i></div>
            <span>Waiting for production entry...</span>
        </div>
        <div class="status-bar status-bar-running d-none" id="statusRunning">
            <span class="pulse-dot"></span>
            <span id="statusRunningText">Running: —</span>
        </div>
        <div class="status-bar status-bar-paused d-none" id="statusPaused">
            <span class="pause-icon"><i class="bi bi-pause-fill" style="color:#fff;font-size:1.1rem;"></i></span>
            <span id="statusPausedText">Paused: —</span>
        </div>
        <div class="status-bar status-bar-stopped d-none" id="statusStopped">
            <span class="stop-icon"></span>
            <span id="statusStoppedText">Stopped: —</span>
        </div>
    </div>
</div>




<div class="modal fade modal-light" id="productionModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-box-seam me-2"></i>Production Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="productionForm">
                    <div class="mb-3">
                        <label for="productName" class="form-label">Product Name <span style="color:var(--clr-red);">*</span></label>
                        <select class="form-control" id="productName" required>
                            <option value="">Select a product</option>
                            <option value="Aima 2ltr">Aima 2ltr</option>
                            <option value="Aima 1ltr">Aima 1ltr</option>
                            <option value="Aima 500ml">Aima 500ml</option>
                            <option value="Electorade Org 300ml">Electorade Org 300ml</option>
                            <option value="Electorade LL 300ml">Electorade LL 300ml</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="inchargeName" class="form-label">Incharge Name <span style="color:var(--clr-red);">*</span></label>
                        <input type="text" class="form-control" id="inchargeName" required placeholder="Enter incharge name">
                    </div>
                    <input type="hidden" id="caseNumber" value="">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm px-3 py-2" style="background:#f0f2f5; color:var(--text-soft); border:none; border-radius:10px; font-weight:600;" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-sm px-4 py-2" style="background:linear-gradient(135deg,#007870,#00a396); color:#fff; border:none; border-radius:10px; font-weight:700; box-shadow:0 4px 12px rgba(0,120,112,.25);" id="btnSaveProduction">
                    <i class="bi bi-check-lg me-1"></i>Save
                </button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade modal-light" id="caseModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-upc-scan me-2"></i>Case Number</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                
                <div style="background:#f8f9fb; border-radius:10px; padding:10px 14px; margin-bottom:16px; display:flex; justify-content:space-between; align-items:center;">
                    <span style="font-size:.78rem; font-weight:600; color:#8896a8; text-transform:uppercase; letter-spacing:.5px;">Current Cases</span>
                    <span id="caseCurrentValue" style="font-size:1.25rem; font-weight:800; color:#007870;">0</span>
                </div>
                
                <div class="d-flex gap-2 mb-3" id="caseModeToggle">
                    <button type="button" id="caseModeAdd" onclick="setCaseMode('add')"
                        style="flex:1; padding:8px; border-radius:10px; border:2px solid #007870; background:#007870; color:#fff; font-weight:700; font-size:.82rem; cursor:pointer; transition:all .2s;">
                        <i class="bi bi-plus-circle me-1"></i>Add
                    </button>
                    <button type="button" id="caseModeSubtract" onclick="setCaseMode('subtract')"
                        style="flex:1; padding:8px; border-radius:10px; border:2px solid #e5e7eb; background:#f8f9fb; color:#8896a8; font-weight:700; font-size:.82rem; cursor:pointer; transition:all .2s;">
                        <i class="bi bi-dash-circle me-1"></i>Subtract
                    </button>
                </div>
                <form id="caseForm">
                    <div class="mb-0">
                        <label for="caseNumberUpdate" class="form-label" id="caseModeLabel">Cases to Add <span style="color:var(--clr-red);">*</span></label>
                        <input type="number" class="form-control" id="caseNumberUpdate" required min="1" placeholder="Enter amount (e.g. 10)">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm px-3 py-2" style="background:#f0f2f5; color:var(--text-soft); border:none; border-radius:10px; font-weight:600;" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-sm px-4 py-2" style="background:linear-gradient(135deg,#007870,#00a396); color:#fff; border:none; border-radius:10px; font-weight:700; box-shadow:0 4px 12px rgba(0,120,112,.25);" id="btnSaveCase">
                    <i class="bi bi-check-lg me-1"></i>Save
                </button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade modal-light modal-pause" id="pauseModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" style="color:#fff;"><i class="bi bi-pause-circle me-2"></i>Pause Machine</h5>
            </div>
            <div class="modal-body">
                <form id="pauseForm">
                    <div class="mb-0">
                        <label for="pauseReason" class="form-label">Pause Reason <span style="color:var(--clr-red);">*</span></label>
                        <textarea class="form-control" id="pauseReason" rows="3" required placeholder="Why are you pausing?"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm px-3 py-2" style="background:#f0f2f5; color:var(--text-soft); border:none; border-radius:10px; font-weight:600;" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-sm px-4 py-2" style="background:linear-gradient(135deg,#d97706,#f59e0b); color:#fff; border:none; border-radius:10px; font-weight:700; box-shadow:0 4px 12px rgba(217,119,6,.3);" id="btnConfirmPause">
                    <i class="bi bi-pause-circle me-1"></i>Confirm Pause
                </button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade modal-light modal-stop" id="stopModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" style="color:#fff;"><i class="bi bi-stop-circle me-2"></i>End of Shift</h5>
            </div>
            <div class="modal-body">
                <form id="stopForm">
                    <div class="mb-0">
                        <label for="stopReason" class="form-label">Stop Reason <span style="color:var(--clr-red);">*</span></label>
                        <textarea class="form-control" id="stopReason" rows="3" required placeholder="Why are you stopping?"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm px-3 py-2" style="background:#f0f2f5; color:var(--text-soft); border:none; border-radius:10px; font-weight:600;" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-sm px-4 py-2" style="background:linear-gradient(135deg,#dc2626,#f54927); color:#fff; border:none; border-radius:10px; font-weight:700; box-shadow:0 4px 12px rgba(220,38,38,.3);" id="btnConfirmStop">
                    <i class="bi bi-stop-circle me-1"></i>Confirm Stop
                </button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade modal-light" id="shiftReportModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #1a1a2e, #2d2d4e);">
                <h5 class="modal-title" style="color:#fff;"><i class="bi bi-file-earmark-bar-graph me-2"></i>End of Shift Report</h5>
            </div>
            <div class="modal-body" style="padding: 28px 24px;">
                
                <div style="display:flex; gap:10px; margin-bottom:20px;">
                    <div style="flex:1; background:#f0fdfb; border-radius:12px; padding:12px 16px; border-left:3px solid #007870;">
                        <div style="font-size:.6rem; color:#8896a8; text-transform:uppercase; letter-spacing:2px; font-weight:700;">Total Case</div>
                        <div style="font-size:1.3rem; font-weight:800; color:#007870;" id="reportCases">—</div>
                    </div>
                    <div style="flex:1; background:#f0fdf4; border-radius:12px; padding:12px 16px; border-left:3px solid #16a34a;">
                        <div style="font-size:.6rem; color:#8896a8; text-transform:uppercase; letter-spacing:2px; font-weight:700;">Run Time</div>
                        <div style="font-size:1.3rem; font-weight:800; color:#16a34a;" id="reportRunTime">—</div>
                    </div>
                    <div style="flex:1; background:#eff6ff; border-radius:12px; padding:12px 16px; border-left:3px solid #1a73e8;">
                        <div style="font-size:.6rem; color:#8896a8; text-transform:uppercase; letter-spacing:2px; font-weight:700;">OEE</div>
                        <div style="font-size:1.3rem; font-weight:800; color:#1a73e8;" id="reportOee">—</div>
                    </div>
                </div>

                
                <a id="btnExportPdf" href="#" target="_blank"
                   style="display:flex; align-items:center; justify-content:center; gap:10px; width:100%; padding:13px; border-radius:12px; background:linear-gradient(135deg,#780045,#a0005e); color:#fff; font-weight:700; font-size:.9rem; text-decoration:none; margin-bottom:16px; box-shadow:0 4px 16px rgba(120,0,69,.2); transition:all .3s ease;">
                    <i class="bi bi-file-earmark-pdf-fill" style="font-size:1.1rem;"></i>
                    Export Activity Report (PDF)
                </a>

                
                <div style="border-top:1px solid #e5e7eb; padding-top:16px;">
                    <label style="font-size:.75rem; font-weight:700; color:#1a1a2e; letter-spacing:1px; text-transform:uppercase; margin-bottom:8px; display:block;">
                        <i class="bi bi-envelope me-1"></i>Send Report by Email
                    </label>
                    <div style="font-size:.75rem; color:#8896a8; margin-bottom:8px;">Enter multiple emails separated by commas</div>
                    <textarea id="reportEmails" rows="2"
                              style="width:100%; background:#f8f9fb; border:1px solid #e5e7eb; border-radius:10px; padding:10px 14px; font-size:.85rem; color:#1a1a2e; resize:none; outline:none;"
                              placeholder="e.g. manager@company.com, admin@company.com"></textarea>
                    <div id="reportEmailMsg" style="font-size:.78rem; margin-top:6px; display:none;"></div>
                    <button type="button" id="btnSendReport"
                            style="width:100%; margin-top:10px; padding:12px; border:none; border-radius:10px; background:linear-gradient(135deg,#007870,#00a396); color:#fff; font-weight:700; font-size:.9rem; cursor:pointer; box-shadow:0 4px 14px rgba(0,120,112,.2);">
                        <i class="bi bi-send-fill me-2"></i>Send Report
                    </button>
                </div>
            </div>
            <div class="modal-footer" style="border-top:1px solid #e5e7eb;">
                <button type="button" class="btn btn-sm px-4 py-2"
                        style="background:#f0f2f5; color:#1a1a2e; border:none; border-radius:10px; font-weight:600;"
                        data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
(function() {
    const CSRF = document.querySelector('meta[name="csrf-token"]').content;
    const BASE = '<?php echo e(url("/machine")); ?>';

    // Filling rates map (matches controller)
    const FILLING_RATES = {
        'Aima 2ltr': 250,
        'Aima 1ltr': 150,
        'Aima 500ml': 150,
        'Electorade Org 300ml': 250,
        'Electorade LL 300ml': 250
    };

    let machineState = 'idle'; // idle | running | paused | stopped
    let sessionStartIso = null; // ISO string of current session start_time
    let timerInterval = null;
    let oeeInterval = null;
    let timerStartTime = null;
    let totalPauseDuration = 0; // seconds
    let currentPauseStart = null; // Date when current pause started
    let fillingRate = 0;
    let caseNumber = 0; // parsed as integer from case_number field for OEE
    let caseHistory = ''; // tracks history like "10+15+5"
    let productionData = null;
    let sessionPauses = []; // array of pause objects from server

    // Segment-level tracking
    let segmentCaseNumber = 0;
    let segmentCaseHistory = '';
    let segmentFillingRate = 0;
    let segmentStartTime = null;
    let segmentPauseDuration = 0; // pause seconds within current segment
    let completedSegments = []; // array of finished segments for display

    // Product name → image mapping
    const productImageMap = {
        'Aima 2ltr': '/products/aima_2ltr.png',
        'Aima 1ltr': '/products/aima_1ltr.png',
        'Aima 500ml': '/products/aima_500ml.png',
        'Electorade Org 300ml': '/products/Electorade_Org.png',
        'Electorade LL 300ml': '/products/Electorade_LL.png',
    };

    function showProductImage(productName) {
        const wrap = document.getElementById('monitorProductImageWrap');
        const img  = document.getElementById('monitorProductImage');
        const src  = productImageMap[productName];
        if (src) {
            img.src = src;
            wrap.style.display = 'block';
        } else {
            wrap.style.display = 'none';
        }
    }

    function renderSegmentHistory() {
        const wrap = document.getElementById('segmentHistoryWrap');
        const list = document.getElementById('segmentHistoryList');
        if (completedSegments.length === 0) {
            wrap.classList.add('d-none');
            return;
        }
        wrap.classList.remove('d-none');
        let html = '';
        completedSegments.forEach(function(seg) {
            const cases = seg.case_number || 0;
            const history = seg.case_number_history || '';
            const hasMultipleOps = history.length > 1 && /[+\-]/.test(history.slice(1));
            const caseDisplay = hasMultipleOps ? history + ' = ' + cases : String(cases);
            const runTime = seg.run_seconds > 0 ? formatTimer(seg.run_seconds) : '—';
            html += '<div class="segment-item">'
                + '<div><span class="segment-item-product">' + escapeHtml(seg.product_name) + '</span></div>'
                + '<div class="d-flex gap-3 align-items-center">'
                + '<span class="segment-item-cases">' + caseDisplay + ' cases</span>'
                + '<span class="segment-item-time">' + runTime + '</span>'
                + '</div></div>';
        });
        list.innerHTML = html;
    }

    // DOM elements
    const $monitorProduct  = document.getElementById('monitorProduct');
    const $monitorIncharge = document.getElementById('monitorIncharge');
    const $monitorCase     = document.getElementById('monitorCase');
    const $monitorPause    = document.getElementById('monitorPauseDuration');
    const $runningTimer    = document.getElementById('runningTimer');

    const $statusIdle      = document.getElementById('statusIdle');
    const $statusRunning   = document.getElementById('statusRunning');
    const $statusRunText   = document.getElementById('statusRunningText');
    const $statusPaused    = document.getElementById('statusPaused');
    const $statusPauseText = document.getElementById('statusPausedText');
    const $statusStopped   = document.getElementById('statusStopped');
    const $statusStopText  = document.getElementById('statusStoppedText');
    const $runningBgOverlay = document.getElementById('runningBgOverlay');

    const $btnRun          = document.getElementById('btnRun');
    const $btnPause        = document.getElementById('btnPause');
    const $btnResume       = document.getElementById('btnResume');
    const $btnStop         = document.getElementById('btnStop');
    const $btnProductionEntry = document.getElementById('btnProductionEntry');
    const $btnCaseEntry = document.getElementById('btnCaseEntry');
    const $speedoWrap  = document.querySelector('.speedo-wrapper');
    const $pauseInfo   = document.getElementById('pauseInfo');
    const $pauseInfoProduct = document.getElementById('pauseInfoProduct');
    const $pauseInfoReason  = document.getElementById('pauseInfoReason');
    const $pauseInfoTime = document.getElementById('pauseInfoTime');

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

    const $timelineTrack = document.getElementById('timelineTrack');

    function ajax(url, data) {
        return fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
            body: JSON.stringify(data)
        }).then(r => r.json().then(d => ({ ok: r.ok, data: d })));
    }

    function ajaxGet(url) {
        return fetch(url, {
            headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF }
        }).then(r => r.json());
    }

    function showToast(message, type = 'success') {
        const id = 'toast-' + Date.now();
        const bg = type === 'success' ? 'bg-success' : type === 'danger' ? 'bg-danger' : 'bg-warning';
        const html = `<div id="${id}" class="toast align-items-center text-white ${bg} border-0 show" role="alert">
            <div class="d-flex"><div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>`;
        document.getElementById('toastContainer').insertAdjacentHTML('beforeend', html);
        setTimeout(() => { const el = document.getElementById(id); if (el) el.remove(); }, 4000);
    }

    function formatTimer(seconds) {
        seconds = Math.max(0, Math.floor(seconds));
        const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
        const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
        const s = String(Math.floor(seconds % 60)).padStart(2, '0');
        return h + ':' + m + ':' + s;
    }

    function formatShortTime(seconds) {
        seconds = Math.max(0, Math.floor(seconds));
        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        if (h > 0) return h + ':' + String(m).padStart(2, '0') + 'h';
        return m + ':' + String(Math.floor(seconds % 60)).padStart(2, '0');
    }

    // ── Timer ──
    function startTimer(startIso) {
        timerStartTime = new Date(startIso);
        clearInterval(timerInterval);
        updateTimerDisplay();
        timerInterval = setInterval(updateTimerDisplay, 1000);
    }

    function updateTimerDisplay() {
        if (!timerStartTime) return;
        const elapsed = Math.floor((Date.now() - timerStartTime.getTime()) / 1000);
        let pauseNow = totalPauseDuration;
        if (machineState === 'paused' && currentPauseStart) {
            pauseNow += Math.floor((Date.now() - currentPauseStart.getTime()) / 1000);
        }
        const actualRun = Math.max(0, elapsed - pauseNow);
        $runningTimer.textContent = formatTimer(actualRun);
        $monitorPause.textContent = formatTimer(pauseNow);
        if (machineState === 'paused') {
            $pauseInfoTime.textContent = formatTimer(actualRun);
        }
    }

    function stopTimer() {
        clearInterval(timerInterval);
        timerInterval = null;
    }

    // ── OEE ──
    function startOeeUpdater() {
        clearInterval(oeeInterval);
        updateOee();
        oeeInterval = setInterval(updateOee, 1000);
    }

    function stopOeeUpdater() {
        clearInterval(oeeInterval);
        oeeInterval = null;
    }

    function updateOee() {
        const rate = segmentFillingRate || fillingRate;
        const cases = segmentCaseNumber;
        const segStart = segmentStartTime || timerStartTime;

        if (!segStart || rate <= 0) {
            setOeeDisplay(0);
            $statCases.textContent = cases;
            $statRate.textContent = rate + '/hr';
            $statRunTime.textContent = '0:00';
            return;
        }

        const segElapsed = Math.floor((Date.now() - segStart.getTime()) / 1000);
        // Calculate pause time within this segment
        let segPause = segmentPauseDuration;
        if (machineState === 'paused' && currentPauseStart) {
            segPause += Math.floor((Date.now() - currentPauseStart.getTime()) / 1000);
        }
        const segRunSeconds = Math.max(0, segElapsed - segPause);
        const segRunHours = segRunSeconds / 3600;
        const expectedOutput = segRunHours * rate;

        let oee = 0;
        if (cases > 0 && expectedOutput > 0) {
            oee = (cases / expectedOutput) * 100;
        }

        setOeeDisplay(oee);
        $statCases.textContent = cases;
        $statRate.textContent = rate + '/hr';
        $statRunTime.textContent = formatShortTime(segRunSeconds);
    }

    // ── Speedometer Setup ──
    const SPEEDO_MAX = 100; // max scale value
    const SPEEDO_CX = 110, SPEEDO_CY = 110, SPEEDO_R = 90;
    const SPEEDO_START_ANGLE = -180; // left (degrees)
    const SPEEDO_END_ANGLE = 0;     // right (degrees)
    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>';

        // Fill the arc proportionally (clamp visual to SPEEDO_MAX)
        const ratio = Math.min(pct, SPEEDO_MAX) / SPEEDO_MAX;
        const offset = SPEEDO_ARC_LENGTH - (SPEEDO_ARC_LENGTH * ratio);
        $oeeRing.style.strokeDashoffset = offset;

        // Rotate needle: -180deg (left/0) to 0deg (right/max)
        const needleAngle = SPEEDO_START_ANGLE + (SPEEDO_END_ANGLE - SPEEDO_START_ANGLE) * ratio;
        $speedoNeedle.style.transform = 'rotate(' + (needleAngle + 90) + 'deg)';

        // Glow when active
        $speedoGlow.classList.toggle('active', pct > 0);
    }

    // ── UI State ──
    function setUI(state, data) {
        machineState = state;
        // Hide all status bars
        $statusIdle.classList.add('d-none');
        $statusRunning.classList.add('d-none');
        $statusPaused.classList.add('d-none');
        $statusStopped.classList.add('d-none');

        // Toggle running background animation
        $runningBgOverlay.classList.toggle('active', state === 'running');

        // Enable Case Number button while running, disable when idle/paused/stopped
        $btnCaseEntry.disabled = (state === 'idle' || state === 'paused');

        // Toggle meter vs pause info
        if (state === 'paused') {
            $speedoWrap.classList.add('d-none');
            $pauseInfo.classList.remove('d-none');
            $pauseInfoProduct.textContent = (data && data.product_name) || '—';
            $pauseInfoReason.textContent  = (data && data.pause_reason) || '—';
        } else {
            $speedoWrap.classList.remove('d-none');
            $pauseInfo.classList.add('d-none');
        }

        // Reset button visibility
        $btnPause.classList.remove('d-none');
        $btnResume.classList.add('d-none');

        if (state === 'idle') {
            $statusIdle.classList.remove('d-none');
            $btnRun.disabled = false;
            $btnPause.disabled = true;
            $btnStop.disabled = true;
            $btnProductionEntry.disabled = false;
            $btnProductionEntry.querySelector('div > div:first-child').textContent = 'Production Entry';
            $btnProductionEntry.querySelector('.btn-label').textContent = 'Set product & incharge';
            $runningTimer.textContent = '00:00:00';
            $runningTimer.style.color = '#fff';
            $runningTimer.style.textShadow = '0 0 10px rgba(255,255,255,.3)';
            $monitorPause.textContent = '00:00:00';
            stopTimer();
            stopOeeUpdater();
            setOeeDisplay(0);
            setStartTimeFooter(null);
        } else if (state === 'running') {
            $statusRunning.classList.remove('d-none');
            $statusRunText.textContent = 'Running: ' + (data.product_name || '—');
            $btnRun.disabled = true;
            $btnPause.disabled = false;
            $btnStop.disabled = false;
            $btnProductionEntry.disabled = false;
            $btnProductionEntry.querySelector('div > div:first-child').textContent = 'Change Product';
            $btnProductionEntry.querySelector('.btn-label').textContent = 'Switch to different product';
            $runningTimer.style.color = '#bbf7d0';
            $runningTimer.style.textShadow = '0 0 12px rgba(74,222,128,.5)';
            currentPauseStart = null;
            startOeeUpdater();
            if (data && data.start_time) { sessionStartIso = data.start_time; }
            if (sessionStartIso) setStartTimeFooter(sessionStartIso);
        } else if (state === 'paused') {
            $statusPaused.classList.remove('d-none');
            $statusPauseText.textContent = 'Paused: ' + (data.pause_reason || data.product_name || '—');
            $btnRun.disabled = true;
            $btnPause.classList.add('d-none');
            $btnResume.classList.remove('d-none');
            $btnResume.disabled = false;
            $btnStop.disabled = false;
            $btnProductionEntry.disabled = false;
            $btnProductionEntry.querySelector('div > div:first-child').textContent = 'Change Product';
            $btnProductionEntry.querySelector('.btn-label').textContent = 'Switch to different product';
            $runningTimer.style.color = '#fde68a';
            $runningTimer.style.textShadow = '0 0 12px rgba(217,119,6,.4)';
            startOeeUpdater();
            if (sessionStartIso) setStartTimeFooter(sessionStartIso);
        } else if (state === 'stopped') {
            $statusStopped.classList.remove('d-none');
            $statusStopText.textContent = 'Stopped: ' + (data.product_name || '—') + ' — Reason: ' + (data.stop_reason || '—');
            $btnRun.disabled = false;
            $btnPause.disabled = true;
            $btnStop.disabled = true;
            $btnProductionEntry.disabled = false;
            $btnProductionEntry.querySelector('div > div:first-child').textContent = 'Production Entry';
            $btnProductionEntry.querySelector('.btn-label').textContent = 'Set product & incharge';
            $runningTimer.style.color = '#fca5a5';
            $runningTimer.style.textShadow = '0 0 12px rgba(220,38,38,.4)';
            stopTimer();
            stopOeeUpdater();
            setStartTimeFooter(null);
        }
    }

    // ── Timeline ──
    // Compute net run seconds for a segment (uses saved value if closed, otherwise calculates live)
    function segRunSeconds(seg, pauses) {
        if (!seg || !seg.started_at) return 0;
        if (seg.run_seconds > 0) return seg.run_seconds; // already computed on close
        const segStart = new Date(seg.started_at).getTime();
        const segEnd   = seg.ended_at ? new Date(seg.ended_at).getTime() : Date.now();
        const wall     = Math.max(0, Math.floor((segEnd - segStart) / 1000));
        const pauseSec = (pauses || []).reduce((sum, p) => {
            if (!p.pause_time) return sum;
            const pS = new Date(p.pause_time).getTime();
            const pE = p.resume_time ? new Date(p.resume_time).getTime() : Date.now();
            const oS = Math.max(segStart, pS);
            const oE = Math.min(segEnd,   pE);
            return sum + (oE > oS ? Math.floor((oE - oS) / 1000) : 0);
        }, 0);
        return Math.max(0, wall - pauseSec);
    }

    function renderTimeline(session) {
        if (!session) {
            $timelineTrack.innerHTML = '<div class="timeline-empty">No activity yet. Start a session to see the timeline.</div>';
            return;
        }

        const pauses   = session.pauses   || [];
        const segments = session.segments || [];
        let events = [];

        const sortedPauses = [...pauses].filter(p => p.pause_time)
            .sort((a, b) => new Date(a.pause_time) - new Date(b.pause_time));

        // Return pauses that belong to a given segment (by timestamp overlap)
        function pausesForSeg(seg) {
            const sStart = new Date(seg.started_at).getTime();
            const sEnd   = seg.ended_at ? new Date(seg.ended_at).getTime() : Infinity;
            return sortedPauses.filter(p => {
                const pt = new Date(p.pause_time).getTime();
                return pt >= sStart && pt < sEnd;
            });
        }

        // Cases for a single run period within a segment:
        // period 0  → seg start   → first pause  (case_number_at_pause of that pause, or total if no pauses)
        // period N  → resume N-1  → pause N      (delta between pause N and pause N-1)
        // last open → resume last → now/stop      (seg.case_number - last_pause.case_number_at_pause)
        function periodCases(seg, periodIdx) {
            const sp = pausesForSeg(seg);
            if (sp.length === 0) return seg.case_number || 0;
            if (periodIdx === 0) return sp[0].case_number_at_pause || 0;
            const prev = sp[periodIdx - 1];
            const curr = sp[periodIdx];
            const endVal = curr ? (curr.case_number_at_pause || 0) : (seg.case_number || 0);
            return Math.max(0, endVal - (prev.case_number_at_pause || 0));
        }

        const firstSeg = segments[0] || null;

        // Start event — period 0 of segment 0
        events.push({
            type: 'start',
            time: new Date(session.start_time),
            title: firstSeg ? firstSeg.product_name : (session.product_name || '—'),
            sub:   'Rate: ' + (firstSeg ? firstSeg.filling_rate : (session.filling_rate || '—')) + '/hr',
            runSeconds: segRunSeconds(firstSeg, pauses),
            caseNumber: firstSeg ? periodCases(firstSeg, 0) : 0,
        });

        // Pause / Resume events
        sortedPauses.forEach(p => {
            if (p.pause_time) {
                events.push({ type: 'pause', time: new Date(p.pause_time), title: p.pause_reason || '—', sub: null, duration: p.duration || 0 });
            }
            if (p.resume_time) {
                // Find which segment this pause belongs to
                const pauseTime = new Date(p.pause_time).getTime();
                const seg = segments.find(s => {
                    const sStart = new Date(s.started_at).getTime();
                    const sEnd   = s.ended_at ? new Date(s.ended_at).getTime() : Infinity;
                    return pauseTime >= sStart && pauseTime < sEnd;
                }) || firstSeg;
                const sp = seg ? pausesForSeg(seg) : [];
                const pIdx = sp.indexOf(p);
                const cases = seg ? periodCases(seg, pIdx + 1) : 0;

                // Run duration of THIS resume period: resume_time → next pause in segment, or segment end, or now
                const resumeMs  = new Date(p.resume_time).getTime();
                const nextPause = sp[pIdx + 1];
                let periodEndMs;
                if (nextPause) {
                    periodEndMs = new Date(nextPause.pause_time).getTime();
                } else if (seg && seg.ended_at) {
                    periodEndMs = new Date(seg.ended_at).getTime();
                } else {
                    periodEndMs = Date.now();
                }
                const resumeRunSec = Math.max(0, Math.floor((periodEndMs - resumeMs) / 1000));

                events.push({ type: 'resume', time: new Date(p.resume_time), title: 'Machine Resumed', sub: null, runSeconds: resumeRunSec, caseNumber: cases });
            }
        });

        // Product change events — period 0 of each subsequent segment
        segments.forEach((seg, i) => {
            if (i > 0) {
                events.push({
                    type: 'product',
                    time: new Date(seg.started_at),
                    title: seg.product_name,
                    sub: 'Rate: ' + seg.filling_rate + '/hr',
                    runSeconds: segRunSeconds(seg, pauses),
                    caseNumber: periodCases(seg, 0),
                });
            }
        });

        // Stop event
        if (session.stop_time) {
            events.push({ type: 'stop', time: new Date(session.stop_time), title: session.stop_reason || '—', sub: null });
        }

        // Sort chronologically
        events.sort((a, b) => a.time - b.time);

        if (events.length === 0) {
            $timelineTrack.innerHTML = '<div class="timeline-empty">No activity yet.</div>';
            return;
        }

        const icons = { start: 'bi-play-fill', product: 'bi-arrow-repeat', pause: 'bi-pause-fill', resume: 'bi-play-fill', stop: 'bi-stop-fill' };
        const labels = { start: 'Session Started', product: 'Product Changed', pause: 'Paused', resume: 'Resumed', stop: 'Session Stopped' };

        let html = '';
        events.forEach((ev, i) => {
            const timeStr = ev.time.toLocaleString('en-US', {
                day: '2-digit', month: 'short', year: 'numeric',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: true, timeZone: 'Asia/Dhaka'
            });
            let subHtml = ev.sub ? `<div class="tl-sub">${escapeHtml(ev.sub)}</div>` : '';

            // For start / product / resume events: show run duration and case count
            if ((ev.type === 'start' || ev.type === 'product' || ev.type === 'resume') && (ev.runSeconds > 0 || ev.caseNumber > 0)) {
                const parts = [];
                if (ev.runSeconds > 0) parts.push('<i class="bi bi-stopwatch me-1"></i>Duration: ' + formatTimer(ev.runSeconds));
                if (ev.caseNumber > 0) parts.push('<i class="bi bi-box-seam me-1"></i>' + ev.caseNumber + ' Cases');
                subHtml += `<div class="tl-sub tl-stats-row">${parts.join('<span class="tl-stats-sep"> · </span>')}</div>`;
            }

            // For pause events: show pause duration
            if (ev.type === 'pause' && ev.duration > 0) {
                subHtml += `<div class="tl-sub"><i class="bi bi-hourglass-split me-1"></i>Duration: ${formatTimer(ev.duration)}</div>`;
            }

            html += `<div class="tl-item">
                <div class="tl-dot tl-dot-${ev.type}">${i + 1}</div>
                <div class="tl-card tl-card-${ev.type}">
                    <span class="tl-badge tl-badge-${ev.type}">
                        <i class="bi ${icons[ev.type] || 'bi-circle-fill'} me-1"></i>${labels[ev.type] || ''}
                    </span>
                    <div class="tl-title">${escapeHtml(ev.title)}</div>
                    ${subHtml}
                    <div class="tl-time"><i class="bi bi-clock me-1"></i>${timeStr}</div>
                </div>
            </div>`;
        });

        $timelineTrack.innerHTML = html;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // ── Clock ──
    const $clockStartTime = document.getElementById('clockStartTime');

    function updateClock() {
        const now = new Date();
        const tz = 'Asia/Dhaka';
        const timeStr = now.toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true, timeZone: tz });
        const match = timeStr.match(/(\d{1,2}):(\d{2}):(\d{2})\s*(AM|PM)/i);
        if (match) {
            document.getElementById('clockHours').textContent   = match[1].padStart(2, '0');
            document.getElementById('clockMinutes').textContent  = match[2];
            document.getElementById('clockSeconds').textContent  = match[3];
            document.getElementById('clockAmPm').textContent     = match[4];
        }
        document.getElementById('clockDate').textContent = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', timeZone: tz });
    }
    updateClock();
    setInterval(updateClock, 1000);

    function setStartTimeFooter(isoString) {
        if (!isoString) { $clockStartTime.classList.add('d-none'); return; }
        const d = new Date(isoString);
        const str = d.toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true, timeZone: 'Asia/Dhaka' });
        $clockStartTime.textContent = 'Start Time: ' + str;
        $clockStartTime.classList.remove('d-none');
    }

    // ── Save Production / Change Product ──
    document.getElementById('btnSaveProduction').addEventListener('click', async function() {
        const product  = document.getElementById('productName').value.trim();
        const incharge = document.getElementById('inchargeName').value.trim();
        const caseNum  = document.getElementById('caseNumber').value.trim();

        // If machine is running or paused, this is a product change
        if (machineState === 'running' || machineState === 'paused') {
            if (!product) { showToast('Please select a product.', 'warning'); return; }
            const res = await ajax(BASE + '/change-product', { product_name: product });
            if (res.ok && res.data.success) {
                // Save previous segment to history before resetting
                if (segmentStartTime) {
                    const segElapsed = Math.floor((Date.now() - segmentStartTime.getTime()) / 1000);
                    let segPause = segmentPauseDuration;
                    if (machineState === 'paused' && currentPauseStart) {
                        segPause += Math.floor((Date.now() - currentPauseStart.getTime()) / 1000);
                    }
                    completedSegments.push({
                        product_name: productionData.product_name,
                        case_number: segmentCaseNumber,
                        case_number_history: segmentCaseHistory,
                        run_seconds: Math.max(0, segElapsed - segPause),
                        filling_rate: segmentFillingRate || fillingRate,
                    });
                }

                // Reset segment-level counters
                segmentCaseNumber = 0;
                segmentCaseHistory = '';
                segmentFillingRate = res.data.filling_rate;
                fillingRate = res.data.filling_rate;
                segmentStartTime = new Date(res.data.segment.started_at);
                segmentPauseDuration = 0;

                productionData.product_name = product;
                $monitorProduct.textContent = product;
                $monitorCase.textContent = '0';
                $statCases.textContent = '0';
                $statRate.textContent = fillingRate + '/hr';
                showProductImage(product);
                renderSegmentHistory();

                if (machineState === 'running') {
                    $statusRunText.textContent = 'Running: ' + product;
                } else if (machineState === 'paused') {
                    $pauseInfoProduct.textContent = product;
                }

                bootstrap.Modal.getInstance(document.getElementById('productionModal')).hide();
                showToast('Product changed to ' + product);
                updateOee();
            } else { showToast(res.data.message || 'Failed to change product.', 'danger'); }
            return;
        }

        // Normal production entry (idle/stopped)
        if (!product || !incharge) { showToast('Product Name and Incharge Name are required.', 'warning'); return; }

        const res = await ajax(BASE + '/production', { product_name: product, incharge_name: incharge, case_number: caseNum });
        if (res.ok && res.data.success) {
            productionData = res.data.data;
            fillingRate = res.data.filling_rate || 0;
            $monitorProduct.textContent  = productionData.product_name;
            $monitorIncharge.textContent = productionData.incharge_name;
            $monitorCase.textContent     = productionData.case_number || '—';
            $statRate.textContent = fillingRate + '/hr';
            showProductImage(productionData.product_name);
            if (machineState === 'idle') {
                $statusIdle.innerHTML = '<div class="status-icon-wrap" style="background:linear-gradient(135deg,#007870,#00a396);animation:none;"><i class="bi bi-check-lg" style="color:#fff;font-size:.9rem;"></i></div><span>Ready: ' + escapeHtml(productionData.product_name) + '</span>';
                $statusIdle.style.background = 'linear-gradient(135deg, #ccfbf1, #99f6e4, #a7f3d0)';
                $statusIdle.style.color = '#065f46';
                $statusIdle.style.borderColor = 'rgba(0,120,112,.25)';
            }
            bootstrap.Modal.getInstance(document.getElementById('productionModal')).hide();
            showToast('Production entry saved.');
        } else { showToast(res.data.message || 'Failed to save.', 'danger'); }
    });

    // ── Case modal: mode toggle (Add / Subtract) ──
    let caseMode = 'add';
    window.setCaseMode = function(mode) {
        caseMode = mode;
        const addBtn  = document.getElementById('caseModeAdd');
        const subBtn  = document.getElementById('caseModeSubtract');
        const label   = document.getElementById('caseModeLabel');
        if (mode === 'add') {
            addBtn.style.cssText += 'background:#007870;color:#fff;border-color:#007870;';
            subBtn.style.cssText += 'background:#f8f9fb;color:#8896a8;border-color:#e5e7eb;';
            label.innerHTML = 'Cases to Add <span style="color:var(--clr-red);">*</span>';
        } else {
            subBtn.style.cssText += 'background:#dc2626;color:#fff;border-color:#dc2626;';
            addBtn.style.cssText += 'background:#f8f9fb;color:#8896a8;border-color:#e5e7eb;';
            label.innerHTML = 'Cases to Subtract <span style="color:var(--clr-red);">*</span>';
        }
    };

    // Reset modal state each time it opens
    document.getElementById('caseModal').addEventListener('show.bs.modal', function() {
        caseMode = 'add';
        setCaseMode('add');
        document.getElementById('caseNumberUpdate').value = '';
        document.getElementById('caseCurrentValue').textContent = segmentCaseNumber || caseNumber || 0;
    });

    // ── Save Case ──
    document.getElementById('btnSaveCase').addEventListener('click', async function() {
        const rawNum = document.getElementById('caseNumberUpdate').value.trim();
        if (!rawNum || isNaN(rawNum) || parseInt(rawNum) <= 0) { showToast('Please enter a valid positive amount.', 'warning'); return; }
        const signedValue = caseMode === 'subtract' ? -parseInt(rawNum) : parseInt(rawNum);
        const res = await ajax(BASE + '/case-number', { case_number: signedValue });
        if (res.ok && res.data.success) {
            // Session-level totals
            caseHistory = res.data.case_number_history || String(res.data.case_number);
            caseNumber = parseInt(res.data.case_number) || 0;

            // Segment-level
            segmentCaseNumber = parseInt(res.data.segment_case_number) || 0;
            segmentCaseHistory = res.data.segment_case_number_history || String(segmentCaseNumber);

            // Display segment case number in monitor
            const hasHistory = segmentCaseHistory.includes('+') || segmentCaseHistory.includes('-');
            $monitorCase.textContent = hasHistory ? segmentCaseHistory + ' = ' + segmentCaseNumber : String(segmentCaseNumber);
            if (productionData) productionData.case_number = String(caseNumber);
            updateOee();
            bootstrap.Modal.getInstance(document.getElementById('caseModal')).hide();
            const verb = caseMode === 'subtract' ? 'Removed' : 'Added';
            showToast(verb + ' ' + Math.abs(res.data.added) + ' cases. Segment: ' + segmentCaseNumber + ' | OEE: ' + (res.data.oee || 0) + '%');
        } else { showToast(res.data.message || 'Failed to save.', 'danger'); }
    });

    // ── Run ──
    $btnRun.addEventListener('click', async function() {
        if (machineState === 'running' || machineState === 'paused') return;
        if (!productionData || !productionData.product_name) { showToast('Please fill Production Entry first.', 'warning'); return; }
        $btnRun.disabled = true;
        const res = await ajax(BASE + '/run', {});
        if (res.ok && res.data.success) {
            fillingRate = res.data.filling_rate || 0;
            caseNumber = parseInt(productionData.case_number) || 0;
            totalPauseDuration = 0;
            currentPauseStart = null;
            sessionPauses = [];
            // Init segment
            segmentCaseNumber = 0;
            segmentCaseHistory = '';
            segmentFillingRate = fillingRate;
            segmentStartTime = new Date(res.data.active_segment.started_at);
            segmentPauseDuration = 0;
            completedSegments = [];
            renderSegmentHistory();
            setUI('running', res.data.session);
            startTimer(res.data.start_time);
            renderTimeline(res.data.session);
            showToast('Machine started!');
        } else { $btnRun.disabled = false; showToast(res.data.message || 'Failed to start.', 'danger'); }
    });

    // ── Pause ──
    $btnPause.addEventListener('click', function() {
        if (machineState !== 'running') return;
        document.getElementById('pauseReason').value = '';
        new bootstrap.Modal(document.getElementById('pauseModal')).show();
    });

    document.getElementById('btnConfirmPause').addEventListener('click', async function() {
        const reason = document.getElementById('pauseReason').value.trim();
        if (!reason) { showToast('Please enter a pause reason.', 'warning'); return; }
        this.disabled = true;
        const res = await ajax(BASE + '/pause', { pause_reason: reason });
        if (res.ok && res.data.success) {
            currentPauseStart = new Date(res.data.pause_time);
            sessionPauses = res.data.session.pauses || [];
            setUI('paused', { product_name: productionData?.product_name, pause_reason: reason });
            renderTimeline(res.data.session);
            bootstrap.Modal.getInstance(document.getElementById('pauseModal')).hide();
            showToast('Machine paused.');
        } else { showToast(res.data.message || 'Failed to pause.', 'danger'); }
        this.disabled = false;
    });

    // ── Resume ──
    $btnResume.addEventListener('click', async function() {
        if (machineState !== 'paused') return;
        $btnResume.disabled = true;
        const res = await ajax(BASE + '/resume', {});
        if (res.ok && res.data.success) {
            // Update total pause duration from server
            // Add this pause's duration to segment pause tracking
            if (currentPauseStart) {
                const pauseDur = Math.floor((Date.now() - currentPauseStart.getTime()) / 1000);
                segmentPauseDuration += pauseDur;
            }
            totalPauseDuration = res.data.session.total_pause_duration || 0;
            currentPauseStart = null;
            sessionPauses = res.data.session.pauses || [];
            setUI('running', res.data.session);
            renderTimeline(res.data.session);
            showToast('Machine resumed!');
        } else { $btnResume.disabled = false; showToast(res.data.message || 'Failed to resume.', 'danger'); }
    });

    // ── Stop ──
    $btnStop.addEventListener('click', async function() {
        if (machineState !== 'running' && machineState !== 'paused') return;
        this.disabled = true;
        const res = await ajax(BASE + '/stop', { stop_reason: '' });
        if (res.ok && res.data.success) {
            totalPauseDuration = res.data.session.total_pause_duration || 0;
            currentPauseStart = null;
            setUI('stopped', res.data.session);
            $runningTimer.textContent = res.data.duration_formatted;
            $monitorPause.textContent = res.data.pause_formatted;
            renderTimeline(res.data.session);
            showShiftReportModal(res.data.session, res.data.duration_formatted, res.data.oee);
        } else { showToast(res.data.message || 'Failed to stop.', 'danger'); }
        this.disabled = false;
    });

    // ── Shift Report Modal ──
    const shiftReportModal = new bootstrap.Modal(document.getElementById('shiftReportModal'));
    const $btnExportPdf    = document.getElementById('btnExportPdf');
    const $btnSendReport   = document.getElementById('btnSendReport');
    const $reportEmails    = document.getElementById('reportEmails');
    const $reportEmailMsg  = document.getElementById('reportEmailMsg');
    const $reportCases     = document.getElementById('reportCases');
    const $reportRunTime   = document.getElementById('reportRunTime');
    const $reportOee       = document.getElementById('reportOee');

    function showShiftReportModal(session, runTime, oee) {
        $reportCases.textContent   = session.case_number ?? '0';
        $reportRunTime.textContent = runTime || '—';
        const oeeVal = oee != null ? oee : 0;
        $reportOee.textContent = oeeVal + '%';
        $reportOee.style.color = oeeVal >= 100 ? '#16a34a' : (oeeVal >= 60 ? '#d97706' : '#dc2626');
        $btnExportPdf.href = BASE + '/session/' + session.id + '/export-pdf';
        $reportEmails.value = '';
        $reportEmailMsg.style.display = 'none';
        shiftReportModal.show();
    }

    $btnSendReport.addEventListener('click', async function() {
        const emails = $reportEmails.value.trim();
        if (!emails) {
            $reportEmailMsg.style.cssText = 'display:block; color:#dc2626;';
            $reportEmailMsg.textContent = 'Please enter at least one email address.';
            return;
        }
        this.disabled = true;
        this.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Sending...';
        const sessionId = $btnExportPdf.href.match(/\/session\/(\d+)\//)?.[1];
        try {
            const res = await fetch(BASE + '/session/' + sessionId + '/send-email', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
                body: JSON.stringify({ emails }),
            });
            const d = await res.json();
            if (d.success) {
                $reportEmailMsg.style.cssText = 'display:block; color:#16a34a; font-weight:600;';
                $reportEmailMsg.textContent = '✓ ' + d.message;
                $reportEmails.value = '';
            } else {
                $reportEmailMsg.style.cssText = 'display:block; color:#dc2626;';
                $reportEmailMsg.textContent = d.message || 'Failed to send.';
            }
        } catch(e) {
            $reportEmailMsg.style.cssText = 'display:block; color:#dc2626;';
            $reportEmailMsg.textContent = 'Network error. Please try again.';
        }
        this.disabled = false;
        this.innerHTML = '<i class="bi bi-send-fill me-2"></i>Send Report';
    });

    // ── Restore state on page load ──
    <?php if($activeSession): ?>
    (function() {
        const session = <?php echo json_encode($activeSession, 15, 512) ?>;
        productionData = { product_name: session.product_name, incharge_name: session.incharge_name, case_number: session.case_number || '' };
        fillingRate = session.filling_rate || 0;
        caseNumber = parseInt(session.case_number) || 0;
        caseHistory = session.case_number_history || '';
        totalPauseDuration = session.total_pause_duration || 0;
        sessionPauses = session.pauses || [];

        // Restore active segment data and completed segments
        const allSegments = session.segments || [];
        completedSegments = [];
        const activeSeg = session.active_segment;

        // Build completed segments list (all non-active segments)
        allSegments.forEach(function(seg) {
            if (!seg.is_active) {
                completedSegments.push({
                    product_name: seg.product_name,
                    case_number: parseInt(seg.case_number) || 0,
                    case_number_history: seg.case_number_history || '',
                    run_seconds: seg.run_seconds || 0,
                    filling_rate: seg.filling_rate || 0,
                });
            }
        });

        if (activeSeg) {
            segmentCaseNumber = parseInt(activeSeg.case_number) || 0;
            segmentCaseHistory = activeSeg.case_number_history || '';
            segmentFillingRate = activeSeg.filling_rate || 0;
            segmentStartTime = new Date(activeSeg.started_at);
            // Calculate segment pause duration from closed pauses that overlap with this segment
            segmentPauseDuration = 0;
            const segStartTs = segmentStartTime.getTime();
            (session.pauses || []).forEach(function(p) {
                if (p.resume_time) {
                    const pStart = Math.max(new Date(p.pause_time).getTime(), segStartTs);
                    const pEnd = new Date(p.resume_time).getTime();
                    if (pEnd > pStart) {
                        segmentPauseDuration += Math.floor((pEnd - pStart) / 1000);
                    }
                }
            });
        } else {
            segmentCaseNumber = caseNumber;
            segmentCaseHistory = caseHistory;
            segmentFillingRate = fillingRate;
            segmentStartTime = new Date(session.start_time);
            segmentPauseDuration = totalPauseDuration;
        }

        $monitorProduct.textContent  = session.product_name;
        $monitorIncharge.textContent = session.incharge_name;
        showProductImage(session.product_name);
        renderSegmentHistory();
        // Display segment case number
        if (segmentCaseHistory && segmentCaseHistory.length > 1 && /[+\-]/.test(segmentCaseHistory.slice(1))) {
            $monitorCase.textContent = segmentCaseHistory + ' = ' + segmentCaseNumber;
        } else {
            $monitorCase.textContent = segmentCaseNumber > 0 ? String(segmentCaseNumber) : '—';
        }
        $statRate.textContent = (segmentFillingRate || fillingRate) + '/hr';

        sessionStartIso = session.start_time;
        if (session.status === 'paused') {
            const openPause = sessionPauses.find(p => !p.resume_time);
            if (openPause) {
                currentPauseStart = new Date(openPause.pause_time);
            }
            setUI('paused', { product_name: session.product_name, pause_reason: openPause ? openPause.pause_reason : '' });
        } else {
            setUI('running', session);
        }
        startTimer(session.start_time);
        renderTimeline(session);
    })();
    <?php endif; ?>
})();
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/electorade/machine.goldenarkbd.com/resources/views/operator/dashboard.blade.php ENDPATH**/ ?>