<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin — Sonora</title>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#07070d;--sur:#0f0f18;--panel:#141420;--card:#1a1a28;--bdr:#242438;--acc:#00e5a0;--acc2:#7c6ff7;--acc3:#ff4d6d;--txt:#f0f0f8;--mut:#6b6b85;--dim:#2e2e48}
body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--txt);min-height:100dvh}
.layout{display:flex;min-height:100dvh}

/* SIDEBAR */
.sidebar{width:220px;background:var(--sur);border-right:1px solid var(--bdr);display:flex;flex-direction:column;padding:20px 0;flex-shrink:0;position:fixed;inset:0 auto 0 0;z-index:100;transition:transform .25s;overflow-y:auto}
.sidebar.closed{transform:translateX(-100%)}
.logo-wrap{padding:0 16px 18px;display:flex;align-items:center;gap:8px}
.s-logo-icon{font-size:22px}
.s-logo-name{font-family:'Bebas Neue',sans-serif;font-size:22px;letter-spacing:3px;color:var(--acc);transition:color .3s}
.badge{margin:0 10px 16px;background:rgba(124,111,247,.12);border:1px solid rgba(124,111,247,.22);border-radius:8px;padding:8px 12px;font-size:11px;color:var(--acc2);font-weight:600;letter-spacing:.5px}
.nl{font-size:10px;font-weight:700;letter-spacing:2px;color:var(--mut);text-transform:uppercase;padding:0 16px;margin:10px 0 4px}
.ni{display:flex;align-items:center;gap:9px;padding:9px 10px;margin:1px 8px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:500;color:var(--mut);transition:all .15s;border:none;background:none;font-family:'DM Sans',sans-serif;width:calc(100% - 16px);text-align:left;-webkit-tap-highlight-color:transparent}
.ni:hover,.ni.act{background:var(--card);color:var(--acc)}
.sfoot{margin-top:auto;padding:14px 10px 0;border-top:1px solid var(--bdr)}
.lout{display:flex;align-items:center;gap:8px;padding:9px 10px;border-radius:8px;cursor:pointer;font-size:13px;color:var(--acc3);border:none;background:none;font-family:'DM Sans',sans-serif;width:100%;-webkit-tap-highlight-color:transparent}
.lout:hover{background:rgba(255,77,109,.08)}

/* OVERLAY */
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:99}
.overlay.show{display:block}

/* MAIN */
.main-wrap{flex:1;margin-left:220px;display:flex;flex-direction:column;transition:margin .25s}
@media(max-width:768px){.main-wrap{margin-left:0}}

