// =========================================================================
// DASHBOARD — 3 variantes (Hoy / Funnel / Hero)
// =========================================================================

// Estos cuatro KPIs eran un literal escrito a mano: "Objetivo del mes 27,8k €
// de 45.000 €" con la barra al 62 %, "Facturación propia 12,6k € +18% MoM"…
// Números que no salían de ningún sitio y que se pintaban igual con la base
// vacía, con la base llena o sin sesión. Es la primera pantalla que se ve al
// entrar, así que era lo primero que la herramienta afirmaba, y era falso.
//
// Ahora se calculan. Y lo que no tiene de dónde calcularse NO SE PINTA: un
// hueco se busca, una cifra inventada se da por buena y viaja.
const kpisDelDia = () => {
  const { Icons, DATA } = window;
  const d = DATA || {};
  const yo = d.USER || {};
  const clientes = d.CLIENTS || [];
  const inmuebles = d.INMUEBLES || [];
  const tareas = d.TASKS || [];

  // El objetivo vive en la ficha del usuario (usuarios.objetivo_mensual) y
  // está sin rellenar para todo el equipo. Sin objetivo no hay barra ni
  // porcentaje: inventar el denominador es exactamente lo que hacía antes.
  const miFicha = (d.TEAM || []).find(m => m.initials && yo.initials && m.initials === yo.initials);
  const objetivo = Number((miFicha && miFicha.supabase && miFicha.supabase.objetivo_mensual) || 0);

  // Solo las comisiones que son MÍAS. Un comercial ve únicamente las suyas
  // (así lo filtra RLS), pero el front no debe depender de eso para sumar.
  const mias = (d.COMISIONES_EQUIPO || []).filter(c =>
    yo.initials && c.comercialIniciales === yo.initials);
  const cobrado = mias.reduce((a, c) => a + (Number(c.importe) || 0), 0);

  const items = [];

  if (objetivo > 0) {
    items.push({
      icon: Icons.Trophy, label: "Objetivo del mes", value: window.fmtEUR(cobrado),
      sub: "de " + window.fmtEUR(objetivo), bar: Math.min(100, Math.round(cobrado / objetivo * 100)),
      accent: true,
    });
  }

  items.push({ icon: Icons.Users, label: "Mis clientes", value: clientes.length,
    sub: clientes.length ? null : "sin cartera asignada" });
  items.push({ icon: Icons.Building, label: "Inmuebles en cartera", value: inmuebles.length });
  items.push({ icon: Icons.CheckSq, label: "Tareas pendientes",
    value: tareas.filter(t => !t.done).length });

  // La comisión propia solo se enseña si hay alguna. Un "0 €" el primer día
  // no informa de nada y se lee como si algo hubiera fallado.
  if (mias.length) {
    items.push({ icon: Icons.Euro, label: "Mis comisiones", value: window.fmtEUR(cobrado),
      sub: mias.length + (mias.length === 1 ? " operación" : " operaciones") });
  }

  return items;
};

