<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

$page_title = 'Inicio · Vale';
$extra_head = <<<'CSS'
<style>
:root{
  --rust:#A8392A;--rust-soft:#c9785f;
  --cocoa:#3B2F27;--ink:#33302B;--muted:#897D70;
  --cream:#F4ECE0;--cream2:#FBF4E8;
  --gold:#C9962F;--ok:#3F7A52;
  --d1:#241a14;--d2:#0c0a08;
  --r:18px;
}
/* ── Saludo ── */
.dash-top{padding:18px 20px 22px;display:block;background:linear-gradient(180deg,var(--d1),var(--d2));margin-bottom:0}
.dash-date{font-size:13px;color:#cdbfb2;font-weight:600;margin-bottom:4px}
.dash-biz{font-family:'Fraunces',serif;font-weight:600;font-size:30px;line-height:1.05;color:#fff;letter-spacing:-.3px;margin:0}
/* ── Scroll body oscuro ── */
.dash-scroll{flex:1;overflow-y:auto;padding:16px 16px 100px;background:linear-gradient(180deg,var(--d2) 0%,#2a1c15 38%,#5b2e22 100%)}
/* ── Vale Hoy card ── */
.vale-hoy{border:1px solid var(--rust-soft);border-radius:var(--r);background:rgba(0,0,0,.18);padding:16px 18px;margin-bottom:13px}
.vh-k{font:600 11px/1 'Hanken Grotesk';letter-spacing:.18em;text-transform:uppercase;color:var(--rust-soft);margin-bottom:8px}
.vh-line{color:#fff;font-size:15px;font-weight:600;line-height:1.35;margin-bottom:14px}
.vh-stats{display:flex;gap:10px;border-top:1px solid rgba(255,255,255,.12);padding-top:13px}
.vh-stat{flex:1}
.vh-num{font:600 30px/1 'Fraunces';color:#fff}
.vh-lab{color:#c2b3a6;font-size:11px;margin-top:5px;line-height:1.25}
/* ── Próxima cita (dark) ── */
.next-card{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);border-radius:var(--r);padding:14px 16px;margin-bottom:13px;display:flex;align-items:center;gap:12px}
.nx-time{font-family:'Fraunces',serif;font-weight:600;font-size:20px;color:var(--rust-soft);flex:none;line-height:1;text-align:center}
.nx-time small{display:block;font-family:'Hanken Grotesk',sans-serif;font-size:10.5px;font-weight:700;color:#c2b3a6;letter-spacing:.3px;margin-top:2px}
.nx-name{font-size:15px;font-weight:700;color:#fff}
.nx-svc{font-size:12.5px;color:#c2b3a6;margin-top:2px}
.nx-badge{margin-left:auto;background:rgba(201,120,95,.2);color:var(--rust-soft);font-size:11px;font-weight:700;padding:4px 9px;border-radius:99px;white-space:nowrap;flex:none}
/* ── Action cards ── */
.action-list{margin-bottom:13px}
.action-card{display:flex;align-items:center;gap:14px;border-radius:var(--r);padding:15px 18px;margin-bottom:11px;text-decoration:none;color:var(--ink);width:100%;cursor:pointer;transition:opacity .15s;text-align:left;font-family:inherit;border:none}
.action-card:nth-child(odd){background:var(--cream)}
.action-card:nth-child(even){background:#fff}
.action-card:active{opacity:.82}
.ac-ico{color:var(--rust);flex-shrink:0;display:flex}
.ac-label{flex:1;font-size:16px;font-weight:600;color:var(--ink)}
.ac-badge{font-size:12px;font-weight:600;padding:6px 12px;border-radius:20px;white-space:nowrap;flex:none}
.ac-badge.cta{background:var(--rust-soft);color:#fff}
.ac-badge.ghost{background:rgba(168,57,42,.15);color:var(--rust)}
.ac-badge.dim{background:rgba(168,57,42,.08);color:var(--muted)}
/* ── Actividades recientes ── */
.recent-card{border:1px solid var(--rust-soft);border-radius:var(--r);padding:15px 18px;background:rgba(0,0,0,.18);margin-bottom:13px}
.recent-h{margin:0;color:#fff;font:600 16px/1 'Hanken Grotesk'}
.recent-sub{color:#c2b3a6;font-size:12px;margin:3px 0 12px}
.recent-row{display:flex;align-items:flex-start;gap:11px;padding:11px 0;border-top:1px solid rgba(255,255,255,.1)}
.recent-row:first-of-type{border-top:0;padding-top:0}
.recent-check{color:var(--gold);flex-shrink:0;margin-top:1px}
.recent-txt{flex:1;color:#efe6dc;font-size:13.5px;line-height:1.3}
.recent-time{display:block;color:#a8978a;font-size:11.5px;margin-top:2px}
.recent-empty{color:#c2b3a6;font-size:13.5px;line-height:1.55;padding:6px 0 4px}
/* ── Config section (dark) ── */
.feed{background:rgba(255,255,255,.05);border-radius:var(--r);padding:16px 18px 6px;border:1px solid rgba(255,255,255,.1);margin-bottom:13px}
.feed-h{font-family:'Fraunces',serif;font-weight:600;font-size:17px;letter-spacing:-.2px;margin-bottom:2px;color:#fff}
.feed-sub{font-size:12px;color:#c2b3a6;margin-bottom:0}
.act{display:flex;align-items:center;gap:11px;padding:10px 0;border-top:1px solid rgba(255,255,255,.08)}
.act:first-of-type{border-top:none}
.act-ic{width:30px;height:30px;border-radius:99px;display:flex;align-items:center;justify-content:center;flex:none}
.act-body{font-size:13.5px;font-weight:600;flex:1;min-width:0;color:#efe6dc}
.act-body small{display:block;font-weight:400;color:#a8978a;font-size:12px;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.act-time{font-size:11.5px;color:#a8978a;flex:none;font-weight:600}
.chip{display:inline-flex;align-items:center;font-size:11.5px;font-weight:700;padding:4px 9px;border-radius:99px;margin-top:0;width:fit-content}
.chip.alert{background:rgba(168,57,42,.28);color:#f5a090}.chip.ok{background:rgba(31,168,85,.22);color:#7ddba0}.chip.dim{background:rgba(255,255,255,.1);color:#c2b3a6}
.empty-feed{text-align:center;padding:18px 0 12px;color:#c2b3a6;font-size:13.5px;line-height:1.55}
</style>
CSS;

ob_start();
?>
<div class="dashboard-container">
    <?php $activeNav = 'inicio'; require __DIR__ . '/partials/sidebar.php'; ?>

    <main class="main-content">
        <?php if (!empty($upgradePlan)): ?>
            <?php $planLabels = ['growth'=>'Growth ($29/mes)','pro'=>'Pro ($69/mes)']; ?>
            <div style="background:#3B2F27;color:#F4EDE3;padding:.75rem 1.2rem;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">
                <span style="font-size:.9rem;">🎉 ¡Tu negocio está listo! Activá el plan <strong><?= $planLabels[$upgradePlan] ?></strong> para desbloquear todas las funciones.</span>
                <a href="/billing?plan=<?= htmlspecialchars($upgradePlan) ?>" style="background:#A8331A;color:#fff;padding:.4rem 1rem;border-radius:8px;font-size:.85rem;font-weight:700;text-decoration:none;white-space:nowrap;">Activar ahora →</a>
            </div>
        <?php endif; ?>
        <?php if (!empty($_SESSION['impersonated_by_admin'])): ?>
            <div style="background:#E0A33E;color:#221C18;padding:.5rem 1rem;font-size:.85rem;display:flex;justify-content:space-between;align-items:center;">
                <span>Estás viendo como <strong><?= htmlspecialchars($_SESSION['tenant_name'] ?? 'negocio') ?></strong> (impersonación de admin).</span>
                <a href="/admin/stop-impersonate" style="color:#A8331A;font-weight:600;">Salir</a>
            </div>
        <?php endif; ?>

        <!-- Saludo -->
        <div class="dash-top">
            <div class="dash-date"><?= htmlspecialchars($greeting) ?> · <?= ucfirst($dayName) . ' ' . date('d') . ' de ' . (['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'][(int)date('n')-1]) ?></div>
            <div class="dash-biz"><?= htmlspecialchars($bizName) ?></div>
        </div>

        <!-- Scrollable content -->
        <div class="dash-scroll">

            <!-- Vale Hoy -->
            <div class="vale-hoy">
                <div class="vh-k">Vale hoy</div>
                <div class="vh-line">
                    <?php if ($ai_replies > 0): ?>
                        Respondió <b><?= $ai_replies ?> <?= $ai_replies === 1 ? 'mensaje' : 'mensajes' ?></b><?php if ($appts_today > 0): ?> y agendó <b><?= $appts_today ?> <?= $appts_today === 1 ? 'cita' : 'citas' ?></b><?php endif; ?> por vos.
                    <?php else: ?>
                        Todo tranquilo. Vale está activo y listo para atender.
                    <?php endif; ?>
                </div>
                <div class="vh-stats">
                    <div class="vh-stat">
                        <div class="vh-num"><?= $ai_replies ?></div>
                        <div class="vh-lab">Mensajes hoy</div>
                    </div>
                    <div class="vh-stat">
                        <div class="vh-num"><?= $week_replies ?></div>
                        <div class="vh-lab">Esta semana</div>
                    </div>
                    <div class="vh-stat">
                        <div class="vh-num"><?= $open_convs ?></div>
                        <div class="vh-lab">Conversaciones abiertas</div>
                    </div>
                </div>
            </div>

            <!-- Próxima cita -->
            <?php if ($next_appt): ?>
            <div class="next-card">
                <div class="nx-time">
                    <?= date('H:i', strtotime($next_appt['scheduled_at'])) ?>
                    <small><?php
                        $ts = strtotime($next_appt['scheduled_at']); $diff = $ts - time();
                        if ($diff < 3600) echo 'en ' . round($diff/60) . ' min';
                        elseif (date('Y-m-d',$ts) === date('Y-m-d')) echo 'hoy';
                        else echo date('d/m', $ts);
                    ?></small>
                </div>
                <div>
                    <div class="nx-name"><?= htmlspecialchars($next_appt['contact_name']) ?></div>
                    <?php if (!empty($next_appt['service_name'])): ?>
                        <div class="nx-svc"><?= htmlspecialchars($next_appt['service_name']) ?></div>
                    <?php endif; ?>
                </div>
                <span class="nx-badge">Próxima cita</span>
            </div>
            <?php endif; ?>

            <!-- Cards de acción -->
            <div class="action-list">
                <button class="action-card" onclick="vcOpen()">
                    <span class="ac-ico">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                    </span>
                    <span class="ac-label">Hablar con Vale</span>
                    <span class="ac-badge cta">Empieza aquí</span>
                </button>

                <a href="/clientes" class="action-card">
                    <span class="ac-ico">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
                    </span>
                    <span class="ac-label">Leads y contactos</span>
                    <span class="ac-badge <?= $leads_new > 0 ? 'cta' : 'ghost' ?>"><?= $leads_new > 0 ? "$leads_new nuevo" . ($leads_new > 1 ? 's' : '') : 'Al día' ?></span>
                </a>

                <a href="/agenda" class="action-card">
                    <span class="ac-ico">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="3"/><path d="M3 9h18M8 2v4M16 2v4"/></svg>
                    </span>
                    <span class="ac-label">Citas del día</span>
                    <span class="ac-badge <?= $appts_today > 0 ? 'cta' : 'ghost' ?>"><?= $appts_today > 0 ? "$appts_today hoy" : 'Sin citas' ?></span>
                </a>

                <a href="/mensajes" class="action-card">
                    <span class="ac-ico">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.5 8.5 0 01-12.3 7.6L3 20.5l1.5-5.2A8.5 8.5 0 1121 11.5z"/></svg>
                    </span>
                    <span class="ac-label">Conversaciones</span>
                    <span class="ac-badge <?= $open_convs > 0 ? 'cta' : 'ghost' ?>"><?= $open_convs > 0 ? "$open_convs nuevo" . ($open_convs > 1 ? 's' : '') : 'Al día' ?></span>
                </a>
            </div>

            <!-- Actividades recientes -->
            <div class="recent-card">
                <p class="recent-h">Actividades recientes</p>
                <p class="recent-sub">Lo que Vale maneja por vos</p>
                <?php if (empty($recent)): ?>
                    <p class="recent-empty">Todavía no hay actividad.<br>Vale mostrará los mensajes que atienda acá.</p>
                <?php else: ?>
                    <?php foreach ($recent as $r):
                        $name = $r['cname'] ?: $r['cphone'] ?: 'Cliente';
                        $isAI = $r['sender'] === 'ai';
                        $ts   = strtotime($r['created_at']); $diff = time() - $ts;
                        if ($diff < 60)        $ago = 'ahora';
                        elseif ($diff < 3600)  $ago = round($diff/60) . ' min';
                        elseif ($diff < 86400) $ago = round($diff/3600) . ' h';
                        else                   $ago = date('d/m', $ts);
                        $preview = mb_substr($r['last_msg'], 0, 60) . (mb_strlen($r['last_msg']) > 60 ? '…' : '');
                    ?>
                    <div class="recent-row">
                        <span class="recent-check">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 13l4 4L19 7"/></svg>
                        </span>
                        <div class="recent-txt">
                            <?php if ($isAI): ?>Vale respondió a <strong><?= htmlspecialchars($name) ?></strong>
                            <?php else: ?>Mensaje de <strong><?= htmlspecialchars($name) ?></strong><?php endif; ?>
                            <time class="recent-time"><?= htmlspecialchars($preview) ?> · <?= $ago ?></time>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Terminá de configurar -->
            <div class="feed">
                <div class="feed-h">Terminá de configurar</div>
                <div class="feed-sub">Cuando quieras, sin apuro. Vale ya funciona.</div>

                <div class="act">
                    <div class="act-ic" style="background:#E3F5EA">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="#1FA855"><path d="M12 2a10 10 0 00-8.6 15L2 22l5.2-1.4A10 10 0 1012 2z"/></svg>
                    </div>
                    <div class="act-body">WhatsApp<small>Vale responde automáticamente</small></div>
                    <?php if ($metaConnected): ?>
                        <span class="chip ok" style="margin-top:0;flex:none">Activo</span>
                    <?php else: ?>
                        <a href="/ajustes" class="chip alert" style="margin-top:0;flex:none;text-decoration:none">Conectar</a>
                    <?php endif; ?>
                </div>

                <div class="act">
                    <div class="act-ic" style="background:#FBF1DD">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#C9962F" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
                    </div>
                    <div class="act-body">Mi negocio<small>Servicios, horarios y perfil</small></div>
                    <?php if ($knowledgeDone): ?>
                        <span class="chip ok" style="margin-top:0;flex:none">Listo</span>
                    <?php else: ?>
                        <a href="/negocio" class="chip alert" style="margin-top:0;flex:none;text-decoration:none">Completar</a>
                    <?php endif; ?>
                </div>

                <div class="act">
                    <div class="act-ic" style="background:#F6E7E3">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#A8331A" stroke-width="2" stroke-linecap="round"><rect x="3" y="4.5" width="18" height="16" rx="3"/><path d="M3 9h18M8 2.5v4M16 2.5v4"/></svg>
                    </div>
                    <div class="act-body">Google Calendar<small>Para agendar sin choques</small></div>
                    <?php if ($calConnected): ?>
                        <span class="chip ok" style="margin-top:0;flex:none">Conectado</span>
                    <?php else: ?>
                        <a href="/auth/google/calendar" class="chip alert" style="margin-top:0;flex:none;text-decoration:none">Conectar</a>
                    <?php endif; ?>
                </div>

                <?php if ($publicSlug):
                    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') ? 'https' : 'http';
                    $publicUrl = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? '') . '/n/' . rawurlencode($publicSlug);
                ?>
                <div class="act">
                    <div class="act-ic" style="background:#EEF1F7">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#5a6b8c" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 010 20M12 2a15 15 0 000 20"/></svg>
                    </div>
                    <div class="act-body">Página pública<small><?= htmlspecialchars($publicUrl) ?></small></div>
                    <a href="<?= htmlspecialchars($publicUrl) ?>" target="_blank" class="chip ok" style="margin-top:0;flex:none;text-decoration:none">Ver</a>
                </div>
                <?php endif; ?>
            </div>

        </div><!-- /dash-scroll -->
    </main>
</div>

<?php require __DIR__ . '/partials/vale_chat.php'; ?>

<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/views/layout.php';