/* TOPBAR */
.topbar{background:var(--sur);border-bottom:1px solid var(--bdr);padding:13px 20px;display:flex;align-items:center;gap:12px;position:sticky;top:0;z-index:50}
.mbtn{background:none;border:none;color:var(--mut);cursor:pointer;display:none;padding:4px;-webkit-tap-highlight-color:transparent}
@media(max-width:768px){.mbtn{display:flex}}
.ptitle{font-family:'Bebas Neue',sans-serif;font-size:20px;letter-spacing:2px;flex:1}
.ainfo{display:flex;align-items:center;gap:8px}
.av{width:30px;height:30px;background:var(--acc2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#fff;flex-shrink:0}
.aname{font-size:13px;font-weight:600;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@media(max-width:500px){.aname{display:none}}

/* CONTENT */
.content{padding:18px;flex:1;overflow-y:auto}

/* STATS */
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px}
@media(max-width:800px){.stats{grid-template-columns:repeat(2,1fr)}}
.sc{background:var(--panel);border:1px solid var(--bdr);border-radius:12px;padding:16px;position:relative;overflow:hidden}
.sc::before{content:'';position:absolute;top:0;left:0;right:0;height:2px}
.sc:nth-child(1)::before{background:var(--acc)}
.sc:nth-child(2)::before{background:var(--acc2)}
.sc:nth-child(3)::before{background:#f7c16f}
.sc:nth-child(4)::before{background:var(--acc3)}
.sl{font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--mut);margin-bottom:6px}
.sv{font-family:'Bebas Neue',sans-serif;font-size:clamp(26px,4vw,34px);line-height:1}
.sc:nth-child(1) .sv{color:var(--acc)}
.sc:nth-child(2) .sv{color:var(--acc2)}
.sc:nth-child(3) .sv{color:#f7c16f}
.sc:nth-child(4) .sv{color:var(--acc3)}
.ss{font-size:11px;color:var(--mut);margin-top:4px}

/* SECTION */
.section{background:var(--panel);border:1px solid var(--bdr);border-radius:14px;overflow:hidden;margin-bottom:18px}
.shead{padding:14px 16px;border-bottom:1px solid var(--bdr);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
.stitle{font-family:'Bebas Neue',sans-serif;font-size:16px;letter-spacing:1.5px}
.hact{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.sf-wrap{position:relative;display:flex;align-items:center}
.sf-wrap svg{position:absolute;left:9px;color:var(--mut);pointer-events:none}
.sf{background:var(--card);border:1px solid var(--bdr);border-radius:8px;padding:8px 10px 8px 30px;font-family:'DM Sans',sans-serif;font-size:13px;color:var(--txt);outline:none;width:clamp(110px,18vw,170px);transition:border-color .2s}
.sf:focus{border-color:var(--acc)}
.sf::placeholder{color:var(--mut)}

/* BUTTONS */
.btn{padding:8px 14px;border-radius:8px;border:none;font-family:'DM Sans',sans-serif;font-size:13px;font-weight:600;cursor:pointer;transition:all .15s;display:inline-flex;align-items:center;gap:5px;-webkit-tap-highlight-color:transparent;touch-action:manipulation;white-space:nowrap}
.btn:active{transform:scale(.96)}
.ba{background:var(--acc);color:#000}.ba:hover{filter:brightness(1.08)}
.bg{background:var(--card);color:var(--txt);border:1px solid var(--bdr)}.bg:hover{border-color:var(--acc);color:var(--acc)}
.bd{background:rgba(255,77,109,.1);color:var(--acc3);border:1px solid rgba(255,77,109,.18)}.bd:hover{background:rgba(255,77,109,.2)}
.bs{padding:5px 10px;font-size:12px}

/* TABLE */
.tw{overflow-x:auto;-webkit-overflow-scrolling:touch}
table{width:100%;border-collapse:collapse;min-width:560px}
th{padding:10px 14px;text-align:left;font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--mut);background:var(--card);white-space:nowrap}
td{padding:11px 14px;border-top:1px solid var(--bdr);font-size:13px;vertical-align:middle}
tr:hover td{background:rgba(255,255,255,.015)}
.ucell{display:flex;align-items:center;gap:9px}
.uav{width:32px;height:32px;border-radius:8px;background:var(--card);display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;border:1px solid var(--bdr)}
.un{font-weight:600;font-size:13px;white-space:nowrap}
.ue{font-size:11px;color:var(--mut);white-space:nowrap}
.bdg{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600;white-space:nowrap}
.bdg::before{content:'';width:5px;height:5px;border-radius:50%;background:currentColor}
.gn{background:rgba(0,229,160,.1);color:var(--acc)}
.gr{background:rgba(255,77,109,.1);color:var(--acc3)}
.gb{background:rgba(124,111,247,.1);color:var(--acc2)}
.gy{background:rgba(247,193,111,.1);color:#f7c16f}
.acts{display:flex;gap:5px;flex-wrap:wrap}
.em{padding:32px;text-align:center;color:var(--mut);font-size:14px}

/* MODAL */
.mbg{position:fixed;inset:0;background:rgba(0,0,0,.72);backdrop-filter:blur(4px);z-index:200;display:flex;align-items:center;justify-content:center;padding:16px;opacity:0;pointer-events:none;transition:opacity .2s}
.mbg.open{opacity:1;pointer-events:all}
.modal{background:var(--panel);border:1px solid var(--bdr);border-radius:18px;padding:clamp(18px,4vw,26px);width:100%;max-width:460px;position:relative;transform:translateY(14px);transition:transform .2s;max-height:90dvh;overflow-y:auto}
.mbg.open .modal{transform:translateY(0)}
.mt{font-family:'Bebas Neue',sans-serif;font-size:20px;letter-spacing:2px;margin-bottom:3px}
.ms{font-size:13px;color:var(--mut);margin-bottom:18px}
.mf{margin-bottom:12px}
.mf label{display:block;font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--mut);margin-bottom:5px}
.mf input,.mf select,.mf textarea{width:100%;background:var(--card);border:1px solid var(--bdr);border-radius:8px;padding:11px 13px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--txt);outline:none;transition:border-color .2s;-webkit-appearance:none;resize:vertical}
.mf input:focus,.mf select:focus,.mf textarea:focus{border-color:var(--acc)}
.mf select option{background:var(--card)}
.r2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
@media(max-width:400px){.r2{grid-template-columns:1fr}}
.mfoot{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap}
.xbtn{position:absolute;top:14px;right:14px;background:none;border:none;color:var(--mut);cursor:pointer;padding:4px;border-radius:6px;display:flex;-webkit-tap-highlight-color:transparent}

/* SETTINGS */
.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;padding:16px}
@media(max-width:600px){.settings-grid{grid-template-columns:1fr}}
.set-card{background:var(--card);border:1px solid var(--bdr);border-radius:12px;padding:18px}
.set-label{font-size:11px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--mut);margin-bottom:12px}
.color-row{display:flex;align-items:center;gap:10px}
.color-input{width:44px;height:44px;border-radius:8px;border:2px solid var(--bdr);cursor:pointer;background:none;padding:2px}
.preview-logo{display:flex;align-items:center;gap:8px;margin-top:10px;padding:10px;background:var(--panel);border-radius:8px}
.prev-icon{font-size:24px}
.prev-name{font-family:'Bebas Neue',sans-serif;font-size:20px;letter-spacing:3px;color:var(--acc)}

/* Plans editor */
.plans-list{display:flex;flex-direction:column;gap:16px}
.plan-card-edit{background:var(--card);border:1px solid var(--bdr);border-radius:14px;overflow:hidden}
.plan-card-header{display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid var(--bdr)}
.plan-card-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
.plan-card-name-lbl{font-family:'Bebas Neue',sans-serif;font-size:17px;letter-spacing:1.5px;flex:1}
.plan-card-body{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:14px 16px}
@media(max-width:700px){.plan-card-body{grid-template-columns:1fr 1fr}}
@media(max-width:420px){.plan-card-body{grid-template-columns:1fr}}
.plan-field{display:flex;flex-direction:column;gap:5px}
.plan-field label{font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--mut)}
.plan-field input,.plan-field select{background:var(--panel);border:1px solid var(--bdr);border-radius:7px;padding:9px 11px;font-family:'DM Sans',sans-serif;font-size:13px;color:var(--txt);outline:none;width:100%;transition:border-color .2s;-webkit-appearance:none}
.plan-field input:focus,.plan-field select:focus{border-color:var(--acc)}
.plan-field select option{background:var(--card)}
.plan-field textarea{background:var(--panel);border:1px solid var(--bdr);border-radius:7px;padding:9px 11px;font-family:'DM Sans',sans-serif;font-size:12px;color:var(--txt);outline:none;width:100%;resize:vertical;min-height:70px;transition:border-color .2s;line-height:1.6}
.plan-field textarea:focus{border-color:var(--acc)}
.plan-card-footer{padding:10px 16px;border-top:1px solid var(--bdr);display:flex;align-items:center;gap:8px}
.plan-preview{flex:1;font-size:12px;color:var(--mut)}
.plan-preview strong{color:var(--txt)}
.dur-row{display:flex;gap:8px}
.dur-row input{flex:1}
.dur-row select{flex:1.5}

/* TOAST */
.toast{position:fixed;bottom:20px;right:20px;left:20px;max-width:300px;margin:0 auto;background:var(--card);border:1px solid var(--bdr);border-radius:12px;padding:12px 16px;font-size:13px;display:flex;align-items:center;gap:8px;transform:translateY(70px);opacity:0;transition:all .3s;z-index:300;pointer-events:none}
@media(min-width:480px){.toast{left:auto;right:20px;margin:0}}
.toast.show{transform:translateY(0);opacity:1}
.loading{display:flex;align-items:center;justify-content:center;padding:28px;gap:8px;color:var(--mut)}
.spin{width:16px;height:16px;border:2px solid var(--dim);border-top-color:var(--acc);border-radius:50%;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>
<body>
<div class="overlay" id="ov" onclick="closeSidebar()"></div>
<div class="layout">

<!-- SIDEBAR -->
<aside class="sidebar" id="sb">
  <div class="logo-wrap">
    <span class="s-logo-icon" id="s-icon">🎵</span>
    <span class="s-logo-name" id="s-name">SONORA</span>
  </div>
  <div class="badge">⚙ PAINEL ADMIN</div>
  <div class="nl">Gestão</div>
  <button class="ni act" onclick="showPage('clients',this)"><svg width="15" height="15" fill="currentColor" viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>Clientes</button>
  <button class="ni" onclick="showPage('plans',this)"><svg width="15" height="15" fill="currentColor" viewBox="0 0 24 24"><path d="M11.5 2C6.81 2 3 5.81 3 10.5S6.81 19 11.5 19h.5v3c4.86-2.34 8-7 8-11.5C20 5.81 16.19 2 11.5 2zm1 14.5h-2v-2h2v2zm0-4h-2c0-3.25 3-3 3-5 0-1.1-.9-2-2-2s-2 .9-2 2h-2c0-2.21 1.79-4 4-4s4 1.79 4 4c0 2.5-3 2.75-3 5z"/></svg>Planos</button>
  <button class="ni" onclick="showPage('admins',this)"><svg width="15" height="15" fill="currentColor" viewBox="0 0 24 24"><path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z"/></svg>Administradores</button>
  <button class="ni" onclick="showPage('settings',this)"><svg width="15" height="15" fill="currentColor" viewBox="0 0 24 24"><path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/></svg>Configurações</button>
  <div class="sfoot">
    <button class="lout" onclick="logout()"><svg width="15" height="15" fill="currentColor" viewBox="0 0 24 24"><path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/></svg>Sair</button>
  </div>
</aside>

<div class="main-wrap">
  <div class="topbar">
    <button class="mbtn" onclick="toggleSidebar()"><svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg></button>
    <div class="ptitle" id="ptitle">Gerenciar Clientes</div>
    <div class="ainfo"><div class="av" id="adm-av">A</div><div class="aname" id="adm-name">—</div></div>
  </div>

  <div class="content">

    <!-- CLIENTES -->
    <div id="pg-clients">
      <div class="stats" id="stats"><div style="grid-column:1/-1" class="loading"><div class="spin"></div></div></div>
      <div class="section">
        <div class="shead">
          <div class="stitle">Clientes</div>
          <div class="hact">
            <div class="sf-wrap">
              <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
              <input class="sf" id="q" placeholder="Buscar..." oninput="filterTable()">
            </div>
            <button class="btn bg bs" onclick="exportCSV()"><svg width="13" height="13" fill="currentColor" viewBox="0 0 24 24"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>CSV</button>
            <button class="btn ba bs" onclick="openModal()"><svg width="13" height="13" fill="currentColor" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>Novo</button>
          </div>
        </div>
        <div class="tw"><table><thead><tr><th>Cliente</th><th>Plano</th><th>Status</th><th>Cadastrado</th><th>Ações</th></tr></thead><tbody id="tbody"></tbody></table></div>
        <div id="em" class="em" style="display:none">Nenhum cliente</div>
      </div>
    </div>

    <!-- PLANOS -->
    <div id="pg-plans" style="display:none">
      <div class="section">
        <div class="shead">
          <div class="stitle">Planos & Preços</div>
          <button class="btn ba bs" onclick="savePlans()">
            <svg width="13" height="13" fill="currentColor" viewBox="0 0 24 24"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>Salvar tudo
          </button>
        </div>
        <div style="padding:16px">
          <div class="plans-list" id="plans-list"></div>
          <p style="font-size:12px;color:var(--mut);margin-top:12px;line-height:1.7">
            💡 <strong style="color:var(--txt)">Dica:</strong> Use "Funcionalidades" para listar o que está incluso no plano (uma por linha). Use "Restrições" para o que <em>não</em> está incluso. Essas informações são exibidas na tela de planos do cliente.
          </p>
        </div>
      </div>
    </div>

    <!-- ADMINS -->
    <div id="pg-admins" style="display:none">
      <div class="section">
        <div class="shead"><div class="stitle">Administradores</div><button class="btn ba bs" onclick="openAdmModal()"><svg width="13" height="13" fill="currentColor" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>Novo</button></div>
        <div class="tw"><table><thead><tr><th>Admin</th><th>Cadastrado</th><th>Ações</th></tr></thead><tbody id="atbody"></tbody></table></div>
      </div>
    </div>

    <!-- CONFIGURAÇÕES -->
    <div id="pg-settings" style="display:none">
      <div class="section">
        <div class="shead"><div class="stitle">Configurações do Site</div><button class="btn ba bs" onclick="saveSettings()"><svg width="13" height="13" fill="currentColor" viewBox="0 0 24 24"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>Salvar</button></div>
        <div class="settings-grid">
          <div class="set-card">
            <div class="set-label">Identidade do Site</div>
            <div class="mf"><label>Nome do site</label><input type="text" id="set-name" placeholder="Sonora" oninput="updatePreview()"></div>
            <div class="mf"><label>Logo (emoji ou letra)</label><input type="text" id="set-logo" placeholder="🎵" maxlength="4" oninput="updatePreview()"></div>
            <div class="mf">
              <label>Cor principal</label>
              <div class="color-row">
                <input type="color" class="color-input" id="set-color" value="#00e5a0" oninput="updatePreview()">
                <input type="text" id="set-color-txt" placeholder="#00e5a0" style="flex:1" oninput="syncColor()">
              </div>
            </div>
            <div class="set-label" style="margin-top:14px">Prévia</div>
            <div class="preview-logo">
              <span class="prev-icon" id="prev-icon">🎵</span>
              <span class="prev-name" id="prev-name">SONORA</span>
            </div>
          </div>
          <div class="set-card">
            <div class="set-label">Informações gerais</div>
            <p style="font-size:13px;color:var(--mut);line-height:1.7">As configurações aqui salvas são aplicadas em todas as páginas do sistema:<br><br>
            • Login: exibe logo e nome do site<br>
            • Admin: atualiza sidebar<br>
            • Player: atualiza topbar<br><br>
            Alterações de cor afetam a cor de destaque em toda a interface.</p>
          </div>
        </div>
      </div>
    </div>

  </div><!-- /content -->
</div><!-- /main-wrap -->
</div><!-- /layout -->

<!-- MODAL CLIENTE -->
<div class="mbg" id="cm">
  <div class="modal">
    <button class="xbtn" onclick="closeModal()"><svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
    <div class="mt" id="cm-t">Novo Cliente</div>
    <div class="ms" id="cm-s">Preencha os dados</div>
    <input type="hidden" id="f-id">
    <div class="r2">
      <div class="mf"><label>Nome</label><input type="text" id="f-name" placeholder="Nome completo" autocomplete="off"></div>
      <div class="mf"><label>Avatar</label><input type="text" id="f-avatar" placeholder="🎵" maxlength="2"></div>
    </div>
    <div class="mf"><label>Email</label><input type="email" id="f-email" placeholder="email@exemplo.com" inputmode="email" autocomplete="off"></div>
    <div class="r2">
      <div class="mf"><label>Senha <small id="pw-hint" style="color:var(--mut);font-weight:400;text-transform:none;font-size:9px;letter-spacing:0">(em branco = manter)</small></label><input type="password" id="f-pw" placeholder="••••••••" autocomplete="new-password"></div>
      <div class="mf"><label>Plano</label><select id="f-plan" title="Selecione o plano"></select></div>
    </div>
    <div class="mf"><label>Status</label><select id="f-active"><option value="1">Ativo</option><option value="0">Desativado</option></select></div>
    <div class="mfoot">
      <button class="btn bg" onclick="closeModal()">Cancelar</button>
      <button class="btn ba" onclick="saveClient()"><svg width="14" height="14" fill="currentColor" viewBox="0 0 24 24"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>Salvar</button>
    </div>
  </div>
</div>

<!-- MODAL ADMIN -->
<div class="mbg" id="am">
  <div class="modal">
    <button class="xbtn" onclick="closeAdmModal()"><svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
    <div class="mt">Novo Admin</div>
    <div class="ms">Acesso total ao painel</div>
    <div class="mf"><label>Nome</label><input type="text" id="a-name" placeholder="Nome completo"></div>
    <div class="mf"><label>Email</label><input type="email" id="a-email" placeholder="admin@email.com" inputmode="email"></div>
    <div class="mf"><label>Senha</label><input type="password" id="a-pw" placeholder="••••••••"></div>
    <div class="mfoot">
      <button class="btn bg" onclick="closeAdmModal()">Cancelar</button>
      <button class="btn ba" onclick="saveAdmin()">Salvar</button>
    </div>
  </div>
</div>

<div class="toast" id="toast"><span id="tmsg"></span></div>

<script>
var NAME=localStorage.getItem('snr_name')||'Admin';
document.getElementById('adm-name').textContent=NAME;
document.getElementById('adm-av').textContent=NAME.charAt(0).toUpperCase();

// Verifica sessão
(async function(){
  try{
    var r=await api('me');
    if(!r.ok||r.role!=='admin'){location.href='login.php';return;}
    document.getElementById('adm-name').textContent=r.name||NAME;
    document.getElementById('adm-av').textContent=(r.name||NAME).charAt(0).toUpperCase();
  }catch(e){location.href='login.php';return;}
  await loadSettings();
  loadAll();
})();

async function api(action,body){
  body=body||{}; body.action=action;
  try{
    var r=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    var t=await r.text();
    try{return JSON.parse(t);}catch(e){console.error('PHP:',t.slice(0,500));return{ok:false,error:'Erro PHP — veja F12'};}
  }catch(e){return{ok:false,error:'Rede: '+e.message};}
}

// Sidebar
function isMobile(){return window.innerWidth<=768;}
function toggleSidebar(){
  if(isMobile()){document.getElementById('sb').classList.toggle('closed');document.getElementById('ov').classList.toggle('show');}
}
function closeSidebar(){
  // Fecha só no mobile — no desktop o menu fica sempre aberto
  if(isMobile()){document.getElementById('sb').classList.add('closed');document.getElementById('ov').classList.remove('show');}
}
// Inicia fechado apenas no mobile
if(isMobile()) document.getElementById('sb').classList.add('closed');
window.addEventListener('resize',function(){
  if(!isMobile()){
    document.getElementById('sb').classList.remove('closed');
    document.getElementById('ov').classList.remove('show');
  } else {
    if(!document.getElementById('ov').classList.contains('show'))
      document.getElementById('sb').classList.add('closed');
  }
});

// Pages
var pages={clients:'Gerenciar Clientes',plans:'Planos',admins:'Administradores',settings:'Configurações do Site'};
function showPage(name,btn){
  Object.keys(pages).forEach(function(p){document.getElementById('pg-'+p).style.display=p===name?'':'none';});
  document.querySelectorAll('.ni').forEach(function(el){el.classList.remove('act');});
  if(btn)btn.classList.add('act');
  document.getElementById('ptitle').textContent=pages[name]||'';
  if(isMobile()) closeSidebar();
  if(name==='clients')loadAll();
  if(name==='admins')loadAdmins();
  if(name==='plans')loadPlans();
  if(name==='settings')loadSettingsPage();
}

// SETTINGS
var currentSettings={};
async function loadSettings(){
  var d=await api('settings_get');
  if(!d.ok)return;
  currentSettings=d.settings||{};
  applySettings(currentSettings);
}
function applySettings(s){
  if(s.site_name){document.getElementById('s-name').textContent=s.site_name;document.title='Admin — '+s.site_name;}
  if(s.site_logo)document.getElementById('s-icon').textContent=s.site_logo;
  if(s.site_color){document.getElementById('s-name').style.color=s.site_color;document.documentElement.style.setProperty('--acc',s.site_color);}
}
function loadSettingsPage(){
  var s=currentSettings;
  document.getElementById('set-name').value=s.site_name||'Sonora';
  document.getElementById('set-logo').value=s.site_logo||'🎵';
  document.getElementById('set-color').value=s.site_color||'#00e5a0';
  document.getElementById('set-color-txt').value=s.site_color||'#00e5a0';
  updatePreview();
}
function updatePreview(){
  var nm=document.getElementById('set-name').value||'Sonora';
  var ic=document.getElementById('set-logo').value||'🎵';
  var cl=document.getElementById('set-color').value||'#00e5a0';
  document.getElementById('prev-name').textContent=nm.toUpperCase();
  document.getElementById('prev-name').style.color=cl;
  document.getElementById('prev-icon').textContent=ic;
  document.getElementById('set-color-txt').value=cl;
}
function syncColor(){
  var v=document.getElementById('set-color-txt').value;
  if(/^#[0-9a-fA-F]{6}$/.test(v))document.getElementById('set-color').value=v;
}
async function saveSettings(){
  var d=await api('settings_save',{
    site_name:document.getElementById('set-name').value.trim(),
    site_logo:document.getElementById('set-logo').value.trim(),
    site_color:document.getElementById('set-color').value
  });
  if(!d.ok){toast('⚠ '+d.error);return;}
  currentSettings=d.settings;
  applySettings(d.settings);
  toast('✓ Configurações salvas');
}

// PLANS
var currentPlans=[];
async function loadPlans(){
  var d=await api('settings_get');
  if(!d.ok)return;
  currentPlans=(d.settings||{}).plans||[];
  renderPlans();
}

var durUnits=[
  {val:'',label:'Sem vencimento'},
  {val:'day',label:'Dia(s)'},
  {val:'week',label:'Semana(s)'},
  {val:'month',label:'Mês/Meses'},
  {val:'year',label:'Ano(s)'},
];

function durLabel(p){
  if(!p.duration||!p.duration_unit) return 'Acesso gratuito / vitalício';
  var u=durUnits.find(function(x){return x.val===p.duration_unit;});
  var un=u?u.label.replace('(s)',''):p.duration_unit;
  return p.duration+' '+un+(p.duration>1&&p.duration_unit==='month'?'es':'');
}

function renderPlans(){
  document.getElementById('plans-list').innerHTML=currentPlans.map(function(p,i){
    var durOpts=durUnits.map(function(u){
      return '<option value="'+u.val+'"'+(p.duration_unit===u.val?' selected':'')+'>'+u.label+'</option>';
    }).join('');

    var featVal=Array.isArray(p.features)?p.features.join('\n'):(p.features||'');
    var disVal=Array.isArray(p.disabled)?p.disabled.join('\n'):(p.disabled||'');

    return '<div class="plan-card-edit">'+
      '<div class="plan-card-header">'+
        '<div class="plan-card-dot" style="background:'+(p.color||'#6b6b85')+'"></div>'+
        '<div class="plan-card-name-lbl" style="color:'+(p.color||'var(--txt)')+'">'+esc(p.name)+'</div>'+
        '<span style="font-size:12px;color:var(--mut)" id="dur-preview-'+i+'">'+durLabel(p)+'</span>'+
        '<input type="color" style="width:34px;height:32px;border-radius:6px;border:1px solid var(--bdr);cursor:pointer;background:none;padding:2px;flex-shrink:0" value="'+(p.color||'#6b6b85')+'" title="Cor do plano" onchange="currentPlans['+i+'].color=this.value;renderPlans()">'+
      '</div>'+
      '<div class="plan-card-body">'+
        '<div class="plan-field">'+
          '<label>Nome do plano</label>'+
          '<input value="'+esc(p.name)+'" placeholder="Ex: Premium" onchange="currentPlans['+i+'].name=this.value;renderPlans()">'+
        '</div>'+
        '<div class="plan-field">'+
          '<label>Preço (exibição)</label>'+
          '<input value="'+esc(p.price||'')+'" placeholder="R$19,90 ou Grátis" onchange="currentPlans['+i+'].price=this.value">'+
        '</div>'+
        '<div class="plan-field">'+
          '<label>Valor numérico (R$)</label>'+
          '<input type="number" min="0" step="0.01" value="'+(p.price_value||0)+'" placeholder="0.00" onchange="currentPlans['+i+'].price_value=parseFloat(this.value)||0">'+
        '</div>'+
        '<div class="plan-field">'+
          '<label>Duração do acesso</label>'+
          '<div class="dur-row">'+
            '<input type="number" min="0" max="365" value="'+(p.duration||0)+'" placeholder="0" title="Quantidade" onchange="currentPlans['+i+'].duration=parseInt(this.value)||0;updateDurPreview('+i+')">'+
            '<select onchange="currentPlans['+i+'].duration_unit=this.value;updateDurPreview('+i+')">'+durOpts+'</select>'+
          '</div>'+
        '</div>'+
        '<div class="plan-field">'+
          '<label>Funcionalidades (1 por linha)</label>'+
          '<textarea placeholder="Reprodução ilimitada&#10;Sem anúncios&#10;Downloads" onchange="currentPlans['+i+'].features=this.value">'+esc(featVal)+'</textarea>'+
        '</div>'+
        '<div class="plan-field">'+
          '<label>Restrições (1 por linha)</label>'+
          '<textarea placeholder="Downloads&#10;Offline" onchange="currentPlans['+i+'].disabled=this.value">'+esc(disVal)+'</textarea>'+
        '</div>'+
      '</div>'+
      '<div class="plan-card-footer">'+
        '<div class="plan-preview" id="plan-preview-'+i+'">'+planPreviewText(p)+'</div>'+
      '</div>'+
    '</div>';
  }).join('');
}

function updateDurPreview(i){
  var p=currentPlans[i];
  var el=document.getElementById('dur-preview-'+i);
  if(el) el.textContent=durLabel(p);
  var el2=document.getElementById('plan-preview-'+i);
  if(el2) el2.innerHTML=planPreviewText(p);
}

function planPreviewText(p){
  var price=p.price||'Grátis';
  var dur=(!p.duration||!p.duration_unit)?'sem vencimento':durLabel(p);
  return '<strong>'+esc(p.name)+'</strong> · '+esc(price)+' · Vence em: <strong>'+esc(dur)+'</strong>';
}

async function savePlans(){
  // Normaliza features e disabled para arrays antes de salvar
  var toSave=currentPlans.map(function(p){
    var cp=Object.assign({},p);
    if(typeof cp.features==='string') cp.features=cp.features.split('\n').map(function(s){return s.trim();}).filter(Boolean);
    if(typeof cp.disabled==='string') cp.disabled=cp.disabled.split('\n').map(function(s){return s.trim();}).filter(Boolean);
    return cp;
  });
  var d=await api('settings_save',{plans:toSave});
  if(!d.ok){toast('⚠ '+d.error);return;}
  currentPlans=d.settings.plans||toSave;
  renderPlans();
  toast('✓ Planos salvos com sucesso');
}

// STATS + CLIENTS
var allClients=[];
async function loadStats(){
  var d=await api('stats');
  if(!d.ok){document.getElementById('stats').innerHTML='<div style="grid-column:1/-1;padding:16px;color:var(--acc3)">⚠ '+esc(d.error)+'</div>';return;}
  document.getElementById('stats').innerHTML=
    '<div class="sc"><div class="sl">Total</div><div class="sv">'+d.total+'</div><div class="ss">clientes</div></div>'+
    '<div class="sc"><div class="sl">Ativos</div><div class="sv">'+d.active+'</div><div class="ss">com acesso</div></div>'+
    '<div class="sc"><div class="sl">Premium</div><div class="sv">'+d.premium+'</div><div class="ss">assinantes</div></div>'+
    '<div class="sc"><div class="sl">Inativos</div><div class="sv">'+d.inactive+'</div><div class="ss">bloqueados</div></div>';
}
async function loadClients(){
  var d=await api('clients_list');
  if(!d.ok){document.getElementById('em').style.display='';document.getElementById('em').textContent='⚠ '+d.error;document.getElementById('tbody').innerHTML='';return;}
  allClients=d.clients||[];
  renderTable(allClients);
}
async function loadAll(){await loadPlans();loadStats();loadClients();}
function filterTable(){var q=document.getElementById('q').value.toLowerCase();renderTable(q?allClients.filter(function(c){return c.name.toLowerCase().includes(q)||c.email.toLowerCase().includes(q);}):allClients);}
function planBadge(p){var m={Premium:'gn',Familiar:'gb',Básico:'gy'};return '<span class="bdg '+(m[p]||'gy')+'">'+esc(p)+'</span>';}
function renderTable(list){
  var tb=document.getElementById('tbody'),em=document.getElementById('em');
  if(!list||!list.length){tb.innerHTML='';em.style.display='';em.textContent='Nenhum cliente encontrado';return;}
  em.style.display='none';
  tb.innerHTML=list.map(function(c){
    return '<tr><td><div class="ucell"><div class="uav">'+(c.avatar||'🎵')+'</div><div><div class="un">'+esc(c.name)+'</div><div class="ue">'+esc(c.email)+'</div></div></div></td>'+
      '<td>'+planBadge(c.plan)+'</td>'+
      '<td><span class="bdg '+(c.active?'gn':'gr')+'">'+(c.active?'Ativo':'Inativo')+'</span></td>'+
      '<td style="color:var(--mut);font-size:12px;white-space:nowrap">'+fmtDate(c.created_at)+'</td>'+
      '<td><div class="acts"><button class="btn bg bs" onclick="editClient(\''+c.id+'\')">Editar</button><button class="btn bg bs" onclick="toggleClient(\''+c.id+'\')">'+( c.active?'Desativar':'Ativar')+'</button><button class="btn bd bs" onclick="delClient(\''+c.id+'\')">Excluir</button></div></td></tr>';
  }).join('');
}
function openModal(isEdit){
  if(!isEdit){document.getElementById('f-id').value='';document.getElementById('cm-t').textContent='Novo Cliente';document.getElementById('cm-s').textContent='Preencha os dados';document.getElementById('pw-hint').style.display='none';['f-name','f-email','f-pw'].forEach(function(id){document.getElementById(id).value='';});document.getElementById('f-avatar').value='🎵';populatePlanSelect('Premium');document.getElementById('f-active').value='1';}
  document.getElementById('cm').classList.add('open');
}
function closeModal(){document.getElementById('cm').classList.remove('open');}
async function editClient(id){
  var c=allClients.find(function(x){return x.id===id;});if(!c)return;
  document.getElementById('f-id').value=c.id;document.getElementById('cm-t').textContent='Editar Cliente';document.getElementById('cm-s').textContent='Atualize os dados';document.getElementById('pw-hint').style.display='inline';
  document.getElementById('f-name').value=c.name;document.getElementById('f-email').value=c.email;document.getElementById('f-pw').value='';document.getElementById('f-avatar').value=c.avatar||'🎵';populatePlanSelect(c.plan);document.getElementById('f-active').value=c.active?'1':'0';
  openModal(true);
}
async function saveClient(){
  var id=document.getElementById('f-id').value,name=document.getElementById('f-name').value.trim(),email=document.getElementById('f-email').value.trim(),pw=document.getElementById('f-pw').value,plan=document.getElementById('f-plan').value,active=document.getElementById('f-active').value==='1',avatar=document.getElementById('f-avatar').value||'🎵';
  if(!name||!email){toast('⚠ Nome e email obrigatórios');return;}
  if(!id&&!pw){toast('⚠ Defina uma senha');return;}
  var body={name:name,email:email,plan:plan,active:active,avatar:avatar};
  if(id)body.id=id;if(pw)body.password=pw;
  var d=await api(id?'client_update':'client_create',body);
  if(!d.ok){toast('⚠ '+d.error);return;}
  toast(id?'✓ Cliente atualizado':'✓ Cliente cadastrado');closeModal();loadAll();
}
async function toggleClient(id){var d=await api('client_toggle',{id:id});if(!d.ok){toast('⚠ '+d.error);return;}toast('✓ Status alterado');loadAll();}
async function delClient(id){if(!confirm('Excluir permanentemente?'))return;var d=await api('client_delete',{id:id});if(!d.ok){toast('⚠ '+d.error);return;}toast('✓ Excluído');loadAll();}
function exportCSV(){
  var rows=[['Nome','Email','Plano','Status','Cadastrado']];
  allClients.forEach(function(c){rows.push([c.name,c.email,c.plan,c.active?'Ativo':'Inativo',fmtDate(c.created_at)]);});
  var csv=rows.map(function(r){return r.map(function(v){return '"'+String(v).replace(/"/g,'""')+'"';}).join(',');}).join('\n');
  var a=document.createElement('a');a.href='data:text/csv;charset=utf-8,\uFEFF'+encodeURIComponent(csv);a.download='clientes.csv';a.click();toast('✓ CSV exportado');
}

// ADMINS
async function loadAdmins(){
  var d=await api('admins_list');if(!d.ok)return;
  document.getElementById('atbody').innerHTML=(d.admins||[]).map(function(a,i){
    return '<tr><td><div class="ucell"><div class="uav" style="background:var(--acc2);color:#fff;font-weight:700">'+a.name.charAt(0)+'</div><div><div class="un">'+esc(a.name)+'</div><div class="ue">'+esc(a.email)+'</div></div></div></td>'+
      '<td style="color:var(--mut);font-size:12px">'+fmtDate(a.created_at)+'</td>'+
      '<td>'+(i===0?'<span style="font-size:12px;color:var(--mut)">Principal</span>':'<button class="btn bd bs" onclick="delAdmin(\''+a.id+'\')">Remover</button>')+'</td></tr>';
  }).join('');
}
function openAdmModal(){document.getElementById('am').classList.add('open');}
function closeAdmModal(){document.getElementById('am').classList.remove('open');}
async function saveAdmin(){
  var name=document.getElementById('a-name').value.trim(),email=document.getElementById('a-email').value.trim(),pw=document.getElementById('a-pw').value;
  if(!name||!email||!pw){toast('⚠ Preencha todos os campos');return;}
  var d=await api('admin_create',{name:name,email:email,password:pw});
  if(!d.ok){toast('⚠ '+d.error);return;}
  toast('✓ Admin adicionado');closeAdmModal();['a-name','a-email','a-pw'].forEach(function(id){document.getElementById(id).value='';});loadAdmins();
}
async function delAdmin(id){
  if(!confirm('Remover este administrador?'))return;
  var d=await api('admin_delete',{id:id});if(!d.ok){toast('⚠ '+d.error);return;}
  toast('✓ Removido');loadAdmins();
}

// Popula select de plano dinamicamente com os planos cadastrados
function populatePlanSelect(selectedPlan){
  var sel=document.getElementById('f-plan');
  if(!sel)return;
  var plans=(currentPlans&&currentPlans.length)?currentPlans:[{name:'Básico',price:''},{name:'Premium',price:'R$19,90'},{name:'Familiar',price:'R$34,90'}];
  sel.innerHTML=plans.map(function(p){
    var extra='';
    if(p.price&&p.price!=='Grátis') extra+=' — '+p.price;
    if(p.duration&&p.duration_unit) extra+=', '+durLabel(p);
    return '<option value="'+esc(p.name)+'"'+(p.name===selectedPlan?' selected':'')+'>'+esc(p.name)+esc(extra)+'</option>';
  }).join('');
}

async function logout(){await api('logout');localStorage.clear();location.href='login.php';}
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function fmtDate(iso){if(!iso)return'—';return new Date(iso).toLocaleDateString('pt-BR');}
var tT;function toast(m){var el=document.getElementById('toast');document.getElementById('tmsg').textContent=m;el.classList.add('show');clearTimeout(tT);tT=setTimeout(function(){el.classList.remove('show');},2800);}
</script>
</body>
</html>
