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

// ── Vars básicos ──────────────────────────────────────────────────────────────
$bizName   = htmlspecialchars($tenant['name'] ?? 'Negocio');
$monogram  = mb_strtoupper(mb_substr($tenant['name'] ?? 'N', 0, 1, 'UTF-8'));
$rubro     = strtolower($tenant['rubro'] ?? $tenant['business_type'] ?? '');
$publicKey = $tenant['web_public_key'] ?? '';
$plan      = $tenant['plan']           ?? 'free';
$desc_es   = $tenant['descripcion']    ?? '';
$desc_en   = $tenant['descripcion_en'] ?? '';
$ciudad    = $tenant['ciudad']         ?? '';
$horasRow  = $horasTexto               ?? '';
$logoUrl   = $tenant['logo_url']       ?? '';
$bannerUrl = $tenant['banner_url']     ?? '';

// ── WhatsApp deep link ────────────────────────────────────────────────────────
$waRaw    = preg_replace('/[^0-9]/', '', $tenant['whatsapp_number'] ?? '');
$useWa    = $waRaw !== '';
$waText   = 'Hola ' . ($tenant['name'] ?? '') . ', me gustaría reservar un servicio.';
$waLink   = $useWa ? 'https://wa.me/' . $waRaw . '?text=' . rawurlencode($waText) : '#';

// ── Colores de marca ──────────────────────────────────────────────────────────
$colorP   = $tenant['color_primario']   ?? null;
$colorA   = $tenant['color_acento']     ?? null;
$colorCta = $tenant['color_texto_cta']  ?? '#ffffff';
$tenantCss = '';
if ($colorP && preg_match('/^#[0-9A-Fa-f]{6}$/', $colorP)) {
    // Versión oscura para hover (88% del valor RGB)
    $hex = ltrim($colorP, '#');
    $dk  = sprintf('#%02x%02x%02x',
        (int)(hexdec(substr($hex,0,2)) * 0.88),
        (int)(hexdec(substr($hex,2,2)) * 0.88),
        (int)(hexdec(substr($hex,4,2)) * 0.88)
    );
    $acento = ($colorA && preg_match('/^#[0-9A-Fa-f]{6}$/', $colorA)) ? $colorA : '#DDA02C';
    $tenantCss = "<style>:root{"
        . "--terracota:{$colorP};--terra-dk:{$dk};--amber:{$acento};--cta-txt:" . htmlspecialchars($colorCta) . ";"
        . "}</style>";
}

// ── Hooks por rubro ───────────────────────────────────────────────────────────
$hooks = [
    'barberia'    => ['es' => 'Tu mejor corte,<br>reservado en un mensaje.', 'en' => 'Your best cut,<br>booked in one message.'],
    'odontologia' => ['es' => 'Tu cita dental,<br>agendada al instante.',    'en' => 'Your appointment,<br>booked instantly.'],
    'belleza'     => ['es' => 'Tu turno de belleza,<br>sin llamar.',          'en' => 'Your beauty appointment,<br>no calls needed.'],
];
$hook_es  = $hooks[$rubro]['es'] ?? 'Reservá en un mensaje,<br>a cualquier hora.';
$hook_en  = $hooks[$rubro]['en'] ?? 'Book in one message,<br>anytime.';

// ── CTA label por rubro ───────────────────────────────────────────────────────
$ctaLabel_es = match($rubro) {
    'barberia', 'belleza' => 'Reservar por WhatsApp',
    'odontologia'         => 'Agendar cita por WhatsApp',
    default               => 'Hablar con Vale',
};
$ctaLabel_en = match($rubro) {
    'barberia', 'belleza' => 'Book via WhatsApp',
    'odontologia'         => 'Book appointment via WhatsApp',
    default               => 'Chat with Vale',
};

