<?php
if (!function_exists('fmtDate')) {
    function fmtDate($d, $t = false) {
        if (!$d || $d === '0000-00-00' || $d === '0000-00-00 00:00:00') return '—';
        try {
            $dt = new DateTime($d);
            return $t ? $dt->format('m/d/Y g:i A') : $dt->format('m/d/Y');
        } catch (Exception $e) {
            return htmlspecialchars((string)$d);
        }
    }
}
$active = $active ?? 'projects';
$pageTitle = 'Company KPI Dashboard';
$accountsRecords = $accountsRecords ?? [];
// Use workspace header when $project is set (coming from workspace project page)
// Use admin header when accessed directly via /projects/kpi/company
if (!empty($project) || (isset($user) && ($user['user_type'] ?? '') === 'manager' && ($user['username'] ?? '') === 'sara.lasher')) {
    require __DIR__ . '/../layout/workspace_header.php';
} else {
    require __DIR__ . '/../layout/admin_header.php';
}
$statusColors = ['draft'=>'badge-role-default','submitted'=>'badge-role-manager','reviewed'=>'badge-role-director','approved'=>'badge-role-employee','returned'=>'badge-role-ceo','locked'=>'badge-role-super'];
$qs = $_GET;
?>
<div class="topbar">
  <div>
    <h1>Company KPI Dashboard</h1>
    <div class="crumbs">
      <a href="/workspace" style="color:var(--blue-600);">Workspace</a> →
      <?php if (!empty($project)): ?>
        <a href="/project?id=<?= $project['id'] ?>" style="color:var(--blue-600);">KPI</a> →
      <?php else: ?>
        Admin → Projects →
      <?php endif; ?>
      KPI Tracker
    </div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($admin['name']) ?></div>
</div>

<div class="card">
  <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:4px;">
    <?php foreach ($departments as $d): ?>
      <a href="/projects/kpi/company?dept=<?= $d['id'] ?>"
         class="btn-secondary" style="text-decoration:none; <?= $activeDeptId === (int)$d['id'] ? 'background:linear-gradient(120deg,var(--blue-600),var(--indigo-600));color:#fff;border:none;' : '' ?>">
        <?= htmlspecialchars($d['name']) ?>
      </a>
    <?php endforeach; ?>
  </div>
</div>

<?php if ($activeDeptId !== $schedulingDeptId): ?>
  <div class="card">
    <p style="color:var(--text-muted);text-align:center;padding:40px 20px;">
      KPI tracker for this department is not finalized yet.
    </p>
  </div>
