@extends('layouts.master')

@section('title', 'Diary Dashboard')

@push('styles')
<link href="https://fonts.googleapis.com/css2?family=Lora:wght@400;600;700&family=Outfit:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
/* ══ SHARED DESIGN TOKENS ══ */
:root {
    --ink:        #0f1923;
    --ink-soft:   #3a4a5c;
    --ink-muted:  #7a8fa6;
    --paper:      #f6fafd;
    --surface:    #ffffff;
    --rule:       #dce8f2;
    --rule-strong:#b8d0e8;
    --blue:       #1d6fce;
    --blue-light: #2d87f0;
    --blue-pale:  #e8f2fd;
    --blue-deep:  #124fa0;
    --blue-grad:  linear-gradient(135deg, #2d87f0, #124fa0);
    --amber:      #d97706;
    --amber-pale: #fef3cd;
    --rose:       #dc2626;
    --rose-pale:  #fee2e2;
    --emerald:    #059669;
    --emerald-pale:#d1fae5;
    --slate:      #64748b;
    --slate-pale: #f1f5f9;
    --font-serif: 'Lora', Georgia, serif;
    --font-sans:  'Outfit', system-ui, sans-serif;
    --r-sm: 6px; --r-md: 10px; --r-lg: 16px; --r-xl: 22px;
    --sh-sm: 0 1px 4px rgba(15,25,35,.07);
    --sh-md: 0 4px 16px rgba(15,25,35,.09);
    --sh-lg: 0 10px 36px rgba(15,25,35,.12);
    --sh-blue: 0 6px 22px rgba(29,111,206,.22);

    /* Keep dashboard's internal sky palette vars intact */
    --sky-50:  #f0f9ff; --sky-100: #e0f2fe; --sky-200: #bae6fd;
    --sky-300: #7dd3fc; --sky-400: #38bdf8; --sky-500: #0ea5e9;
    --sky-600: #0284c7; --sky-700: #0369a1;
    --bg-base:    var(--paper);
    --bg-card:    #ffffff;
    --bg-surface: #f5fbff;
    --border:        #cce8f8;
    --border-strong: #93d4f0;
    --text-primary:   var(--ink);
    --text-secondary: var(--ink-soft);
    --text-muted:     var(--ink-muted);
    --accent:      #0ea5e9;
    --accent-deep: #0284c7;
    --accent-soft: rgba(14,165,233,0.10);
    --font-display: var(--font-serif);
    --font-body:    var(--font-sans);
    --font-mono:    'DM Mono', monospace;
    --r-sm-d: 8px; --r-md-d: 14px; --r-lg-d: 18px; --r-xl-d: 22px;
    --shadow-sm: 0 1px 5px rgba(14,100,180,0.08);
    --shadow-md: 0 4px 18px rgba(14,100,180,0.11);
    --shadow-lg: 0 8px 30px rgba(14,100,180,0.14);
}

body, .content-wrapper { background: var(--paper) !important; font-family: var(--font-sans); }

/* ─ Breadcrumb ─ */
.diary-topnav {
    display:flex; align-items:center; gap:7px;
    font-size:.77rem; font-weight:500; color:var(--ink-muted);
    margin-bottom:18px; letter-spacing:.02em;
}
.diary-topnav a { color:var(--blue); text-decoration:none; transition:color .15s; }
.diary-topnav a:hover { color:var(--blue-deep); }
.diary-topnav .sep { opacity:.4; }
.diary-topnav .current { color:var(--ink-soft); font-weight:600; }

/* ─ Unified buttons ─ */
.btn-diary {
    display:inline-flex; align-items:center; gap:7px;
    padding:8px 16px; border-radius:var(--r-md); font-family:var(--font-sans);
    font-size:.8rem; font-weight:600; text-decoration:none; border:none;
    cursor:pointer; transition:all .18s; white-space:nowrap;
    box-shadow:var(--sh-sm); line-height:1.3;
}
.btn-diary:hover { transform:translateY(-1px); box-shadow:var(--sh-md); text-decoration:none; }
.btn-diary-primary {
    background:var(--blue-grad); color:#fff; box-shadow:var(--sh-blue);
}
.btn-diary-primary:hover { filter:brightness(1.07); color:#fff; }
.btn-diary-ghost {
    background:var(--surface); color:var(--ink-soft);
    border:1.5px solid var(--rule-strong);
}
.btn-diary-ghost:hover { background:var(--blue-pale); color:var(--blue-deep); border-color:var(--blue); }

/* ─ Modal (Add Entry) ─ */
.diary-modal {
    border-radius: 18px;
    border: 1px solid rgba(14, 165, 233, 0.22);
    overflow: hidden;
    box-shadow: 0 18px 60px rgba(2, 132, 199, 0.22);
}
.diary-modal-h {
    background: linear-gradient(135deg, #ffffff 0%, var(--sky-50) 55%, var(--sky-100) 100%);
    padding: 16px 18px;
}
.diary-modal-h .modal-title {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    font-family: var(--font-display);
    font-weight: 700;
    color: var(--ink);
    letter-spacing: -.01em;
}
.diary-modal-ico {
    width: 36px;
    height: 36px;
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: var(--blue-grad);
    color: #fff;
    box-shadow: 0 8px 22px rgba(29, 111, 206, 0.22);
}
.diary-modal-b { padding: 16px 18px 18px; background: #fff; }
.diary-modal-sub { margin: 2px 0 12px; font-size: .85rem; color: var(--ink-muted); }
.diary-choice {
    display: flex;
    flex-direction: column;
    gap: 8px;
    text-decoration: none;
    border-radius: 16px;
    padding: 16px;
    min-height: 140px;
    border: 1.5px solid var(--rule);
    box-shadow: var(--sh-sm);
    transition: transform .16s ease, box-shadow .16s ease, border-color .16s ease;
}
.diary-choice:hover { transform: translateY(-2px); box-shadow: var(--sh-md); border-color: rgba(14,165,233,.35); text-decoration:none; }
.diary-choice-ico {
    width: 44px;
    height: 44px;
    border-radius: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
}
.diary-choice-t { font-weight: 800; letter-spacing: -.01em; }
.diary-choice-d { font-size: .8rem; line-height: 1.35; opacity: .9; }
.diary-choice-ghost { background: #fff; color: var(--ink); }
.diary-choice-ghost .diary-choice-ico { background: var(--blue-pale); color: var(--blue-deep); border: 1px solid rgba(29,111,206,.18); }
.diary-choice-solid { background: var(--blue-grad); color: #fff; border-color: rgba(18,79,160,.25); }
.diary-choice-solid .diary-choice-ico { background: rgba(255,255,255,.14); color:#fff; border: 1px solid rgba(255,255,255,.18); }
.diary-choice-solid .diary-choice-d { opacity: .92; }

/* ─ Alerts ─ */
.diary-alert {
    display:flex; align-items:flex-start; gap:10px;
    padding:12px 16px; border-radius:var(--r-md);
    font-size:.84rem; margin-bottom:18px;
}
.diary-alert.success { background:var(--emerald-pale); color:#065f46; border:1px solid #a7f3d0; }
.diary-alert.error   { background:var(--rose-pale);    color:#991b1b; border:1px solid #fca5a5; }
.diary-alert.warning { background:var(--rose-pale);    color:#991b1b; border:1.5px solid #fca5a5; }
.da-close { margin-left:auto; background:none; border:none; cursor:pointer; color:inherit; opacity:.55; font-size:.9rem; padding:0; }
.da-close:hover { opacity:1; }

/* ─ Animations ─ */
@keyframes dn { from{opacity:0;transform:translateY(-13px)} to{opacity:1;transform:translateY(0)} }
@keyframes up  { from{opacity:0;transform:translateY(15px)}  to{opacity:1;transform:translateY(0)} }
@keyframes slideUp { from{opacity:0;transform:translateY(14px)} to{opacity:1;transform:translateY(0)} }

/* ─ Dashboard wrapper + all internal dashboard CSS (preserved from original) ─ */
.wrap { padding: 24px 28px; max-width: 1400px; margin: 0 auto; font-family: var(--font-body); }

.hdr { display:flex;align-items:center;justify-content:space-between;margin-bottom:26px;padding-bottom:20px;border-bottom:1.5px solid var(--border);animation:dn .5s ease both; }
.hdr-l { display:flex;align-items:center;gap:15px; }
.hdr-ico { width:48px;height:48px;border-radius:var(--r-md-d);background:linear-gradient(140deg,var(--sky-400),var(--sky-700));display:flex;align-items:center;justify-content:center;font-size:1.2rem;color:#fff;box-shadow:0 4px 14px rgba(14,165,233,.35); }
.hdr-l h1 { font-family:var(--font-display);font-size:1.75rem;font-weight:700;color:var(--text-primary);letter-spacing:-.02em;line-height:1.1;margin:0; }
.hdr-sub { font-size:.75rem;color:var(--text-muted);letter-spacing:.05em;margin-top:3px; }
.chip { display:inline-block;color:var(--accent-deep);background:var(--accent-soft);border:1px solid var(--sky-200);padding:1px 8px;border-radius:4px;margin-right:6px;font-weight:500; }
.hdr-r { display:flex;gap:8px; }

.stats { display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px; }
.sc { background:#fff;border:1.5px solid var(--border);border-radius:var(--r-xl-d);padding:20px 22px 16px;position:relative;overflow:hidden;text-decoration:none;display:block;transition:all .22s ease;box-shadow:var(--shadow-sm);animation:up .5s ease both; }
.sc:nth-child(1){animation-delay:.05s} .sc:nth-child(2){animation-delay:.10s} .sc:nth-child(3){animation-delay:.15s} .sc:nth-child(4){animation-delay:.20s}
.sc:hover { transform:translateY(-4px);box-shadow:var(--shadow-lg);border-color:rgba(14,165,233,.35);text-decoration:none; }
.sc::after { content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:var(--r-xl-d) var(--r-xl-d) 0 0; }
.sc.sky::after    { background:linear-gradient(90deg,var(--sky-400),var(--sky-300)); }
.sc.amber::after  { background:linear-gradient(90deg,#f59e0b,#fde68a); }
.sc.rose::after   { background:linear-gradient(90deg,#f43f5e,#fda4af); }
.sc.emerald::after{ background:linear-gradient(90deg,#10b981,#6ee7b7); }
.sc .wm { position:absolute;bottom:-6px;right:10px;font-size:4.8rem;opacity:.05;line-height:1;transition:opacity .22s,transform .22s;pointer-events:none; }
.sc:hover .wm { opacity:.09;transform:scale(1.07) rotate(-4deg); }
.sc-ico { width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:.95rem;margin-bottom:13px; }
.sc.sky     .sc-ico { background:var(--sky-100);            color:var(--sky-700); }
.sc.amber   .sc-ico { background:rgba(251,191,36,.16);      color:#b45309; }
.sc.rose    .sc-ico { background:rgba(244,63,94,.10);       color:#be123c; }
.sc.emerald .sc-ico { background:rgba(16,185,129,.10);      color:#047857; }
.sc-val { font-family:var(--font-display);font-size:2.5rem;font-weight:700;color:var(--text-primary);line-height:1;margin-bottom:3px;letter-spacing:-.03em; }
.sc-lbl { font-size:.73rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:.09em;font-weight:600; }
.sc-foot { margin-top:13px;padding-top:11px;border-top:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;font-size:.72rem;color:var(--text-muted);transition:color .18s; }
.sc:hover .sc-foot { color:var(--accent-deep); }
.sc-foot .arr { font-size:.65rem;transition:transform .15s; }
.sc:hover .arr { transform:translateX(3px); }

.mg { display:grid;grid-template-columns:1fr 320px;gap:20px;animation:up .5s .25s ease both; }

.panel { background:#fff;border:1.5px solid var(--border);border-radius:var(--r-xl-d);overflow:hidden;box-shadow:var(--shadow-sm); }
.ph { padding:14px 22px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;background:linear-gradient(to right,var(--sky-50),#fff); }
.pt { font-family:var(--font-display);font-size:.96rem;font-weight:700;color:var(--text-primary);letter-spacing:-.01em; }
.pb { font-size:.69rem;color:var(--accent-deep);background:var(--accent-soft);border:1px solid var(--sky-200);padding:3px 10px;border-radius:20px;font-weight:600; }

.tbl { width:100%;border-collapse:collapse; }
.tbl thead th { padding:10px 17px;font-size:.67rem;text-transform:uppercase;letter-spacing:.09em;color:var(--text-muted);font-weight:600;background:var(--sky-50);border-bottom:1px solid var(--border); }
.tbl thead th:first-child { padding-left:22px; }
.tbl tbody tr { border-bottom:1px solid var(--border);transition:background .13s; }
.tbl tbody tr:last-child { border-bottom:none; }
.tbl tbody tr:hover { background:#f5fbff; }
.tbl tbody td { padding:12px 17px;font-size:.84rem;color:var(--text-secondary);vertical-align:middle; }
.tbl tbody td:first-child { padding-left:22px; }
.ed  { font-size:.76rem;color:var(--text-primary);font-weight:500; }
.et  { font-size:.69rem;color:var(--text-muted);margin-top:2px; }
.etl { color:var(--text-primary);font-weight:500;font-size:.84rem; }

.bp { display:inline-flex;align-items:center;padding:3px 10px;border-radius:20px;font-size:.68rem;font-weight:600;letter-spacing:.05em;text-transform:uppercase;white-space:nowrap; }
.bp::before { content:'';width:5px;height:5px;border-radius:50%;margin-right:5px;flex-shrink:0; }
.b-high { background:rgba(220,38,38,.09);color:#dc2626;border:1px solid rgba(220,38,38,.20); } .b-high::before { background:#dc2626; }
.b-med  { background:rgba(217,119,6,.09);color:#d97706;border:1px solid rgba(217,119,6,.20); } .b-med::before  { background:#d97706; }
.b-low  { background:var(--accent-soft);color:var(--sky-700);border:1px solid var(--sky-200); } .b-low::before  { background:var(--sky-400); }
.b-done { background:rgba(5,150,105,.09);color:#059669;border:1px solid rgba(5,150,105,.20); } .b-done::before { background:#059669; }
.b-prog { background:var(--accent-soft);color:var(--accent-deep);border:1px solid var(--sky-200); } .b-prog::before { background:var(--accent); }
.b-pend { background:rgba(217,119,6,.09);color:#d97706;border:1px solid rgba(217,119,6,.20); } .b-pend::before { background:#d97706; }

.eb { display:inline-flex;align-items:center;justify-content:center;width:29px;height:29px;border-radius:7px;background:var(--sky-50);color:var(--sky-500);border:1px solid var(--border);text-decoration:none;transition:all .15s;font-size:.73rem; }
.eb:hover { background:var(--accent);color:#fff;border-color:var(--accent);box-shadow:0 2px 8px rgba(14,165,233,.28); }
.eb.danger { color:#be123c; }
.eb.danger:hover { background:#dc2626; border-color:#dc2626; }
.eb.warn { color:#b45309; }
.eb.warn:hover { background:#d97706; border-color:#d97706; }
.eb.slate { color:#475569; }
.eb.slate:hover { background:#64748b; border-color:#64748b; }
.eb.ok { color:#15803d; }
.eb.ok:hover { background:#16a34a; border-color:#16a34a; }

.dt-row { cursor:pointer; }
.dt-row:hover .etl { text-decoration:underline; text-decoration-color:rgba(14,165,233,.35); }
.dt-actions { display:flex; gap:6px; justify-content:flex-end; }

.ss { display:flex;flex-direction:column;gap:16px; }
.qa-list { display:flex;flex-direction:column;gap:8px;padding:13px; }
.qa { display:flex;align-items:center;gap:12px;padding:11px 14px;border-radius:var(--r-md-d);background:var(--bg-surface);border:1.5px solid var(--border);color:var(--text-secondary);text-decoration:none;font-size:.82rem;font-weight:500;transition:all .18s; }
.qa:hover { background:var(--sky-100);color:var(--accent-deep);border-color:var(--accent);transform:translateX(3px);box-shadow:var(--shadow-sm);text-decoration:none; }
.qi { width:31px;height:31px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:.78rem;flex-shrink:0; }
.qi-a { background:linear-gradient(135deg,var(--sky-400),var(--sky-700));color:#fff;box-shadow:0 2px 8px rgba(14,165,233,.25); }
.qi-b { background:var(--sky-100);color:var(--sky-700);border:1px solid var(--sky-200); }
.qi-c { background:rgba(251,191,36,.16);color:#b45309;border:1px solid rgba(217,119,6,.22); }
.qi-d { background:rgba(239,68,68,.10);color:#be123c;border:1px solid rgba(220,38,38,.22); }

.dl { padding:14px 20px;display:flex;flex-direction:column;gap:13px; }
.dm { display:flex;justify-content:space-between;align-items:center;margin-bottom:6px; }
.dlb { font-size:.79rem;color:var(--text-secondary);font-weight:500; }
.dc  { font-size:.71rem;color:var(--accent-deep);background:var(--accent-soft);border:1px solid var(--sky-200);padding:1px 7px;border-radius:4px;font-weight:600; }
.dbt { height:5px;background:var(--sky-100);border-radius:99px;overflow:hidden;border:1px solid var(--sky-200); }
.dbf { height:100%;background:linear-gradient(90deg,var(--sky-400),var(--sky-600));border-radius:99px;transition:width .8s cubic-bezier(.22,1,.36,1); }

@media(max-width:1100px){ .stats{grid-template-columns:repeat(2,1fr)} .mg{grid-template-columns:1fr} }
@media(max-width:640px) { .stats{grid-template-columns:1fr} .hdr{flex-direction:column;align-items:flex-start;gap:16px} .wrap{padding:16px} }
</style>
@endpush

@section('content')
{{-- Add Entry Modal (before content) --}}
<div class="modal fade" id="addEntryModal" tabindex="-1" aria-labelledby="addEntryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content diary-modal">
            <div class="modal-header diary-modal-h border-0">
                <h5 class="modal-title" id="addEntryModalLabel">
                    <span class="diary-modal-ico"><i class="fas fa-plus"></i></span>
                    Add New Entry
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body diary-modal-b text-center">
                <p class="diary-modal-sub">Choose how you want to capture this entry.</p>
                <div class="row g-3">
                    <div class="col-md-6">
                        <a href="{{ route('modules.processing.diary.add') }}" class="diary-choice diary-choice-ghost">
                            <span class="diary-choice-ico"><i class="fas fa-align-left"></i></span>
                            <div class="diary-choice-t">Contextual Entry</div>
                            <div class="diary-choice-d">Full form with category, tags, priority, duration.</div>
                        </a>
                    </div>
                    <div class="col-md-6">
                        <a href="{{ route('modules.processing.diary.quick-create') }}" class="diary-choice diary-choice-solid">
                            <span class="diary-choice-ico"><i class="fas fa-bolt"></i></span>
                            <div class="diary-choice-t">Quick Actions Entry</div>
                            <div class="diary-choice-d">Date, type, title, assignee, notes.</div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Task View Modal --}}
<div class="modal fade" id="taskViewModal" tabindex="-1" aria-labelledby="taskViewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content diary-modal">
            <div class="modal-header diary-modal-h border-0">
                <h5 class="modal-title" id="taskViewModalLabel">
                    <span class="diary-modal-ico"><i class="fas fa-clipboard-check"></i></span>
                    Task Details
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body diary-modal-b">
                <div style="display:flex;flex-direction:column;gap:10px;">
                    <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;">
                        <div>
                            <div id="taskModalTitle" style="font-family:var(--font-display);font-size:1.2rem;font-weight:700;color:var(--ink);line-height:1.25;"></div>
                            <div id="taskModalMeta" style="font-size:.82rem;color:var(--ink-muted);margin-top:4px;"></div>
                        </div>
                        <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;justify-content:flex-end;">
                            <span id="taskModalPriority" class="bp b-low">Medium</span>
                            <span id="taskModalStatus" class="bp b-pend">Pending</span>
                        </div>
                    </div>

                    <div id="taskModalNotesWrap" style="background:var(--sky-50);border:1px solid var(--border);border-radius:14px;padding:14px 16px;">
                        <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.08em;color:var(--ink-muted);font-weight:700;margin-bottom:6px;">Notes</div>
                        <div id="taskModalNotes" style="font-size:.9rem;color:var(--ink-soft);white-space:pre-wrap;"></div>
                    </div>

                    <div style="display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end;padding-top:6px;">
                        <a id="taskModalView" href="#" class="btn-diary btn-diary-ghost"><i class="fas fa-eye"></i> View</a>
                        <a id="taskModalEdit" href="#" class="btn-diary btn-diary-ghost"><i class="fas fa-edit"></i> Edit</a>
                        <a id="taskModalPrint" href="#" target="_blank" class="btn-diary btn-diary-ghost"><i class="fas fa-print"></i> Print</a>
                        <form id="taskModalDeleteForm" method="POST" onsubmit="return confirm('Delete this entry?')">
                            @csrf @method('DELETE')
                            <button type="submit" class="btn-diary btn-diary-ghost" style="border-color:rgba(220,38,38,.35);color:#be123c;">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="wrap">

    {{-- Breadcrumb --}}
    <nav class="diary-topnav" aria-label="Breadcrumb">
        <a href="{{ url('/') }}"><i class="fas fa-home"></i></a>
        <span class="sep">/</span>
        <a href="{{ route('modules.processing.diary.dashboard') }}">Diary</a>
        <span class="sep">/</span>
        <span class="current">Dashboard</span>
    </nav>

    {{-- Header --}}
    <header class="hdr">
        <div class="hdr-l">
            <div class="hdr-ico"><i class="fas fa-chart-bar"></i></div>
            <div>
                <h1>Diary Dashboard</h1>
                <div class="hdr-sub">
                    <span class="chip">{{ now()->format('D, d M Y') }}</span>task &amp; schedule overview
                </div>
            </div>
        </div>
        <div class="hdr-r">
            <a href="{{ route('modules.processing.diary.calendar') }}" class="btn-diary btn-diary-ghost">
                <i class="fas fa-calendar-alt"></i> Calendar
            </a>
            <a href="{{ route('modules.processing.diary.list') }}" class="btn-diary btn-diary-ghost">
                <i class="fas fa-list"></i> All Entries
            </a>
            <a href="#" class="btn-diary btn-diary-primary" data-bs-toggle="modal" data-bs-target="#addEntryModal">
                <i class="fas fa-plus"></i> New Entry
            </a>
        </div>
    </header>

    {{-- Alerts --}}
    @if(session('success'))
        <div class="diary-alert success" role="alert">
            <i class="fas fa-check-circle"></i>
            <span>{{ session('success') }}</span>
            <button class="da-close" onclick="this.closest('.diary-alert').remove()">&times;</button>
        </div>
    @endif
    @if(session('error'))
        <div class="diary-alert error" role="alert">
            <i class="fas fa-exclamation-circle"></i>
            <span>{{ session('error') }}</span>
            <button class="da-close" onclick="this.closest('.diary-alert').remove()">&times;</button>
        </div>
    @endif

    @if(($overdueCount ?? 0) > 0)
        <div class="diary-alert warning" role="alert">
            <i class="fas fa-exclamation-circle fa-lg"></i>
            <div>
                <strong>{{ $overdueCount }} overdue {{ Str::plural('task', $overdueCount) }}</strong>
                require your attention.
                <a href="{{ route('modules.processing.diary.overdue') }}"
                   style="color:#991b1b;text-decoration:underline;margin-left:8px;">
                    View overdue tasks →
                </a>
            </div>
            <button class="da-close" onclick="this.closest('.diary-alert').remove()">&times;</button>
        </div>
    @endif

    {{-- Stat Cards --}}
    <div class="stats">
        <a href="{{ route('modules.processing.diary.today') }}" class="sc sky">
            <div class="wm"><i class="fas fa-calendar-day"></i></div>
            <div class="sc-ico"><i class="fas fa-calendar-day"></i></div>
            <div class="sc-val">{{ $todayCount ?? 0 }}</div>
            <div class="sc-lbl">Today's Entries</div>
            <div class="sc-foot"><span>View today</span><i class="fas fa-arrow-right arr"></i></div>
        </a>
        <a href="{{ route('modules.processing.diary.upcoming') }}" class="sc amber">
            <div class="wm"><i class="fas fa-calendar-plus"></i></div>
            <div class="sc-ico"><i class="fas fa-calendar-plus"></i></div>
            <div class="sc-val">{{ $upcomingCount ?? 0 }}</div>
            <div class="sc-lbl">Upcoming Entries</div>
            <div class="sc-foot"><span>View upcoming</span><i class="fas fa-arrow-right arr"></i></div>
        </a>
        <a href="{{ route('modules.processing.diary.overdue') }}" class="sc rose">
            <div class="wm"><i class="fas fa-calendar-times"></i></div>
            <div class="sc-ico"><i class="fas fa-calendar-times"></i></div>
            <div class="sc-val">{{ $overdueCount ?? 0 }}</div>
            <div class="sc-lbl">Overdue Entries</div>
            <div class="sc-foot"><span>Needs attention</span><i class="fas fa-arrow-right arr"></i></div>
        </a>
        <a href="{{ route('modules.processing.diary.list') }}" class="sc emerald">
            <div class="wm"><i class="fas fa-calendar-alt"></i></div>
            <div class="sc-ico"><i class="fas fa-calendar-alt"></i></div>
            <div class="sc-val">{{ $totalCount ?? 0 }}</div>
            <div class="sc-lbl">Total Entries</div>
            <div class="sc-foot"><span>View all</span><i class="fas fa-arrow-right arr"></i></div>
        </a>
    </div>

    {{-- Main Grid --}}
    <div class="mg">

        {{-- Daily Tasks --}}
        <div class="panel">
            <div class="ph">
                <span class="pt">Daily Tasks</span>
                <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end;">
                    <span class="pb">{{ optional($selectedDate ?? null)->format('D, d M Y') ?? now()->format('D, d M Y') }}</span>
                    <form method="GET" action="{{ route('modules.processing.diary.dashboard') }}" style="display:flex;align-items:center;gap:8px;">
                        <input type="date"
                               name="date"
                               value="{{ optional($selectedDate ?? null)->toDateString() ?? now()->toDateString() }}"
                               style="padding:6px 10px;border-radius:10px;border:1.5px solid var(--border);background:#fff;font-size:.78rem;">
                        <button type="submit" class="btn-diary btn-diary-ghost" style="padding:6px 12px;font-size:.78rem;box-shadow:none;">
                            Go
                        </button>
                    </form>
                </div>
            </div>

            @if(isset($dailyEntries) && $dailyEntries->count() > 0)
                <div style="overflow-x:auto">
                    <table class="tbl">
                        <thead>
                            <tr>
                                <th>Date / Time</th>
                                <th>Task</th>
                                <th>Priority</th>
                                <th>Status</th>
                                <th style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($dailyEntries as $entry)
                                @php
                                    $entryType = $entry['type'] ?? 'contextual';
                                    $entryId = $entry['id'] ?? null;
                                    $taskTitle = $entry['title'] ?? 'Untitled';
                                    $priority = $entry['priority'] ?? 'medium';
                                    $status = $entry['status'] ?? 'pending';

                                    $showUrl = $entryId ? route('modules.processing.diary.entry.show', ['type' => $entryType, 'id' => $entryId]) : '#';
                                    $editUrl = $entryId ? route('modules.processing.diary.entry.edit', ['type' => $entryType, 'id' => $entryId]) : '#';
                                    $printUrl = $entryId ? route('modules.processing.diary.entry.print', ['type' => $entryType, 'id' => $entryId]) : '#';
                                    $destroyUrl = $entryId ? route('modules.processing.diary.entry.destroy', ['type' => $entryType, 'id' => $entryId]) : '#';

                                    $payload = [
                                        'title' => $taskTitle,
                                        'date' => $entry['formatted_date'] ?? '—',
                                        'time' => $entry['formatted_time'] ?? '—',
                                        'task_type' => $entry['task_type'] ?? null,
                                        'client_case' => $entry['client_case'] ?? null,
                                        'priority' => $priority,
                                        'status' => $status,
                                        'notes' => $entry['notes'] ?? null,
                                        'showUrl' => $showUrl,
                                        'editUrl' => $editUrl,
                                        'printUrl' => $printUrl,
                                        'destroyUrl' => $destroyUrl,
                                    ];
                                @endphp
                                <tr>
                                    <td>
                                        <div class="ed">{{ $entry['formatted_date'] ?? '—' }}</div>
                                        <div class="et">{{ $entry['formatted_time'] ?? '—' }}</div>
                                    </td>
                                    <td class="dt-row" data-entry="{{ e(json_encode($payload)) }}">
                                        <span class="etl">{{ Str::limit($taskTitle, 46) }}</span>
                                        <div class="et">
                                            {{ $entryType === 'quick' ? 'Quick' : ucwords(str_replace('-', ' ', $entry['task_type'] ?? 'Task')) }}
                                            @if(!empty($entry['client_case']))
                                                — {{ Str::limit($entry['client_case'], 34) }}
                                            @endif
                                        </div>
                                    </td>
                                    <td>
                                        @if($priority == 'high')
                                            <span class="bp b-high">High</span>
                                        @elseif($priority == 'medium')
                                            <span class="bp b-med">Medium</span>
                                        @else
                                            <span class="bp b-low">Low</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php $s = $status; @endphp
                                        @if($s == 'completed')
                                            <span class="bp b-done">Completed</span>
                                        @elseif($s == 'in-progress')
                                            <span class="bp b-prog">In Progress</span>
                                        @elseif($s == 'pending')
                                            <span class="bp b-pend">Pending</span>
                                        @else
                                            <span class="bp b-low">{{ ucfirst($s) }}</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="dt-actions">
                                            @if($entryId)
                                                <form action="{{ route('modules.processing.diary.entry.complete', ['type' => $entryType, 'id' => $entryId]) }}"
                                                      method="POST"
                                                      style="display:inline;"
                                                      onclick="event.stopPropagation()">
                                                    @csrf
                                                    @method('PATCH')
                                                    <input type="hidden" name="is_completed" value="{{ ($status ?? 'pending') === 'completed' ? 0 : 1 }}">
                                                    <button type="submit" class="eb ok" title="{{ ($status ?? 'pending') === 'completed' ? 'Mark as Pending' : 'Mark as Completed' }}" style="cursor:pointer;">
                                                        <i class="fas {{ ($status ?? 'pending') === 'completed' ? 'fa-rotate-left' : 'fa-check' }}"></i>
                                                    </button>
                                                </form>
                                            @endif
                                            <a href="{{ $showUrl }}" class="eb" title="View" onclick="event.stopPropagation()">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{{ $editUrl }}" class="eb warn" title="Edit" onclick="event.stopPropagation()">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="{{ $printUrl }}" target="_blank" class="eb slate" title="Print" onclick="event.stopPropagation()">
                                                <i class="fas fa-print"></i>
                                            </a>
                                            <form action="{{ $destroyUrl }}" method="POST" onsubmit="return confirm('Delete this entry?')" style="display:inline;">
                                                @csrf @method('DELETE')
                                                <button type="submit" class="eb danger" title="Delete" style="cursor:pointer;">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <div style="padding:50px 24px;text-align:center">
                    <div style="width:52px;height:52px;border-radius:14px;background:var(--sky-50);border:1.5px solid var(--border);display:inline-flex;align-items:center;justify-content:center;font-size:1.3rem;color:var(--text-muted);margin-bottom:14px">
                        <i class="fas fa-book-open"></i>
                    </div>
                    <p style="font-family:var(--font-display);font-size:1.05rem;font-weight:600;color:var(--text-primary);margin-bottom:6px">No tasks for this day</p>
                    <p style="font-size:.83rem;color:var(--text-muted);margin-bottom:20px">Add an entry to start tracking your daily tasks.</p>
                    <a href="#" class="btn-diary btn-diary-primary" data-bs-toggle="modal" data-bs-target="#addEntryModal">
                        <i class="fas fa-plus"></i> Add First Entry
                    </a>
                </div>
            @endif
        </div>

        {{-- Sidebar --}}
        <div class="ss">

            <div class="panel">
                <div class="ph"><span class="pt">Quick Actions</span></div>
                <div class="qa-list">
                    <a href="#" class="qa" data-bs-toggle="modal" data-bs-target="#addEntryModal">
                        <span class="qi qi-a"><i class="fas fa-plus"></i></span> Add New Entry
                    </a>
                    <a href="{{ route('modules.processing.diary.today') }}"    class="qa"><span class="qi qi-b"><i class="fas fa-calendar-day"></i></span> Today's Tasks</a>
                    <a href="{{ route('modules.processing.diary.upcoming') }}" class="qa"><span class="qi qi-c"><i class="fas fa-calendar-plus"></i></span> Upcoming Tasks</a>
                    <a href="{{ route('modules.processing.diary.overdue') }}"  class="qa"><span class="qi qi-d"><i class="fas fa-calendar-times"></i></span> Overdue Tasks</a>
                </div>
            </div>

            <div class="panel">
                <div class="ph">
                    <span class="pt">Completion Rate</span>
                    <span class="pb">{{ $completionRate ?? 0 }}%</span>
                </div>
                <div style="padding:16px 20px">
                    <div style="background:#e0f2fe;border-radius:999px;height:10px;overflow:hidden;">
                        <div style="width:{{ $completionRate ?? 0 }}%;background:linear-gradient(90deg,#0ea5e9,#0369a1);height:100%;border-radius:999px;transition:width 1s ease;"></div>
                    </div>
                    <div style="display:flex;justify-content:space-between;margin-top:8px;font-size:.75rem;color:#6daece;">
                        <span>{{ $completedCount ?? 0 }} completed</span>
                        <span>{{ $totalCount ?? 0 }} total</span>
                    </div>
                </div>
            </div>

            <div class="panel">
                <div class="ph">
                    <span class="pt">This Week</span>
                    <span class="pb">Last 7 days</span>
                </div>
                <div style="padding:16px 20px">
                    <canvas id="weeklyChart" height="120"></canvas>
                </div>
            </div>

            <div class="panel">
                <div class="ph"><span class="pt">Status Breakdown</span></div>
                <div style="padding:16px 20px">
                    <canvas id="statusDonut" height="180"></canvas>
                </div>
            </div>

            <div class="panel">
                <div class="ph"><span class="pt">Task Distribution</span></div>
                <div class="dl">
                    @php
                        $taskTypes = ['meeting','draft-review','call','follow-up','internal-task','assignment','other'];
                        $typeCounts = [];
                        foreach($taskTypes as $type) {
                            $typeCounts[$type] = \App\Models\Diary::where('task_type', $type)->count();
                        }
                        $maxCount = max(array_values($typeCounts) ?: [1]);
                        $hasAny   = collect($typeCounts)->sum() > 0;
                    @endphp
                    @if($hasAny)
                        @foreach($taskTypes as $type)
                            @if($typeCounts[$type] > 0)
                                <div>
                                    <div class="dm">
                                        <span class="dlb">{{ ucwords(str_replace('-',' ',$type)) }}</span>
                                        <span class="dc">{{ $typeCounts[$type] }}</span>
                                    </div>
                                    <div class="dbt">
                                        <div class="dbf" style="width:{{ ($typeCounts[$type] / $maxCount) * 100 }}%"></div>
                                    </div>
                                </div>
                            @endif
                        @endforeach
                    @else
                        <p style="font-size:.8rem;color:var(--text-muted);padding:10px 0">No task data available yet.</p>
                    @endif
                </div>
            </div>

        </div>
    </div>

</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Daily Tasks modal wiring
    var taskModalEl = document.getElementById('taskViewModal');
    var taskModal = (taskModalEl && typeof bootstrap !== 'undefined') ? new bootstrap.Modal(taskModalEl) : null;

    function badgeForPriority(priority) {
        if (priority === 'high') return { cls: 'bp b-high', label: 'High' };
        if (priority === 'low') return { cls: 'bp b-low', label: 'Low' };
        return { cls: 'bp b-med', label: 'Medium' };
    }

    function badgeForStatus(status) {
        if (status === 'completed') return { cls: 'bp b-done', label: 'Completed' };
        if (status === 'in-progress') return { cls: 'bp b-prog', label: 'In Progress' };
        if (status === 'pending') return { cls: 'bp b-pend', label: 'Pending' };
        return { cls: 'bp b-low', label: (status || 'Unknown').replace('-', ' ') };
    }

    document.querySelectorAll('.dt-row[data-entry]').forEach(function (cell) {
        cell.addEventListener('click', function () {
            if (!taskModal) return;

            var raw = cell.getAttribute('data-entry') || '{}';
            var data;
            try { data = JSON.parse(raw); } catch (e) { data = {}; }

            var titleEl = document.getElementById('taskModalTitle');
            var metaEl = document.getElementById('taskModalMeta');
            var notesWrap = document.getElementById('taskModalNotesWrap');
            var notesEl = document.getElementById('taskModalNotes');
            var prEl = document.getElementById('taskModalPriority');
            var stEl = document.getElementById('taskModalStatus');

            if (titleEl) titleEl.textContent = data.title || 'Untitled';

            var metaBits = [];
            if (data.date) metaBits.push(data.date + (data.time && data.time !== '—' ? (' • ' + data.time) : ''));
            if (data.task_type) metaBits.push(String(data.task_type).replace(/-/g, ' '));
            if (data.client_case) metaBits.push(data.client_case);
            if (metaEl) metaEl.textContent = metaBits.filter(Boolean).join('  —  ');

            var notes = (data.notes || '').trim();
            if (notesEl) notesEl.textContent = notes || '—';
            if (notesWrap) notesWrap.style.display = notes ? '' : 'none';

            var pr = badgeForPriority(data.priority || 'medium');
            if (prEl) { prEl.className = pr.cls; prEl.textContent = pr.label; }
            var st = badgeForStatus(data.status || 'pending');
            if (stEl) { stEl.className = st.cls; stEl.textContent = st.label; }

            var viewA = document.getElementById('taskModalView');
            var editA = document.getElementById('taskModalEdit');
            var printA = document.getElementById('taskModalPrint');
            if (viewA) viewA.href = data.showUrl || '#';
            if (editA) editA.href = data.editUrl || '#';
            if (printA) printA.href = data.printUrl || '#';

            var delForm = document.getElementById('taskModalDeleteForm');
            if (delForm) delForm.action = data.destroyUrl || '#';

            taskModal.show();
        });
    });

    var weeklyLabels = @json($weeklyTrend->pluck('label'));
    var weeklyData   = @json($weeklyTrend->pluck('count'));

    var ctx = document.getElementById('weeklyChart');
    if (ctx && typeof Chart !== 'undefined') {
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: weeklyLabels,
                datasets: [{
                    label: 'Entries',
                    data: weeklyData,
                    backgroundColor: 'rgba(14,165,233,0.18)',
                    borderColor: '#0ea5e9',
                    borderWidth: 2,
                    borderRadius: 4,
                }]
            },
            options: {
                responsive: true,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero:true, ticks:{ stepSize:1, font:{size:10} }, grid:{ color:'#e0f2fe' } },
                    x: { ticks:{ font:{size:10} }, grid:{ display:false } }
                }
            }
        });
    }

    var statusCtx = document.getElementById('statusDonut');
    if (statusCtx && typeof Chart !== 'undefined') {
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Pending', 'In Progress', 'Completed', 'Deferred'],
                datasets: [{
                    data: [
                        {{ $pendingCount ?? 0 }},
                        {{ $inProgressCount ?? 0 }},
                        {{ $completedCount ?? 0 }},
                        {{ max(($totalCount ?? 0) - (($pendingCount ?? 0) + ($inProgressCount ?? 0) + ($completedCount ?? 0)), 0) }}
                    ],
                    backgroundColor: ['#f59e0b','#0ea5e9','#10b981','#94a3b8'],
                    borderWidth: 2, borderColor: '#fff',
                }]
            },
            options: {
                cutout: '70%',
                plugins: { legend: { position:'bottom', labels:{ font:{size:11}, padding:12 } } }
            }
        });
    }
});
</script>
@endpush