// ── Estado abierto/cerrado ────────────────────────────────────────────────────
// $isOpen viene del controlador (null | true | false)
$statusEs = match(true) {
    $isOpen === true  => 'Abierto ahora · responde al instante',
    $isOpen === false => 'Cerrado ahora',
    default           => null,
};
$statusEn = match(true) {
    $isOpen === true  => 'Open now · responds instantly',
    $isOpen === false => 'Closed now',
    default           => null,
};
?>
<!DOCTYPE html>
<html lang="es" id="htmlRoot">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $bizName ?> · <?= $ciudad ? htmlspecialchars($ciudad) . ' · ' : '' ?>Vale</title>
<meta name="description" content="<?= htmlspecialchars($desc_es ?: 'Reservá por WhatsApp con ' . ($tenant['name'] ?? 'este negocio') . '. Vale AI atiende al instante.') ?>">
<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=Fraunces:opsz,wght@9..144,400;9..144,500&family=Hanken+Grotesk:wght@400;500&display=swap" rel="stylesheet">
<?= $tenantCss ?>
<style>
:root{
  --bg:#F6F0E6;--ink-bg:#1E1C17;--card:#FFFFFF;--terracota:#A23D2C;--terra-dk:#8A3324;
  --ink:#211C16;--muted:#8C8275;--hairline:#E8DFD1;--green:#2E7D5B;--green-bg:#E4F0E8;
  --pill:#F0E4D6;--amber-bg:#FAEEDA;--amber-tx:#9A6A14;--amber:#DDA02C;--r:16px;
  --cta-txt:#ffffff;
}
*{box-sizing:border-box}
html{overflow-x:hidden}
body{margin:0;background:var(--bg);color:var(--ink);overflow-x:hidden;
  font-family:"Hanken Grotesk",-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
.serif{font-family:"Fraunces",Georgia,serif;font-weight:400}
.ctr{max-width:760px;margin:0 auto;padding:0 24px}
a{color:inherit;text-decoration:none}

/* ── header ── */
header{position:sticky;top:0;z-index:20;background:rgba(246,240,230,.88);backdrop-filter:blur(8px);
  border-bottom:.5px solid var(--hairline)}
.hd{display:flex;align-items:center;justify-content:space-between;padding:11px 24px;max-width:760px;margin:0 auto}
.biz{display:flex;align-items:center;gap:10px}
.biz-ic{width:34px;height:34px;border-radius:9px;background:var(--terracota);color:var(--cta-txt);
  display:flex;align-items:center;justify-content:center;font-family:"Fraunces",serif;font-size:17px;
  overflow:hidden;flex:none}
.biz-ic img{width:100%;height:100%;object-fit:cover}
.biz-nm{font-weight:500;font-size:14px}
.biz-sub{font-size:11px;color:var(--muted)}
.lang{display:flex;gap:2px}
.lang span{font-size:12px;padding:5px 10px;border-radius:999px;cursor:pointer;user-select:none}
.lang .on{background:var(--ink-bg);color:#F6F0E6}
.lang .off{color:var(--muted)}

/* ── hero ── */
.hero{text-align:center;padding:54px 24px 8px}
.eyebrow{display:inline-flex;align-items:center;gap:7px;font-size:13px;border-radius:999px;padding:5px 13px;margin-bottom:22px}
.eyebrow.open{color:var(--green);background:var(--green-bg)}
.eyebrow.closed{color:var(--muted);background:rgba(230,220,210,.7)}
.eyebrow .dot{width:7px;height:7px;border-radius:50%;background:currentColor}
.hero h1{font-family:"Fraunces",serif;font-weight:400;font-size:clamp(32px,7vw,48px);
  line-height:1.05;letter-spacing:-0.015em;margin:0 0 16px}
.hero .lede{font-size:17px;color:var(--muted);margin:0 auto 30px;max-width:460px;line-height:1.55}
.cta-btn{display:inline-flex;align-items:center;gap:10px;background:var(--terracota);
  color:var(--cta-txt);text-decoration:none;font-weight:500;font-size:17px;
  padding:16px 34px;border-radius:14px;
  box-shadow:0 8px 22px rgba(162,61,44,.24);transition:.18s;border:none;cursor:pointer;
  font-family:inherit}
.cta-btn:hover{transform:translateY(-2px);background:var(--terra-dk);box-shadow:0 12px 28px rgba(162,61,44,.3)}
.undercta{font-size:13px;color:var(--muted);margin:14px 0 0}

/* ── trust band ── */
.trust{display:flex;justify-content:center;gap:24px;flex-wrap:wrap;
  padding:32px 24px;border-top:.5px solid var(--hairline);border-bottom:.5px solid var(--hairline);margin-top:40px}
.trust-item{display:flex;align-items:center;gap:9px;font-size:14px;color:var(--ink)}
.trust-item svg{color:var(--terracota);flex:none}

/* ── secciones ── */
.sec{padding:44px 24px}
.sec h2{font-family:"Fraunces",serif;font-weight:400;font-size:26px;text-align:center;margin:0 0 32px}

/* steps */
.steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:20px}
.step{text-align:center}
.step-n{width:40px;height:40px;border-radius:50%;background:var(--terracota);color:var(--cta-txt);
  font-family:"Fraunces",serif;font-size:18px;display:flex;align-items:center;justify-content:center;
  margin:0 auto 14px}
.step h3{font-size:15px;font-weight:500;margin:0 0 6px}
.step p{font-size:13.5px;color:var(--muted);margin:0;line-height:1.5}

/* services */
.panel{background:var(--card);border:.5px solid var(--hairline);border-radius:var(--r);padding:26px}
.panel h2{font-family:"Fraunces",serif;font-weight:400;font-size:22px;margin:0 0 18px;text-align:left}
.svcs{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}
.svc{background:var(--bg);border:.5px solid var(--hairline);border-radius:12px;padding:14px}
.svc-name{font-weight:500;font-size:14px;margin:0 0 8px;line-height:1.3}
.pills{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}
.pill{font-size:12px;border-radius:999px;padding:3px 10px;background:var(--pill);color:#6B6457}
.pill.price{background:var(--amber-bg);color:var(--amber-tx);font-weight:500}
.svc-desc{font-size:12.5px;color:var(--muted);line-height:1.5;margin:0}

/* final cta */
.final{background:var(--ink-bg);color:#F6F0E6;text-align:center;
  padding:52px 24px;border-radius:var(--r);margin:0 20px 10px}
.final h2{font-family:"Fraunces",serif;font-weight:400;font-size:28px;margin:0 0 20px;color:#F6F0E6}

/* footer */
.pub-foot{text-align:center;color:var(--muted);font-size:13px;padding:28px 24px 110px}
.pub-foot a{color:var(--muted);text-decoration:underline}
.vale-seal{display:inline-flex;align-items:center;gap:5px;font-weight:600;font-size:12px}

/* floating FAB */
.fab{position:fixed;right:20px;bottom:20px;z-index:30;
  display:inline-flex;align-items:center;gap:9px;
  background:var(--terracota);color:var(--cta-txt);text-decoration:none;
  font-weight:500;font-size:15px;padding:14px 22px;border-radius:999px;
  box-shadow:0 10px 26px rgba(162,61,44,.35);transition:.18s}
.fab:hover{background:var(--terra-dk)}
@media(max-width:600px){.hero h1{font-size:32px}.fab span.txt{display:none}.fab{padding:16px;border-radius:50%}}

/* chat drawer (fallback si no hay WA) */
.pub-overlay{display:none;position:fixed;inset:0;background:rgba(34,28,24,.4);backdrop-filter:blur(3px);z-index:200}
.pub-overlay.show{display:block}
.pub-chat-wrap{position:fixed;bottom:20px;right:20px;z-index:201}
.pub-chat-fab{width:54px;height:54px;border-radius:99px;background:var(--terracota);color:var(--cta-txt);
  border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;
  box-shadow:0 8px 24px rgba(162,61,44,.5);transition:.18s}
.pub-chat-fab:hover{transform:scale(1.07)}
.pub-chat-drawer{position:fixed;bottom:0;left:0;right:0;height:82dvh;background:#FFFDF9;
  border-radius:26px 26px 0 0;display:flex;flex-direction:column;z-index:201;
  transform:translateY(110%);transition:transform .35s cubic-bezier(.2,.8,.2,1);
  box-shadow:0 -20px 50px rgba(34,28,24,.18);overflow:hidden}
.pub-chat-drawer.open{transform:translateY(0)}
@media(min-width:680px){
  .pub-chat-wrap{bottom:32px;right:32px}
  .pub-chat-drawer{bottom:0;top:0;right:0;left:auto;width:400px;height:100dvh;border-radius:26px 0 0 26px;transform:translateX(110%)}
  .pub-chat-drawer.open{transform:translateX(0)}
}
.pch-head{background:var(--ink-bg);color:#fff;padding:14px 18px;display:flex;align-items:center;gap:11px;flex:none;min-width:0}
.pch-av{width:40px;height:40px;border-radius:99px;background:var(--terracota);display:flex;align-items:center;justify-content:center;font-family:"Fraunces",serif;font-weight:600;font-size:18px;flex:none}
.pch-ttl{font-family:"Fraunces",serif;font-weight:600;font-size:17px;color:var(--amber)}
.pch-hinfo{flex:1;min-width:0;overflow:hidden}
.pch-cls{flex:none;background:rgba(255,255,255,.1);border:none;color:#fff;width:30px;height:30px;border-radius:99px;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.pch-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:8px;background:#F6F0E8}
.pch-bubble{max-width:82%;padding:10px 14px;border-radius:16px;font-size:14.5px;line-height:1.5;word-wrap:break-word}
.pch-in{align-self:flex-start;background:#fff;border-bottom-left-radius:4px;box-shadow:0 2px 6px rgba(34,28,24,.06)}
.pch-out{align-self:flex-end;background:var(--terracota);color:var(--cta-txt);border-bottom-right-radius:4px}
.pch-typing{align-self:flex-start;background:#fff;border-radius:16px;border-bottom-left-radius:4px;padding:12px 14px;display:flex;gap:5px;align-items:center}
.pch-typing span{width:6px;height:6px;border-radius:99px;background:var(--muted);animation:pDot 1.2s infinite}
.pch-typing span:nth-child(2){animation-delay:.2s}.pch-typing span:nth-child(3){animation-delay:.4s}
@keyframes pDot{0%,100%{opacity:.3;transform:translateY(0)}50%{opacity:1;transform:translateY(-4px)}}
.pch-form{display:flex;gap:8px;padding:10px 12px;padding-bottom:max(10px,env(safe-area-inset-bottom,10px));border-top:1px solid var(--hairline);background:#FFFDF9;flex:none}
.pch-form input{flex:1;border:1px solid var(--hairline);border-radius:20px;padding:10px 14px;font-size:14.5px;font-family:inherit;outline:none;background:#fff;transition:border-color .15s}
.pch-form input:focus{border-color:var(--terracota)}
.pch-send{width:42px;height:42px;border-radius:99px;background:var(--terracota);border:none;color:var(--cta-txt);cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}
.pch-chips{align-self:flex-start;display:flex;flex-wrap:wrap;gap:6px;max-width:88%}
.pch-chip{padding:7px 14px;border-radius:20px;border:1.5px solid var(--terracota);background:#fff;color:var(--terracota);font-family:inherit;font-size:13.5px;cursor:pointer;transition:background .15s,color .15s}
.pch-chip:hover{background:var(--terracota);color:var(--cta-txt)}
</style>
</head>
<body>

<!-- ── Header ── -->
<header>
  <div class="hd">
    <div class="biz">
      <div class="biz-ic">
        <?php if ($logoUrl): ?>
          <img src="<?= htmlspecialchars($logoUrl) ?>" alt="<?= $bizName ?>">
        <?php else: ?>
          <?= htmlspecialchars($monogram) ?>
        <?php endif; ?>
      </div>
      <div>
        <div class="biz-nm"><?= $bizName ?></div>
        <div class="biz-sub" id="valeLabel">Atendido por Vale</div>
      </div>
    </div>
    <div style="display:flex;align-items:center;gap:12px">
      <div class="lang">
        <span class="on" id="btnEs" onclick="setLang('es')">ES</span>
        <span class="off" id="btnEn" onclick="setLang('en')">EN</span>
      </div>
    </div>
  </div>
</header>

<!-- ── Hero ── -->
<section class="hero">
  <?php if ($statusEs): ?>
    <span class="eyebrow <?= $isOpen ? 'open' : 'closed' ?>">
      <?php if ($isOpen): ?><span class="dot"></span><?php endif; ?>
      <span class="i18n" data-es="<?= htmlspecialchars($statusEs) ?>" data-en="<?= htmlspecialchars($statusEn) ?>"><?= htmlspecialchars($statusEs) ?></span>
    </span><br>
  <?php endif; ?>

  <h1 class="serif i18n"
      data-es="<?= $hook_es ?>"
      data-en="<?= $hook_en ?>"><?= $hook_es ?></h1>

  <p class="lede i18n"
     data-es="<?= htmlspecialchars($desc_es ?: 'Escribile a ' . ($tenant['name'] ?? '') . ' por WhatsApp y Vale te atiende al momento: horarios, precios y agenda. Sin llamar, sin esperar.') ?>"
     data-en="<?= htmlspecialchars($desc_en ?: 'Message ' . ($tenant['name'] ?? '') . ' on WhatsApp and Vale responds instantly: schedules, prices, and bookings. No calls, no waiting.') ?>">
    <?= htmlspecialchars($desc_es ?: 'Escribile a ' . ($tenant['name'] ?? '') . ' por WhatsApp y Vale te atiende al momento: horarios, precios y agenda. Sin llamar, sin esperar.') ?>
  </p>

  <?php if ($useWa): ?>
    <a class="cta-btn" href="<?= htmlspecialchars($waLink) ?>" target="_blank" rel="noopener">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.38 8.38 0 0 1-4-1L3 20l1-5.5a8.38 8.38 0 0 1-1-4A8.5 8.5 0 0 1 21 11.5z"/></svg>
      <span class="i18n" data-es="<?= htmlspecialchars($ctaLabel_es) ?>" data-en="<?= htmlspecialchars($ctaLabel_en) ?>"><?= htmlspecialchars($ctaLabel_es) ?></span>
    </a>
  <?php else: ?>
    <button class="cta-btn" onclick="pchOpen()">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
      <span class="i18n" data-es="<?= htmlspecialchars($ctaLabel_es) ?>" data-en="<?= htmlspecialchars($ctaLabel_en) ?>"><?= htmlspecialchars($ctaLabel_es) ?></span>
    </button>
  <?php endif; ?>
  <p class="undercta i18n" data-es="Respuesta en minutos · disponible 24/7" data-en="Response in minutes · available 24/7">Respuesta en minutos · disponible 24/7</p>
</section>

<!-- ── Trust band ── -->
<div class="trust">
  <div class="trust-item">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
    <span class="i18n" data-es="Respuesta al instante" data-en="Instant response">Respuesta al instante</span>
  </div>
  <div class="trust-item">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 16 14"/></svg>
    <span class="i18n" data-es="Reservá 24/7" data-en="Book 24/7">Reservá 24/7</span>
  </div>
  <div class="trust-item">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
    <span class="i18n" data-es="Sin llamadas" data-en="No calls needed">Sin llamadas</span>
  </div>
</div>

<!-- ── 3 pasos ── -->
<section class="sec ctr">
  <h2 class="serif i18n" data-es="Reservar toma 3 pasos" data-en="Booking takes 3 steps">Reservar toma 3 pasos</h2>
  <div class="steps">
    <div class="step">
      <div class="step-n">1</div>
      <h3 class="i18n" data-es="Escribí" data-en="Message">Escribí</h3>
      <p class="i18n" data-es="Decile a Vale qué servicio querés, por WhatsApp." data-en="Tell Vale which service you want, via WhatsApp.">Decile a Vale qué servicio querés, por WhatsApp.</p>
    </div>
    <div class="step">
      <div class="step-n">2</div>
      <h3 class="i18n" data-es="Elegí" data-en="Choose">Elegí</h3>
      <p class="i18n" data-es="Vale te muestra los horarios disponibles al instante." data-en="Vale shows available slots instantly.">Vale te muestra los horarios disponibles al instante.</p>
    </div>
    <div class="step">
      <div class="step-n">3</div>
      <h3 class="i18n" data-es="Listo" data-en="Done">Listo</h3>
      <p class="i18n" data-es="Confirmás y te llega el recordatorio. Sin llamadas." data-en="Confirm and get a reminder. No calls.">Confirmás y te llega el recordatorio. Sin llamadas.</p>
    </div>
  </div>
</section>

<!-- ── Servicios ── -->
<?php if (!empty($services)): ?>
<section class="sec ctr">
  <div class="panel">
    <h2 class="serif i18n" data-es="Servicios" data-en="Services">Servicios</h2>
    <div class="svcs">
      <?php foreach ($services as $s): ?>
      <div class="svc">
        <p class="svc-name"><?= htmlspecialchars($s['name']) ?></p>
        <div class="pills">
          <?php if ($s['duration_min']): ?>
            <span class="pill"><?= (int)$s['duration_min'] ?> min</span>
          <?php endif; ?>
          <?php if ($s['price_min'] !== null): ?>
            <span class="pill price">
              <?php
                $p = (float)$s['price_min'];
                if ($s['price_max'] !== null && (float)$s['price_max'] > $p)
                    echo '$' . number_format($p,0) . '–$' . number_format((float)$s['price_max'],0);
                else
                    echo '$' . number_format($p, 0);
              ?>
            </span>
          <?php endif; ?>
          <?php if (!$s['duration_min'] && $s['price_min'] === null): ?>
            <span class="pill i18n" data-es="Cotización" data-en="Quote">Cotización</span>
          <?php endif; ?>
        </div>
        <?php if (!empty($s['description'])): ?>
          <p class="svc-desc"><?= htmlspecialchars($s['description']) ?></p>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<!-- ── Final CTA ── -->
<section class="final">
  <h2 class="serif i18n" data-es="¿Listo para reservar?" data-en="Ready to book?">¿Listo para reservar?</h2>
  <?php if ($useWa): ?>
    <a class="cta-btn" href="<?= htmlspecialchars($waLink) ?>" target="_blank" rel="noopener">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.38 8.38 0 0 1-4-1L3 20l1-5.5a8.38 8.38 0 0 1-1-4A8.5 8.5 0 0 1 21 11.5z"/></svg>
      <span class="i18n" data-es="Hablar con Vale" data-en="Chat with Vale">Hablar con Vale</span>
    </a>
  <?php else: ?>
    <button class="cta-btn" onclick="pchOpen()">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
      <span class="i18n" data-es="Hablar con Vale" data-en="Chat with Vale">Hablar con Vale</span>
    </button>
  <?php endif; ?>
</section>

<!-- ── Footer ── -->
<p class="pub-foot">
  <?php if ($horasRow || $ciudad): ?>
    <?= $horasRow ? nl2br(htmlspecialchars($horasRow)) : '' ?>
    <?= ($horasRow && $ciudad) ? ' · ' : '' ?>
    <?= $ciudad ? htmlspecialchars($ciudad) : '' ?><br><br>
  <?php endif; ?>
  <?php if ($plan === 'free'): ?>
    <span class="vale-seal">
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10z"/></svg>
      Atendido por Vale
    </span> ·
  <?php endif; ?>
  Hecho por <a href="https://supraide.com" target="_blank" rel="noopener">Supraide</a>
  &nbsp;·&nbsp;<a href="/privacy">Privacidad</a>
</p>

<!-- ── Floating FAB ── -->
<?php if ($useWa): ?>
  <a class="fab" href="<?= htmlspecialchars($waLink) ?>" target="_blank" rel="noopener" aria-label="Reservar por WhatsApp">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.38 8.38 0 0 1-4-1L3 20l1-5.5a8.38 8.38 0 0 1-1-4A8.5 8.5 0 0 1 21 11.5z"/></svg>
    <span class="txt i18n" data-es="Reservar" data-en="Book">Reservar</span>
  </a>
<?php else: ?>
  <!-- Chat widget FAB (fallback sin número WA) -->
  <div class="pub-overlay" id="pubOverlay" onclick="pchClose()"></div>
  <div class="pub-chat-wrap">
    <button class="pub-chat-fab" onclick="pchOpen()" aria-label="Hablar con Vale">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>
    </button>
  </div>
  <div class="pub-chat-drawer" id="pubChatDrawer">
    <div class="pch-head">
      <div class="pch-av"><?= htmlspecialchars($monogram) ?></div>
      <div class="pch-hinfo">
        <div class="pch-ttl">Vale</div>
        <div style="font-size:11.5px;opacity:.6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" class="i18n" data-es="Asistente de <?= addslashes($tenant['name'] ?? '') ?>" data-en="Assistant for <?= addslashes($tenant['name'] ?? '') ?>">Asistente de <?= $bizName ?></div>
      </div>
      <button class="pch-cls" onclick="pchClose()" aria-label="Cerrar">&#215;</button>
    </div>
    <div class="pch-msgs" id="pchMsgs"></div>
    <form class="pch-form" id="pchForm" onsubmit="pchSend(event)">
      <input type="text" id="pchInput" placeholder="Escribí tu mensaje…" autocomplete="off">
      <button type="submit" class="pch-send">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
      </button>
    </form>
  </div>
<?php endif; ?>

<script>
var CUR_LANG    = 'es';
var PUB_KEY     = <?= json_encode($publicKey) ?>;
var pchHistory  = [], pchBusy = false, pchReady = false;
var pchVisitorId = '';
var GREET_ES  = '¡Hola! Soy Vale, el asistente de <?= addslashes($tenant['name'] ?? '') ?>. ¿En qué te puedo ayudar?';
var GREET_EN  = 'Hi! I\'m Vale, assistant for <?= addslashes($tenant['name'] ?? '') ?>. How can I help?';

function setLang(lang) {
    CUR_LANG = lang;
    document.getElementById('htmlRoot').lang = lang;
    document.querySelectorAll('.i18n').forEach(function(el) {
        var v = el.getAttribute('data-' + lang);
        if (v !== null) el.innerHTML = v;
    });
    document.getElementById('btnEs').className = lang === 'es' ? 'on' : 'off';
    document.getElementById('btnEn').className = lang === 'en' ? 'on' : 'off';
}

<?php if (!$useWa): ?>
function pchOpen() {
    document.getElementById('pubOverlay').classList.add('show');
    document.getElementById('pubChatDrawer').classList.add('open');
    if (!pchReady) { pchReady = true; pchAddBubble(CUR_LANG === 'en' ? GREET_EN : GREET_ES, 'in'); }
    setTimeout(function(){ document.getElementById('pchInput').focus(); }, 320);
}
function pchClose() {
    document.getElementById('pubOverlay').classList.remove('show');
    document.getElementById('pubChatDrawer').classList.remove('open');
}
function pchAddBubble(text, type) {
    var msgs = document.getElementById('pchMsgs');
    var d = document.createElement('div');
    d.className = 'pch-bubble pch-' + type;
    if (type === 'in') d.innerHTML = text.replace(/\n/g,'<br>'); else d.textContent = text;
    msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
function pchAddChips(options) {
    if (!options || !options.length) return;
    var msgs = document.getElementById('pchMsgs');
    var wrap = document.createElement('div');
    wrap.className = 'pch-chips'; wrap.id = 'pchChips';
    options.forEach(function(opt) {
        var btn = document.createElement('button');
        btn.className = 'pch-chip';
        btn.textContent = opt;
        btn.onclick = function() {
            if (pchBusy) return;
            var w = document.getElementById('pchChips');
            if (w) w.remove();
            pchSendText(opt);
        };
        wrap.appendChild(btn);
    });
    msgs.appendChild(wrap); msgs.scrollTop = msgs.scrollHeight;
}
function pchSendText(text) {
    if (pchBusy || !text) return;
    pchBusy = true;
    pchAddBubble(text, 'out');
    pchHistory.push({role:'user', text:text});
    pchShowTyping();
    fetch('/agent/web', {method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({message:text, key:PUB_KEY, visitorId:pchVisitorId})})
    .then(function(r){ return r.json(); })
    .then(function(data){
        pchHideTyping();
        if (data.visitorId) pchVisitorId = data.visitorId;
        var reply = data.reply || (CUR_LANG==='en' ? 'One moment…' : 'Un momento…');
        pchAddBubble(reply, 'in');
        pchHistory.push({role:'model', text:reply});
        pchAddChips(data.options);
        pchBusy = false;
    }).catch(function(){
        pchHideTyping();
        pchAddBubble(CUR_LANG==='en'?'Connection error. Try again.':'Error de conexión. Intentá de nuevo.','in');
        pchBusy = false;
    });
}
function pchShowTyping() {
    var msgs = document.getElementById('pchMsgs');
    var d = document.createElement('div'); d.className = 'pch-typing'; d.id = 'pchTyping';
    d.innerHTML = '<span></span><span></span><span></span>';
    msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
function pchHideTyping() { var t=document.getElementById('pchTyping'); if(t) t.remove(); }
function pchSend(e) {
    e.preventDefault();
    var input = document.getElementById('pchInput');
    var text = input.value.trim(); if (!text) return;
    input.value = '';
    var chips = document.getElementById('pchChips');
    if (chips) chips.remove();
    pchSendText(text);
}
<?php endif; ?>
</script>
</body>
</html>