<?php else: ?>
  <?php $summary = \App\Models\KpiScheduling::summaryFor($records); ?>
  <div class="card">
    <div style="display:flex;gap:8px;margin-bottom:20px;">
      <button class="btn-secondary kpi-subtab active" data-tab="overview" onclick="kpiShowTab('overview')">Overview</button>
      <button class="btn-secondary kpi-subtab" data-tab="bydept" onclick="kpiShowTab('bydept')">By Department</button>
      <button class="btn-secondary kpi-subtab" data-tab="fulltable" onclick="kpiShowTab('fulltable')">Full Table</button>
    </div>

    <div id="kpiTab-overview">
      <div class="stat-grid">
        <div class="stat-card"><div class="label">Total Hours</div><div class="value"><?= $summary['total_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Static Hours</div><div class="value"><?= $summary['static_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Patrol Hours</div><div class="value"><?= $summary['patrol_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Event Hours</div><div class="value"><?= $summary['event_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">OT Hours</div><div class="value"><?= $summary['ot_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">OT %</div><div class="value"><?= $summary['ot_pct'] !== null ? $summary['ot_pct'] . '%' : '—' ?></div></div>
        <div class="stat-card"><div class="label">DT Hours</div><div class="value"><?= $summary['dt_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Open Post Hours</div><div class="value"><?= $summary['open_post_hours'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">New Hires</div><div class="value"><?= $summary['new_hires'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Incidents</div><div class="value"><?= $summary['incidents'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Client Complaints</div><div class="value"><?= $summary['client_complaints'] ?: 0 ?></div></div>
        <div class="stat-card"><div class="label">Entries Logged</div><div class="value"><?= $summary['entries_logged'] ?></div></div>
      </div>
    </div>

    <div id="kpiTab-bydept" style="display:none;">
      <table>
        <thead><tr><th>Department</th><th>Entries</th><th>Total Hours</th><th>Incidents</th></tr></thead>
        <tbody>
          <tr>
            <td style="font-weight:700;">Scheduling</td>
            <td><?= $summary['entries_logged'] ?></td>
            <td><?= $summary['total_hours'] ?: 0 ?></td>
            <td><?= $summary['incidents'] ?: 0 ?></td>
          </tr>
        </tbody>
      </table>
    </div>

    <div id="kpiTab-fulltable" style="display:none;">
    <div class="toolbar">
      <form method="GET" action="/projects/kpi/company" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">
        <input type="hidden" name="dept" value="<?= $activeDeptId ?>">
        <div class="field" style="margin-bottom:0;">
          <label>Employee</label>
          <select name="employee" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;">
            <option value="">All</option>
            <?php foreach ($submitters as $s): ?>
              <option value="<?= $s['id'] ?>" <?= ($qs['employee'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field" style="margin-bottom:0;">
          <label>Status</label>
          <select name="status" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;">
            <option value="">All</option>
            <?php foreach (['draft','submitted','reviewed','returned','locked'] as $s): ?>
              <option value="<?= $s ?>" <?= ($qs['status'] ?? '') === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field" style="margin-bottom:0;">
          <label>Range</label>
          <select name="range" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;">
            <option value="">Custom</option>
            <option value="current_week" <?= ($qs['range'] ?? '') === 'current_week' ? 'selected' : '' ?>>Current Week</option>
            <option value="previous_week" <?= ($qs['range'] ?? '') === 'previous_week' ? 'selected' : '' ?>>Previous Week</option>
            <option value="current_month" <?= ($qs['range'] ?? '') === 'current_month' ? 'selected' : '' ?>>Current Month</option>
            <option value="current_year" <?= ($qs['range'] ?? '') === 'current_year' ? 'selected' : '' ?>>Current Year</option>
          </select>
        </div>
        <div class="field" style="margin-bottom:0;"><label>From Date</label><input type="date" name="from_date" value="<?= htmlspecialchars($qs['from_date'] ?? '') ?>" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;"></div>
        <div class="field" style="margin-bottom:0;"><label>To Date</label><input type="date" name="to_date" value="<?= htmlspecialchars($qs['to_date'] ?? '') ?>" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;"></div>
        <a href="/projects/kpi/export.csv?<?= htmlspecialchars(http_build_query($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ CSV</a>
        <a href="/projects/kpi/export.xlsx?<?= htmlspecialchars(http_build_query($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ Excel</a>
        <a href="/projects/kpi/export.pdf?<?= htmlspecialchars(http_build_query($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ PDF</a>
      </form>
    </div>

    <table>
      <thead><tr><th>Submitted By</th><th>Week Starting</th><th>Week Ending</th><th>Status</th><th>Total Hours</th><th>Incidents</th><th>Score</th><th>Reviewer</th><th></th></tr></thead>
      <tbody>
        <?php foreach ($records as $r): ?>
          <tr>
            <td style="font-weight:700;"><?= htmlspecialchars($r['submitter_name']) ?></td>
            <td style="color:var(--text-muted);font-size:13px;"><?= $r['week_starting'] ? fmtDate($r['week_starting']) : '—' ?></td>
            <td><?= fmtDate($r['week_ending']) ?></td>
            <td><span class="badge <?= $statusColors[$r['status']] ?? '' ?>"><?= ucfirst($r['status']) ?></span></td>
            <td><?= htmlspecialchars($r['total_hours'] ?? '—') ?></td>
            <td><?= htmlspecialchars($r['incidents'] ?? '—') ?></td>
            <td>
              <?php if ($r['review_score'] ?? 0): ?>
                <span style="background:#FAEEDA;color:#633806;border-radius:8px;padding:3px 10px;font-size:13px;font-weight:600;">
                  <?= (int)$r['review_score'] ?>/10<?= !empty($r['score_revised']) ? ' ✎' : '' ?>
                </span>
              <?php else: ?>
                <span style="color:var(--text-muted);">—</span>
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($r['reviewer_name'] ?? '—') ?></td>
            <td><a href="/projects/kpi/view?id=<?= $r['id'] ?>" class="btn-secondary" style="text-decoration:none;padding:6px 12px;font-size:12px;">Open</a></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($records)): ?>
          <tr><td colspan="9" style="text-align:center;color:var(--text-muted);padding:30px;">No KPI records available.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
    </div>
  </div>
<?php endif; ?>

<script>
function kpiShowTab(name){
  ['overview','bydept','fulltable'].forEach(t => {
    document.getElementById('kpiTab-' + t).style.display = (t === name) ? '' : 'none';
  });
  document.querySelectorAll('.kpi-subtab').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.tab === name);
    if (btn.dataset.tab === name) {
      btn.style.background = 'linear-gradient(120deg,var(--blue-600),var(--indigo-600))';
      btn.style.color = '#fff';
      btn.style.border = 'none';
    } else {
      btn.style.background = '';
      btn.style.color = '';
      btn.style.border = '';
    }
  });
}
</script>

<?php
// Cesar KPI section — always visible to Sara as super admin
$cesarRecords = \App\Models\CesarKpi::all();
$cesarPending = array_filter($cesarRecords, fn($r) => $r['status'] === 'submitted');
?>
<div class="card" style="margin-top:4px;">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;">
    <div>
      <h3 style="margin:0 0 4px;font-size:15px;font-weight:700;">Operations Manager KPI — César Saona</h3>
      <div style="font-size:13px;color:var(--text-muted);">Weekly KPI submissions from the Operations Manager</div>
    </div>
    <a href="/projects/cesar-kpi/review" class="btn-primary" style="text-decoration:none;white-space:nowrap;">
      Open Review Queue →
    </a>
  </div>

  <?php if (count($cesarPending) > 0): ?>
  <div style="padding:12px 16px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:12px;margin-bottom:16px;font-size:13px;color:#1d4ed8;">
    ⚠️ <strong><?= count($cesarPending) ?></strong> entr<?= count($cesarPending)===1?'y':'ies' ?> pending your review
  </div>
  <?php endif; ?>

  <?php if (empty($cesarRecords)): ?>
    <p style="color:var(--text-muted);font-size:13px;text-align:center;padding:20px 0;">No KPI submissions from César yet.</p>
  <?php else: ?>
  <?php
  $statusColors = ['draft'=>'#6b7280','submitted'=>'#2563eb','reviewed'=>'#7c3aed','approved'=>'#059669','locked'=>'#059669','returned'=>'#dc2626'];
  ?>
  <table>
    <thead>
      <tr>
        <th>Week Starting</th>
        <th>Week Ending</th>
        <th>Status</th>
        <th>Submitted</th>
        <th>Score</th>
        <th>Reviewer</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach (array_slice($cesarRecords, 0, 10) as $r): ?>
      <tr>
        <td style="color:var(--text-muted);font-size:13px;"><?= $r['week_starting'] ? fmtDate($r['week_starting']) : '—' ?></td>
        <td style="font-weight:700;"><?= fmtDate($r['week_ending']) ?></td>
        <td>
          <span style="display:inline-block;padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;
            background:<?= $statusColors[$r['status']] ?? '#6b7280' ?>22;
            color:<?= $statusColors[$r['status']] ?? '#6b7280' ?>;">
            <?= ucfirst($r['status']) ?>
          </span>
        </td>
        <td style="color:var(--text-muted);font-size:13px;"><?= $r['submitted_at'] ? fmtDate($r['submitted_at']) : '—' ?></td>
        <td>
          <?php if ($r['review_score'] ?? 0): ?>
            <span style="background:#FAEEDA;color:#633806;border-radius:8px;padding:3px 10px;font-size:13px;font-weight:600;">
              <?= (int)$r['review_score'] ?>/10<?= !empty($r['score_revised']) ? ' ✎' : '' ?>
            </span>
          <?php else: ?>
            <span style="color:var(--text-muted);">—</span>
          <?php endif; ?>
        </td>
        <td style="color:var(--text-muted);font-size:13px;"><?= $r['reviewer_name'] ? htmlspecialchars($r['reviewer_name']) : '—' ?></td>
        <td>
          <?php if ($r['status'] === 'submitted'): ?>
            <button type="button" onclick="openCesarModal('/projects/cesar-kpi/view?id=<?= $r['id'] ?>&modal=1','César KPI — <?= $r['week_ending'] ?>')" class="btn-primary" style="font-size:12px;padding:5px 14px;">Review</button>
          <?php else: ?>
            <button type="button" onclick="openCesarModal('/projects/cesar-kpi/view?id=<?= $r['id'] ?>&modal=1','César KPI — <?= $r['week_ending'] ?>')" class="btn-secondary" style="font-size:12px;padding:5px 14px;">View</button>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
  <?php if (count($cesarRecords) > 10): ?>
    <div style="text-align:center;margin-top:12px;">
      <a href="/projects/cesar-kpi/review" style="font-size:13px;color:var(--blue-600);">View all <?= count($cesarRecords) ?> entries →</a>
    </div>
  <?php endif; ?>
  <?php endif; ?>
</div>

<!-- ── Accounts KPI — Jatinder Kumar ─────────────────────────────────── -->
<?php
$accountsPending = array_filter($accountsRecords ?? [], fn($r) => $r['status'] === 'submitted');
?>
<div class="card" style="margin-bottom:24px;">
  <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:18px;">
    <div>
      <h3 style="margin:0 0 4px;font-size:15px;font-weight:700;">Accounts KPI — Jatinder Kumar</h3>
      <div style="font-size:13px;color:var(--text-muted);">Weekly KPI submissions from Accounts</div>
    </div>
    <div style="display:flex;gap:10px;align-items:center;">
      <?php if (!empty($accountsPending)): ?>
        <span style="background:#fef3c7;color:#92400e;border-radius:20px;padding:4px 12px;font-size:12px;font-weight:700;">
          <?= count($accountsPending) ?> pending review
        </span>
      <?php endif; ?>
      <a href="/projects/jatinder-kpi/review" class="btn-primary" style="text-decoration:none;padding:8px 16px;font-size:13px;">
        Open Review Queue →
      </a>
    </div>
  </div>

  <?php if (empty($accountsRecords)): ?>
    <p style="color:var(--text-muted);font-size:13px;padding:20px 0;">No Accounts KPI entries yet.</p>
  <?php else: ?>
  <table>
    <thead><tr>
      <th>Submitted By</th>
      <th>Week Starting</th>
      <th>Week Ending</th>
      <th>Status</th>
      <th>Submitted</th>
      <th>Score</th>
      <th>Reviewer</th>
      <th>Actions</th>
    </tr></thead>
    <tbody>
    <?php foreach (array_slice($accountsRecords, 0, 10) as $r):
      $sc = ['draft'=>'#6b7280','submitted'=>'#2563eb','reviewed'=>'#7c3aed','approved'=>'#059669','locked'=>'#059669','returned'=>'#dc2626'][$r['status']] ?? '#6b7280';
      $sl = ['draft'=>'Draft','submitted'=>'Submitted','reviewed'=>'Reviewed','approved'=>'Approved','locked'=>'Locked','returned'=>'Returned'][$r['status']] ?? ucfirst($r['status']);
    ?>
    <tr class="<?= $r['status']==='submitted'?'needs-action':'' ?>">
      <td style="font-weight:700;"><?= htmlspecialchars($r['submitter_name']) ?></td>
      <td style="color:var(--text-muted);font-size:13px;"><?= fmtDate($r['week_starting'] ?? '') ?></td>
      <td><?= fmtDate($r['week_ending']) ?></td>
      <td><span style="display:inline-block;padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;background:<?= $sc ?>22;color:<?= $sc ?>;"><?= $sl ?></span></td>
      <td style="color:var(--text-muted);font-size:13px;"><?= fmtDate($r['submitted_at'] ?? '') ?></td>
      <td>
        <?php if ($r['review_score'] ?? 0): ?>
          <span style="background:#FAEEDA;color:#633806;border-radius:8px;padding:3px 10px;font-size:13px;font-weight:600;"><?= (int)$r['review_score'] ?>/10<?= !empty($r['score_revised'])?' ✎':'' ?></span>
        <?php else: ?><span style="color:var(--text-muted);">—</span><?php endif; ?>
      </td>
      <td style="font-size:13px;color:var(--text-muted);"><?= htmlspecialchars($r['reviewer_name'] ?? '—') ?></td>
      <td>
        <button type="button" onclick="openAccountsModal('/projects/jatinder-kpi/view?id=<?= $r['id'] ?>&modal=1','<?= htmlspecialchars(addslashes($r['submitter_name'])) ?> — <?= fmtDate($r['week_ending']) ?>')"
                class="<?= $r['status']==='submitted'?'btn-primary':'btn-secondary' ?>" style="font-size:12px;padding:5px 14px;">
          <?= $r['status']==='submitted'?'Review':'View' ?>
        </button>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <?php if (count($accountsRecords) > 10): ?>
    <div style="text-align:center;margin-top:12px;">
      <a href="/projects/jatinder-kpi/review" style="font-size:13px;color:var(--blue-600);">View all <?= count($accountsRecords) ?> entries →</a>
    </div>
  <?php endif; ?>
  <?php endif; ?>
</div>

<?php if (!empty($project)): ?>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
<?php else: ?>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
<?php endif; ?>

<!-- César KPI Review Modal -->
<style>
#cesar-modal-backdrop{display:none;position:fixed;inset:0;z-index:1000;background:rgba(15,23,42,0.55);backdrop-filter:blur(3px);align-items:flex-start;justify-content:center;padding:28px 16px;overflow-y:auto;}
#cesar-modal-backdrop.open{display:flex;}
#cesar-modal{background:#fff;border-radius:20px;width:100%;max-width:960px;box-shadow:0 24px 80px rgba(0,0,0,0.22);overflow:hidden;min-height:400px;}
#cesar-modal-header{display:flex;justify-content:space-between;align-items:center;padding:18px 24px 14px;border-bottom:1px solid var(--border);background:#fff;position:sticky;top:0;z-index:10;}
#cesar-modal-header h2{margin:0;font-size:17px;font-weight:800;}
#cesar-modal-close{background:none;border:none;cursor:pointer;font-size:22px;color:#6b7280;line-height:1;padding:4px 8px;border-radius:8px;}
#cesar-modal-iframe{width:100%;border:none;display:block;min-height:600px;}
</style>
<div id="cesar-modal-backdrop">
  <div id="cesar-modal">
    <div id="cesar-modal-header">
      <h2 id="cesar-modal-title">KPI Record</h2>
      <button type="button" id="cesar-modal-close" onclick="closeCesarModal()">✕</button>
    </div>
    <iframe id="cesar-modal-iframe" src="" title="César KPI Record"></iframe>
  </div>
</div>
<script>
function openCesarModal(src, title) {
  document.getElementById('cesar-modal-title').textContent = title || 'KPI Record';
  document.getElementById('cesar-modal-iframe').src = src;
  document.getElementById('cesar-modal-backdrop').classList.add('open');
  document.body.style.overflow = 'hidden';
  document.getElementById('cesar-modal-iframe').onload = function() {
    try { var h = this.contentWindow.document.body.scrollHeight; this.style.height = Math.min(Math.max(h+40,500), window.innerHeight-120)+'px'; } catch(e) { this.style.height='80vh'; }
  };
}
function closeCesarModal() {
  document.getElementById('cesar-modal-backdrop').classList.remove('open');
  document.getElementById('cesar-modal-iframe').src = '';
  document.body.style.overflow = '';
  window.location.reload();
}
document.getElementById('cesar-modal-backdrop').addEventListener('click', function(e){ if(e.target===this) closeCesarModal(); });
document.addEventListener('keydown', function(e){ if(e.key==='Escape') closeCesarModal(); });
window.addEventListener('message', function(e){
  if(e.data && e.data.type==='kpi-resize'){
    var iframe=document.getElementById('cesar-modal-iframe');
    if(iframe) iframe.style.height=Math.min(e.data.height+40,window.innerHeight-120)+'px';
  }
});
</script>

<!-- Accounts KPI Review Modal -->
<style>
#accounts-modal-backdrop{display:none;position:fixed;inset:0;z-index:1000;background:rgba(15,23,42,0.55);backdrop-filter:blur(3px);align-items:flex-start;justify-content:center;padding:28px 16px;overflow-y:auto;}
#accounts-modal-backdrop.open{display:flex;}
#accounts-modal{background:#fff;border-radius:20px;width:100%;max-width:960px;box-shadow:0 24px 80px rgba(0,0,0,0.22);overflow:hidden;min-height:400px;}
#accounts-modal-header{display:flex;justify-content:space-between;align-items:center;padding:18px 24px 14px;border-bottom:1px solid var(--border);background:#fff;position:sticky;top:0;z-index:10;}
#accounts-modal-header h2{margin:0;font-size:17px;font-weight:800;}
#accounts-modal-close{background:none;border:none;cursor:pointer;font-size:22px;color:#6b7280;line-height:1;padding:4px 8px;border-radius:8px;}
#accounts-modal-iframe{width:100%;border:none;display:block;min-height:600px;}
</style>
<div id="accounts-modal-backdrop">
  <div id="accounts-modal">
    <div id="accounts-modal-header">
      <h2 id="accounts-modal-title">Accounts KPI Record</h2>
      <button type="button" id="accounts-modal-close" onclick="closeAccountsModal()">✕</button>
    </div>
    <iframe id="accounts-modal-iframe" src="" title="Accounts KPI Record"></iframe>
  </div>
</div>
<script>
function openAccountsModal(src, title) {
  document.getElementById('accounts-modal-title').textContent = title || 'Accounts KPI Record';
  document.getElementById('accounts-modal-iframe').src = src;
  document.getElementById('accounts-modal-backdrop').classList.add('open');
  document.body.style.overflow = 'hidden';
  document.getElementById('accounts-modal-iframe').onload = function() {
    try { var h = this.contentWindow.document.body.scrollHeight; this.style.height = Math.min(Math.max(h+40,500), window.innerHeight-120)+'px'; } catch(e) { this.style.height='80vh'; }
  };
}
function closeAccountsModal() {
  document.getElementById('accounts-modal-backdrop').classList.remove('open');
  document.getElementById('accounts-modal-iframe').src = '';
  document.body.style.overflow = '';
  window.location.reload();
}
document.getElementById('accounts-modal-backdrop').addEventListener('click', function(e){ if(e.target===this) closeAccountsModal(); });
document.addEventListener('keydown', function(e){ if(e.key==='Escape') closeAccountsModal(); });
window.addEventListener('message', function(e){
  if(e.data && e.data.type==='kpi-resize'){
    var iframe=document.getElementById('accounts-modal-iframe');
    if(iframe) iframe.style.height=Math.min(e.data.height+40,window.innerHeight-120)+'px';
  }
  if(e.data && (e.data.type==='review-done'||e.data.type==='kpi-saved')){
    closeAccountsModal();
  }
});
</script>