// ---------- VARIANT A — "Mi día" (lista priorizada) ----------
const DashboardA = ({ goTo }) => {
  const { Icons, DATA, Card, KPIRow, PageHeader } = window;
  const Action = ({ a }) => {
    const map = { call: "Llamar", visit: "Confirmar", wa: "WhatsApp", firma: "Recordar", deal: "Llamar", capt: "Ver ruta" };
    return <button className="btn xs secondary">{map[a] || "Abrir"}</button>;
  };
  // Usuario actual + fecha reales (bug #11 / #4). El saludo ya no es "Elena".
  const _now = new Date();
  const _h = _now.getHours();
  const _saludo = _h < 6 ? "Buenas noches" : _h < 14 ? "Buenos días" : _h < 21 ? "Buenas tardes" : "Buenas noches";
  const _nombre = (DATA.USER?.name || "").split(" ")[0];
  const _hoy = _now.toLocaleDateString("es-ES", { day: "2-digit", month: "short" }).replace(".", "").toUpperCase();
  const _nTareas = (DATA.TODAY_AGENDA || []).length;
  const _nRiesgo = (DATA.COOLING_CLIENTS || []).length;
  return (
    <>
      <PageHeader
        eyebrow={_saludo + (_nombre ? ", " + _nombre : "")}
        title={"HOY · " + _hoy}
        sub={`${_nTareas} ${_nTareas === 1 ? "tarea" : "tareas"} hoy · ${_nRiesgo} ${_nRiesgo === 1 ? "cliente" : "clientes"} en riesgo`}
        actions={<>
          <button className="btn secondary"><Icons.Calendar/> Ver semana</button>
          <button className="btn primary" onClick={() => window.RevinNav?.crearInmueble?.()}><Icons.Plus/> Crear inmueble</button>
        </>}
      />
      <KPIRow items={kpisDelDia()}/>
      <div className="dash-2col">
        <Card
          title={"Mi día · " + _now.toLocaleDateString("es-ES", { day: "numeric", month: "long" })}
          right={<button className="btn xs ghost"><Icons.MoreH/></button>}
          b={false}
        >
          <div className="today-list">
            {DATA.TODAY_AGENDA.map((t, i) => {
              const IcoMap = { Phone: Icons.Phone, Eye: Icons.Eye, Doc: Icons.Doc, Whatsapp: Icons.Whatsapp, Calendar: Icons.Calendar, Receipt: Icons.Receipt, Plus: Icons.Plus };
              const I = IcoMap[t.icon] || Icons.Clock;
              return (
                <div className="today-item" key={i} onClick={() => goTo("inmuebles")}>
                  <div className="time-slot">{t.time}</div>
                  <div className={"ico-wrap " + t.tone}><I/></div>
                  <div className="today-body">
                    <div className="today-title">{t.title}</div>
                    <div className="today-sub">{t.sub}</div>
                  </div>
                  <div className="today-actions"><Action a={t.action}/></div>
                </div>
              );
            })}
          </div>
        </Card>
        <div style={{display: "flex", flexDirection: "column", gap: 16}}>
          <div className="cooling-card">
            <div className="cc-h">
              <h3><Icons.Flame/> Clientes en riesgo</h3>
              <span className="pill red">{_nRiesgo}</span>
            </div>
            {DATA.COOLING_CLIENTS.map(c => (
              <div className="cooling-row" key={c.id} onClick={() => goTo("clientes")}>
                <div className="ava">{c.name.split(" ").map(p => p[0]).slice(0,2).join("")}</div>
                <div className="cooling-body">
                  <div className="cooling-name">{c.name}</div>
                  <div className="cooling-sub">{c.reason}</div>
                </div>
                <div className="cooling-days">{c.days}d</div>
              </div>
            ))}
          </div>
          <Card title="Cierres esta semana" b={false}>
            <window.DemoBlockMark bloque="WEEKLY_BARS">Gráfico de ejemplo.</window.DemoBlockMark>
            <div style={{padding: "8px 16px 12px"}}>
              <div className="chart-bars">
                {DATA.WEEKLY_BARS.map((b, i) => (
                  <div key={i} className={"bar-col" + (b.active ? " active" : "")}>
                    <div className="bar-val">{b.val}</div>
                    <div className="bar" style={{height: (b.val * 22 + 4) + "px"}}/>
                    <div className="bar-lbl">{b.day}</div>
                  </div>
                ))}
              </div>
              <div style={{fontSize: 11, color: "var(--fg-3)", marginTop: 4}}>Cierres/día · hoy: <b style={{color: "var(--fg-1)"}}>4 firmas</b></div>
            </div>
          </Card>
        </div>
      </div>

      <div style={{marginTop: 20}}>
        <Card
          title="Inventario por fase del Playbook"
          right={<button className="btn xs ghost" onClick={() => goTo("pipeline")}><Icons.ArrowUpRight/> Abrir pipeline</button>}
        >
          <window.DemoBlockMark bloque="PIPELINE_DONUT">Gráfico de ejemplo.</window.DemoBlockMark>
          <div style={{display: "flex", gap: 24, alignItems: "center"}}>
            <div className="donut"/>
            <div className="donut-legend">
              {DATA.PIPELINE_DONUT.map((p, i) => (
                <div className="legend-item" key={i}>
                  <span className="swatch" style={{background: p.color}}/>
                  {p.lbl}
                  <span className="val">{p.val} inmuebles</span>
                </div>
              ))}
              <div className="legend-item" style={{marginTop: 8, paddingTop: 8, borderTop: "1px solid var(--border-1)"}}>
                <b>Total</b>
                <span className="val"><b>29 inmuebles</b> · 4,8 M €</span>
              </div>
            </div>
          </div>
        </Card>
      </div>
    </>
  );
};

