<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Configuración de Metas — ARKHON</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
<style>
:root{
  --bg:#f7f8fc;--surface:#fff;--border:#eaecf4;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --orange:#f97316;--orange-lt:rgba(249,115,22,.10);
  --green:#10b981;--green-lt:rgba(16,185,129,.12);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --amber:#f59e0b;--amber-lt:rgba(245,158,11,.10);
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--shadow:0 2px 8px rgba(17,24,39,.08);
  --r:12px;
}
*{margin:0;padding:0;box-sizing:border-box;}
html,body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;font-size:13px;-webkit-font-smoothing:antialiased;}
button,input{font-family:'Plus Jakarta Sans',sans-serif;}
::-webkit-scrollbar{width:4px;height:4px;}
::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:8px;}
@keyframes spin{to{transform:rotate(360deg);}}
@keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.5;}}

.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:58px;padding:0 20px;display:flex;align-items:center;gap:12px;box-shadow:var(--shadow-sm);position:sticky;top:0;z-index:20;}
.topbar-icon{width:34px;height:34px;border-radius:9px;flex-shrink:0;background:var(--orange);display:flex;align-items:center;justify-content:center;box-shadow:0 3px 10px rgba(249,115,22,.28);}
.topbar-icon svg{width:16px;height:16px;stroke:#fff;stroke-width:2.2;fill:none;}
.topbar h1{font-size:15px;font-weight:800;color:var(--text);letter-spacing:-.3px;flex:1;}
.topbar-save{display:flex;align-items:center;gap:6px;padding:8px 18px;background:var(--orange);color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;box-shadow:0 2px 8px rgba(249,115,22,.28);transition:.15s;}
.topbar-save:hover{transform:translateY(-1px);}
.topbar-save:disabled{opacity:.5;cursor:not-allowed;transform:none;}
.topbar-save svg{width:13px;height:13px;stroke:#fff;stroke-width:2.2;fill:none;}

.container{max-width:900px;margin:0 auto;padding:22px 18px 50px;}

.section-label{font-size:10px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--text-3);margin-bottom:10px;padding-left:2px;}

.progress-grid{display:grid;grid-template-columns:1fr;gap:12px;margin-bottom:24px;}
@media(min-width:640px){.progress-grid{grid-template-columns:repeat(3,1fr);}}

.progress-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:20px;box-shadow:var(--shadow-sm);animation:fadeUp .25s ease;position:relative;overflow:hidden;}
.progress-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:var(--r) var(--r) 0 0;}
.progress-card.diaria::before{background:var(--orange);}
.progress-card.mensual::before{background:var(--blue);}
.progress-card.anual::before{background:var(--green);}

.pc-label{font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;margin-bottom:14px;}
.pc-label.diaria{color:var(--orange);}
.pc-label.mensual{color:var(--blue);}
.pc-label.anual{color:var(--green);}

.donut-wrap{display:flex;align-items:center;gap:16px;margin-bottom:14px;}
.donut-svg{flex-shrink:0;}
.donut-info{}
.donut-pct{font-size:22px;font-weight:800;letter-spacing:-.5px;line-height:1;}
.donut-pct.diaria{color:var(--orange);}
.donut-pct.mensual{color:var(--blue);}
.donut-pct.anual{color:var(--green);}
.donut-completado{font-size:10px;font-weight:700;margin-top:2px;opacity:.7;}

.pc-row{display:flex;justify-content:space-between;font-size:11px;margin-top:4px;}
.pc-row-label{color:var(--text-3);font-weight:600;}
.pc-row-val{font-weight:700;color:var(--text);}
.pc-row-val.resta{color:var(--red);}
.pc-row-val.ok{color:var(--green);}

.config-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:20px 22px;box-shadow:var(--shadow-sm);margin-bottom:24px;}
.config-card-head{font-size:13px;font-weight:800;color:var(--text);margin-bottom:16px;display:flex;align-items:center;gap:8px;}
.config-card-head svg{width:15px;height:15px;stroke:var(--orange);stroke-width:2.2;fill:none;}

.fields-grid{display:grid;grid-template-columns:1fr;gap:14px;}
@media(min-width:500px){.fields-grid{grid-template-columns:repeat(3,1fr);}}

.fg{display:flex;flex-direction:column;gap:5px;}
.fl{font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--text-3);}
.fi-wrap{position:relative;}
.fi-prefix{position:absolute;left:10px;top:50%;transform:translateY(-50%);font-size:13px;font-weight:700;color:var(--text-3);}
input[type=number]{
  width:100%;padding:10px 10px 10px 24px;border:1.5px solid var(--border);border-radius:9px;
  font-size:13px;font-weight:700;color:var(--text);outline:none;transition:.15s;background:var(--surface);
}
input[type=number]:focus{border-color:var(--orange);box-shadow:0 0 0 3px rgba(249,115,22,.1);}
input[type=number].invalid{border-color:var(--red);box-shadow:0 0 0 3px var(--red-lt);}
.fi-hint{font-size:10px;color:var(--text-3);font-weight:500;margin-top:2px;}

