{% extends "base.html" %}

{% block title %}Dashboard - {{ config.INSTANCE_NAME or 'Data Analyst Portal' }}{% endblock %}

{% block head_extra %}
{% if not config.THEME_FONT_URL %}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
{% endif %}
<style>
        /* ── Header ── */
        .header {
            background: var(--surface);
            border-bottom: 1px solid var(--border);
            padding: 0 32px;
            height: 72px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-left {
            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 2px;
        }

        .header-logo {
            display: inline-flex;
            align-items: center;
            text-decoration: none;
            color: inherit;
        }
        .header-logo svg {
            display: block;
        }
        a.header-logo:focus-visible {
            outline: 2px solid var(--primary);
            outline-offset: 2px;
            border-radius: 4px;
        }

        .header-subtitle {
            font-size: 11px;
            font-weight: 500;
            color: var(--text-secondary);
            letter-spacing: 0.4px;
            text-transform: uppercase;
            margin-top: 2px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .header-email {
            font-size: 13px;
            color: var(--text-secondary);
            font-weight: 500;
        }

        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--primary-light);
            color: var(--primary);
            font-size: 13px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            letter-spacing: 0.3px;
        }

        .avatar-img {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: 2px solid var(--border);
        }

        .btn-logout {
            font-family: var(--font-primary);
            font-size: 13px;
            font-weight: 500;
            color: var(--text-secondary);
            background: none;
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 6px 14px;
            cursor: pointer;
            transition: all 0.15s ease;
            text-decoration: none;
        }

        .btn-logout:hover {
            color: var(--text-primary);
            border-color: #D1D5DB;
            background: var(--border-light);
        }

        /* ── Main Container ── */
        .main {
            max-width: 1280px;
            margin: 0 auto;
            padding: 28px 32px 48px;
        }

        /* ── Stats Row ── */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 16px;
            margin-bottom: 28px;
        }

        .stat-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px 22px;
            display: flex;
            flex-direction: column;
            gap: 4px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
        }

        .stat-label {
            font-size: 12px;
            font-weight: 500;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--text-primary);
            letter-spacing: -0.5px;
            line-height: 1.2;
        }

        /* ── Credit Line ── */
        .credit-line {
            text-align: center;
            font-size: 12px;
            color: #9CA3AF;
            margin-bottom: 20px;
        }

        .credit-line .heart {
            color: #EF4444;
        }

        .credit-line strong {
            color: #6B7280;
            font-weight: 500;
        }

        /* ── Two-Column Layout ── */
        .dashboard-grid {
            display: grid;
            grid-template-columns: 1fr 400px;
            grid-template-rows: auto auto;
            gap: 24px;
        }

        .left-column {
            grid-row: 1 / 3;
            display: grid;
            grid-template-rows: subgrid;
            gap: 24px;
        }

        .right-column {
            grid-row: 1 / 3;
            display: grid;
            grid-template-rows: subgrid;
            gap: 24px;
            position: sticky;
            top: 24px;
        }

        /* ── Card Base ── */
        .card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 12px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
            overflow: hidden;
        }

        .card-header {
            padding: 22px 24px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .card-header-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .card-body {
            padding: 20px 24px 24px;
        }


        /* ── Bottom Cards Row ── */
        .bottom-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }

        /* ── Notifications Card ── */
        .notif-channels {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .notif-channel {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px;
            border: 1px solid var(--border);
            border-radius: 10px;
            background: var(--surface);
        }

        .notif-channel-icon {
            width: 38px;
            height: 38px;
            border-radius: 8px;
            background: var(--border-light);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .notif-channel-icon.telegram {
            background: rgba(25, 118, 210, 0.1);
            color: #1976D2;
        }

        .notif-channel-icon.desktop {
            background: rgba(124, 58, 237, 0.1);
            color: #7C3AED;
        }

        .notif-channel-icon svg {
            color: inherit;
        }

        .notif-channel-name {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 2px;
        }

        .notif-status {
            font-size: 12px;
            font-weight: 500;
        }

        .notif-status--active {
            color: var(--success);
        }

        .notif-status--inactive {
            color: #9CA3AF;
        }

        .link-manage {
            font-size: 13px;
            font-weight: 600;
            color: var(--primary);
            text-decoration: none;
            cursor: pointer;
        }

        .link-manage:hover {
            text-decoration: underline;
        }

        .link-manage.active {
            color: var(--text-secondary);
        }

        .notif-badge {
            margin-left: auto;
            flex-shrink: 0;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 500;
            white-space: nowrap;
        }

        .notif-badge.active {
            background: rgba(16, 183, 127, 0.1);
            color: #059669;
        }

        .notif-unlink {
            display: none;
            margin-left: auto;
            flex-shrink: 0;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 500;
            background: rgba(239, 68, 68, 0.1);
            color: #EF4444;
            border: 1px solid rgba(239, 68, 68, 0.2);
            cursor: pointer;
            transition: background 0.15s;
            white-space: nowrap;
        }

        .notif-unlink:hover {
            background: rgba(239, 68, 68, 0.2);
        }

        .notif-unlink.visible,
        .notif-managing .notif-unlink {
            display: inline-block;
        }

        .notif-managing .notif-badge {
            display: none;
        }

        .notif-link {
            display: none;
            margin-left: auto;
            flex-shrink: 0;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 500;
            background: rgba(37, 99, 235, 0.1);
            color: #2563EB;
            border: 1px solid rgba(37, 99, 235, 0.2);
            cursor: pointer;
            transition: background 0.15s;
            white-space: nowrap;
        }

        .notif-link:hover {
            background: rgba(37, 99, 235, 0.2);
        }

        .notif-managing .notif-link {
            display: inline-block;
        }

        .telegram-verify {
            display: none;
            margin-top: 12px;
            padding: 12px;
            background: var(--background);
            border-radius: 8px;
            font-size: 12px;
            color: var(--text-secondary);
        }

        .telegram-verify.visible {
            display: block;
        }

        .telegram-verify ol {
            margin: 8px 0 12px 18px;
            line-height: 1.8;
        }

        .telegram-verify-row {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .telegram-verify-row input {
            width: 120px;
            padding: 6px 10px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 13px;
            text-align: center;
        }

        .telegram-verify-row button {
            padding: 6px 14px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
            background: var(--primary);
            color: white;
            border: none;
            cursor: pointer;
        }

        .telegram-verify-row button:hover {
            opacity: 0.9;
        }

        .telegram-verify-error {
            color: var(--error);
            font-size: 11px;
            margin-top: 6px;
            display: none;
        }


        /* ── Setup Banner ── */
        /* ── Environment Setup CTA (shown after account creation) ── */
        .env-setup-cta {
            background: linear-gradient(135deg, #0073D1 0%, #0056A3 100%);
            border-radius: 12px;
            padding: 24px 32px;
            margin-bottom: 24px;
            box-shadow: 0 4px 16px rgba(0, 115, 209, 0.2);
            color: white;
        }

        .env-setup-cta h3 {
            font-size: 16px;
            font-weight: 700;
            margin: 0 0 4px 0;
            color: white;
        }

        .env-setup-cta .env-subtitle {
            font-size: 13px;
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 16px;
        }

        .env-setup-row {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .env-setup-row .code-pill {
            background: rgba(255, 255, 255, 0.15);
            padding: 8px 16px;
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 14px;
            color: white;
        }

        .env-setup-row .btn-setup {
            font-family: var(--font-primary);
            font-size: 13px;
            font-weight: 600;
            color: var(--primary);
            background: #FFFFFF;
            border: none;
            border-radius: 6px;
            padding: 8px 20px;
            cursor: pointer;
            transition: all 0.15s ease;
            white-space: nowrap;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .env-setup-row .btn-setup:hover {
            background: #F0F7FF;
        }

        .env-setup-row .btn-setup.copied {
            background: var(--success);
            color: white;
        }

        .env-setup-row .env-meta {
            display: inline-flex;
            align-items: center;
            gap: 12px;
        }

        .env-setup-row .env-hint {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.6);
        }

        .env-setup-link {
            font-size: 13px;
            color: rgba(255, 255, 255, 0.9);
            text-decoration: underline;
            text-underline-offset: 2px;
        }
        .env-setup-link:hover { color: #fff; }

        .setup-link-banner {
            margin-top: 12px;
            padding: 10px 16px;
            font-size: 13px;
            color: var(--text-secondary, #6b7280);
            text-align: center;
        }
        .setup-link-banner a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        .setup-link-banner a:hover { text-decoration: underline; }

        .env-setup-cta .btn-setup[disabled] {
            opacity: 0.7;
            cursor: wait;
        }
        /* .setup-error + .setup-fallback-* styles now live in
           templates/_claude_setup_cta.jinja so /home reuses them. */

        .btn-setup-secondary {
            font-family: var(--font-primary);
            font-size: 13px;
            font-weight: 500;
            color: var(--primary);
            background: transparent;
            border: 1px solid var(--primary);
            border-radius: 6px;
            padding: 6px 16px;
            cursor: pointer;
            transition: all 0.15s ease;
            white-space: nowrap;
        }

        .btn-setup-secondary:hover {
            background: rgba(0, 115, 209, 0.05);
        }

        .btn-setup-secondary.copied {
            background: var(--success);
            color: white;
            border-color: var(--success);
        }

        /* ── Support Banner ── */
        .support-banner {
            text-align: center;
            padding: 16px;
            font-size: 13px;
            color: var(--text-secondary);
            margin-top: 24px;
        }

        .support-banner .heart {
            color: #EF4444;
        }

        .slack-badge {
            display: inline-block;
            margin-left: 8px;
            padding: 2px 8px;
            background: var(--background);
            border-radius: 4px;
            color: var(--text-primary);
            text-decoration: none;
            font-size: 12px;
        }

        .slack-badge:hover {
            background: var(--border);
        }

        /* ── Footer ── */
        .footer {
            text-align: center;
            padding: 32px;
            font-size: 12px;
            color: #9CA3AF;
        }

        /* ── Flash Messages ── */
        .flash-messages {
            max-width: 1280px;
            margin: 0 auto;
            padding: 16px 32px 0;
        }

        .flash {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 13px;
        }

        .flash-success {
            background: rgba(16, 183, 127, 0.1);
            color: var(--success);
            border-left: 3px solid var(--success);
        }

        .flash-error {
            background: rgba(234, 88, 12, 0.1);
            color: var(--error);
            border-left: 3px solid var(--error);
        }

        /* ── New User Layout ── */
        .new-user-grid {
            max-width: 960px;
            margin: 0 auto;
        }

        .setup-card {
            padding: 32px 36px;
        }

        .setup-card h3 {
            font-size: 18px;
            font-weight: 700;
            color: var(--text-primary);
            margin: 0;
        }

        .setup-header {
            display: flex;
            align-items: baseline;
            gap: 12px;
            margin-bottom: 20px;
        }

        .setup-header .setup-subtitle {
            color: var(--text-secondary);
            font-size: 13px;
        }

        /* ── Onboarding sections ── */
        .onboard-section {
            margin-bottom: 20px;
        }

        .onboard-section:last-child {
            margin-bottom: 0;
        }

        .onboard-label {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }

        .onboard-label .step-num {
            width: 22px;
            height: 22px;
            background: var(--primary);
            color: white;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            font-weight: 700;
            flex-shrink: 0;
        }

        .onboard-label strong {
            font-size: 13px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .onboard-label .step-hint {
            font-size: 12px;
            color: var(--text-secondary);
            margin-left: auto;
        }

        /* ── Terminal block (steps 1-3 combined) ── */
        .terminal-block {
            background: #1e1e2e;
            border-radius: 8px;
            overflow: hidden;
            font-family: var(--font-mono);
            font-size: 13px;
        }

        .terminal-bar {
            background: #313244;
            padding: 6px 12px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .terminal-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }

        .terminal-dot.r { background: #f38ba8; }
        .terminal-dot.y { background: #f9e2af; }
        .terminal-dot.g { background: #a6e3a1; }

        .terminal-lines {
            padding: 12px 16px;
        }

        .terminal-line {
            display: flex;
            align-items: center;
            padding: 4px 0;
            color: #cdd6f4;
            line-height: 1.6;
        }

        .terminal-line .prompt {
            color: #a6e3a1;
            margin-right: 8px;
            user-select: none;
        }

        .terminal-line .cmd {
            flex: 1;
        }

        .terminal-line .comment {
            color: #6c7086;
            font-size: 12px;
        }

        .terminal-line .btn-copy-term {
            padding: 2px 6px;
            background: transparent;
            border: 1px solid #45475a;
            color: #6c7086;
            cursor: pointer;
            border-radius: 4px;
            font-size: 11px;
            font-family: var(--font-mono);
            margin-left: 8px;
            transition: all 0.15s;
            flex-shrink: 0;
        }

        .terminal-line .btn-copy-term:hover {
            border-color: #89b4fa;
            color: #89b4fa;
        }

        .terminal-line .btn-copy-term.copied {
            border-color: #a6e3a1;
            color: #a6e3a1;
        }

        /* ── Registration inline (step 4) ── */
        .reg-inline {
            background: var(--background);
            border-radius: 8px;
            padding: 16px 20px;
        }

        .reg-inline .reg-row {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .reg-inline .reg-field {
            flex: 1;
        }

        .reg-inline .reg-field label {
            display: block;
            font-size: 12px;
            font-weight: 500;
            color: var(--text-secondary);
            margin-bottom: 4px;
        }

        .reg-inline .reg-field textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 12px;
            resize: none;
            box-sizing: border-box;
        }

        .reg-inline .reg-field textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(0, 115, 209, 0.1);
        }

        .reg-inline .reg-meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 8px;
            font-size: 12px;
            color: var(--text-secondary);
        }

        .reg-inline .username-tag {
            font-family: var(--font-mono);
            font-weight: 600;
            color: var(--primary);
            background: rgba(0, 115, 209, 0.08);
            padding: 2px 8px;
            border-radius: 4px;
        }

        .reg-inline .btn-register {
            padding: 8px 20px;
            background: var(--primary);
            color: white;
            font-size: 13px;
            font-weight: 600;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.15s;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .reg-inline .btn-register:hover {
            background: #005BA3;
        }

        /* ── Claude Code section (step 5) ── */
        .claude-section {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .claude-section .code-inline {
            background: var(--background);
            padding: 8px 14px;
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 13px;
            color: var(--text-primary);
        }

        .btn-copy-v2 {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 18px;
            background: var(--primary);
            color: white;
            font-size: 13px;
            font-weight: 600;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.15s;
        }

        .btn-copy-v2:hover {
            background: #005BA3;
        }

        .btn-copy-v2.copied {
            background: var(--success);
        }

        .claude-hint {
            font-size: 12px;
            color: var(--text-secondary);
            margin-left: auto;
        }

        .helper-text {
            margin-top: 24px;
            font-size: 13px;
            color: var(--text-secondary);
        }

        /* ── Registration Card ── */
        .registration-card h3 {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
            margin: 0 0 16px 0;
        }

        .info-box-v2 {
            background: var(--background);
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .username-preview {
            font-family: var(--font-mono);
            font-weight: 600;
            color: var(--primary);
            margin-left: 8px;
        }

        .form-v2 {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .form-group-v2 label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 6px;
        }

        .form-group-v2 textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 13px;
            resize: vertical;
        }

        .form-group-v2 textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(0, 115, 209, 0.1);
        }

        .form-row-v2 {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .form-info-v2 {
            font-size: 13px;
            color: var(--text-secondary);
        }

        .form-info-v2 code {
            background: var(--background);
            padding: 2px 8px;
            border-radius: 4px;
            font-family: var(--font-mono);
            color: var(--text-primary);
        }

        .btn-v2 {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 500;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.15s;
            text-decoration: none;
            border: none;
        }

        .btn-primary-v2 {
            background: var(--primary);
            color: white;
        }

        .btn-primary-v2:hover {
            background: #005BA3;
        }

        .help-text-v2 {
            font-size: 13px;
            color: var(--text-secondary);
        }

        /* ── Alert ── */
        .alert-v2 {
            padding: 20px;
            border-radius: 8px;
            display: flex;
            gap: 16px;
        }

        .alert-error-v2 {
            background: rgba(234, 88, 12, 0.1);
            border-left: 3px solid var(--error);
        }

        .alert-icon {
            width: 24px;
            height: 24px;
            background: var(--error);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            flex-shrink: 0;
        }

        .alert-v2 h4 {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary);
            margin: 0 0 8px 0;
        }

        .alert-v2 p {
            font-size: 13px;
            color: var(--text-secondary);
            margin: 4px 0;
        }

        .beta-badge {
            display: inline-block;
            padding: 2px 7px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            background: #F3F4F6;
            color: #9CA3AF;
            border: 1px solid #E5E7EB;
            vertical-align: middle;
            margin-left: 6px;
        }

        /* ── Responsive ── */
        @media (max-width: 1100px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
                grid-template-rows: auto;
            }

            .left-column,
            .right-column {
                grid-row: auto;
                grid-template-rows: auto;
                position: static;
            }

            .stats-row {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 700px) {
            .header {
                padding: 0 16px;
            }

            .main {
                padding: 20px 16px 40px;
            }

            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }

            .bottom-row {
                grid-template-columns: 1fr;
            }

            .onboard-label {
                flex-wrap: wrap;
            }

            .onboard-label .step-hint {
                width: 100%;
                margin-left: 30px;
                margin-top: 4px;
            }

            .claude-section {
                flex-wrap: wrap;
            }

            .claude-hint {
                width: 100%;
                margin-left: 0;
            }
        }
    </style>
{% endblock %}

{% block layout %}
    {% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
    <div class="flash-messages">
        {% for category, message in messages %}
        <div class="flash flash-{{ category }}">
            {{ message }}
        </div>
        {% endfor %}
    </div>
    {% endif %}
    {% endwith %}

    {% if user_info.exists %}
    {# ── EXISTING USER ── #}

    <main class="main">

        {% if not account_details or not account_details.last_sync_display %}
        <!-- ═══════════════ ENVIRONMENT SETUP CTA ═══════════════ -->
        <div class="env-setup-cta">
            <h3>Set up a new Claude Code</h3>
            <p class="env-subtitle">Generates a personal access token and copies a ready-to-paste setup script to your clipboard. Paste into Claude Code to finish.</p>
            <div class="env-setup-row">
                <button type="button" onclick="setupNewClaude(this)" class="btn-setup" id="setupClaudeBtn">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                        <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                    </svg>
                    Setup a new Claude Code
                </button>
                <span class="env-meta">
                    <span class="env-hint">Valid 90 days · token stays in clipboard only</span>
                    <a href="/setup" class="env-setup-link">Open the full setup page →</a>
                </span>
            </div>
            <div id="setupClaudeError" class="setup-error" role="alert" style="display:none;"></div>
        </div>
        {% endif %}

        <!-- ═══════════════ STATS ROW ═══════════════ -->
        <div class="stats-row">
            <div class="stat-card">
                <span class="stat-label">Tables</span>
                <span class="stat-value">{{ data_stats.tables }}</span>
            </div>
            <div class="stat-card">
                <span class="stat-label">Columns</span>
                <span class="stat-value">{{ data_stats.columns }}</span>
            </div>
            <div class="stat-card">
                <span class="stat-label">Rows</span>
                <span class="stat-value">{{ data_stats.rows_display }}</span>
            </div>
            <div class="stat-card">
                <span class="stat-label">Data Size</span>
                <span class="stat-value">{{ data_stats.size_display }}</span>
            </div>
        </div>

        <!-- Credit line -->
        <div class="credit-line">
            {{ config.INSTANCE_NAME }}
        </div>

        <!-- ═══════════════ DASHBOARD GRID ═══════════════ -->
        <div class="dashboard-grid">

            <!-- ── Left Column ── -->
            <div class="left-column">

                <div class="bottom-row">

                    <!-- Notifications Card -->
                    <div class="card">
                        <div class="card-header" style="padding-bottom: 0;">
                            <span class="card-title">Notifications</span>
                            <a class="link-manage" onclick="toggleNotifManage(this)">Manage</a>
                        </div>
                        <div class="card-body">
                            <div class="notif-channels">
                                <div class="notif-channel">
                                    <div class="notif-channel-icon telegram">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M22 2L11 13"/>
                                            <path d="M22 2L15 22L11 13L2 9L22 2Z"/>
                                        </svg>
                                    </div>
                                    <div>
                                        <div class="notif-channel-name">Telegram</div>
                                        {% if not telegram_status.linked %}
                                        <span class="notif-status notif-status--inactive">Not linked</span>
                                        {% endif %}
                                    </div>
                                    {% if telegram_status.linked %}
                                    <span class="notif-badge active">Active</span>
                                    <button class="notif-unlink" onclick="unlinkChannel('telegram')">Unlink</button>
                                    {% else %}
                                    <button class="notif-link" onclick="showTelegramVerify()">Link</button>
                                    {% endif %}
                                </div>
                                <div class="notif-channel">
                                    <div class="notif-channel-icon desktop">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                                            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
                                            <line x1="8" y1="21" x2="16" y2="21"/>
                                            <line x1="12" y1="17" x2="12" y2="21"/>
                                        </svg>
                                    </div>
                                    <div style="min-width: 0;">
                                        <div class="notif-channel-name">macOS App</div>
                                        <span class="beta-badge" style="margin-left: 0;">private beta</span>
                                        {% if not desktop_status.linked %}
                                        <span class="notif-status notif-status--inactive">Not linked</span>
                                        {% endif %}
                                    </div>
                                    {% if desktop_status.linked %}
                                    <span class="notif-badge active">Active</span>
                                    <button class="notif-unlink" onclick="unlinkChannel('desktop')">Unlink</button>
                                    {% endif %}
                                </div>
                            </div>
                            <div id="telegramVerify" class="telegram-verify">
                                <ol>
                                    <li>Message <code>/start</code> to <strong>@{{ config.TELEGRAM_BOT_USERNAME or 'your-bot' }}</strong> on Telegram</li>
                                    <li>Enter the verification code below</li>
                                </ol>
                                <div class="telegram-verify-row">
                                    <input type="text" id="verifyCode" placeholder="6-digit code" maxlength="6">
                                    <button onclick="verifyTelegram()" id="verifyBtn">Verify</button>
                                </div>
                                <div id="telegramError" class="telegram-verify-error"></div>
                            </div>
                        </div>
                    </div>


                </div><!-- /bottom-row -->
            </div><!-- /left-column -->

        </div><!-- /dashboard-grid -->

        {% if account_details and account_details.last_sync_display %}
        <div class="setup-link-banner">
            Need to set up another machine? <a href="/setup">Open the setup page →</a>
        </div>
        {% endif %}

    </main>

    {% else %}
    {# ── NEW USER ── #}

    <main class="main">
        <div class="new-user-grid">
            {% if not username_available %}
            <div class="alert-v2 alert-error-v2" style="margin-bottom: 16px;">
                <span class="alert-icon">!</span>
                <div>
                    <h4>Username Not Available</h4>
                    <p>{{ username_error }}</p>
                    <p>Your email generates username <code>{{ username }}</code>, which cannot be used. Contact an administrator.</p>
                </div>
            </div>
            {% endif %}

            <div class="card setup-card">
                <div class="setup-header">
                    <h3>Get Started</h3>
                    <span class="setup-subtitle">Set up your workspace in 4 steps</span>
                </div>

                {# ── Steps 1-3: Terminal commands ── #}
                <div class="onboard-section">
                    <div class="onboard-label">
                        <span class="step-num">1</span>
                        <strong>Create folder</strong>
                        <span class="step-num" style="margin-left: 12px;">2</span>
                        <strong>Generate SSH key</strong>
                        <span class="step-num" style="margin-left: 12px;">3</span>
                        <strong>Copy public key</strong>
                        <span class="step-hint">Run these in your terminal</span>
                    </div>
                    <div class="terminal-block">
                        <div class="terminal-bar">
                            <span class="terminal-dot r"></span>
                            <span class="terminal-dot y"></span>
                            <span class="terminal-dot g"></span>
                        </div>
                        <div class="terminal-lines">
                            <div class="terminal-line">
                                <span class="prompt">$</span>
                                <span class="cmd">mkdir -p {{ project_dir }} && cd {{ project_dir }}</span>
                                <button onclick="copyTermLine(this, 'mkdir -p {{ project_dir }} && cd {{ project_dir }}')" class="btn-copy-term">copy</button>
                            </div>
                            <div class="terminal-line">
                                <span class="prompt">$</span>
                                <span class="cmd">ssh-keygen -t ed25519 -f {{ ssh_key }} -N ''</span>
                                <button onclick="copyTermLine(this, &quot;ssh-keygen -t ed25519 -f {{ ssh_key }} -N ''&quot;)" class="btn-copy-term">copy</button>
                            </div>
                            <div class="terminal-line">
                                <span class="prompt">$</span>
                                <span class="cmd">cat {{ ssh_key }}.pub</span>
                                <button onclick="copyTermLine(this, 'cat {{ ssh_key }}.pub')" class="btn-copy-term">copy</button>
                            </div>
                            <div class="terminal-line">
                                <span class="comment"># Copy the output above and paste it below</span>
                            </div>
                        </div>
                    </div>
                </div>

                {# ── Step 4: Register ── #}
                {% if username_available %}
                <div class="onboard-section">
                    <div class="onboard-label">
                        <span class="step-num">4</span>
                        <strong>Create your account</strong>
                        <span class="step-hint">
                            Username: <span class="username-tag" style="font-family: var(--font-mono); font-weight: 600; color: var(--primary);">{{ username }}</span>
                        </span>
                    </div>
                    <div class="reg-inline">
                        <form action="{{ url_for('register') }}" method="post">
                            <div class="reg-row">
                                <div class="reg-field">
                                    <label for="ssh_key">Paste your SSH public key</label>
                                    <textarea name="ssh_key" id="ssh_key" rows="1"
                                        placeholder="ssh-ed25519 AAAA... or ssh-rsa AAAA..." required></textarea>
                                </div>
                                <button type="submit" class="btn-register">Create Account</button>
                            </div>
                        </form>
                    </div>
                </div>
                {% endif %}

                {# Step 5 (Claude Code setup) appears on dashboard after account creation #}
            </div>
        </div>

        <div class="support-banner" style="margin-top: 16px;">
            {{ config.INSTANCE_NAME }} - need help? Contact your platform team.
        </div>
    </main>
    {% endif %}

    <footer class="footer">
        <p>&copy; {{ now().year if now is defined else 2024 }} {{ config.INSTANCE_COPYRIGHT or 'AI Data Analyst' }}</p>
        </footer>
    {# Setup-CTA JS (copyToClipboard, defaultTokenName, showSetupFallback,
       setupNewClaude) + the SETUP_INSTRUCTIONS_TEMPLATE renderer all live
       in the shared partial below. Both /dashboard and /home include it
       so the clipboard payload, error handling, and fallback modal stay
       in lockstep. The partial exposes copyToClipboard on window so the
       copyCode / copyTermLine helpers below resolve it via global scope. #}
    {% include "_claude_setup_cta.jinja" %}

    <script>
    function copyCode(button, text) {
        var originalHTML = button.innerHTML;
        copyToClipboard(text).then(function() {
            button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg>';
            button.classList.add('copied');
            setTimeout(function() {
                button.innerHTML = originalHTML;
                button.classList.remove('copied');
            }, 2000);
        });
    }

    function copyTermLine(button, text) {
        copyToClipboard(text).then(function() {
            button.textContent = 'done';
            button.classList.add('copied');
            setTimeout(function() {
                button.textContent = 'copy';
                button.classList.remove('copied');
            }, 2000);
        });
    }

    async function updateSyncSettings() {
        const jiraToggle = document.getElementById('toggle-jira');
        const attachmentsToggle = document.getElementById('toggle-jira_attachments');

        // Handle dependency: jira_attachments requires jira
        if (!jiraToggle.checked) {
            attachmentsToggle.checked = false;
            attachmentsToggle.disabled = true;
        } else {
            attachmentsToggle.disabled = false;
        }

        const datasets = {
            jira: jiraToggle.checked,
            jira_attachments: attachmentsToggle.checked
        };

        try {
            const resp = await fetch('/api/sync-settings', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({datasets: datasets})
            });
            if (resp.ok) {
                // Reload to reflect real-time section change
                location.reload();
            }
        } catch (e) {
            console.error('Failed to update settings:', e);
        }
    }

    // Load Corporate Memory stats
    async function loadMemoryStats() {
        try {
            const resp = await fetch('/api/memory/stats');
            if (resp.ok) {
                const data = await resp.json();
                document.getElementById('memoryKnowledgeCount').textContent = data.total || 0;
                const approved = (data.by_status && data.by_status.approved) || 0;
                const mandatory = (data.by_status && data.by_status.mandatory) || 0;
                document.getElementById('memoryContributors').textContent = approved + mandatory;
                document.getElementById('memoryYourRules').textContent = mandatory || 0;
            }
        } catch (e) {
            // Silently fail - widget will show defaults
            console.log('Could not load memory stats:', e);
        }
    }

    // Load memory stats on page load. Memory is admin-only, so non-admin
    // visitors never see the widget — skip the fetch to avoid pointless
    // 401s in their console.
    {% if user_info.exists and session.user.is_admin %}
    document.addEventListener('DOMContentLoaded', loadMemoryStats);
    {% endif %}

    // Notification management
    function toggleNotifManage(link) {
        const channels = link.closest('.card').querySelector('.notif-channels');
        const managing = channels.classList.toggle('notif-managing');
        link.textContent = managing ? 'Done' : 'Manage';
        link.classList.toggle('active', managing);
        // Hide verify panel when exiting manage mode
        if (!managing) {
            document.getElementById('telegramVerify').classList.remove('visible');
        }
    }

    function showTelegramVerify() {
        document.getElementById('telegramVerify').classList.toggle('visible');
    }

    async function verifyTelegram() {
        const code = document.getElementById('verifyCode').value.trim();
        const errorEl = document.getElementById('telegramError');
        const btn = document.getElementById('verifyBtn');
        errorEl.style.display = 'none';

        if (!code || code.length !== 6) {
            errorEl.textContent = 'Please enter a 6-digit code.';
            errorEl.style.display = 'block';
            return;
        }

        btn.disabled = true;
        btn.textContent = 'Verifying...';

        try {
            const resp = await fetch('/api/telegram/verify', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({code: code})
            });
            const data = await resp.json();

            if (resp.ok) {
                location.reload();
            } else {
                errorEl.textContent = data.error || 'Verification failed.';
                errorEl.style.display = 'block';
            }
        } catch (e) {
            errorEl.textContent = 'Network error. Please try again.';
            errorEl.style.display = 'block';
        }

        btn.disabled = false;
        btn.textContent = 'Verify';
    }

    async function unlinkChannel(channel) {
        const label = channel === 'telegram' ? 'Telegram' : 'macOS App';
        if (!confirm(`Unlink ${label}? You will stop receiving notifications.`)) return;
        try {
            const resp = await fetch(`/api/${channel}/unlink`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            });
            if (resp.ok) {
                location.reload();
            } else {
                const data = await resp.json();
                alert(data.error || 'Failed to unlink.');
            }
        } catch (e) {
            console.error('Unlink failed:', e);
            alert('Failed to unlink. Please try again.');
        }
    }
    </script>
{% endblock %}