// ---------- VARIANT B — "Embudo de operaciones" ----------
const DashboardB = ({ goTo }) => {
  const { Icons, DATA, Card, KPIRow, PageHeader } = window;
  const funnel = [
    { lbl: "Leads", val: 142, pct: 100, cls: "" },
    { lbl: "Cualificados", val: 86, pct: 60, cls: "info" },
    { lbl: "Visitas", val: 42, pct: 30, cls: "warn" },
    { lbl: "Ofertas", val: 12, pct: 9, cls: "red" },
    { lbl: "Cerrados", val: 4, pct: 3, cls: "success" },
  ];
  return (
    <>
      <PageHeader
        eyebrow="Vista de operaciones"
        title="EMBUDO · MARZO"
        sub="Conversión global de leads a cierres este mes · datos en tiempo real"
        actions={<>
          <button className="btn secondary"><Icons.Download/> Exportar</button>
          <button className="btn primary" onClick={() => window.RevinNav?.crearInmueble?.()}><Icons.Plus/> Crear inmueble</button>
        </>}
      />
      <KPIRow items={kpisDelDia()}/>
      <div className="dash-2col">
        <Card title="Embudo del mes">
          <div className="funnel-stack">
            {funnel.map((f, i) => (
              <div className="funnel-row" key={i}>
                <span className="lbl">{f.lbl}</span>
                <div className={"funnel-bar " + f.cls} style={{width: f.pct + "%"}}>
                  {f.val}
                  <span className="pct">{f.pct}%</span>
                </div>
              </div>
            ))}
          </div>
          <div style={{marginTop: 16, padding: 12, background: "var(--bg-inset)", borderRadius: 4, fontSize: 12, color: "var(--fg-2)", lineHeight: 1.6}}>
            <b style={{color: "var(--fg-1)"}}>Cuello de botella detectado:</b> caída del 71% entre visitas y ofertas. Revisar feedback de visitas en <a onClick={() => goTo("inmuebles")} style={{color: "var(--revin-red)", cursor: "pointer", fontWeight: 600}}>la sección de cartera</a>.
          </div>
        </Card>
        <Card title="Top performers" right={<Pill tone="brand">MARZO</Pill>}>
          {(window.RevinTeam?.comercialesConComisiones() || []).map((m, i) => {
            const comms = (DATA.COMMISSIONS || []).filter(c => c.captador === m.id || c.comercializador === m.id);
            const facturado = comms.reduce((s, c) => s + (c.captador === m.id ? c.capt : 0) + (c.comercializador === m.id ? c.com : 0), 0);
            const objetivo = m.supabase?.objetivo_mensual || 0;
            const pct = objetivo > 0 ? Math.min(100, Math.round((facturado / objetivo) * 100)) : 0;
            const hasData = comms.length > 0;
            return (
              <div className="leader-row" key={m.initials} style={{padding: "10px 0", gridTemplateColumns: "20px 1fr 90px 60px"}}>
                <div className="pos">{i + 1}</div>
                <div className="who"><div className="ava">{m.initials}</div><div><div className="name">{m.name}</div><div className="role">{m.role}</div></div></div>
                <div className={"num " + (hasData ? "fin-amt fin-in" : "fin-info")}>{hasData ? window.fmtEUR(facturado) : "—"}</div>
                <div className="target-bar"><div className="bar"><span style={{width: pct + "%"}}/></div></div>
              </div>
            );
          })}
          {(window.RevinTeam?.comercialesConComisiones() || []).length === 0 && (
            <div className="empty" style={{padding: 12}}>
              <span style={{fontSize: 12}}>Aún no hay comerciales en el equipo.</span>
            </div>
          )}
        </Card>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 20}}>
        <div className="cooling-card">
          <div className="cc-h">
            <h3><Icons.Flame/> Clientes en riesgo de enfriamiento</h3>
            <span className="pill red">3</span>
          </div>
          {DATA.COOLING_CLIENTS.map(c => (
            <div className="cooling-row" key={c.id} onClick={() => goTo("clientes")}>
              <div className="ava">{c.name.split(" ").map(p => p[0]).slice(0,2).join("")}</div>
              <div className="cooling-body">
                <div className="cooling-name">{c.name}</div>
                <div className="cooling-sub">{c.reason}</div>
              </div>
              <div className="cooling-days">{c.days}d</div>
            </div>
          ))}
        </div>
        <Card title="Ofertas pendientes">
          <div style={{display: "flex", flexDirection: "column", gap: 10}}>
            {[
              { addr: "Virgen Cabeza 41 · Andújar", off: "224.000 €", ask: "248.000 €", days: 2 },
              { addr: "Plaza San Francisco 6", off: "165.000 €", ask: "168.000 €", days: 1 },
              { addr: "Real 24, 3ºD · Jaén", off: "138.000 €", ask: "145.000 €", days: 4 },
            ].map((o, i) => (
              <div key={i} style={{display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 12px", border: "1px solid var(--border-1)", borderRadius: 4}}>
                <div>
                  <div style={{fontSize: 13, fontWeight: 600}}>{o.addr}</div>
                  <div style={{fontSize: 11, color: "var(--fg-3)", marginTop: 2}}>Asking: {o.ask} · hace {o.days}d</div>
                </div>
                <div style={{fontFamily: "var(--font-display)", fontSize: 16, color: "var(--revin-red)"}}>{o.off}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
};

// ---------- VARIANT C — "Hero brutalista" ----------
const DashboardC = ({ goTo }) => {
  const { Icons, DATA, Card, KPIRow } = window;
  // Saludo/fecha/nombre reales (bug #11 / #4). Firmas/facturado siguen mock.
  const _now = new Date();
  const _h = _now.getHours();
  const _saludo = _h < 6 ? "BUENAS NOCHES" : _h < 14 ? "BUENOS DÍAS" : _h < 21 ? "BUENAS TARDES" : "BUENAS NOCHES";
  const _fecha = _now.toLocaleDateString("es-ES", { day: "2-digit", month: "short", weekday: "long" }).replace(".", "").toUpperCase();
  const _nombre = ((DATA.USER?.name || "").split(" ")[0] || "").toUpperCase();
  const _nTareas = (DATA.TODAY_AGENDA || []).length;
  const _nRiesgo = (DATA.COOLING_CLIENTS || []).length;
  return (
    <>
      <div className="dash-hero" style={{borderRadius: 4, marginBottom: 24}}>
        <div className="chev-mark">›››</div>
        <div className="he-greet">{_saludo + " · " + _fecha}</div>
        <h1>HOLA <span className="red">{_nombre ? _nombre + "." : "REVIN."}</span><br/>HOY HAY <span className="red">3 FIRMAS.</span></h1>
        <div className="stats">
          <div><div className="stat-num">27.8k €</div><div className="stat-lbl">Facturado este mes</div></div>
          <div><div className="stat-num">62%</div><div className="stat-lbl">Objetivo cumplido</div></div>
          <div><div className="stat-num">{_nTareas}</div><div className="stat-lbl">Tareas hoy</div></div>
          <div><div className="stat-num" style={{color: "var(--revin-red)"}}>{_nRiesgo}</div><div className="stat-lbl">Clientes en riesgo</div></div>
        </div>
      </div>

      <div className="dash-2col">
        <Card
          title="Próximas acciones"
          right={<button className="btn xs primary" onClick={() => goTo("agenda")}><Icons.Calendar/> Ver agenda</button>}
          b={false}
        >
          <div className="today-list">
            {DATA.TODAY_AGENDA.slice(0, 5).map((t, i) => {
              const IcoMap = { Phone: Icons.Phone, Eye: Icons.Eye, Doc: Icons.Doc, Whatsapp: Icons.Whatsapp, Calendar: Icons.Calendar, Receipt: Icons.Receipt, Plus: Icons.Plus };
              const I = IcoMap[t.icon] || Icons.Clock;
              return (
                <div className="today-item" key={i} onClick={() => goTo("inmuebles")}>
                  <div className="time-slot">{t.time}</div>
                  <div className={"ico-wrap " + t.tone}><I/></div>
                  <div className="today-body">
                    <div className="today-title">{t.title}</div>
                    <div className="today-sub">{t.sub}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
        <Card title="Cierres semana" b={false}>
          <window.DemoBlockMark bloque="WEEKLY_BARS">Gráfico de ejemplo.</window.DemoBlockMark>
          <div style={{padding: "8px 16px 12px"}}>
            <div className="chart-bars">
              {DATA.WEEKLY_BARS.map((b, i) => (
                <div key={i} className={"bar-col" + (b.active ? " active" : "")}>
                  <div className="bar-val">{b.val}</div>
                  <div className="bar" style={{height: (b.val * 22 + 4) + "px"}}/>
                  <div className="bar-lbl">{b.day}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{padding: "0 16px 16px"}}>
            <div className="cooling-card" style={{marginTop: 12}}>
              <div className="cc-h">
                <h3><Icons.Flame/> En riesgo · 3</h3>
              </div>
              {DATA.COOLING_CLIENTS.slice(0, 2).map(c => (
                <div className="cooling-row" key={c.id}>
                  <div className="ava">{c.name.split(" ").map(p => p[0]).slice(0,2).join("")}</div>
                  <div className="cooling-body">
                    <div className="cooling-name">{c.name}</div>
                    <div className="cooling-sub">{c.reason}</div>
                  </div>
                  <div className="cooling-days">{c.days}d</div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>
    </>
  );
};

window.DashboardA = DashboardA;
window.DashboardB = DashboardB;
window.DashboardC = DashboardC;
