gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198629 Sutichaykuna

⎇ 7eb620aa170f825b5dec6ff454baac07c48bd9f1 crates/modules/tahuantinsuyu/tahuantinsuyu-canvas/src/lib.rs Rust · 2821 siq'ikuna · 102.5 KB Ñawpa willay Pi imata llamkarqan ch'uya

feat(tahuantinsuyu): GR dual-ring + topo ascensional pegado al dial + coords 7eb620aa1 · sergio ·

1//! `tahuantinsuyu-canvas` — el widget GPUI del lienzo astrológico.
2//!
3//! Modela el cielo como un lienzo de **geometría reactiva**: un estado
4//! unificado [`CanvasState`] guarda offsets de rotación, flags de
5//! visibilidad y la lista de `Layer`s a pintar. Las interacciones
6//! (drag, hotkeys, toggles) mutan el estado; el render lee la última
7//! `RenderModel` y la deriva al frame.
8//!
9//! ## Convención de rotación
10//!
11//! El Ascendente cae a las 9 del reloj (lado izquierdo). Las casas
12//! crecen contrarreloj visualmente. Para una longitud eclíptica `L` y
13//! un ascendente `asc`:
14//!
15//! ```text
16//!   screen_angle_rad = π - (L - asc + view_rotation) · π/180
17//!   point = (cx + r·cos(θ), cy + r·sin(θ))
18//! ```
19//!
20//! ## Interacciones (fase 4)
21//!
22//! - **Drag en el aro exterior** (jog-dial perimetral): rota la rueda
23//!   visualmente mientras dura el drag y, al soltar, traduce el delta
24//!   angular a minutos (1° ≈ 4 min) y emite
25//!   [`CanvasEvent::TimeOffsetChanged`]. El host (la app) recomputa la
26//!   carta para el instante desplazado.
27//! - **Hotkeys**: `D`/`H`/`X`/`P` togglean SignDial/Houses/Aspects/
28//!   Bodies. Click sobre el wheel le da focus al widget.
29
30#![forbid(unsafe_code)]
31#![warn(rust_2018_idioms)]
32
33use std::collections::HashMap;
34use std::f32::consts::PI;
35
36use gpui::{
37    Bounds, Context, EventEmitter, FocusHandle, Focusable, Hsla, IntoElement,
38    KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement,
39    PathBuilder, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, SharedString, Styled,
40    Window, canvas, div, hsla, point, prelude::*, px,
41};
42
43use tahuantinsuyu_engine::{Geometry, Layer, LayerKind, OUTER_RING_MODULES, RenderModel};
44use tahuantinsuyu_model::{ChartId, ContactId, GroupId};
45use tahuantinsuyu_theme::{AspectKind as TAspectKind, AstroPalette, Element, Planet};
46use yahweh_theme::Theme;
47
48// =====================================================================
49// Eventos
50// =====================================================================
51
52#[derive(Clone, Debug)]
53pub enum CanvasEvent {
54    /// Doble click sobre un thumbnail.
55    ChartRequested(ChartId),
56    /// Drag terminado: el offset acumulado de tiempo (en minutos)
57    /// cambió. El host debe recomputar el chart con este offset.
58    TimeOffsetChanged(i64),
59    /// El usuario togggleó una capa via hotkey — el panel debería
60    /// reflejarlo si quisiera mantenerse en sync.
61    LayerVisibilityChanged { kind: LayerKind, visible: bool },
62    /// El usuario togggleó los coord labels via hotkey C. El panel
63    /// debe sincronizar el toggle "show_coords" del NatalModule.
64    ShowCoordsChanged(bool),
65    /// El usuario pidió exportar el render actual como SVG. El shell
66    /// se encarga de escribir el archivo (la engine genera el string).
67    ExportSvgRequested,
68}
69
70// =====================================================================
71// Estado
72// =====================================================================
73
74#[derive(Clone, Debug, Default)]
75pub enum CanvasMode {
76    #[default]
77    Empty,
78    Wheel { render: Box<RenderModel> },
79    Thumbnails {
80        scope: ThumbnailScope,
81        items: Vec<ThumbnailItem>,
82    },
83}
84
85#[derive(Clone, Debug)]
86pub enum ThumbnailScope {
87    Group(GroupId),
88    Contact(ContactId),
89}
90
91#[derive(Clone, Debug)]
92pub struct ThumbnailItem {
93    pub chart_id: ChartId,
94    pub label: SharedString,
95    pub subtitle: Option<SharedString>,
96    pub preview: Option<RenderModel>,
97}
98
99/// Estado de un drag activo del jog-dial. `last_screen_angle_deg` se
100/// actualiza en cada `MouseMoveEvent`; `accumulated_delta_deg` lleva la
101/// rotación total desde que arrancó el drag (puede pasar de ±360°).
102#[derive(Clone, Debug)]
103struct JogDragState {
104    last_screen_angle_deg: f32,
105    accumulated_delta_deg: f32,
106}
107
108/// Drag activo de pan (MMB o LMB con Space). Captura el pan inicial al
109/// hacer mousedown; el move agrega delta_pos a esos valores.
110#[derive(Clone, Debug)]
111struct PanDragState {
112    start_pos: Point<Pixels>,
113    pan_x_start: f32,
114    pan_y_start: f32,
115}
116
117#[derive(Clone, Debug)]
118pub struct CanvasState {
119    pub mode: CanvasMode,
120    /// Rotación visual transitoria durante un drag. Se resetea a `0` al
121    /// soltar — el render nuevo trae el `ascendant_deg` ya rotado.
122    pub view_rotation_deg: f32,
123    /// Offset acumulado en minutos. Persiste entre drags hasta que el
124    /// host lo resetee.
125    pub time_offset_minutes: i64,
126    /// Factor de zoom multiplicativo aplicado al wheel. `1.0` = tamaño
127    /// nominal. Clampeado a [VIEW_SCALE_MIN, VIEW_SCALE_MAX].
128    pub view_scale: f32,
129    /// Pan horizontal en px (positivo = desplaza el wheel a la derecha
130    /// desde el centro). Se aplica como margin shift sobre el centrado
131    /// natural del flex parent.
132    pub view_pan_x: f32,
133    /// Pan vertical en px (positivo = abajo).
134    pub view_pan_y: f32,
135    /// Por-LayerKind: `true` = visible. Default = todo visible.
136    pub layer_visibility: HashMap<LayerKind, bool>,
137    /// Indicadores de grado al lado de cada planeta y cusp de casa.
138    /// Default `true` — el usuario los espera ver para leer la
139    /// carta. Se togglean con `C` (Coords) o desde el panel.
140    pub show_coords: bool,
141    /// Planeta hovered actualmente (para tooltip). `None` cuando el
142    /// mouse no está sobre ningún cuerpo.
143    pub hover: Option<HoverInfo>,
144    drag_jog: Option<JogDragState>,
145    drag_pan: Option<PanDragState>,
146}
147
148/// Límites del zoom — bajo 0.5 los glyphs se vuelven ilegibles; sobre
149/// 3.0 el wheel desborda incluso pantallas grandes.
150pub const VIEW_SCALE_MIN: f32 = 0.5;
151pub const VIEW_SCALE_MAX: f32 = 3.0;
152
153/// Info del elemento bajo el cursor — usado por el render para mostrar
154/// un tooltip flotante con detalles. Cubre body glyphs, cusps de casa,
155/// y líneas de aspectos.
156#[derive(Clone, Debug)]
157pub enum HoverInfo {
158    Body {
159        module_id: String,
160        symbol: String,
161        deg: f32,
162        house: Option<u8>,
163        retrograde: bool,
164        dignity_marker: Option<String>,
165        annotation: Option<String>,
166        local_x: f32,
167        local_y: f32,
168    },
169    HouseCusp {
170        house_number: u8,
171        deg: f32,
172        local_x: f32,
173        local_y: f32,
174    },
175    /// Hover sobre una línea de aspecto. `from_body`/`to_body` y `kind`
176    /// vienen de la LineSeg; `orb_deg` también. Los coords son el
177    /// punto medio del segmento donde se muestra el tooltip.
178    Aspect {
179        module_id: String,
180        from_body: String,
181        to_body: String,
182        kind: String,
183        orb_deg: f32,
184        local_x: f32,
185        local_y: f32,
186    },
187}
188
189impl HoverInfo {
190    fn local(&self) -> (f32, f32) {
191        match self {
192            HoverInfo::Body { local_x, local_y, .. } => (*local_x, *local_y),
193            HoverInfo::HouseCusp { local_x, local_y, .. } => (*local_x, *local_y),
194            HoverInfo::Aspect { local_x, local_y, .. } => (*local_x, *local_y),
195        }
196    }
197
198    fn key(&self) -> String {
199        match self {
200            HoverInfo::Body {
201                module_id, symbol, ..
202            } => format!("body:{}:{}", module_id, symbol),
203            HoverInfo::HouseCusp { house_number, .. } => format!("cusp:{}", house_number),
204            HoverInfo::Aspect {
205                module_id,
206                from_body,
207                to_body,
208                kind,
209                ..
210            } => format!("aspect:{}:{}-{}-{}", module_id, from_body, kind, to_body),
211        }
212    }
213}
214
215impl Default for CanvasState {
216    fn default() -> Self {
217        Self {
218            mode: CanvasMode::default(),
219            view_rotation_deg: 0.0,
220            time_offset_minutes: 0,
221            view_scale: 1.0,
222            view_pan_x: 0.0,
223            view_pan_y: 0.0,
224            layer_visibility: HashMap::new(),
225            show_coords: true,
226            hover: None,
227            drag_jog: None,
228            drag_pan: None,
229        }
230    }
231}
232
233impl CanvasState {
234    pub fn is_layer_visible(&self, kind: LayerKind) -> bool {
235        self.layer_visibility.get(&kind).copied().unwrap_or(true)
236    }
237}
238
239// =====================================================================
240// Widget
241// =====================================================================
242
243pub struct AstrologyCanvas {
244    state: CanvasState,
245    focus_handle: FocusHandle,
246}
247
248impl EventEmitter<CanvasEvent> for AstrologyCanvas {}
249
250impl Focusable for AstrologyCanvas {
251    fn focus_handle(&self, _: &gpui::App) -> FocusHandle {
252        self.focus_handle.clone()
253    }
254}
255
256impl AstrologyCanvas {
257    pub fn new(cx: &mut Context<'_, Self>) -> Self {
258        cx.observe_global::<Theme>(|_, cx| cx.notify()).detach();
259        Self {
260            state: CanvasState::default(),
261            focus_handle: cx.focus_handle(),
262        }
263    }
264
265    pub fn state(&self) -> &CanvasState {
266        &self.state
267    }
268
269    pub fn set_mode(&mut self, mode: CanvasMode, cx: &mut Context<'_, Self>) {
270        self.state.mode = mode;
271        cx.notify();
272    }
273
274    pub fn set_layer_visible(&mut self, kind: LayerKind, visible: bool, cx: &mut Context<'_, Self>) {
275        self.state.layer_visibility.insert(kind, visible);
276        cx.notify();
277    }
278
279    pub fn toggle_layer(&mut self, kind: LayerKind, cx: &mut Context<'_, Self>) {
280        let current = self.state.is_layer_visible(kind);
281        self.set_layer_visible(kind, !current, cx);
282        cx.emit(CanvasEvent::LayerVisibilityChanged {
283            kind,
284            visible: !current,
285        });
286    }
287
288    pub fn reset_time_offset(&mut self, cx: &mut Context<'_, Self>) {
289        if self.state.time_offset_minutes != 0 || self.state.view_rotation_deg != 0.0 {
290            self.state.time_offset_minutes = 0;
291            self.state.view_rotation_deg = 0.0;
292            cx.emit(CanvasEvent::TimeOffsetChanged(0));
293            cx.notify();
294        }
295    }
296
297    pub fn set_view_rotation(&mut self, deg: f32, cx: &mut Context<'_, Self>) {
298        self.state.view_rotation_deg = deg.rem_euclid(360.0);
299        cx.notify();
300    }
301
302    pub fn toggle_coords(&mut self, cx: &mut Context<'_, Self>) {
303        let new_val = !self.state.show_coords;
304        self.set_show_coords(new_val, cx);
305        cx.emit(CanvasEvent::ShowCoordsChanged(new_val));
306    }
307
308    /// Setter idempotente — el shell lo usa para reflejar cambios del
309    /// panel sin disparar el `ShowCoordsChanged` (que iría en el otro
310    /// sentido y crearía un loop).
311    pub fn set_show_coords(&mut self, value: bool, cx: &mut Context<'_, Self>) {
312        if self.state.show_coords != value {
313            self.state.show_coords = value;
314            cx.notify();
315        }
316    }
317
318    /// Resetea zoom y pan a sus defaults (1.0 y 0,0). No toca rotation
319    /// ni time offset — esos son ortogonales y tienen su propio reset.
320    pub fn reset_view(&mut self, cx: &mut Context<'_, Self>) {
321        if self.state.view_scale != 1.0
322            || self.state.view_pan_x != 0.0
323            || self.state.view_pan_y != 0.0
324        {
325            self.state.view_scale = 1.0;
326            self.state.view_pan_x = 0.0;
327            self.state.view_pan_y = 0.0;
328            cx.notify();
329        }
330    }
331
332    /// Zoom multiplicativo. El nuevo scale es `current * factor`, clamp
333    /// al rango permitido. El zoom es centrado (no rastrea el cursor) —
334    /// para mover el foco después del zoom, el usuario paneja con MMB.
335    fn zoom_by(&mut self, factor: f32, cx: &mut Context<'_, Self>) {
336        let new_scale =
337            (self.state.view_scale * factor).clamp(VIEW_SCALE_MIN, VIEW_SCALE_MAX);
338        if (new_scale - self.state.view_scale).abs() < 1e-4 {
339            return;
340        }
341        // Mantener el centro del wheel anclado al centro de pantalla:
342        // como el pan está en coords de la pantalla y el zoom es desde
343        // el centro del wheel, el pan se escala proporcional al ratio.
344        let ratio = new_scale / self.state.view_scale;
345        self.state.view_pan_x *= ratio;
346        self.state.view_pan_y *= ratio;
347        self.state.view_scale = new_scale;
348        cx.notify();
349    }
350
351    #[allow(dead_code)]
352    fn pan_by(&mut self, dx: f32, dy: f32, cx: &mut Context<'_, Self>) {
353        if dx == 0.0 && dy == 0.0 {
354            return;
355        }
356        self.state.view_pan_x += dx;
357        self.state.view_pan_y += dy;
358        cx.notify();
359    }
360
361    // ----- Internos: handlers de jog-dial -----
362
363    /// Despacha el LMB down entre jog-dial y pan. El jog-dial es un
364    /// control "fuerte" (mueve el tiempo de la carta), así que se
365    /// activa SOLO con modifier Ctrl/Cmd + click sobre el anillo de
366    /// signos — sin modifier es siempre pan, incluso sobre el anillo,
367    /// para que no haya rotaciones accidentales al manipular la
368    /// rueda.
369    fn on_primary_down(
370        &mut self,
371        position: Point<Pixels>,
372        modifiers: gpui::Modifiers,
373        bounds: Bounds<Pixels>,
374        cx: &mut Context<'_, Self>,
375    ) {
376        // Sin modifier: pan, sin importar dónde caiga el click.
377        if !(modifiers.control || modifiers.platform) {
378            self.on_pan_down(position, cx);
379            return;
380        }
381        let (cx_px, cy_px) = bounds_center(bounds);
382        let mx: f32 = position.x.into();
383        let my: f32 = position.y.into();
384        let dx = mx - cx_px;
385        let dy = my - cy_px;
386        let dist = (dx * dx + dy * dy).sqrt();
387        let r_outer = effective_r_outer(bounds);
388        let radii = Radii::from_outer(r_outer);
389        let on_dial = dist >= radii.sign_inner * 0.95 && dist <= radii.sign_outer * 1.10;
390        if on_dial {
391            let angle = dy.atan2(dx).to_degrees();
392            self.state.drag_jog = Some(JogDragState {
393                last_screen_angle_deg: angle,
394                accumulated_delta_deg: 0.0,
395            });
396        } else {
397            // Ctrl+click fuera del anillo: pan también — el modifier
398            // habilita el jog-dial pero no impide la navegación.
399            self.on_pan_down(position, cx);
400        }
401    }
402
403    fn on_jog_move(
404        &mut self,
405        position: Point<Pixels>,
406        bounds: Bounds<Pixels>,
407        cx: &mut Context<'_, Self>,
408    ) {
409        let Some(jog) = self.state.drag_jog.as_mut() else {
410            return;
411        };
412        let (cx_px, cy_px) = bounds_center(bounds);
413        let mx: f32 = position.x.into();
414        let my: f32 = position.y.into();
415        let dx = mx - cx_px;
416        let dy = my - cy_px;
417        let angle = dy.atan2(dx).to_degrees();
418        let mut delta = angle - jog.last_screen_angle_deg;
419        // Normalizar a (-180, 180] para cruzar el wrap sin saltar.
420        if delta > 180.0 {
421            delta -= 360.0;
422        } else if delta < -180.0 {
423            delta += 360.0;
424        }
425        jog.accumulated_delta_deg += delta;
426        jog.last_screen_angle_deg = angle;
427        // Reflejo visual durante el drag (sin recomputar).
428        self.state.view_rotation_deg = jog.accumulated_delta_deg;
429        cx.notify();
430    }
431
432    /// Hit-test sobre body glyphs + house cusps. Para bodies: distancia
433    /// al centro del glyph dentro de threshold. Para cusps: el mouse
434    /// debe estar cerca del ring de casas Y angularmente cerca del
435    /// cusp (proximidad a la línea radial).
436    fn on_hover_check(
437        &mut self,
438        position: Point<Pixels>,
439        bounds: Bounds<Pixels>,
440        cx: &mut Context<'_, Self>,
441    ) {
442        let CanvasMode::Wheel { render } = &self.state.mode else {
443            if self.state.hover.take().is_some() {
444                cx.notify();
445            }
446            return;
447        };
448        let (cx_px, cy_px) = bounds_center(bounds);
449        let mx: f32 = position.x.into();
450        let my: f32 = position.y.into();
451        let ox: f32 = bounds.origin.x.into();
452        let oy: f32 = bounds.origin.y.into();
453        let r_outer = effective_r_outer(bounds);
454        let radii = Radii::from_outer(r_outer);
455        let asc = render.ascendant_deg;
456        let rot = self.state.view_rotation_deg;
457        let body_threshold = 14.0_f32;
458
459        let mut best: Option<(f32, HoverInfo)> = None;
460
461        // 1) Body glyphs (incluye natal, overlays, midpoints).
462        for layer in &render.layers {
463            let ring = match layer.kind {
464                LayerKind::Bodies => radii.body_ring(&layer.module_id),
465                LayerKind::Midpoints => radii.midpoints,
466                LayerKind::Outer if OUTER_RING_MODULES.contains(&layer.module_id.as_str()) => {
467                    radii.transits
468                }
469                _ => continue,
470            };
471            for g in &layer.glyphs {
472                let (gx, gy) = polar_to_screen(g.deg, asc, rot, ring);
473                let dx = mx - (cx_px + gx);
474                let dy = my - (cy_px + gy);
475                let dist = (dx * dx + dy * dy).sqrt();
476                if dist > body_threshold {
477                    continue;
478                }
479                if best.as_ref().map(|(d, _)| dist < *d).unwrap_or(true) {
480                    best = Some((
481                        dist,
482                        HoverInfo::Body {
483                            module_id: layer.module_id.clone(),
484                            symbol: g.symbol.clone(),
485                            deg: g.deg,
486                            house: g.house,
487                            retrograde: g.retrograde,
488                            dignity_marker: g.dignity_marker.clone(),
489                            annotation: g.annotation.clone(),
490                            local_x: cx_px + gx - ox,
491                            local_y: cy_px + gy - oy,
492                        },
493                    ));
494                }
495            }
496        }
497
498        // 2) Aspect lines (segundo: las líneas son más "frágiles" que
499        // los planetas; si un body matcheó arriba ya tomó precedencia).
500        // Computa distancia punto-segmento del mouse al line.
501        if best.is_none() {
502            for layer in &render.layers {
503                if !matches!(layer.kind, LayerKind::Aspects) {
504                    continue;
505                }
506                let (r_from, r_to) = radii.aspect_endpoints(&layer.module_id);
507                if let Geometry::Lines(segs) = &layer.geometry {
508                    for seg in segs {
509                        if seg.from_body.is_empty() || seg.to_body.is_empty() {
510                            continue;
511                        }
512                        let (ax, ay) = polar_to_screen(seg.from_deg, asc, rot, r_from);
513                        let (bx, by) = polar_to_screen(seg.to_deg, asc, rot, r_to);
514                        let px_a = cx_px + ax;
515                        let py_a = cy_px + ay;
516                        let px_b = cx_px + bx;
517                        let py_b = cy_px + by;
518                        let dist = dist_point_segment(mx, my, px_a, py_a, px_b, py_b);
519                        if dist > 4.0 {
520                            continue;
521                        }
522                        if best.as_ref().map(|(d, _)| dist < *d).unwrap_or(true) {
523                            let mid_x = (px_a + px_b) / 2.0;
524                            let mid_y = (py_a + py_b) / 2.0;
525                            best = Some((
526                                dist,
527                                HoverInfo::Aspect {
528                                    module_id: layer.module_id.clone(),
529                                    from_body: seg.from_body.clone(),
530                                    to_body: seg.to_body.clone(),
531                                    kind: seg.kind.clone(),
532                                    orb_deg: seg.orb_deg,
533                                    local_x: mid_x - ox,
534                                    local_y: mid_y - oy,
535                                },
536                            ));
537                        }
538                    }
539                }
540            }
541        }
542
543        // 3) House cusps — solo si el mouse está cerca del anillo de
544        // casas (radio entre houses_inner y houses_outer + margen) y
545        // ningún body ganó. Las cusps son líneas radiales — la
546        // distancia angular al cusp más cercano determina el hit.
547        if best.is_none() {
548            let dx = mx - cx_px;
549            let dy = my - cy_px;
550            let mouse_r = (dx * dx + dy * dy).sqrt();
551            let r_in = radii.houses_inner - 6.0;
552            let r_out = radii.houses_outer + 6.0;
553            if mouse_r >= r_in && mouse_r <= r_out {
554                // Calcular la longitud zodiacal que corresponde a este
555                // ángulo de pantalla (inversa de polar_to_screen).
556                let screen_angle_deg = dy.atan2(dx).to_degrees(); // (-180, 180]
557                // polar_to_screen: deg = 180 - (lon - asc + rot)
558                // → lon = asc + 180 - screen_angle_deg - rot
559                let lon = ((asc + 180.0 - screen_angle_deg - rot) as f32).rem_euclid(360.0);
560                // Buscar cusp más cercano (con wraparound).
561                for layer in &render.layers {
562                    if matches!(layer.kind, LayerKind::Houses) {
563                        if let Geometry::Ring { cusps_deg } = &layer.geometry {
564                            for (i, c) in cusps_deg.iter().enumerate() {
565                                let mut diff = (lon - c).abs();
566                                if diff > 180.0 {
567                                    diff = 360.0 - diff;
568                                }
569                                if diff < 2.5 {
570                                    // Mouse cerca de ESTE cusp.
571                                    let (gx, gy) = polar_to_screen(
572                                        *c,
573                                        asc,
574                                        rot,
575                                        (radii.houses_inner + radii.houses_outer) / 2.0,
576                                    );
577                                    best = Some((
578                                        diff,
579                                        HoverInfo::HouseCusp {
580                                            house_number: (i as u8) + 1,
581                                            deg: *c,
582                                            local_x: cx_px + gx - ox,
583                                            local_y: cy_px + gy - oy,
584                                        },
585                                    ));
586                                    break;
587                                }
588                            }
589                        }
590                    }
591                }
592            }
593        }
594
595        let new_hover = best.map(|(_, h)| h);
596        let changed = match (&self.state.hover, &new_hover) {
597            (Some(a), Some(b)) => a.key() != b.key(),
598            (None, None) => false,
599            _ => true,
600        };
601        if changed {
602            self.state.hover = new_hover;
603            cx.notify();
604        }
605    }
606
607    // ----- Internos: pan drag (MMB) -----
608
609    fn on_pan_down(&mut self, position: Point<Pixels>, _cx: &mut Context<'_, Self>) {
610        self.state.drag_pan = Some(PanDragState {
611            start_pos: position,
612            pan_x_start: self.state.view_pan_x,
613            pan_y_start: self.state.view_pan_y,
614        });
615    }
616
617    fn on_pan_move(&mut self, position: Point<Pixels>, cx: &mut Context<'_, Self>) {
618        let Some(pan) = self.state.drag_pan.as_ref() else {
619            return;
620        };
621        let dx: f32 = (position.x - pan.start_pos.x).into();
622        let dy: f32 = (position.y - pan.start_pos.y).into();
623        self.state.view_pan_x = pan.pan_x_start + dx;
624        self.state.view_pan_y = pan.pan_y_start + dy;
625        cx.notify();
626    }
627
628    fn on_pan_up(&mut self, cx: &mut Context<'_, Self>) {
629        if self.state.drag_pan.take().is_some() {
630            cx.notify();
631        }
632    }
633
634    fn on_scroll(
635        &mut self,
636        event: &ScrollWheelEvent,
637        _w: &mut Window,
638        cx: &mut Context<'_, Self>,
639    ) {
640        let (_dx_px, dy_px) = match event.delta {
641            ScrollDelta::Pixels(p) => (f32::from(p.x), f32::from(p.y)),
642            ScrollDelta::Lines(p) => (p.x * 16.0, p.y * 16.0),
643        };
644        // Wheel = zoom puro, sin modifier. Pan se hace con drag (LMB
645        // fuera del anillo, o MMB). 100px de scroll ≈ ±20% zoom.
646        let factor = (dy_px * 0.002).exp();
647        self.zoom_by(factor, cx);
648    }
649
650    fn on_jog_up(&mut self, cx: &mut Context<'_, Self>) {
651        let Some(jog) = self.state.drag_jog.take() else {
652            return;
653        };
654        // 1° de arco ≈ 4 minutos de tiempo sideral (15°/hora).
655        // CW visual (delta negativa en nuestra convención) → tiempo
656        // hacia adelante.
657        let delta_minutes = (-jog.accumulated_delta_deg * 4.0) as i64;
658        if delta_minutes != 0 {
659            self.state.time_offset_minutes =
660                self.state.time_offset_minutes.saturating_add(delta_minutes);
661            // Snap visual: el shell recomputa con el nuevo offset y el
662            // render trae el ascendant rotado.
663            self.state.view_rotation_deg = 0.0;
664            cx.emit(CanvasEvent::TimeOffsetChanged(self.state.time_offset_minutes));
665            cx.notify();
666        } else {
667            self.state.view_rotation_deg = 0.0;
668            cx.notify();
669        }
670    }
671
672    fn on_key_down(&mut self, event: &KeyDownEvent, _w: &mut Window, cx: &mut Context<'_, Self>) {
673        let key = event.keystroke.key.as_str();
674        let kind = match key {
675            "d" | "D" => LayerKind::SignDial,
676            "h" | "H" => LayerKind::Houses,
677            "x" | "X" => LayerKind::Aspects,
678            "p" | "P" => LayerKind::Bodies,
679            "t" | "T" => LayerKind::Outer,
680            "r" | "R" => {
681                self.reset_time_offset(cx);
682                return;
683            }
684            "0" => {
685                self.reset_view(cx);
686                return;
687            }
688            "c" | "C" => {
689                self.toggle_coords(cx);
690                return;
691            }
692            "s" | "S" => {
693                cx.emit(CanvasEvent::ExportSvgRequested);
694                return;
695            }
696            _ => return,
697        };
698        self.toggle_layer(kind, cx);
699    }
700}
701
702// =====================================================================
703// Geometría de pantalla
704// =====================================================================
705
706const WHEEL_SIZE: f32 = 580.0;
707const WHEEL_MARGIN: f32 = 28.0;
708
709/// Pinta un gradiente radial de profundidad sobre el background del
710/// canvas — efecto vignette. Se aproxima al gradient radial (no
711/// soportado nativamente por gpui en `.bg()`) pintando ~28 anillos
712/// concéntricos del centro hacia afuera, con alpha creciente hacia el
713/// borde. El centro queda claro y los extremos se oscurecen, dando
714/// sensación de "el wheel emerge desde la profundidad".
715///
716/// Solo activo en themes dark — sobre papel (light / print) el panel
717/// queda plano: una viñeta sobre fondo claro tiñe el papel y rompe
718/// la metáfora "impresión".
719fn paint_depth_field(bounds: Bounds<Pixels>, window: &mut Window, theme: &Theme) {
720    if !theme.is_dark {
721        return;
722    }
723    let ox: f32 = bounds.origin.x.into();
724    let oy: f32 = bounds.origin.y.into();
725    let bw: f32 = bounds.size.width.into();
726    let bh: f32 = bounds.size.height.into();
727    if bw <= 0.0 || bh <= 0.0 {
728        return;
729    }
730    let cx = ox + bw / 2.0;
731    let cy = oy + bh / 2.0;
732    // El gradient se extiende hasta la diagonal del rectángulo para
733    // que las esquinas estén dentro del último anillo (sin "halo"
734    // visible donde se corta).
735    let r_max = ((bw * bw + bh * bh).sqrt()) / 2.0 * 1.05;
736    let steps = 28;
737    // Color: casi-negro con tinte ligero del panel (el panel es dark).
738    let deep = hsla(230.0 / 360.0, 0.30, 0.04, 1.0);
739    // Stroke de cada anillo: el ancho cubre 1/steps del radio para
740    // que no queden gaps entre anillos.
741    let stroke_w = (r_max / steps as f32) * 1.15;
742    for i in 0..steps {
743        let t = i as f32 / (steps - 1) as f32;
744        let r = r_max * t;
745        // Curva ease-in: alpha crece de 0 (centro) a ~0.55 (borde),
746        // con la mayor parte del cambio en la mitad exterior. t² da
747        // ese "fondo profundo en el perímetro sin opacar el centro".
748        let alpha = 0.55 * (t * t);
749        stroke_circle(window, cx, cy, r, stroke_w, with_alpha(deep, alpha));
750    }
751}
752
753fn bounds_center(bounds: Bounds<Pixels>) -> (f32, f32) {
754    let ox: f32 = bounds.origin.x.into();
755    let oy: f32 = bounds.origin.y.into();
756    let bw: f32 = bounds.size.width.into();
757    let bh: f32 = bounds.size.height.into();
758    (ox + bw / 2.0, oy + bh / 2.0)
759}
760
761/// Radio del anillo exterior derivado del width *actual* del canvas
762/// (que ya está escalado por view_scale). Mantiene la proporción del
763/// margen contra `WHEEL_SIZE` original, así el hit-test del jog-dial y
764/// las cusps se adapta automáticamente al zoom sin que cada caller
765/// recalcule `view_scale`.
766fn effective_r_outer(bounds: Bounds<Pixels>) -> f32 {
767    let bw: f32 = bounds.size.width.into();
768    let scale = if WHEEL_SIZE > 0.0 { bw / WHEEL_SIZE } else { 1.0 };
769    (bw - WHEEL_MARGIN * scale * 2.0) / 2.0
770}
771
772// =====================================================================
773// Render
774// =====================================================================
775
776impl Render for AstrologyCanvas {
777    fn render(&mut self, _w: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
778        let theme = Theme::global(cx).clone();
779        let palette = AstroPalette::for_theme(&theme);
780        let entity = cx.entity();
781        let focus = self.focus_handle.clone();
782
783        let body = match &self.state.mode {
784            CanvasMode::Empty => render_empty(&theme),
785            CanvasMode::Wheel { render } => render_wheel(
786                &theme,
787                &palette,
788                render,
789                self.state.view_rotation_deg,
790                self.state.time_offset_minutes,
791                self.state.view_scale,
792                self.state.view_pan_x,
793                self.state.view_pan_y,
794                &self.state.layer_visibility,
795                self.state.show_coords,
796                self.state.hover.as_ref(),
797                entity,
798            ),
799            CanvasMode::Thumbnails { items, .. } => render_thumbnails(&theme, items),
800        };
801
802        // Depth field: capa absoluta detrás del body, ocupa todo el
803        // canvas. Vignette radial — el centro queda claro y los
804        // bordes se oscurecen, dando profundidad sin "ruido" de
805        // puntos. Solo en themes dark (en papel rompería la
806        // metáfora).
807        let theme_for_depth = theme.clone();
808        let depth_field = canvas(
809            |_b, _w, _cx| (),
810            move |bounds, _, window, _| paint_depth_field(bounds, window, &theme_for_depth),
811        )
812        .absolute()
813        .size_full();
814
815        div()
816            .id("astrology-canvas-root")
817            .track_focus(&focus)
818            .key_context("AstrologyCanvas")
819            .on_key_down(cx.listener(Self::on_key_down))
820            .on_mouse_down(
821                MouseButton::Left,
822                cx.listener(|this, _, w, _cx| {
823                    w.focus(&this.focus_handle);
824                }),
825            )
826            .on_scroll_wheel(cx.listener(Self::on_scroll))
827            .size_full()
828            .bg(theme.bg_panel.clone())
829            .relative()
830            .overflow_hidden()
831            .child(depth_field)
832            .child(
833                div()
834                    .size_full()
835                    .flex()
836                    .flex_col()
837                    .items_center()
838                    .justify_center()
839                    .child(body),
840            )
841    }
842}
843
844// =====================================================================
845// Modos: empty / thumbnails / wheel
846// =====================================================================
847
848fn render_empty(theme: &Theme) -> gpui::Div {
849    div()
850        .flex()
851        .flex_col()
852        .items_center()
853        .justify_center()
854        .gap(px(12.0))
855        .child(
856            div()
857                .text_size(px(13.0))
858                .text_color(theme.fg_muted)
859                .child("Tahuantinsuyu"),
860        )
861        .child(
862            div()
863                .text_size(px(11.0))
864                .text_color(theme.fg_disabled)
865                .child("Seleccioná una carta en el árbol para empezar."),
866        )
867}
868
869fn render_thumbnails(theme: &Theme, items: &[ThumbnailItem]) -> gpui::Div {
870    if items.is_empty() {
871        return div()
872            .text_size(px(12.0))
873            .text_color(theme.fg_muted)
874            .child("Sin cartas en este grupo todavía.");
875    }
876    let mut row = div().flex().flex_row().flex_wrap().gap(px(12.0));
877    for it in items {
878        row = row.child(
879            div()
880                .w(px(140.0))
881                .h(px(160.0))
882                .rounded(px(6.0))
883                .border_1()
884                .border_color(theme.border)
885                .bg(theme.bg_panel_alt.clone())
886                .flex()
887                .flex_col()
888                .items_center()
889                .justify_end()
890                .pb(px(8.0))
891                .child(
892                    div()
893                        .text_size(px(11.0))
894                        .text_color(theme.fg_text)
895                        .child(it.label.clone()),
896                ),
897        );
898    }
899    row
900}
901
902// =====================================================================
903// Wheel
904// =====================================================================
905
906#[allow(clippy::too_many_arguments)]
907fn render_wheel(
908    theme: &Theme,
909    palette: &AstroPalette,
910    render: &RenderModel,
911    view_rotation_deg: f32,
912    time_offset_minutes: i64,
913    view_scale: f32,
914    view_pan_x: f32,
915    view_pan_y: f32,
916    layer_visibility: &HashMap<LayerKind, bool>,
917    show_coords: bool,
918    hover: Option<&HoverInfo>,
919    entity: gpui::Entity<AstrologyCanvas>,
920) -> gpui::Div {
921    let asc = render.ascendant_deg;
922    let rot_offset = view_rotation_deg;
923    // Todo el wheel escala uniforme: el cuadro contenedor y los anillos
924    // crecen con view_scale, así que glifos, líneas y márgenes mantienen
925    // sus proporciones. cx/cy_center vive en coords locales del wheel,
926    // donde el wheel tiene tamaño `wheel_size` (no WHEEL_SIZE).
927    let wheel_size = WHEEL_SIZE * view_scale;
928    let wheel_margin = WHEEL_MARGIN * view_scale;
929    let cx_center = wheel_size / 2.0;
930    let cy_center = wheel_size / 2.0;
931    let r_outer = (wheel_size - wheel_margin * 2.0) / 2.0;
932    let radii = Radii::from_outer(r_outer);
933
934    let visible = layer_visibility.clone();
935
936    // --- Canvas element con todo el trazo + jog-dial drag ---
937    let palette_paint = palette.clone();
938    let theme_paint = theme.clone();
939    let layers_paint: Vec<Layer> = render.layers.clone();
940    let asc_for_paint = asc;
941    let mc_for_paint = render.midheaven_deg;
942    let visibility_for_paint = visible.clone();
943    let entity_for_canvas = entity.clone();
944    // Hover focus para el highlight de aspectos — solo cuando el hover
945    // es un Body (sobre un planeta), no sobre cusps ni aspectos.
946    let hover_focus_paint: Option<String> = match hover {
947        Some(HoverInfo::Body { symbol, .. }) => Some(symbol.clone()),
948        _ => None,
949    };
950    let canvas_element = canvas(
951        move |_b: Bounds<Pixels>, _w, _cx| (),
952        move |bounds: Bounds<Pixels>, _, window, _| {
953            // Painting de la rueda.
954            paint_wheel(
955                bounds,
956                window,
957                &theme_paint,
958                &palette_paint,
959                &layers_paint,
960                asc_for_paint,
961                mc_for_paint,
962                rot_offset,
963                radii,
964                &visibility_for_paint,
965                hover_focus_paint.as_deref(),
966            );
967
968            // Handlers de mouse — se registran cada frame contra el
969            // window; GPUI los reemplaza al re-renderear. LMB despacha
970            // entre jog-dial (sobre el anillo) y pan (afuera). MMB es
971            // pan secundario para usuarios con scroll-mouse.
972            let entity_d = entity_for_canvas.clone();
973            window.on_mouse_event(move |ev: &MouseDownEvent, _, _w, cx| {
974                if !bounds.contains(&ev.position) {
975                    return;
976                }
977                match ev.button {
978                    MouseButton::Left => {
979                        let mods = ev.modifiers;
980                        entity_d.update(cx, |this, cx| {
981                            this.on_primary_down(ev.position, mods, bounds, cx)
982                        });
983                    }
984                    MouseButton::Middle => {
985                        entity_d.update(cx, |this, cx| this.on_pan_down(ev.position, cx));
986                    }
987                    _ => {}
988                }
989            });
990            let entity_m = entity_for_canvas.clone();
991            window.on_mouse_event(move |ev: &MouseMoveEvent, _, _w, cx| {
992                if ev.dragging() {
993                    entity_m.update(cx, |this, cx| {
994                        if this.state.drag_pan.is_some() {
995                            this.on_pan_move(ev.position, cx);
996                        } else {
997                            this.on_jog_move(ev.position, bounds, cx);
998                        }
999                    });
1000                } else if bounds.contains(&ev.position) {
1001                    // Mouse hover sin drag: hit-test sobre los body
1002                    // glyphs para el tooltip.
1003                    entity_m.update(cx, |this, cx| this.on_hover_check(ev.position, bounds, cx));
1004                } else {
1005                    entity_m.update(cx, |this, cx| {
1006                        if this.state.hover.take().is_some() {
1007                            cx.notify();
1008                        }
1009                    });
1010                }
1011            });
1012            let entity_u = entity_for_canvas.clone();
1013            window.on_mouse_event(move |_: &MouseUpEvent, _, _w, cx| {
1014                entity_u.update(cx, |this, cx| {
1015                    this.on_pan_up(cx);
1016                    this.on_jog_up(cx);
1017                });
1018            });
1019        },
1020    )
1021    .absolute()
1022    .w(px(wheel_size))
1023    .h(px(wheel_size));
1024
1025    // El wheel ya no tiene bg propio — antes era un cuadrado con
1026    // gradient que cortaba contra el fondo del panel; ahora el panel
1027    // (con su starfield encima en `render`) fluye continuo a través
1028    // del área del wheel, dando el efecto de "rueda flotando en el
1029    // universo" en lugar de "rueda sobre placa cuadrada".
1030    let mut wheel = div()
1031        .relative()
1032        .w(px(wheel_size))
1033        .h(px(wheel_size))
1034        .ml(px(view_pan_x))
1035        .mt(px(view_pan_y))
1036        .child(canvas_element);
1037
1038    // Factor de escala para los glyphs DOM. Los radii ya están
1039    // escalados (vienen de wheel_size = WHEEL_SIZE * view_scale), pero
1040    // los tamaños de fuente y disco están hardcoded — los multiplico
1041    // por view_scale para que el zoom afecte uniformemente todo el
1042    // contenido visual del wheel, no solo la geometría del canvas.
1043    let s = view_scale;
1044    // Color del halo para los discos detrás de glyphs y pills — se
1045    // calcula una sola vez, lo usan planetas, casas, ASC/MC y los
1046    // coord labels.
1047    let halo_bg = glyph_halo(theme);
1048    // Sign glyphs.
1049    if visible.get(&LayerKind::SignDial).copied().unwrap_or(true) {
1050        let sign_ring_mid = (radii.sign_outer + radii.sign_inner) / 2.0;
1051        for layer in &render.layers {
1052            if matches!(layer.kind, LayerKind::SignDial) {
1053                for g in &layer.glyphs {
1054                    let (x, y) = polar_to_screen(g.deg, asc, rot_offset, sign_ring_mid);
1055                    let color = element_color_for_sign(palette, &g.symbol);
1056                    wheel = wheel.child(centered_glyph(
1057                        cx_center + x,
1058                        cy_center + y,
1059                        20.0 * s,
1060                        18.0 * s,
1061                        sign_unicode(&g.symbol).into(),
1062                        color,
1063                    ));
1064                }
1065            }
1066        }
1067    }
1068
1069    // House numbers + (opcional) coord del cusp.
1070    if visible.get(&LayerKind::Houses).copied().unwrap_or(true) {
1071        let house_label_r = (radii.houses_outer + radii.houses_inner) / 2.0;
1072        let house_label_color = house_ring_color(palette);
1073        for layer in &render.layers {
1074            if matches!(layer.kind, LayerKind::Houses) {
1075                for g in &layer.glyphs {
1076                    let (x, y) = polar_to_screen(g.deg, asc, rot_offset, house_label_r);
1077                    if let Some(h) = g.house {
1078                        wheel = wheel.child(centered_glyph(
1079                            cx_center + x,
1080                            cy_center + y,
1081                            16.0 * s,
1082                            11.0 * s,
1083                            format!("{}", h).into(),
1084                            house_label_color,
1085                        ));
1086                        // Coord del cusp justo dentro del anillo de
1087                        // casas — los grados se imprimen en una pill
1088                        // pequeña pegada al radio del cusp.
1089                        if show_coords {
1090                            let coord = format_coord_compact(g.deg);
1091                            let label_r = radii.houses_inner - 8.0 * s;
1092                            let (lx, ly) =
1093                                polar_to_screen(g.deg, asc, rot_offset, label_r);
1094                            wheel = wheel.child(coord_label(
1095                                cx_center + lx,
1096                                cy_center + ly,
1097                                coord.into(),
1098                                theme.fg_muted,
1099                                halo_bg,
1100                                8.5 * s,
1101                            ));
1102                        }
1103                    }
1104                }
1105            }
1106        }
1107    }
1108
1109    // Planet glyphs: natal en `bodies` + overlays (progression,
1110    // solar_arc) en sus rings, ambos con disco-halo para legibilidad
1111    // contra cualquier fondo. El natal lleva un tamaño un poco mayor
1112    // que los overlays para que se lea como "el cuerpo principal".
1113    if visible.get(&LayerKind::Bodies).copied().unwrap_or(true) {
1114        for layer in &render.layers {
1115            if matches!(layer.kind, LayerKind::Bodies) {
1116                let is_natal = layer.module_id == "natal";
1117                let is_topo = layer.module_id == "topocentric";
1118                let is_pd_direct = layer.module_id == "pd_direct";
1119                let is_pd_converse = layer.module_id == "pd_converse";
1120                let is_pd = is_pd_direct || is_pd_converse;
1121                let ring = radii.body_ring(&layer.module_id);
1122                let alpha = if is_natal {
1123                    1.0
1124                } else if is_topo {
1125                    0.75
1126                } else if is_pd {
1127                    0.80
1128                } else {
1129                    0.88
1130                };
1131                let font_size = (if is_natal {
1132                    18.0
1133                } else if is_topo {
1134                    15.0
1135                } else if is_pd {
1136                    13.0
1137                } else {
1138                    14.0
1139                }) * s;
1140                let disk_size = (if is_natal {
1141                    26.0
1142                } else if is_topo {
1143                    22.0
1144                } else if is_pd {
1145                    20.0
1146                } else {
1147                    22.0
1148                }) * s;
1149                for g in &layer.glyphs {
1150                    let (x, y) = polar_to_screen(g.deg, asc, rot_offset, ring);
1151                    let color = with_alpha(planet_color(palette, &g.symbol), alpha);
1152                    let mut glyph_text = planet_unicode(&g.symbol).to_string();
1153                    if g.retrograde {
1154                        glyph_text.push('ᴿ');
1155                    }
1156                    if let Some(marker) = &g.dignity_marker {
1157                        glyph_text.push_str(marker);
1158                    }
1159                    wheel = wheel.child(planet_glyph(
1160                        cx_center + x,
1161                        cy_center + y,
1162                        disk_size,
1163                        font_size,
1164                        glyph_text.into(),
1165                        color,
1166                        halo_bg,
1167                        with_alpha(color, 0.85),
1168                    ));
1169
1170                    // Coord label: grado dentro del signo + glyph del
1171                    // signo, pintado afuera del disco del planeta
1172                    // (radialmente). Se pinta para el natal (afuera)
1173                    // y para el topocéntrico (más afuera aún, hacia
1174                    // el sign dial) — los dos sistemas conviven con
1175                    // sus coords. Otros overlays (progression, solar
1176                    // arc) usan badges en el footer.
1177                    if show_coords && (is_natal || is_topo) {
1178                        let coord = format_coord_compact(g.deg);
1179                        // Topo: label hacia ADENTRO (entre planeta y
1180                        // casas P-P arriba); natal: label hacia
1181                        // AFUERA (entre planeta y casas Placidus).
1182                        let label_r = if is_topo {
1183                            ring - disk_size * 0.7
1184                        } else {
1185                            ring + disk_size * 0.7
1186                        };
1187                        let (lx, ly) = polar_to_screen(g.deg, asc, rot_offset, label_r);
1188                        wheel = wheel.child(coord_label(
1189                            cx_center + lx,
1190                            cy_center + ly,
1191                            coord.into(),
1192                            theme.fg_muted,
1193                            halo_bg,
1194                            9.5 * s,
1195                        ));
1196                    }
1197                }
1198            }
1199        }
1200    }
1201
1202    // Planet glyphs en el outer ring — transit o synastry (slot
1203    // compartido, mutuamente excluyentes a nivel de Shell). Disco un
1204    // poco más chico que el natal — el outer es "secundario".
1205    if visible.get(&LayerKind::Outer).copied().unwrap_or(true) {
1206        for layer in &render.layers {
1207            if matches!(layer.kind, LayerKind::Outer)
1208                && (OUTER_RING_MODULES.contains(&layer.module_id.as_str()))
1209            {
1210                for g in &layer.glyphs {
1211                    let (x, y) = polar_to_screen(g.deg, asc, rot_offset, radii.transits);
1212                    let color = with_alpha(planet_color(palette, &g.symbol), 0.92);
1213                    let glyph_text = if g.retrograde {
1214                        format!("{}ᴿ", planet_unicode(&g.symbol))
1215                    } else {
1216                        planet_unicode(&g.symbol).into()
1217                    };
1218                    wheel = wheel.child(planet_glyph(
1219                        cx_center + x,
1220                        cy_center + y,
1221                        20.0 * s,
1222                        13.0 * s,
1223                        glyph_text.into(),
1224                        color,
1225                        halo_bg,
1226                        with_alpha(color, 0.75),
1227                    ));
1228                }
1229            }
1230        }
1231    }
1232
1233    // Tooltip absoluto sobre el elemento hovered (cuerpo o cusp).
1234    if let Some(hov) = hover {
1235        let text = match hov {
1236            HoverInfo::Body {
1237                module_id,
1238                symbol,
1239                deg,
1240                house,
1241                retrograde,
1242                dignity_marker,
1243                annotation,
1244                ..
1245            } => {
1246                let sign_idx = ((deg / 30.0).floor() as usize) % 12;
1247                let sign_name = SIGN_NAMES_ES[sign_idx];
1248                let deg_in_sign = deg - (sign_idx as f32) * 30.0;
1249                let display_symbol = if module_id == "midpoints" {
1250                    // El symbol del midpoint es "a/b" — para el header
1251                    // del tooltip usamos los unicodes individuales.
1252                    if let Some((a, b)) = symbol.split_once('/') {
1253                        format!("{}/{}", planet_unicode(a), planet_unicode(b))
1254                    } else {
1255                        symbol.clone()
1256                    }
1257                } else {
1258                    planet_unicode(symbol).to_string()
1259                };
1260                let mut t = format!("{} {} · {:.1}°", display_symbol, sign_name, deg_in_sign);
1261                if let Some(h) = house {
1262                    t.push_str(&format!(" · Casa {}", h));
1263                }
1264                if *retrograde {
1265                    t.push_str(" · ℞");
1266                }
1267                if let Some(m) = dignity_marker {
1268                    t.push_str(&format!(" · {}", m));
1269                }
1270                if module_id == "midpoints" {
1271                    if let Some(a) = annotation {
1272                        t.push_str(&format!(" · {}", a));
1273                    }
1274                } else if module_id != "natal" {
1275                    t.push_str(&format!(" · {}", module_id));
1276                }
1277                t
1278            }
1279            HoverInfo::HouseCusp {
1280                house_number, deg, ..
1281            } => {
1282                let sign_idx = ((deg / 30.0).floor() as usize) % 12;
1283                let sign_name = SIGN_NAMES_ES[sign_idx];
1284                let deg_in_sign = deg - (sign_idx as f32) * 30.0;
1285                format!(
1286                    "Cusp Casa {} · {} {:.1}°",
1287                    house_number, sign_name, deg_in_sign
1288                )
1289            }
1290            HoverInfo::Aspect {
1291                module_id,
1292                from_body,
1293                to_body,
1294                kind,
1295                orb_deg,
1296                ..
1297            } => {
1298                let mut t = format!(
1299                    "{} {} {}  ·  orb {:.1}°",
1300                    planet_unicode(from_body),
1301                    aspect_unicode(kind),
1302                    planet_unicode(to_body),
1303                    orb_deg
1304                );
1305                if module_id != "natal" {
1306                    t.push_str(&format!(" · {}", module_id));
1307                }
1308                t
1309            }
1310        };
1311        let (lx, ly) = hov.local();
1312        let tip_x = (lx + 14.0).min(WHEEL_SIZE - 220.0).max(8.0);
1313        let tip_y = (ly - 28.0).max(8.0);
1314        wheel = wheel.child(
1315            div()
1316                .absolute()
1317                .left(px(tip_x))
1318                .top(px(tip_y))
1319                .px(px(8.0))
1320                .py(px(4.0))
1321                .rounded(px(6.0))
1322                .bg(theme.bg_panel_alt.clone())
1323                .border_1()
1324                .border_color(palette.angle_highlight)
1325                .text_size(px(11.0))
1326                .text_color(theme.fg_text)
1327                .child(SharedString::from(text)),
1328        );
1329    }
1330
1331    // Labels ASC/MC/DESC/IC como pills en el perímetro — bg del halo
1332    // + border y texto en `angle_highlight`. Más legibles que el
1333    // centered_glyph plano del fase anterior, en especial sobre
1334    // fondos claros donde el ámbar/oro de angle_highlight se diluye.
1335    let angle_labels = [
1336        (asc, "ASC"),
1337        (render.midheaven_deg, "MC"),
1338        (render.descendant_deg, "DESC"),
1339        (render.imum_coeli_deg, "IC"),
1340    ];
1341    let label_r = r_outer * 1.08;
1342    for (deg, label) in angle_labels {
1343        let (x, y) = polar_to_screen(deg, asc, rot_offset, label_r);
1344        let pill_w = (if label.len() > 2 { 38.0 } else { 30.0 }) * s;
1345        let pill_h = 18.0 * s;
1346        wheel = wheel.child(
1347            div()
1348                .absolute()
1349                .left(px(cx_center + x - pill_w / 2.0))
1350                .top(px(cy_center + y - pill_h / 2.0))
1351                .w(px(pill_w))
1352                .h(px(pill_h))
1353                .flex()
1354                .items_center()
1355                .justify_center()
1356                .rounded(px(9.0 * s))
1357                .bg(halo_bg)
1358                .border_1()
1359                .border_color(with_alpha(palette.angle_highlight, 0.85))
1360                .text_size(px(11.0 * s))
1361                .text_color(palette.angle_highlight)
1362                .child(SharedString::from(label)),
1363        );
1364    }
1365
1366    // --- Header + footer + indicador de tiempo ---
1367    let header = div()
1368        .flex()
1369        .flex_col()
1370        .items_center()
1371        .gap(px(2.0))
1372        .child(
1373            div()
1374                .text_size(px(16.0))
1375                .text_color(theme.fg_text)
1376                .child(SharedString::from(render.title.clone())),
1377        );
1378    let header = if let Some(sub) = &render.subtitle {
1379        header.child(
1380            div()
1381                .text_size(px(11.0))
1382                .text_color(theme.fg_muted)
1383                .child(SharedString::from(sub.clone())),
1384        )
1385    } else {
1386        header
1387    };
1388    // Botón export SVG — pequeño, alineado a la derecha del title.
1389    let export_btn = div()
1390        .id("tts-canvas-export-svg")
1391        .px(px(10.0))
1392        .py(px(3.0))
1393        .rounded(px(4.0))
1394        .bg(theme.bg_button())
1395        .hover(|s| s.bg(theme.bg_button_hover()))
1396        .border_1()
1397        .border_color(theme.border)
1398        .text_size(px(10.0))
1399        .text_color(theme.fg_text)
1400        .child("⬇ SVG")
1401        .on_click({
1402            let entity_e = entity.clone();
1403            move |_: &gpui::ClickEvent, _w, cx: &mut gpui::App| {
1404                entity_e.update(cx, |_this, cx| {
1405                    cx.emit(CanvasEvent::ExportSvgRequested);
1406                });
1407            }
1408        });
1409    let header = div()
1410        .flex()
1411        .flex_row()
1412        .items_center()
1413        .gap(px(12.0))
1414        .child(header)
1415        .child(export_btn);
1416
1417    let offset_label = format_offset(time_offset_minutes);
1418    let offset_color = if time_offset_minutes == 0 {
1419        theme.fg_disabled
1420    } else {
1421        palette.angle_highlight
1422    };
1423    let info_row = div()
1424        .flex()
1425        .flex_row()
1426        .gap(px(10.0))
1427        .child(
1428            div()
1429                .text_size(px(10.0))
1430                .text_color(theme.fg_disabled)
1431                .child(SharedString::from(format!(
1432                    "Asc {:.1}°  ·  MC {:.1}°  ·  {} ms",
1433                    render.ascendant_deg, render.midheaven_deg, render.compute_ms,
1434                ))),
1435        )
1436        .child(
1437            div()
1438                .text_size(px(10.0))
1439                .text_color(offset_color)
1440                .child(SharedString::from(offset_label)),
1441        )
1442        .child(
1443            div()
1444                .text_size(px(10.0))
1445                .text_color(theme.fg_disabled)
1446                .child(
1447                    "[D]ial [H]ouses as[X]pects [P]lanets [T]ransits [C]oords  ·  Ctrl+drag = tiempo  ·  [0] reset zoom  ·  [R] reset tiempo  ·  [S]vg",
1448                ),
1449        );
1450
1451    // Badges de overlays activos. Cada uno se pinta como pill con
1452    // background sutil y border tenue. Solo aparecen cuando hay
1453    // overlays — la carta natal pura ve solo el info_row.
1454    let badges_row = if render.overlays.is_empty() {
1455        None
1456    } else {
1457        let mut row = div().flex().flex_row().flex_wrap().gap(px(6.0));
1458        // Badge "natal" base, siempre presente cuando hay overlays —
1459        // ayuda al usuario a leer la pila de izquierda a derecha.
1460        row = row.child(badge(theme, palette, "natal", "Natal", true));
1461        for ov in &render.overlays {
1462            row = row.child(badge(theme, palette, &ov.module_id, &ov.label, false));
1463        }
1464        Some(row)
1465    };
1466
1467    let mut footer = div().flex().flex_col().items_center().gap(px(4.0)).child(info_row);
1468    if let Some(b) = badges_row {
1469        footer = footer.child(b);
1470    }
1471
1472    // Ejes uranianos detectados (cuerpos en la misma posición mod 90).
1473    // Aparece sólo cuando el módulo Uranian está activo y hay
1474    // grupos. Cada grupo se muestra como pill con los unicode de los
1475    // cuerpos + el grado dial-90.
1476    if !render.uranian_groups.is_empty() {
1477        let mut row = div().flex().flex_row().flex_wrap().gap(px(6.0));
1478        for group in &render.uranian_groups {
1479            let bodies_text: String = group
1480                .bodies
1481                .iter()
1482                .map(|b| planet_unicode(b))
1483                .collect::<Vec<_>>()
1484                .join(" ");
1485            row = row.child(
1486                div()
1487                    .px(px(8.0))
1488                    .py(px(2.0))
1489                    .rounded(px(10.0))
1490                    .bg(theme.bg_panel_alt.clone())
1491                    .border_1()
1492                    .border_color(with_alpha(palette.angle_highlight, 0.6))
1493                    .text_size(px(11.0))
1494                    .text_color(theme.fg_text)
1495                    .child(SharedString::from(format!(
1496                        "{}  ·  {:.1}°",
1497                        bodies_text, group.mod90_deg
1498                    ))),
1499            );
1500        }
1501        footer = footer.child(
1502            div()
1503                .flex()
1504                .flex_col()
1505                .items_center()
1506                .gap(px(3.0))
1507                .child(
1508                    div()
1509                        .text_size(px(10.0))
1510                        .text_color(theme.fg_muted)
1511                        .child("Ejes uranianos (90°)"),
1512                )
1513                .child(row),
1514        );
1515    }
1516
1517    // Lista textual de aspectos (top 12 por orb). Compacta, en grid
1518    // de 3 columnas, fonts pequeños. Solo aparece cuando hay aspectos
1519    // computados.
1520    if !render.aspect_summary.is_empty() {
1521        let mut grid = div()
1522            .flex()
1523            .flex_row()
1524            .flex_wrap()
1525            .gap(px(10.0))
1526            .max_w(px(WHEEL_SIZE + 80.0))
1527            .justify_center();
1528        for ap in render.aspect_summary.iter().take(12) {
1529            let kind_sym = aspect_unicode(&ap.kind);
1530            let line = format!(
1531                "{} {} {}  ·  {:.1}°{}",
1532                planet_unicode(&ap.from_body),
1533                kind_sym,
1534                planet_unicode(&ap.to_body),
1535                ap.orb_deg,
1536                match ap.applying {
1537                    Some(true) => " A",
1538                    Some(false) => " S",
1539                    None => "",
1540                }
1541            );
1542            let prefix = if ap.module_id == "natal" {
1543                String::new()
1544            } else {
1545                format!("[{}] ", ap.module_id)
1546            };
1547            grid = grid.child(
1548                div()
1549                    .px(px(6.0))
1550                    .py(px(2.0))
1551                    .text_size(px(11.0))
1552                    .text_color(aspect_color(palette, &ap.kind))
1553                    .child(SharedString::from(format!("{}{}", prefix, line))),
1554            );
1555        }
1556        footer = footer.child(grid);
1557    }
1558
1559    div()
1560        .flex()
1561        .flex_col()
1562        .items_center()
1563        .gap(px(8.0))
1564        .child(header)
1565        .child(wheel)
1566        .child(footer)
1567}
1568
1569/// Pequeña pill con la etiqueta de un overlay activo. El borde toma
1570/// color según el "tipo" del módulo para ayudar a mapear a su anillo
1571/// en el wheel: natal = neutro, outer ring share (transit/synastry/
1572/// planetary_return) = palette.angle_highlight, inner overlays
1573/// (progression/solar_arc) = palette.house_cusp.
1574fn badge(theme: &Theme, palette: &AstroPalette, module_id: &str, label: &str, is_natal: bool) -> gpui::Div {
1575    let border = if is_natal {
1576        theme.border
1577    } else {
1578        match module_id {
1579            "transit" | "synastry" | "planetary_return" => palette.angle_highlight,
1580            "progression" | "solar_arc" => palette.house_cusp,
1581            _ => theme.border,
1582        }
1583    };
1584    div()
1585        .px(px(8.0))
1586        .py(px(2.0))
1587        .rounded(px(10.0))
1588        .bg(theme.bg_panel_alt.clone())
1589        .border_1()
1590        .border_color(border)
1591        .text_size(px(10.0))
1592        .text_color(theme.fg_text)
1593        .child(SharedString::from(label.to_string()))
1594}
1595
1596fn format_offset(minutes: i64) -> String {
1597    if minutes == 0 {
1598        return "⏱ ahora".to_string();
1599    }
1600    let sign = if minutes > 0 { '+' } else { '-' };
1601    let m = minutes.unsigned_abs();
1602    let days = m / (60 * 24);
1603    let hours = (m / 60) % 24;
1604    let mins = m % 60;
1605    if days > 0 {
1606        format!("⏱ {}{}d {:02}h {:02}m", sign, days, hours, mins)
1607    } else if hours > 0 {
1608        format!("⏱ {}{:02}h {:02}m", sign, hours, mins)
1609    } else {
1610        format!("⏱ {}{:02}m", sign, mins)
1611    }
1612}
1613
1614// =====================================================================
1615// Painting
1616// =====================================================================
1617
1618#[derive(Clone, Copy)]
1619struct Radii {
1620    // Layout outer→inner. La capa **ascensional** (sistema topocéntrico
1621    // Polich-Page) va pegada al sign dial — su lógica nace del eje
1622    // ASC/MC y de la ascensión recta del observador, conceptualmente
1623    // hermana del zodiaco. La capa **geocéntrica** clásica
1624    // (casas Placidus + planetas tropicales sin paralaje) vive más
1625    // adentro, alrededor del cinturón de planetas natales.
1626    sign_outer: f32,
1627    sign_inner: f32,
1628    /// Anillo exterior de las casas Polich-Page (topocéntricas), pegado
1629    /// al sign dial. Los cusps llegan hasta el `sign_inner`.
1630    topo_houses_outer: f32,
1631    topo_houses_inner: f32,
1632    /// Carril de planetas topocéntricos — apenas dentro del anillo
1633    /// de casas P-P. Lleva sus propios coord labels.
1634    topocentric: f32,
1635    /// Anillo de glifos de tránsito (cuando el overlay está activo).
1636    transits: f32,
1637    /// Casas geocéntricas (Placidus default) — más adentro que las
1638    /// topocéntricas, claramente diferenciables.
1639    houses_outer: f32,
1640    houses_inner: f32,
1641    /// Anillo de midpoints — entre cuerpos geocéntricos y `houses_inner`.
1642    midpoints: f32,
1643    /// Anillo principal de cuerpos natales geocéntricos.
1644    bodies: f32,
1645    /// Borde interior del cinturón de planetas geocéntricos.
1646    bodies_inner: f32,
1647    /// Direcciones Primarias DIRECTAS (Sistema GR): ring exterior del
1648    /// "abrazo" GR — justo afuera del cinturón natal.
1649    pd_direct: f32,
1650    /// Direcciones Primarias CONVERSAS (Sistema GR): ring interior —
1651    /// el cinturón natal queda entre `pd_direct` (afuera) y
1652    /// `pd_converse` (dentro), formando el dual-ring de rectificación.
1653    pd_converse: f32,
1654    /// Anillo interno con cuerpos progresados (overlay opcional).
1655    progression: f32,
1656    /// Anillo más interno con cuerpos dirigidos por Solar Arc.
1657    solar_arc: f32,
1658    /// Anillo de carta compuesta (midpoint Davison) con un partner.
1659    composite: f32,
1660    /// Círculo donde anclan las líneas de aspecto entre cuerpos
1661    /// natales. Justo dentro del cinturón de planetas.
1662    aspects: f32,
1663}
1664
1665impl Radii {
1666    fn from_outer(r: f32) -> Self {
1667        Self {
1668            sign_outer: r,
1669            sign_inner: r * 0.88,
1670            // Ascensional (Polich-Page): pegado al sign dial.
1671            topo_houses_outer: r * 0.875,
1672            topo_houses_inner: r * 0.79,
1673            // Carril topocéntrico de planetas: justo dentro de las
1674            // casas P-P. Lleva sus coord labels al borde interior.
1675            topocentric: r * 0.755,
1676            // Tránsitos: ring intermedio entre las dos coronas (topo y
1677            // geo), apenas debajo del topocéntrico.
1678            transits: r * 0.71,
1679            // Capa geocéntrica clásica más adentro — claramente
1680            // separada del bloque ascensional.
1681            houses_outer: r * 0.66,
1682            houses_inner: r * 0.54,
1683            midpoints: r * 0.50,
1684            bodies: r * 0.47,
1685            bodies_inner: r * 0.44,
1686            // Dual-ring GR — abraza el cinturón natal por afuera y por
1687            // adentro. Para Saturno los dos rings caen casi en la misma
1688            // posición angular (poca rotación diurna afecta su lon en
1689            // años humanos); para luminarias los rings divergen
1690            // visiblemente y leen "directa rumbo a este grado, conversa
1691            // hacia este otro".
1692            pd_direct: r * 0.495,
1693            pd_converse: r * 0.425,
1694            // aspects justo bajo el carril natal — las líneas entran
1695            // a este radio sin pintar el círculo (sería ruido extra).
1696            aspects: r * 0.41,
1697            progression: r * 0.36,
1698            solar_arc: r * 0.30,
1699            composite: r * 0.24,
1700        }
1701    }
1702
1703    /// Radio del ring de cuerpos según el `module_id` del Layer.
1704    fn body_ring(&self, module_id: &str) -> f32 {
1705        match module_id {
1706            "progression" => self.progression,
1707            "solar_arc" => self.solar_arc,
1708            "composite" => self.composite,
1709            "midpoints" => self.midpoints,
1710            "topocentric" => self.topocentric,
1711            "pd_direct" => self.pd_direct,
1712            "pd_converse" => self.pd_converse,
1713            _ => self.bodies,
1714        }
1715    }
1716
1717    /// Resuelve qué radios corresponden a una capa de aspectos según el
1718    /// `module_id`: natal-natal en `aspects`, cross con cada overlay
1719    /// desde `bodies` (extremo natal) al ring del módulo. Los módulos
1720    /// del outer ring (OUTER_RING_MODULES) comparten el slot de
1721    /// tránsito (son mutuamente excluyentes a nivel de Shell).
1722    fn aspect_endpoints(&self, module_id: &str) -> (f32, f32) {
1723        if OUTER_RING_MODULES.contains(&module_id) {
1724            return (self.bodies, self.transits);
1725        }
1726        match module_id {
1727            "progression" => (self.bodies, self.progression),
1728            "solar_arc" => (self.bodies, self.solar_arc),
1729            "composite" => (self.bodies, self.composite),
1730            _ => (self.aspects, self.aspects),
1731        }
1732    }
1733}
1734
1735#[allow(clippy::too_many_arguments)]
1736// `hover_focus`: symbol del planeta hovereado en este frame (si lo
1737// hay). Las líneas de aspecto que NO tocan a ese planeta se opacan
1738// para que el usuario lea claramente "qué afecta a qué". Si `None`,
1739// todas las líneas se pintan a alpha plena.
1740fn paint_wheel(
1741    bounds: Bounds<Pixels>,
1742    window: &mut Window,
1743    theme: &Theme,
1744    palette: &AstroPalette,
1745    layers: &[Layer],
1746    ascendant_deg: f32,
1747    midheaven_deg: f32,
1748    rot_offset_deg: f32,
1749    radii: Radii,
1750    visibility: &HashMap<LayerKind, bool>,
1751    hover_focus: Option<&str>,
1752) {
1753    let (cx, cy) = bounds_center(bounds);
1754    let show = |k: LayerKind| visibility.get(&k).copied().unwrap_or(true);
1755
1756    // 1. Sectores zodiacales (parte del SignDial layer).
1757    if show(LayerKind::SignDial) {
1758        paint_sign_sectors(window, cx, cy, &radii, palette, ascendant_deg, rot_offset_deg);
1759
1760        // Anillos del dial con efecto 3D: highlight interior + base +
1761        // shadow exterior. El highlight es 1 px hacia el centro con
1762        // luminancia +0.18; la shadow 1 px hacia afuera con -0.18.
1763        // El bevel central — varios strokes finos con alpha en bell
1764        // curve entre sign_inner y sign_outer — da volumen al dial.
1765        stroke_circle_3d(window, cx, cy, radii.sign_outer, 1.5, palette.dial_ring, theme);
1766        stroke_circle_3d(window, cx, cy, radii.sign_inner, 1.0, palette.dial_ring, theme);
1767        paint_dial_bevel(window, cx, cy, &radii, palette, theme);
1768
1769        // Cusps zodiacales cada 30°.
1770        for i in 0..12 {
1771            let lon = (i as f32) * 30.0;
1772            let color = palette.dial_ring;
1773            paint_radial_line(
1774                window,
1775                cx,
1776                cy,
1777                lon,
1778                ascendant_deg,
1779                rot_offset_deg,
1780                radii.sign_inner,
1781                radii.sign_outer,
1782                color,
1783                1.0,
1784            );
1785        }
1786    }
1787
1788    // 2. Casas — doble anillo (inner + outer) + cusps radiales +
1789    // énfasis Asc/IC/Desc/MC. La doble línea vuelve a la zona de
1790    // casas una "corona" claramente identificable. Color derivado
1791    // de `house_cusp` con un hue shift para que el sistema
1792    // ascensional (casas) se distinga visualmente del eclíptico
1793    // (dial zodiacal) que va en dorado.
1794    if show(LayerKind::Houses) {
1795        let house_base = house_ring_color(palette);
1796        let house_color = with_alpha(house_base, 0.85);
1797        stroke_circle_3d(window, cx, cy, radii.houses_outer, 1.1, house_color, theme);
1798        stroke_circle_3d(window, cx, cy, radii.houses_inner, 1.1, house_color, theme);
1799        // Si hay capa topocéntrica activa, pintar también sus dos
1800        // anillos (con stroke más sutil que el geocéntrico, para que
1801        // se lea como "sistema ascensional" sin competir).
1802        if layers
1803            .iter()
1804            .any(|l| matches!(l.kind, LayerKind::Houses) && l.module_id == "topocentric")
1805        {
1806            let topo_color = with_alpha(house_base, 0.55);
1807            stroke_circle(window, cx, cy, radii.topo_houses_outer, 0.8, topo_color);
1808            stroke_circle(window, cx, cy, radii.topo_houses_inner, 0.8, topo_color);
1809        }
1810
1811        for layer in layers {
1812            if matches!(layer.kind, LayerKind::Houses) {
1813                let is_topo = layer.module_id == "topocentric";
1814                let (r_in, r_out) = if is_topo {
1815                    (radii.topo_houses_inner, radii.topo_houses_outer)
1816                } else {
1817                    (radii.houses_inner, radii.houses_outer)
1818                };
1819                if let Geometry::Ring { cusps_deg } = &layer.geometry {
1820                    for (i, c) in cusps_deg.iter().enumerate() {
1821                        let is_angle = i == 0 || i == 3 || i == 6 || i == 9;
1822                        let color = if is_topo {
1823                            with_alpha(house_base, 0.60)
1824                        } else if is_angle {
1825                            palette.angle_highlight
1826                        } else {
1827                            with_alpha(house_base, 0.75)
1828                        };
1829                        let width = if is_angle && !is_topo { 2.0 } else { 0.8 };
1830                        if is_topo {
1831                            // Topocéntrico: cusp como línea punteada
1832                            // en su propio anillo cercano al sign
1833                            // dial — se distingue del Placidus
1834                            // geocéntrico por el dash pattern y la
1835                            // ubicación más exterior.
1836                            paint_segment(
1837                                window,
1838                                cx
1839                                    + polar_to_screen(
1840                                        *c,
1841                                        ascendant_deg,
1842                                        rot_offset_deg,
1843                                        r_in,
1844                                    )
1845                                    .0,
1846                                cy
1847                                    + polar_to_screen(
1848                                        *c,
1849                                        ascendant_deg,
1850                                        rot_offset_deg,
1851                                        r_in,
1852                                    )
1853                                    .1,
1854                                cx
1855                                    + polar_to_screen(
1856                                        *c,
1857                                        ascendant_deg,
1858                                        rot_offset_deg,
1859                                        r_out,
1860                                    )
1861                                    .0,
1862                                cy
1863                                    + polar_to_screen(
1864                                        *c,
1865                                        ascendant_deg,
1866                                        rot_offset_deg,
1867                                        r_out,
1868                                    )
1869                                    .1,
1870                                color,
1871                                Some((3.0, 2.5)),
1872                                1.0,
1873                            );
1874                        } else {
1875                            paint_radial_line(
1876                                window,
1877                                cx,
1878                                cy,
1879                                *c,
1880                                ascendant_deg,
1881                                rot_offset_deg,
1882                                r_in,
1883                                r_out,
1884                                color,
1885                                width,
1886                            );
1887                        }
1888                    }
1889                }
1890            }
1891        }
1892
1893        // Cruz completa Asc-Desc + MC-IC, alpha bastante visible para
1894        // que orienten la lectura sin competir con cuerpos/aspectos.
1895        // 4 radios desde el centro: ASC, DESC (=asc+180), MC, IC
1896        // (=mc+180). `paint_radial_line` con r_inner=0 pinta un radio
1897        // del centro al borde — la cruz es la unión de los 4.
1898        let axis_color = with_alpha(palette.angle_highlight, 0.55);
1899        for axis_deg in [
1900            ascendant_deg,
1901            ascendant_deg + 180.0,
1902            midheaven_deg,
1903            midheaven_deg + 180.0,
1904        ] {
1905            paint_radial_line(
1906                window,
1907                cx,
1908                cy,
1909                axis_deg,
1910                ascendant_deg,
1911                rot_offset_deg,
1912                0.0,
1913                radii.houses_outer,
1914                axis_color,
1915                1.4,
1916            );
1917        }
1918    }
1919
1920    // 2.5. Carril de planetas. `bodies` + `bodies_inner` muy juntos
1921    // delimitan la franja estrecha donde viven los glyphs natales.
1922    // El círculo de aspectos NO se pinta — `radii.aspects` solo
1923    // existe como punto donde se anclan las líneas; un stroke ahí
1924    // sería un anillo extra que confunde sin aportar.
1925    if show(LayerKind::Bodies) {
1926        let belt_color = with_alpha(palette.dial_ring, 0.55);
1927        stroke_circle_3d(window, cx, cy, radii.bodies, 0.9, belt_color, theme);
1928        stroke_circle(
1929            window,
1930            cx,
1931            cy,
1932            radii.bodies_inner,
1933            0.6,
1934            with_alpha(palette.dial_ring, 0.35),
1935        );
1936        // GR dual-ring: si las capas de direcciones primarias están
1937        // presentes, marcar sus anillos para que el visual lea como
1938        // "abrazo" del cinturón natal. La directa va punteada,
1939        // la conversa también — la diferencia entre las dos es la
1940        // ubicación radial (afuera vs adentro del cinturón natal).
1941        let has_pd = layers.iter().any(|l| {
1942            matches!(l.kind, LayerKind::Bodies)
1943                && (l.module_id == "pd_direct" || l.module_id == "pd_converse")
1944        });
1945        if has_pd {
1946            let pd_color = with_alpha(palette.angle_highlight, 0.50);
1947            for r in [radii.pd_direct, radii.pd_converse] {
1948                // Pintamos el anillo como tramo punteado fino: 24
1949                // segmentos cortos a lo largo del círculo.
1950                let steps = 96;
1951                for i in 0..steps {
1952                    if i % 2 != 0 {
1953                        continue;
1954                    }
1955                    let a0 = (i as f32) / (steps as f32) * std::f32::consts::TAU;
1956                    let a1 = ((i + 1) as f32) / (steps as f32) * std::f32::consts::TAU;
1957                    let x0 = cx + r * a0.cos();
1958                    let y0 = cy + r * a0.sin();
1959                    let x1 = cx + r * a1.cos();
1960                    let y1 = cy + r * a1.sin();
1961                    paint_segment(window, x0, y0, x1, y1, pd_color, None, 0.6);
1962                }
1963            }
1964        }
1965    }
1966
1967    // 3. Aspectos. Cada module_id usa su par de radios — natal-natal
1968    // ambos en `aspects`, cross con transit en `bodies → transits`,
1969    // cross con progression en `bodies → progression`.
1970    if show(LayerKind::Aspects) {
1971        let mono = palette.is_monochrome();
1972        for layer in layers {
1973            if matches!(layer.kind, LayerKind::Aspects) {
1974                if let Geometry::Lines(segs) = &layer.geometry {
1975                    let (r_from, r_to) = radii.aspect_endpoints(&layer.module_id);
1976                    let is_cross = r_from != r_to;
1977                    for seg in segs {
1978                        // Filtro minors con orbe ancho: los aspectos
1979                        // menores (quincunx, semi-square, quintile…)
1980                        // solo se trazan si están MUY apretados
1981                        // (orbe ≤ 3°). Sobre 3° ensucian sin aportar.
1982                        if !is_major_aspect(&seg.kind) && seg.orb_deg.abs() > 3.0 {
1983                            continue;
1984                        }
1985                        let base = aspect_color(palette, &seg.kind);
1986                        let base = with_alpha(base, base.a * seg.opacity);
1987                        // Hover focus: si hay un planeta hovereado y
1988                        // este segmento NO lo toca, lo atenuamos al
1989                        // 18%; si lo toca o no hay hover, va pleno.
1990                        let touches_hover = hover_focus
1991                            .map(|sym| seg.from_body == sym || seg.to_body == sym)
1992                            .unwrap_or(true);
1993                        let factor = if touches_hover { 1.0 } else { 0.18 };
1994                        let color = with_alpha(base, base.a * factor);
1995                        let dash = if mono {
1996                            dash_pattern_for_kind(&seg.kind)
1997                        } else {
1998                            None
1999                        };
2000                        // Width inverso al orbe: orbes cerrados se ven
2001                        // gruesos (aspecto "fuerte"), orbes amplios
2002                        // finos. Mayores van un escalón más gruesos
2003                        // que menores en su mismo orbe.
2004                        let width = aspect_width(&seg.kind, seg.orb_deg, mono);
2005                        if is_cross {
2006                            paint_cross_aspect_line(
2007                                window,
2008                                cx,
2009                                cy,
2010                                seg.from_deg,
2011                                seg.to_deg,
2012                                ascendant_deg,
2013                                rot_offset_deg,
2014                                r_from,
2015                                r_to,
2016                                color,
2017                                dash,
2018                            );
2019                        } else {
2020                            paint_aspect_line(
2021                                window,
2022                                cx,
2023                                cy,
2024                                seg.from_deg,
2025                                seg.to_deg,
2026                                ascendant_deg,
2027                                rot_offset_deg,
2028                                r_from,
2029                                color,
2030                                dash,
2031                                width,
2032                            );
2033                        }
2034                    }
2035                }
2036            }
2037        }
2038    }
2039
2040    // 4. Marcadores de posición exacta. Antes el dot era "el planeta";
2041    // ahora el glyph (con halo, en DOM) lo es. El círculo acá queda
2042    // como marker de precisión angular — chico, alpha alta, sobre el
2043    // anillo correspondiente. Glow se mantiene para Sol/Luna como
2044    // toque místico, pero también reducido.
2045    if show(LayerKind::Bodies) {
2046        let dot_r = (radii.sign_outer * 0.009).max(1.5);
2047        for layer in layers {
2048            if matches!(layer.kind, LayerKind::Bodies) {
2049                let ring = radii.body_ring(&layer.module_id);
2050                let is_natal = layer.module_id == "natal";
2051                let alpha = if is_natal { 1.0 } else { 0.85 };
2052                for g in &layer.glyphs {
2053                    let color = with_alpha(planet_color(palette, &g.symbol), alpha);
2054                    let (x, y) = polar_to_screen(g.deg, ascendant_deg, rot_offset_deg, ring);
2055                    if is_natal && (g.symbol == "sun" || g.symbol == "moon") {
2056                        paint_glow(window, cx + x, cy + y, dot_r * 1.8, color);
2057                    }
2058                    fill_circle(window, cx + x, cy + y, dot_r, color);
2059                }
2060            }
2061        }
2062    }
2063
2064    // Anillos guía para los overlays internos (progression, solar_arc).
2065    let guide_inset = radii.sign_outer * 0.03;
2066    for (module_id, ring) in [
2067        ("progression", radii.progression),
2068        ("solar_arc", radii.solar_arc),
2069    ] {
2070        let active = layers
2071            .iter()
2072            .any(|l| matches!(l.kind, LayerKind::Bodies) && l.module_id == module_id);
2073        if active {
2074            stroke_circle(
2075                window,
2076                cx,
2077                cy,
2078                ring + guide_inset,
2079                0.5,
2080                with_alpha(palette.house_cusp, 0.35),
2081            );
2082            stroke_circle(
2083                window,
2084                cx,
2085                cy,
2086                ring - guide_inset,
2087                0.5,
2088                with_alpha(palette.house_cusp, 0.35),
2089            );
2090        }
2091    }
2092
2093    // 5. Outer ring (transit o synastry overlay): anillo guía + dots
2094    // de la capa activa. Son mutuamente excluyentes a nivel de Shell;
2095    // si alguno de los dos está prendido, pintamos el slot.
2096    let outer_active = layers.iter().any(|l| {
2097        matches!(l.kind, LayerKind::Outer)
2098            && OUTER_RING_MODULES.contains(&l.module_id.as_str())
2099    });
2100    if outer_active && show(LayerKind::Outer) {
2101        let band = radii.sign_outer * 0.035;
2102        stroke_circle_3d(
2103            window,
2104            cx,
2105            cy,
2106            radii.transits + band,
2107            0.7,
2108            with_alpha(palette.dial_ring, 0.55),
2109            theme,
2110        );
2111        stroke_circle_3d(
2112            window,
2113            cx,
2114            cy,
2115            radii.transits - band,
2116            0.7,
2117            with_alpha(palette.dial_ring, 0.55),
2118            theme,
2119        );
2120
2121        let dot_r = (radii.sign_outer * 0.008).max(1.5);
2122        for layer in layers {
2123            if matches!(layer.kind, LayerKind::Outer)
2124                && (OUTER_RING_MODULES.contains(&layer.module_id.as_str()))
2125            {
2126                for g in &layer.glyphs {
2127                    let color = with_alpha(planet_color(palette, &g.symbol), 0.85);
2128                    let (x, y) =
2129                        polar_to_screen(g.deg, ascendant_deg, rot_offset_deg, radii.transits);
2130                    fill_circle(window, cx + x, cy + y, dot_r, color);
2131                }
2132            }
2133        }
2134    }
2135}
2136
2137fn paint_sign_sectors(
2138    window: &mut Window,
2139    cx: f32,
2140    cy: f32,
2141    radii: &Radii,
2142    palette: &AstroPalette,
2143    ascendant_deg: f32,
2144    rot_offset_deg: f32,
2145) {
2146    const SUBDIVISIONS: usize = 18;
2147    for i in 0..12 {
2148        let lon_start = (i as f32) * 30.0;
2149        let lon_end = lon_start + 30.0;
2150        let element = sign_element_by_index(i);
2151        let color = with_alpha(palette.element(element), 0.10);
2152
2153        let mut builder = PathBuilder::fill();
2154        let (x0, y0) = polar_to_screen(lon_start, ascendant_deg, rot_offset_deg, radii.sign_inner);
2155        builder.move_to(point(px(cx + x0), px(cy + y0)));
2156
2157        for k in 1..=SUBDIVISIONS {
2158            let t = lon_start + (lon_end - lon_start) * (k as f32) / (SUBDIVISIONS as f32);
2159            let (x, y) = polar_to_screen(t, ascendant_deg, rot_offset_deg, radii.sign_inner);
2160            builder.line_to(point(px(cx + x), px(cy + y)));
2161        }
2162        let (xe, ye) = polar_to_screen(lon_end, ascendant_deg, rot_offset_deg, radii.sign_outer);
2163        builder.line_to(point(px(cx + xe), px(cy + ye)));
2164
2165        for k in (0..SUBDIVISIONS).rev() {
2166            let t = lon_start + (lon_end - lon_start) * (k as f32) / (SUBDIVISIONS as f32);
2167            let (x, y) = polar_to_screen(t, ascendant_deg, rot_offset_deg, radii.sign_outer);
2168            builder.line_to(point(px(cx + x), px(cy + y)));
2169        }
2170        builder.close();
2171        if let Ok(path) = builder.build() {
2172            window.paint_path(path, color);
2173        }
2174    }
2175}
2176
2177fn stroke_circle(window: &mut Window, cx: f32, cy: f32, r: f32, width: f32, color: Hsla) {
2178    const SEGMENTS: usize = 96;
2179    let mut builder = PathBuilder::stroke(px(width));
2180    for i in 0..=SEGMENTS {
2181        let t = (i as f32) / (SEGMENTS as f32) * (2.0 * PI);
2182        let x = cx + r * t.cos();
2183        let y = cy + r * t.sin();
2184        if i == 0 {
2185            builder.move_to(point(px(x), px(y)));
2186        } else {
2187            builder.line_to(point(px(x), px(y)));
2188        }
2189    }
2190    if let Ok(path) = builder.build() {
2191        window.paint_path(path, color);
2192    }
2193}
2194
2195/// Pinta 3 halos concéntricos con alpha decreciente alrededor de un
2196/// punto — usado para Sol/Luna natales. El radio crece, la opacidad
2197/// cae: el ojo lo lee como "esto irradia". Sin glow real (GPUI 0.2 no
2198/// tiene radial gradient), pero el shading concéntrico convence.
2199fn paint_glow(window: &mut Window, cx: f32, cy: f32, base_r: f32, color: Hsla) {
2200    const HALOS: [(f32, f32); 3] = [(5.0, 0.05), (3.0, 0.12), (1.8, 0.22)];
2201    for (mult, alpha) in HALOS {
2202        let r = base_r * mult;
2203        let halo = hsla(color.h, color.s, color.l, alpha);
2204        fill_circle(window, cx, cy, r, halo);
2205    }
2206}
2207
2208fn fill_circle(window: &mut Window, cx: f32, cy: f32, r: f32, color: Hsla) {
2209    const SEGMENTS: usize = 32;
2210    let mut builder = PathBuilder::fill();
2211    builder.move_to(point(px(cx + r), px(cy)));
2212    for i in 1..=SEGMENTS {
2213        let t = (i as f32) / (SEGMENTS as f32) * (2.0 * PI);
2214        let x = cx + r * t.cos();
2215        let y = cy + r * t.sin();
2216        builder.line_to(point(px(x), px(y)));
2217    }
2218    builder.close();
2219    if let Ok(path) = builder.build() {
2220        window.paint_path(path, color);
2221    }
2222}
2223
2224#[allow(clippy::too_many_arguments)]
2225fn paint_radial_line(
2226    window: &mut Window,
2227    cx: f32,
2228    cy: f32,
2229    longitude_deg: f32,
2230    ascendant_deg: f32,
2231    rot_offset_deg: f32,
2232    r_inner: f32,
2233    r_outer: f32,
2234    color: Hsla,
2235    width: f32,
2236) {
2237    let (xi, yi) = polar_to_screen(longitude_deg, ascendant_deg, rot_offset_deg, r_inner);
2238    let (xo, yo) = polar_to_screen(longitude_deg, ascendant_deg, rot_offset_deg, r_outer);
2239    let mut builder = PathBuilder::stroke(px(width));
2240    builder.move_to(point(px(cx + xi), px(cy + yi)));
2241    builder.line_to(point(px(cx + xo), px(cy + yo)));
2242    if let Ok(path) = builder.build() {
2243        window.paint_path(path, color);
2244    }
2245}
2246
2247#[allow(clippy::too_many_arguments)]
2248fn paint_aspect_line(
2249    window: &mut Window,
2250    cx: f32,
2251    cy: f32,
2252    a_deg: f32,
2253    b_deg: f32,
2254    ascendant_deg: f32,
2255    rot_offset_deg: f32,
2256    r: f32,
2257    color: Hsla,
2258    dash: Option<(f32, f32)>,
2259    width: f32,
2260) {
2261    let (xa, ya) = polar_to_screen(a_deg, ascendant_deg, rot_offset_deg, r);
2262    let (xb, yb) = polar_to_screen(b_deg, ascendant_deg, rot_offset_deg, r);
2263    paint_segment(window, cx + xa, cy + ya, cx + xb, cy + yb, color, dash, width);
2264}
2265
2266/// Línea de aspecto natal ↔ tránsito: extremos en radios distintos.
2267/// El `from_deg` cae sobre el ring de cuerpos natales (`r_from`); el
2268/// `to_deg` sobre el ring de tránsito (`r_to`). Trazo más fino que el
2269/// natal-natal para no competir visualmente.
2270#[allow(clippy::too_many_arguments)]
2271fn paint_cross_aspect_line(
2272    window: &mut Window,
2273    cx: f32,
2274    cy: f32,
2275    natal_deg: f32,
2276    transit_deg: f32,
2277    ascendant_deg: f32,
2278    rot_offset_deg: f32,
2279    r_from: f32,
2280    r_to: f32,
2281    color: Hsla,
2282    dash: Option<(f32, f32)>,
2283) {
2284    let (xa, ya) = polar_to_screen(natal_deg, ascendant_deg, rot_offset_deg, r_from);
2285    let (xb, yb) = polar_to_screen(transit_deg, ascendant_deg, rot_offset_deg, r_to);
2286    paint_segment(window, cx + xa, cy + ya, cx + xb, cy + yb, color, dash, 0.7);
2287}
2288
2289/// Pinta un segmento entre dos puntos. Si `dash` es `Some((on, off))`,
2290/// itera el vector pintando trechos de `on` px con gaps de `off` px.
2291/// Si `None`, una sola línea continua. Usado por todos los aspect
2292/// painters — el dash pattern es la forma de distinguir kinds en
2293/// el theme BW (donde el color no sirve).
2294fn paint_segment(
2295    window: &mut Window,
2296    x0: f32,
2297    y0: f32,
2298    x1: f32,
2299    y1: f32,
2300    color: Hsla,
2301    dash: Option<(f32, f32)>,
2302    width: f32,
2303) {
2304    let Some((on, off)) = dash else {
2305        let mut b = PathBuilder::stroke(px(width));
2306        b.move_to(point(px(x0), px(y0)));
2307        b.line_to(point(px(x1), px(y1)));
2308        if let Ok(p) = b.build() {
2309            window.paint_path(p, color);
2310        }
2311        return;
2312    };
2313    let dx = x1 - x0;
2314    let dy = y1 - y0;
2315    let len = (dx * dx + dy * dy).sqrt();
2316    if len < 0.1 {
2317        return;
2318    }
2319    let ux = dx / len;
2320    let uy = dy / len;
2321    let step = on + off;
2322    if step < 0.1 {
2323        return;
2324    }
2325    let mut t = 0.0;
2326    while t < len {
2327        let t_end = (t + on).min(len);
2328        let sx = x0 + ux * t;
2329        let sy = y0 + uy * t;
2330        let ex = x0 + ux * t_end;
2331        let ey = y0 + uy * t_end;
2332        let mut b = PathBuilder::stroke(px(width));
2333        b.move_to(point(px(sx), px(sy)));
2334        b.line_to(point(px(ex), px(ey)));
2335        if let Ok(p) = b.build() {
2336            window.paint_path(p, color);
2337        }
2338        t += step;
2339    }
2340}
2341
2342/// `true` para los 5 aspectos Ptoloméicos (conjunction, sextile,
2343/// square, trine, opposition). Cualquier otro `kind` se considera
2344/// menor — quincunx, semi-square, quintile, sesquiquadrate, etc.
2345fn is_major_aspect(kind: &str) -> bool {
2346    matches!(
2347        kind,
2348        "conjunction" | "sextile" | "square" | "trine" | "opposition"
2349    )
2350}
2351
2352/// Grosor de línea de aspecto inverso al orbe. La idea: a orbe 0°
2353/// (aspecto exacto) la línea va gruesa porque "pesa" más; a orbe
2354/// amplio se afina. Los mayores arrancan en un techo más alto que
2355/// los menores. En BW se le suma un poquito a todos porque las
2356/// líneas competen con sus dash patterns.
2357fn aspect_width(kind: &str, orb_deg: f32, mono: bool) -> f32 {
2358    let orb = orb_deg.abs();
2359    let major = is_major_aspect(kind);
2360    // Orbe de referencia para normalizar: ~8° para mayores, ~3° para
2361    // menores. Más allá la línea ya está afinada al mínimo.
2362    let max_orb = if major { 8.0 } else { 3.0 };
2363    let t = (1.0 - (orb / max_orb)).clamp(0.0, 1.0);
2364    let (min_w, max_w) = if major { (0.7, 2.1) } else { (0.5, 1.2) };
2365    let w = min_w + (max_w - min_w) * t;
2366    if mono { w + 0.2 } else { w }
2367}
2368
2369/// Dash pattern por aspecto, para modo monocromático. En modo color
2370/// el caller pasa `None` y las líneas van sólidas. Patterns elegidos
2371/// para que cada kind sea distinguible a ojo:
2372/// - conjunction/opposition: sólido (más peso visual, son los
2373///   aspectos "fuertes")
2374/// - square: dash medio (4 on / 3 off)
2375/// - trine: dash largo (8 on / 2 off) — casi sólido pero distinguible
2376/// - sextile: dotted (1.5 on / 3 off)
2377/// - minor: dotted finísimo (1 on / 4 off)
2378fn dash_pattern_for_kind(kind: &str) -> Option<(f32, f32)> {
2379    match kind {
2380        "conjunction" | "opposition" => None,
2381        "square" => Some((4.0, 3.0)),
2382        "trine" => Some((8.0, 2.0)),
2383        "sextile" => Some((1.5, 3.0)),
2384        _ => Some((1.0, 4.0)),
2385    }
2386}
2387
2388// =====================================================================
2389// Helpers
2390// =====================================================================
2391
2392/// Distancia mínima entre un punto y un segmento de recta. Usado por
2393/// hover_check para detectar proximity a líneas de aspectos.
2394fn dist_point_segment(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32) -> f32 {
2395    let dx = bx - ax;
2396    let dy = by - ay;
2397    let len_sq = dx * dx + dy * dy;
2398    if len_sq < f32::EPSILON {
2399        // Segmento degenerado → distancia al punto a.
2400        let pdx = px - ax;
2401        let pdy = py - ay;
2402        return (pdx * pdx + pdy * pdy).sqrt();
2403    }
2404    let t = (((px - ax) * dx + (py - ay) * dy) / len_sq).clamp(0.0, 1.0);
2405    let proj_x = ax + t * dx;
2406    let proj_y = ay + t * dy;
2407    let dx2 = px - proj_x;
2408    let dy2 = py - proj_y;
2409    (dx2 * dx2 + dy2 * dy2).sqrt()
2410}
2411
2412fn polar_to_screen(
2413    longitude_deg: f32,
2414    ascendant_deg: f32,
2415    rot_offset_deg: f32,
2416    radius: f32,
2417) -> (f32, f32) {
2418    let deg = 180.0 - (longitude_deg - ascendant_deg + rot_offset_deg);
2419    let rad = deg * PI / 180.0;
2420    (radius * rad.cos(), radius * rad.sin())
2421}
2422
2423fn centered_glyph(
2424    x: f32,
2425    y: f32,
2426    box_size: f32,
2427    font_size: f32,
2428    text: SharedString,
2429    color: Hsla,
2430) -> gpui::Div {
2431    div()
2432        .absolute()
2433        .left(px(x - box_size / 2.0))
2434        .top(px(y - box_size / 2.0))
2435        .w(px(box_size))
2436        .h(px(box_size))
2437        .flex()
2438        .items_center()
2439        .justify_center()
2440        .text_size(px(font_size))
2441        .text_color(color)
2442        .child(text)
2443}
2444
2445/// Glyph de planeta con disco-halo detrás del char. El disco viene en
2446/// `disk_bg` (semi-opaco para que se vea a través el fondo del wheel)
2447/// y `disk_border` (típicamente el color del planeta). El char por
2448/// dentro va en `text_color` — recomendado el color del planeta sobre
2449/// disco neutro, o color contrastante sobre disco coloreado.
2450fn planet_glyph(
2451    x: f32,
2452    y: f32,
2453    disk_size: f32,
2454    font_size: f32,
2455    text: SharedString,
2456    text_color: Hsla,
2457    disk_bg: Hsla,
2458    disk_border: Hsla,
2459) -> gpui::Div {
2460    div()
2461        .absolute()
2462        .left(px(x - disk_size / 2.0))
2463        .top(px(y - disk_size / 2.0))
2464        .w(px(disk_size))
2465        .h(px(disk_size))
2466        .rounded_full()
2467        .bg(disk_bg)
2468        .border_1()
2469        .border_color(disk_border)
2470        .flex()
2471        .items_center()
2472        .justify_center()
2473        .text_size(px(font_size))
2474        .text_color(text_color)
2475        .child(text)
2476}
2477
2478/// Formato compacto con precisión de minutos: "DD°MM'{signo}" donde
2479/// el signo es el glyph zodiacal (♈♉♊…). Ej: 14.93° → "14°56'♈".
2480/// Los minutos se redondean al entero más cercano; si el redondeo
2481/// excede 60, bumpea el grado y mantiene la representación canónica
2482/// (29°60' → 30°00', que a su vez = 0° del signo siguiente — lo
2483/// recalculamos para evitar mostrar "30°00'♈" en vez de "0°00'♉").
2484fn format_coord_compact(deg: f32) -> String {
2485    let normalized = deg.rem_euclid(360.0);
2486    let total_minutes = (normalized * 60.0).round() as i64;
2487    // Carry-overs: 60' → siguiente grado; 30° → siguiente signo (eso
2488    // ya está cubierto porque el total_minutes refleja la posición
2489    // ABSOLUTA y volvemos a derivar sign + minutos del entero limpio).
2490    let total_minutes = total_minutes.rem_euclid(360 * 60);
2491    let sign_idx = (total_minutes / (30 * 60)) as usize % 12;
2492    let within_sign = total_minutes - (sign_idx as i64) * 30 * 60;
2493    let deg_int = (within_sign / 60) as i32;
2494    let minutes = (within_sign % 60) as i32;
2495    let sign_glyph = match sign_idx {
2496        0 => "♈",
2497        1 => "♉",
2498        2 => "♊",
2499        3 => "♋",
2500        4 => "♌",
2501        5 => "♍",
2502        6 => "♎",
2503        7 => "♏",
2504        8 => "♐",
2505        9 => "♑",
2506        10 => "♒",
2507        _ => "♓",
2508    };
2509    format!("{}°{:02}'{}", deg_int, minutes, sign_glyph)
2510}
2511
2512#[cfg(test)]
2513mod coord_tests {
2514    use super::format_coord_compact;
2515
2516    #[test]
2517    fn zero_aries() {
2518        assert_eq!(format_coord_compact(0.0), "0°00'♈");
2519    }
2520
2521    #[test]
2522    fn fourteen_fiftysix_aries() {
2523        // 14.9333° = 14° 56'
2524        assert_eq!(format_coord_compact(14.933_3), "14°56'♈");
2525    }
2526
2527    #[test]
2528    fn rollover_to_taurus() {
2529        // 29.9995° debería redondear a 30° y caer en 0°00'♉.
2530        assert_eq!(format_coord_compact(29.9995), "0°00'♉");
2531    }
2532
2533    #[test]
2534    fn capricorn_anchor() {
2535        // 270° = inicio de Capricornio.
2536        assert_eq!(format_coord_compact(270.0), "0°00'♑");
2537    }
2538
2539    #[test]
2540    fn negative_wraps() {
2541        // -10° = 350° = 20°00'♓.
2542        assert_eq!(format_coord_compact(-10.0), "20°00'♓");
2543    }
2544}
2545
2546/// Pill pequeña con un coord ("14°♈") junto al glyph de un planeta
2547/// o cusp. Fondo halo + texto fg_muted, padding mínimo para no
2548/// saturar la rueda con etiquetas grandes.
2549fn coord_label(
2550    x: f32,
2551    y: f32,
2552    text: SharedString,
2553    fg: Hsla,
2554    halo_bg: Hsla,
2555    font_size: f32,
2556) -> gpui::Div {
2557    // Estimación gruesa del ancho (caracteres × ~5.5 px a font 9.5).
2558    // Suficiente para no recortar; el flex centra dentro.
2559    let w = (text.len() as f32 * (font_size * 0.58)).max(font_size * 2.0);
2560    let h = font_size + 6.0;
2561    div()
2562        .absolute()
2563        .left(px(x - w / 2.0))
2564        .top(px(y - h / 2.0))
2565        .w(px(w))
2566        .h(px(h))
2567        .flex()
2568        .items_center()
2569        .justify_center()
2570        .rounded(px(h / 2.0))
2571        .bg(halo_bg)
2572        .text_size(px(font_size))
2573        .text_color(fg)
2574        .child(text)
2575}
2576
2577/// Color HSL semi-opaco para los halos de los glyphs — derivado del
2578/// theme. En dark va casi negro; en light casi blanco. Alpha alta para
2579/// que el char quede legible contra cualquier cosa que haya detrás
2580/// (anillo, líneas de aspecto, starfield).
2581fn glyph_halo(theme: &Theme) -> Hsla {
2582    if theme.is_dark {
2583        hsla(0.0, 0.0, 0.07, 0.92)
2584    } else {
2585        hsla(0.0, 0.0, 0.97, 0.92)
2586    }
2587}
2588
2589fn with_alpha(c: Hsla, a: f32) -> Hsla {
2590    hsla(c.h, c.s, c.l, a.clamp(0.0, 1.0))
2591}
2592
2593/// Devuelve `c` con la luminancia modificada por `delta` (clamp 0..1).
2594/// Útil para derivar highlight (+luma) y shadow (-luma) de un color
2595/// base manteniendo hue y saturación — efecto bevel/3D barato.
2596fn adjust_luma(c: Hsla, delta: f32) -> Hsla {
2597    hsla(c.h, c.s, (c.l + delta).clamp(0.0, 1.0), c.a)
2598}
2599
2600/// Devuelve `c` con el hue desplazado `delta_deg` grados sobre el
2601/// círculo cromático (wrap a [0,1] en la escala normalizada de gpui).
2602/// Usado para derivar el color del anillo de casas desde el del dial
2603/// zodiacal — los dos sistemas (eclíptica vs ascensional) deben
2604/// distinguirse a primera vista pero compartir "familia" cromática.
2605fn shift_hue(c: Hsla, delta_deg: f32) -> Hsla {
2606    let new_h = (c.h + delta_deg / 360.0).rem_euclid(1.0);
2607    hsla(new_h, c.s, c.l, c.a)
2608}
2609
2610/// Color para los anillos del sistema de casas (ascensional). En
2611/// paletas con color, lo derivamos de `house_cusp` con un hue shift
2612/// de ~140° para diferenciar de la eclíptica (que va con el dorado
2613/// de `dial_ring`). En BW devolvemos `house_cusp` tal cual — un
2614/// shift cromático en monocromo es ruido sin información.
2615fn house_ring_color(palette: &AstroPalette) -> Hsla {
2616    if palette.is_monochrome() {
2617        palette.house_cusp
2618    } else {
2619        shift_hue(palette.house_cusp, 140.0)
2620    }
2621}
2622
2623/// Stroke con efecto embossed: 3 trazos concéntricos. El highlight va
2624/// 0.7 px hacia el centro con luminancia subida; el principal en `r`;
2625/// el shadow 0.7 px hacia afuera con luminancia bajada. La dirección
2626/// del bevel depende del theme: en dark el highlight es exterior (luz
2627/// "desde arriba"), en light interior (sombra "desde arriba" hacia
2628/// el centro).
2629fn stroke_circle_3d(
2630    window: &mut Window,
2631    cx: f32,
2632    cy: f32,
2633    r: f32,
2634    width: f32,
2635    color: Hsla,
2636    theme: &Theme,
2637) {
2638    let (hl_offset, sh_offset) = if theme.is_dark {
2639        (-0.7, 0.7)
2640    } else {
2641        (0.7, -0.7)
2642    };
2643    let hl = with_alpha(adjust_luma(color, 0.20), color.a * 0.55);
2644    let sh = with_alpha(adjust_luma(color, -0.18), color.a * 0.55);
2645    stroke_circle(window, cx, cy, r + hl_offset, (width * 0.7).max(0.4), hl);
2646    stroke_circle(window, cx, cy, r, width, color);
2647    stroke_circle(window, cx, cy, r + sh_offset, (width * 0.7).max(0.4), sh);
2648}
2649
2650/// Bevel central del anillo de signos: ~10 strokes finos entre
2651/// sign_inner y sign_outer, con alpha en bell curve (máximo en el
2652/// medio, decae hacia los bordes). Genera la sensación de volumen
2653/// sin pintar gradient radial (no soportado en gpui canvas).
2654fn paint_dial_bevel(
2655    window: &mut Window,
2656    cx: f32,
2657    cy: f32,
2658    radii: &Radii,
2659    palette: &AstroPalette,
2660    theme: &Theme,
2661) {
2662    let steps = 10;
2663    let base = if theme.is_dark { 0.07 } else { 0.10 };
2664    let color = palette.dial_ring;
2665    for i in 0..steps {
2666        let t = (i as f32 + 0.5) / steps as f32;
2667        let r = radii.sign_inner + (radii.sign_outer - radii.sign_inner) * t;
2668        // Bell curve simétrica: |t-0.5|*2 da 0..1 desde el centro, lo
2669        // invertimos para que el centro tenga peso máximo.
2670        let bell = 1.0 - ((t - 0.5).abs() * 2.0);
2671        let a = base * bell;
2672        stroke_circle(window, cx, cy, r, 1.0, with_alpha(color, a));
2673    }
2674}
2675
2676fn sign_unicode(name: &str) -> &'static str {
2677    match name {
2678        "aries" => "♈",
2679        "taurus" => "♉",
2680        "gemini" => "♊",
2681        "cancer" => "♋",
2682        "leo" => "♌",
2683        "virgo" => "♍",
2684        "libra" => "♎",
2685        "scorpio" => "♏",
2686        "sagittarius" => "♐",
2687        "capricorn" => "♑",
2688        "aquarius" => "♒",
2689        "pisces" => "♓",
2690        _ => "?",
2691    }
2692}
2693
2694const SIGN_NAMES_ES: [&str; 12] = [
2695    "Aries",
2696    "Tauro",
2697    "Géminis",
2698    "Cáncer",
2699    "Leo",
2700    "Virgo",
2701    "Libra",
2702    "Escorpio",
2703    "Sagitario",
2704    "Capricornio",
2705    "Acuario",
2706    "Piscis",
2707];
2708
2709fn aspect_unicode(kind: &str) -> &'static str {
2710    match kind {
2711        "conjunction" => "☌",
2712        "opposition" => "☍",
2713        "trine" => "△",
2714        "square" => "□",
2715        "sextile" => "⚹",
2716        "quincunx" => "⚻",
2717        "semi_sextile" => "⚺",
2718        "semi_square" => "∠",
2719        "sesquiquadrate" => "⚼",
2720        "quintile" => "Q",
2721        "biquintile" => "bQ",
2722        _ => "·",
2723    }
2724}
2725
2726fn planet_unicode(name: &str) -> &'static str {
2727    match name {
2728        "sun" => "☉",
2729        "moon" => "☽",
2730        "mercury" => "☿",
2731        "venus" => "♀",
2732        "mars" => "♂",
2733        "jupiter" => "♃",
2734        "saturn" => "♄",
2735        "uranus" => "♅",
2736        "neptune" => "♆",
2737        "pluto" => "♇",
2738        "north_node" => "☊",
2739        "south_node" => "☋",
2740        "chiron" => "⚷",
2741        "lilith" => "⚸",
2742        "ceres" => "⚳",
2743        "pallas" => "⚴",
2744        "juno" => "⚵",
2745        "vesta" => "⚶",
2746        _ => "•",
2747    }
2748}
2749
2750fn planet_color(p: &AstroPalette, name: &str) -> Hsla {
2751    let planet = match name {
2752        "sun" => Planet::Sun,
2753        "moon" => Planet::Moon,
2754        "mercury" => Planet::Mercury,
2755        "venus" => Planet::Venus,
2756        "mars" => Planet::Mars,
2757        "jupiter" => Planet::Jupiter,
2758        "saturn" => Planet::Saturn,
2759        "uranus" => Planet::Uranus,
2760        "neptune" => Planet::Neptune,
2761        "pluto" => Planet::Pluto,
2762        "chiron" => Planet::Chiron,
2763        "north_node" => Planet::NorthNode,
2764        "south_node" => Planet::SouthNode,
2765        "lilith" => Planet::Lilith,
2766        _ => return p.fg_text_fallback(),
2767    };
2768    p.planet(planet)
2769}
2770
2771fn sign_element_by_index(i: usize) -> Element {
2772    match i % 4 {
2773        0 => Element::Fire,
2774        1 => Element::Earth,
2775        2 => Element::Air,
2776        _ => Element::Water,
2777    }
2778}
2779
2780fn element_color_for_sign(p: &AstroPalette, name: &str) -> Hsla {
2781    let elem = match name {
2782        "aries" | "leo" | "sagittarius" => Element::Fire,
2783        "taurus" | "virgo" | "capricorn" => Element::Earth,
2784        "gemini" | "libra" | "aquarius" => Element::Air,
2785        "cancer" | "scorpio" | "pisces" => Element::Water,
2786        _ => return p.fg_text_fallback(),
2787    };
2788    p.element(elem)
2789}
2790
2791fn aspect_color(p: &AstroPalette, kind: &str) -> Hsla {
2792    let k = match kind {
2793        "conjunction" => TAspectKind::Conjunction,
2794        "opposition" => TAspectKind::Opposition,
2795        "trine" => TAspectKind::Trine,
2796        "square" => TAspectKind::Square,
2797        "sextile" => TAspectKind::Sextile,
2798        "quincunx" => TAspectKind::Quincunx,
2799        "semi_sextile" => TAspectKind::Semisextile,
2800        "semi_square" => TAspectKind::Semisquare,
2801        "sesquiquadrate" => TAspectKind::Sesquisquare,
2802        "quintile" => TAspectKind::Quintile,
2803        "biquintile" => TAspectKind::Biquintile,
2804        _ => return p.minor_aspect,
2805    };
2806    p.aspect(k)
2807}
2808
2809trait AstroPaletteExt {
2810    fn fg_text_fallback(&self) -> Hsla;
2811}
2812
2813impl AstroPaletteExt for AstroPalette {
2814    fn fg_text_fallback(&self) -> Hsla {
2815        if self.is_dark {
2816            hsla(0.0, 0.0, 0.85, 1.0)
2817        } else {
2818            hsla(0.0, 0.0, 0.25, 1.0)
2819        }
2820    }
2821}