.validation-msg{font-size:11px;font-weight:600;color:var(--red);padding:8px 12px;background:var(--red-lt);border-radius:8px;margin-top:10px;display:none;}
.validation-msg.show{display:block;}

.success-banner{display:none;align-items:center;gap:10px;padding:12px 16px;background:var(--green-lt);border:1px solid rgba(16,185,129,.3);border-radius:9px;margin-bottom:16px;font-size:12px;font-weight:700;color:#065f46;animation:fadeUp .2s ease;}
.success-banner.show{display:flex;}
.success-banner svg{width:16px;height:16px;stroke:#065f46;stroke-width:2.2;fill:none;flex-shrink:0;}

.spinner{width:18px;height:18px;border:2.5px solid rgba(249,115,22,.2);border-top-color:var(--orange);border-radius:50%;animation:spin .7s linear infinite;display:inline-block;}

.last-updated{font-size:10px;font-weight:500;color:var(--text-3);margin-top:12px;padding-top:10px;border-top:1px solid var(--border);}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>
<div class="topbar">
  <div class="topbar-icon"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg></div>
  <h1>Configuración de Metas de Ventas</h1>
  <button class="topbar-save" id="btn-save" onclick="guardar()">
    <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
    Guardar metas
  </button>
</div>

<div class="container">

  <div id="success-banner" class="success-banner">
    <svg viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    Metas guardadas correctamente
  </div>

  <div class="section-label">Avance del período</div>
  <div class="progress-grid" id="progress-grid">
    <div class="progress-card diaria" style="display:flex;align-items:center;justify-content:center;min-height:160px;">
      <div class="spinner"></div>
    </div>
  </div>

  <div class="section-label">Configurar metas</div>
  <div class="config-card">
    <div class="config-card-head">
      <svg viewBox="0 0 24 24"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
      Objetivos de venta
    </div>
    <div class="fields-grid">
      <div class="fg">
        <div class="fl">Meta diaria</div>
        <div class="fi-wrap">
          <span class="fi-prefix">$</span>
          <input type="number" id="inp-diaria" min="0" step="100" placeholder="0.00" oninput="validar()"/>
        </div>
        <div class="fi-hint">Objetivo de venta por día</div>
      </div>
      <div class="fg">
        <div class="fl">Meta mensual</div>
        <div class="fi-wrap">
          <span class="fi-prefix">$</span>
          <input type="number" id="inp-mensual" min="0" step="1000" placeholder="0.00" oninput="validar()"/>
        </div>
        <div class="fi-hint">Objetivo de venta del mes</div>
      </div>
      <div class="fg">
        <div class="fl">Meta anual</div>
        <div class="fi-wrap">
          <span class="fi-prefix">$</span>
          <input type="number" id="inp-anual" min="0" step="10000" placeholder="0.00" oninput="validar()"/>
        </div>
        <div class="fi-hint">Objetivo de venta del año</div>
      </div>
    </div>
    <div class="validation-msg" id="val-msg"></div>
    <div class="last-updated" id="last-updated"></div>
  </div>

</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';
// token via _initAuth() de arkhon-utils.js
const fmtPct = n => `${Math.min(999,Math.max(0,Number(n||0))).toFixed(1)}%`;


function donutSVG(pct, color){
  const r = 32, cx = 36, cy = 36, stroke = 7;
  const circ = 2*Math.PI*r;
  const dash = (Math.min(100,pct)/100)*circ;
  return `<svg class="donut-svg" width="72" height="72" viewBox="0 0 72 72">
    <circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="#f3f4f6" stroke-width="${stroke}"/>
    <circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${color}" stroke-width="${stroke}"
      stroke-dasharray="${dash.toFixed(1)} ${(circ-dash).toFixed(1)}"
      stroke-dashoffset="${(circ*0.25).toFixed(1)}"
      stroke-linecap="round" transform="rotate(-90 ${cx} ${cy})"/>
  </svg>`;
}

function renderProgress(d){
  const meta_d = d.meta_diaria||0;
  const meta_m = d.meta_mensual||0;
  const meta_a = d.meta_anual||0;
  const venta_h = d.venta_hoy||0;
  const venta_m = d.venta_mes_actual||0;
  const venta_a = d.venta_anio_actual||0;

  const pct_d = meta_d>0 ? (venta_h/meta_d)*100 : 0;
  const pct_m = meta_m>0 ? (venta_m/meta_m)*100 : 0;
  const pct_a = meta_a>0 ? (venta_a/meta_a)*100 : 0;

  const card = (tipo, cls, color, pct, venta, meta, label) => {
    const resta = Math.max(0, meta-venta);
    const superado = venta >= meta && meta > 0;
    return `<div class="progress-card ${cls}">
      <div class="pc-label ${cls}">${label}</div>
      <div class="donut-wrap">
        ${donutSVG(pct, color)}
        <div class="donut-info">
          <div class="donut-pct ${cls}">${pct.toFixed(1)}%</div>
          <div class="donut-completado">${superado?' Meta alcanzada':pct.toFixed(1)+'% completado'}</div>
        </div>
      </div>
      <div class="pc-row"><span class="pc-row-label">Vendido</span><span class="pc-row-val">${fmt(venta)}</span></div>
      <div class="pc-row"><span class="pc-row-label">Meta</span><span class="pc-row-val">${meta>0?fmt(meta):'Sin definir'}</span></div>
      ${meta>0?`<div class="pc-row"><span class="pc-row-label">${superado?'Excedente':'Resta'}</span><span class="pc-row-val ${superado?'ok':'resta'}">${superado?fmt(venta-meta):fmt(resta)}</span></div>`:''}
    </div>`;
  };

  document.getElementById('progress-grid').innerHTML =
    card('diaria','diaria','#f97316',pct_d,venta_h,meta_d,'Meta diaria — Hoy') +
    card('mensual','mensual','#2563eb',pct_m,venta_m,meta_m,'Meta mensual — Mes actual') +
    card('anual','anual','#10b981',pct_a,venta_a,meta_a,'Meta anual — Año en curso');
}

function validar(){
  const d = parseFloat(document.getElementById('inp-diaria').value)||0;
  const m = parseFloat(document.getElementById('inp-mensual').value)||0;
  const a = parseFloat(document.getElementById('inp-anual').value)||0;
  const msg = document.getElementById('val-msg');
  let err = '';
  if(d>0 && m>0 && d*30>m) err=`La meta diaria (${fmt(d)}) × 30 días (${fmt(d*30)}) supera la meta mensual (${fmt(m)}).`;
  else if(m>0 && a>0 && m*12>a) err=`La meta mensual (${fmt(m)}) × 12 meses (${fmt(m*12)}) supera la meta anual (${fmt(a)}).`;
  msg.textContent = err;
  msg.className = 'validation-msg' + (err?' show':'');
  document.getElementById('inp-diaria').className = 'fi-wrap'+(err&&d>0&&m>0&&d*30>m?' invalid':'');
  return !err;
}

async function cargar(){
  try{
    const d = await api('/metas');
    document.getElementById('inp-diaria').value  = d.meta_diaria||'';
    document.getElementById('inp-mensual').value = d.meta_mensual||'';
    document.getElementById('inp-anual').value   = d.meta_anual||'';
    if(d.fecha_actualizacion){
      document.getElementById('last-updated').textContent =
        'Última actualización: '+new Date(d.fecha_actualizacion).toLocaleString('es-MX',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'});
    }
    renderProgress(d);
  }catch(e){
    document.getElementById('progress-grid').innerHTML =
      `<div style="color:var(--red);font-size:12px;font-weight:600;padding:16px;">Error al cargar: ${e.message}</div>`;
  }
}

async function guardar(){
  if(!validar()) return;
  const btn = document.getElementById('btn-save');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Guardando…';
  try{
    const payload = {
      meta_diaria:  parseFloat(document.getElementById('inp-diaria').value)||0,
      meta_mensual: parseFloat(document.getElementById('inp-mensual').value)||0,
      meta_anual:   parseFloat(document.getElementById('inp-anual').value)||0,
    };
    const d = await api('/metas', {method:'POST',body:JSON.stringify(payload)});
    const banner = document.getElementById('success-banner');
    banner.className = 'success-banner show';
    setTimeout(()=>banner.className='success-banner',3500);
    if(d.data||d.meta_diaria!==undefined) renderProgress(d.data||d);
    await cargar();
  }catch(e){
    const msg = document.getElementById('val-msg');
    msg.textContent = 'Error al guardar: '+e.message;
    msg.className = 'validation-msg show';
  }finally{
    btn.disabled = false;
    btn.innerHTML = '<svg viewBox="0 0 24 24" width="13" height="13" stroke="#fff" stroke-width="2.2" fill="none"><polyline points="20 6 9 17 4 12"/></svg> Guardar metas';
  }
}

(async()=>{await _initAuth();cargar();})();
</script>
</body>
</html>
