gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198629 Definitions

⎇ 074d8bcbc8a4c24397e268331deb872f2e243f61 crates/modules/tahuantinsuyu/tahuantinsuyu-canvas/src/lib.rs Rust · 3209 lines · 119.0 KB History Who touched what raw

feat(tahuantinsuyu): cluster shrink, label compacto, hover destacado con z-order 074d8bcbc · 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    //
1071    // El layer `natal` usa Zona CD (entre aros C y D); `topocentric`
1072    // usa Zona BC (entre aros B y C). Los house numbers se posan al
1073    // centro de la zona; las coord pills se posan adyacentes al aro
1074    // interior de la propia zona, así no se sale del bloque.
1075    if visible.get(&LayerKind::Houses).copied().unwrap_or(true) {
1076        let house_label_color = house_ring_color(palette);
1077        for layer in &render.layers {
1078            if matches!(layer.kind, LayerKind::Houses) {
1079                let is_topo = layer.module_id == "topocentric";
1080                let (r_out, r_in) = if is_topo {
1081                    (radii.topo_houses_outer, radii.topo_houses_inner)
1082                } else {
1083                    (radii.houses_outer, radii.houses_inner)
1084                };
1085                let label_r = (r_out + r_in) / 2.0;
1086                let coord_r = r_in + (r_out - r_in) * 0.18;
1087                for g in &layer.glyphs {
1088                    let (x, y) = polar_to_screen(g.deg, asc, rot_offset, label_r);
1089                    if let Some(h) = g.house {
1090                        wheel = wheel.child(centered_glyph(
1091                            cx_center + x,
1092                            cy_center + y,
1093                            16.0 * s,
1094                            11.0 * s,
1095                            format!("{}", h).into(),
1096                            house_label_color,
1097                        ));
1098                        if show_coords {
1099                            let coord = format_coord_compact(g.deg);
1100                            let (lx, ly) =
1101                                polar_to_screen(g.deg, asc, rot_offset, coord_r);
1102                            wheel = wheel.child(coord_label(
1103                                cx_center + lx,
1104                                cy_center + ly,
1105                                coord.into(),
1106                                theme.fg_muted,
1107                                halo_bg,
1108                                8.5 * s,
1109                            ));
1110                        }
1111                    }
1112                }
1113            }
1114        }
1115    }
1116
1117    // Planet glyphs: natal en `bodies` + overlays (progression,
1118    // solar_arc) en sus rings, ambos con disco-halo para legibilidad
1119    // contra cualquier fondo. El natal lleva un tamaño un poco mayor
1120    // que los overlays para que se lea como "el cuerpo principal".
1121    if visible.get(&LayerKind::Bodies).copied().unwrap_or(true) {
1122        for layer in &render.layers {
1123            if matches!(layer.kind, LayerKind::Bodies) {
1124                let is_natal = layer.module_id == "natal";
1125                let is_topo = layer.module_id == "topocentric";
1126                let is_pd_direct = layer.module_id == "pd_direct";
1127                let is_pd_converse = layer.module_id == "pd_converse";
1128                let is_pd = is_pd_direct || is_pd_converse;
1129                let ring = radii.body_ring(&layer.module_id);
1130                let alpha = if is_natal {
1131                    1.0
1132                } else if is_topo {
1133                    0.75
1134                } else if is_pd {
1135                    0.80
1136                } else {
1137                    0.88
1138                };
1139                let font_size = (if is_natal {
1140                    18.0
1141                } else if is_topo {
1142                    15.0
1143                } else if is_pd {
1144                    13.0
1145                } else {
1146                    14.0
1147                }) * s;
1148                let disk_size_base = (if is_natal {
1149                    26.0
1150                } else if is_topo {
1151                    22.0
1152                } else if is_pd {
1153                    20.0
1154                } else {
1155                    22.0
1156                }) * s;
1157
1158                // Anti-solapamiento: spread directo sobre TODOS los
1159                // glyphs con `min_sep = disk_angular` (tangencial: los
1160                // discos se rozan sin pisarse) y `max_shift = disk_angular`
1161                // (cap fuerte: ningún planeta puede alejarse más de
1162                // un diámetro de disco de su grado real). El cap evita
1163                // que un cluster denso "empuje" a planetas lejanos.
1164                //
1165                // En paralelo, `find_clusters` con threshold = ancho
1166                // del disco × 1.2 detecta pares/tríos cercanos para
1167                // que compartan label. Sin esto, dos planetas en
1168                // conjunción a 5° real se ven con sus discos
1169                // separados a 10° y CADA UNO con su pill — dos labels
1170                // que dicen casi lo mismo, exactamente lo que el
1171                // usuario reporta como "se repiten en vez de
1172                // reutilizarse".
1173                let raw_degs: Vec<f32> = layer.glyphs.iter().map(|g| g.deg).collect();
1174                let disk_angular_deg =
1175                    (disk_size_base / (std::f32::consts::TAU * ring)) * 360.0;
1176                let max_shift = disk_angular_deg;
1177                let (display_degs, residual) =
1178                    spread_angles(&raw_degs, disk_angular_deg, max_shift);
1179                let cluster_thresh = disk_angular_deg * 1.2;
1180                let clusters = find_clusters(&raw_degs, cluster_thresh);
1181
1182                let cluster_centroids: Vec<f32> = clusters
1183                    .iter()
1184                    .map(|c| {
1185                        let mut sx = 0.0_f32;
1186                        let mut sy = 0.0_f32;
1187                        for &idx in c {
1188                            let a = raw_degs[idx].to_radians();
1189                            sx += a.cos();
1190                            sy += a.sin();
1191                        }
1192                        sy.atan2(sx).to_degrees().rem_euclid(360.0)
1193                    })
1194                    .collect();
1195                let display_centroids: Vec<f32> = clusters
1196                    .iter()
1197                    .map(|c| {
1198                        let mut sx = 0.0_f32;
1199                        let mut sy = 0.0_f32;
1200                        for &idx in c {
1201                            let a = display_degs[idx].to_radians();
1202                            sx += a.cos();
1203                            sy += a.sin();
1204                        }
1205                        sy.atan2(sx).to_degrees().rem_euclid(360.0)
1206                    })
1207                    .collect();
1208                let mut cluster_of = vec![0usize; layer.glyphs.len()];
1209                for (ci, c) in clusters.iter().enumerate() {
1210                    for &idx in c {
1211                        cluster_of[idx] = ci;
1212                    }
1213                }
1214
1215                let shrink_residual = (1.0 - residual * 0.30).clamp(0.60, 1.0);
1216
1217                // El hovered glyph y su cluster reciben tratamiento
1218                // especial: lo postponemos para pintarlo al FINAL del
1219                // árbol (queda por encima del resto = z-order), y le
1220                // damos un border más fuerte. Su label cluster también
1221                // se destaca (color fg_text en lugar de fg_muted, font
1222                // un punto más grande).
1223                let hovered_sym: Option<&str> = match hover {
1224                    Some(HoverInfo::Body { symbol, .. }) => Some(symbol.as_str()),
1225                    _ => None,
1226                };
1227                let hovered_idx: Option<usize> = hovered_sym.and_then(|sym| {
1228                    layer.glyphs.iter().position(|g| g.symbol == sym)
1229                });
1230                let hovered_cluster: Option<usize> = hovered_idx.map(|i| cluster_of[i]);
1231
1232                for (i, g) in layer.glyphs.iter().enumerate() {
1233                    if Some(i) == hovered_idx {
1234                        continue; // se pinta al final
1235                    }
1236                    // Achicar discos cuando el glyph está en cluster
1237                    // (≥2 miembros) — al estar pegados se ven mejor
1238                    // un poco más pequeños.
1239                    let cluster_size = clusters[cluster_of[i]].len();
1240                    let in_cluster_shrink = if cluster_size >= 2 { 0.86 } else { 1.0 };
1241                    let effective_shrink = shrink_residual * in_cluster_shrink;
1242                    let disk_size = disk_size_base * effective_shrink;
1243                    let font_size_eff = (font_size * effective_shrink).max(11.0);
1244
1245                    let display_deg = display_degs[i];
1246                    let (x, y) = polar_to_screen(display_deg, asc, rot_offset, ring);
1247                    let color = with_alpha(planet_color(palette, &g.symbol), alpha);
1248                    let mut glyph_text = planet_unicode(&g.symbol).to_string();
1249                    if g.retrograde {
1250                        glyph_text.push('ᴿ');
1251                    }
1252                    if let Some(marker) = &g.dignity_marker {
1253                        glyph_text.push_str(marker);
1254                    }
1255                    wheel = wheel.child(planet_glyph(
1256                        cx_center + x,
1257                        cy_center + y,
1258                        disk_size,
1259                        font_size_eff,
1260                        glyph_text.into(),
1261                        color,
1262                        halo_bg,
1263                        with_alpha(color, 0.85),
1264                    ));
1265
1266                    // Coord label individual: solo cuando el glyph
1267                    // está SOLO en su cluster (≥2 ⇒ label compartido).
1268                    if show_coords && (is_natal || is_topo) && cluster_size == 1 {
1269                        let coord = format_coord_compact(g.deg);
1270                        let label_r = ring - disk_size * 1.3;
1271                        let (lx, ly) =
1272                            polar_to_screen(display_deg, asc, rot_offset, label_r);
1273                        wheel = wheel.child(coord_label(
1274                            cx_center + lx,
1275                            cy_center + ly,
1276                            coord.into(),
1277                            theme.fg_muted,
1278                            halo_bg,
1279                            8.5 * s,
1280                        ));
1281                    }
1282                }
1283
1284                // Label compartido para CADA cluster con ≥2 miembros.
1285                // El del cluster hovereado se destaca: color fg_text
1286                // (vs fg_muted) y font un punto más grande.
1287                if show_coords && (is_natal || is_topo) {
1288                    let disk_size_typical = disk_size_base * shrink_residual * 0.86;
1289                    for (ci, c) in clusters.iter().enumerate() {
1290                        if c.len() < 2 {
1291                            continue;
1292                        }
1293                        let highlighted = Some(ci) == hovered_cluster;
1294                        let center_display_deg = display_centroids[ci];
1295                        let center_real_deg = cluster_centroids[ci];
1296                        let symbols: String = c
1297                            .iter()
1298                            .map(|&idx| planet_unicode(&layer.glyphs[idx].symbol))
1299                            .collect::<Vec<_>>()
1300                            .join(" ");
1301                        let coord = format_coord_compact(center_real_deg);
1302                        let text = format!("{}  {}", symbols, coord);
1303                        let label_r = ring - disk_size_typical * 1.5;
1304                        let (lx, ly) = polar_to_screen(
1305                            center_display_deg,
1306                            asc,
1307                            rot_offset,
1308                            label_r,
1309                        );
1310                        let (fg, font_sz) = if highlighted {
1311                            (theme.fg_text, 10.0 * s)
1312                        } else {
1313                            (theme.fg_muted, 9.0 * s)
1314                        };
1315                        wheel = wheel.child(coord_label(
1316                            cx_center + lx,
1317                            cy_center + ly,
1318                            text.into(),
1319                            fg,
1320                            halo_bg,
1321                            font_sz,
1322                        ));
1323                    }
1324                }
1325
1326                // Render del glyph hovered al FINAL: queda encima del
1327                // resto en z-order. Disco un poco más grande y border
1328                // más prominente para destacar.
1329                if let Some(hi) = hovered_idx {
1330                    let g = &layer.glyphs[hi];
1331                    let display_deg = display_degs[hi];
1332                    let (x, y) = polar_to_screen(display_deg, asc, rot_offset, ring);
1333                    let color = with_alpha(planet_color(palette, &g.symbol), alpha);
1334                    let mut glyph_text = planet_unicode(&g.symbol).to_string();
1335                    if g.retrograde {
1336                        glyph_text.push('ᴿ');
1337                    }
1338                    if let Some(marker) = &g.dignity_marker {
1339                        glyph_text.push_str(marker);
1340                    }
1341                    let disk_size = disk_size_base * shrink_residual * 1.18;
1342                    let font_size_eff = font_size * shrink_residual * 1.12;
1343                    wheel = wheel.child(planet_glyph(
1344                        cx_center + x,
1345                        cy_center + y,
1346                        disk_size,
1347                        font_size_eff,
1348                        glyph_text.into(),
1349                        color,
1350                        halo_bg,
1351                        color, // border al color pleno (no .85) — destaca
1352                    ));
1353                    // Si el hovered no está en cluster compartido,
1354                    // pintamos su coord individual destacada acá.
1355                    let cluster_size = clusters[cluster_of[hi]].len();
1356                    if show_coords && (is_natal || is_topo) && cluster_size == 1 {
1357                        let coord = format_coord_compact(g.deg);
1358                        let label_r = ring - disk_size * 1.3;
1359                        let (lx, ly) =
1360                            polar_to_screen(display_deg, asc, rot_offset, label_r);
1361                        wheel = wheel.child(coord_label(
1362                            cx_center + lx,
1363                            cy_center + ly,
1364                            coord.into(),
1365                            theme.fg_text,
1366                            halo_bg,
1367                            10.0 * s,
1368                        ));
1369                    }
1370                }
1371            }
1372        }
1373    }
1374
1375    // Planet glyphs en el outer ring — transit o synastry (slot
1376    // compartido, mutuamente excluyentes a nivel de Shell). Disco un
1377    // poco más chico que el natal — el outer es "secundario".
1378    if visible.get(&LayerKind::Outer).copied().unwrap_or(true) {
1379        for layer in &render.layers {
1380            if matches!(layer.kind, LayerKind::Outer)
1381                && (OUTER_RING_MODULES.contains(&layer.module_id.as_str()))
1382            {
1383                let disk_base = 20.0 * s;
1384                let raw_degs: Vec<f32> = layer.glyphs.iter().map(|g| g.deg).collect();
1385                let disk_angular =
1386                    (disk_base / (std::f32::consts::TAU * radii.transits)) * 360.0;
1387                let (display_degs, residual) =
1388                    spread_angles(&raw_degs, disk_angular, disk_angular);
1389                let shrink = (1.0 - residual * 0.30).clamp(0.60, 1.0);
1390                for (i, g) in layer.glyphs.iter().enumerate() {
1391                    let display_deg = display_degs[i];
1392                    let (x, y) = polar_to_screen(display_deg, asc, rot_offset, radii.transits);
1393                    let color = with_alpha(planet_color(palette, &g.symbol), 0.92);
1394                    let glyph_text = if g.retrograde {
1395                        format!("{}ᴿ", planet_unicode(&g.symbol))
1396                    } else {
1397                        planet_unicode(&g.symbol).into()
1398                    };
1399                    wheel = wheel.child(planet_glyph(
1400                        cx_center + x,
1401                        cy_center + y,
1402                        20.0 * s * shrink,
1403                        13.0 * s * shrink,
1404                        glyph_text.into(),
1405                        color,
1406                        halo_bg,
1407                        with_alpha(color, 0.75),
1408                    ));
1409                }
1410            }
1411        }
1412    }
1413
1414    // Tooltip absoluto sobre el elemento hovered (cuerpo o cusp).
1415    if let Some(hov) = hover {
1416        let text = match hov {
1417            HoverInfo::Body {
1418                module_id,
1419                symbol,
1420                deg,
1421                house,
1422                retrograde,
1423                dignity_marker,
1424                annotation,
1425                ..
1426            } => {
1427                let sign_idx = ((deg / 30.0).floor() as usize) % 12;
1428                let sign_name = SIGN_NAMES_ES[sign_idx];
1429                let deg_in_sign = deg - (sign_idx as f32) * 30.0;
1430                let display_symbol = if module_id == "midpoints" {
1431                    // El symbol del midpoint es "a/b" — para el header
1432                    // del tooltip usamos los unicodes individuales.
1433                    if let Some((a, b)) = symbol.split_once('/') {
1434                        format!("{}/{}", planet_unicode(a), planet_unicode(b))
1435                    } else {
1436                        symbol.clone()
1437                    }
1438                } else {
1439                    planet_unicode(symbol).to_string()
1440                };
1441                let mut t = format!("{} {} · {:.1}°", display_symbol, sign_name, deg_in_sign);
1442                if let Some(h) = house {
1443                    t.push_str(&format!(" · Casa {}", h));
1444                }
1445                if *retrograde {
1446                    t.push_str(" · ℞");
1447                }
1448                if let Some(m) = dignity_marker {
1449                    t.push_str(&format!(" · {}", m));
1450                }
1451                if module_id == "midpoints" {
1452                    if let Some(a) = annotation {
1453                        t.push_str(&format!(" · {}", a));
1454                    }
1455                } else if module_id != "natal" {
1456                    t.push_str(&format!(" · {}", module_id));
1457                }
1458                t
1459            }
1460            HoverInfo::HouseCusp {
1461                house_number, deg, ..
1462            } => {
1463                let sign_idx = ((deg / 30.0).floor() as usize) % 12;
1464                let sign_name = SIGN_NAMES_ES[sign_idx];
1465                let deg_in_sign = deg - (sign_idx as f32) * 30.0;
1466                format!(
1467                    "Cusp Casa {} · {} {:.1}°",
1468                    house_number, sign_name, deg_in_sign
1469                )
1470            }
1471            HoverInfo::Aspect {
1472                module_id,
1473                from_body,
1474                to_body,
1475                kind,
1476                orb_deg,
1477                ..
1478            } => {
1479                let mut t = format!(
1480                    "{} {} {}  ·  orb {:.1}°",
1481                    planet_unicode(from_body),
1482                    aspect_unicode(kind),
1483                    planet_unicode(to_body),
1484                    orb_deg
1485                );
1486                if module_id != "natal" {
1487                    t.push_str(&format!(" · {}", module_id));
1488                }
1489                t
1490            }
1491        };
1492        let (lx, ly) = hov.local();
1493        let tip_x = (lx + 14.0).min(WHEEL_SIZE - 220.0).max(8.0);
1494        let tip_y = (ly - 28.0).max(8.0);
1495        wheel = wheel.child(
1496            div()
1497                .absolute()
1498                .left(px(tip_x))
1499                .top(px(tip_y))
1500                .px(px(8.0))
1501                .py(px(4.0))
1502                .rounded(px(6.0))
1503                .bg(theme.bg_panel_alt.clone())
1504                .border_1()
1505                .border_color(palette.angle_highlight)
1506                .text_size(px(11.0))
1507                .text_color(theme.fg_text)
1508                .child(SharedString::from(text)),
1509        );
1510    }
1511
1512    // Labels ASC/MC/DESC/IC como pills en el perímetro — bg del halo
1513    // + border y texto en `angle_highlight`. Más legibles que el
1514    // centered_glyph plano del fase anterior, en especial sobre
1515    // fondos claros donde el ámbar/oro de angle_highlight se diluye.
1516    let angle_labels = [
1517        (asc, "ASC"),
1518        (render.midheaven_deg, "MC"),
1519        (render.descendant_deg, "DESC"),
1520        (render.imum_coeli_deg, "IC"),
1521    ];
1522    let label_r = r_outer * 1.08;
1523    for (deg, label) in angle_labels {
1524        let (x, y) = polar_to_screen(deg, asc, rot_offset, label_r);
1525        let pill_w = (if label.len() > 2 { 38.0 } else { 30.0 }) * s;
1526        let pill_h = 18.0 * s;
1527        wheel = wheel.child(
1528            div()
1529                .absolute()
1530                .left(px(cx_center + x - pill_w / 2.0))
1531                .top(px(cy_center + y - pill_h / 2.0))
1532                .w(px(pill_w))
1533                .h(px(pill_h))
1534                .flex()
1535                .items_center()
1536                .justify_center()
1537                .rounded(px(9.0 * s))
1538                .bg(halo_bg)
1539                .border_1()
1540                .border_color(with_alpha(palette.angle_highlight, 0.85))
1541                .text_size(px(11.0 * s))
1542                .text_color(palette.angle_highlight)
1543                .child(SharedString::from(label)),
1544        );
1545    }
1546
1547    // --- Header + footer + indicador de tiempo ---
1548    let header = div()
1549        .flex()
1550        .flex_col()
1551        .items_center()
1552        .gap(px(2.0))
1553        .child(
1554            div()
1555                .text_size(px(16.0))
1556                .text_color(theme.fg_text)
1557                .child(SharedString::from(render.title.clone())),
1558        );
1559    let header = if let Some(sub) = &render.subtitle {
1560        header.child(
1561            div()
1562                .text_size(px(11.0))
1563                .text_color(theme.fg_muted)
1564                .child(SharedString::from(sub.clone())),
1565        )
1566    } else {
1567        header
1568    };
1569    // Botón export SVG — pequeño, alineado a la derecha del title.
1570    let export_btn = div()
1571        .id("tts-canvas-export-svg")
1572        .px(px(10.0))
1573        .py(px(3.0))
1574        .rounded(px(4.0))
1575        .bg(theme.bg_button())
1576        .hover(|s| s.bg(theme.bg_button_hover()))
1577        .border_1()
1578        .border_color(theme.border)
1579        .text_size(px(10.0))
1580        .text_color(theme.fg_text)
1581        .child("⬇ SVG")
1582        .on_click({
1583            let entity_e = entity.clone();
1584            move |_: &gpui::ClickEvent, _w, cx: &mut gpui::App| {
1585                entity_e.update(cx, |_this, cx| {
1586                    cx.emit(CanvasEvent::ExportSvgRequested);
1587                });
1588            }
1589        });
1590    let header = div()
1591        .flex()
1592        .flex_row()
1593        .items_center()
1594        .gap(px(12.0))
1595        .child(header)
1596        .child(export_btn);
1597
1598    let offset_label = format_offset(time_offset_minutes);
1599    let offset_color = if time_offset_minutes == 0 {
1600        theme.fg_disabled
1601    } else {
1602        palette.angle_highlight
1603    };
1604    let info_row = div()
1605        .flex()
1606        .flex_row()
1607        .gap(px(10.0))
1608        .child(
1609            div()
1610                .text_size(px(10.0))
1611                .text_color(theme.fg_disabled)
1612                .child(SharedString::from(format!(
1613                    "Asc {:.1}°  ·  MC {:.1}°  ·  {} ms",
1614                    render.ascendant_deg, render.midheaven_deg, render.compute_ms,
1615                ))),
1616        )
1617        .child(
1618            div()
1619                .text_size(px(10.0))
1620                .text_color(offset_color)
1621                .child(SharedString::from(offset_label)),
1622        )
1623        .child(
1624            div()
1625                .text_size(px(10.0))
1626                .text_color(theme.fg_disabled)
1627                .child(
1628                    "[D]ial [H]ouses as[X]pects [P]lanets [T]ransits [C]oords  ·  Ctrl+drag = tiempo  ·  [0] reset zoom  ·  [R] reset tiempo  ·  [S]vg",
1629                ),
1630        );
1631
1632    // Badges de overlays activos. Cada uno se pinta como pill con
1633    // background sutil y border tenue. Solo aparecen cuando hay
1634    // overlays — la carta natal pura ve solo el info_row.
1635    let badges_row = if render.overlays.is_empty() {
1636        None
1637    } else {
1638        let mut row = div().flex().flex_row().flex_wrap().gap(px(6.0));
1639        // Badge "natal" base, siempre presente cuando hay overlays —
1640        // ayuda al usuario a leer la pila de izquierda a derecha.
1641        row = row.child(badge(theme, palette, "natal", "Natal", true));
1642        for ov in &render.overlays {
1643            row = row.child(badge(theme, palette, &ov.module_id, &ov.label, false));
1644        }
1645        Some(row)
1646    };
1647
1648    let mut footer = div().flex().flex_col().items_center().gap(px(4.0)).child(info_row);
1649    if let Some(b) = badges_row {
1650        footer = footer.child(b);
1651    }
1652
1653    // Ejes uranianos detectados (cuerpos en la misma posición mod 90).
1654    // Aparece sólo cuando el módulo Uranian está activo y hay
1655    // grupos. Cada grupo se muestra como pill con los unicode de los
1656    // cuerpos + el grado dial-90.
1657    if !render.uranian_groups.is_empty() {
1658        let mut row = div().flex().flex_row().flex_wrap().gap(px(6.0));
1659        for group in &render.uranian_groups {
1660            let bodies_text: String = group
1661                .bodies
1662                .iter()
1663                .map(|b| planet_unicode(b))
1664                .collect::<Vec<_>>()
1665                .join(" ");
1666            row = row.child(
1667                div()
1668                    .px(px(8.0))
1669                    .py(px(2.0))
1670                    .rounded(px(10.0))
1671                    .bg(theme.bg_panel_alt.clone())
1672                    .border_1()
1673                    .border_color(with_alpha(palette.angle_highlight, 0.6))
1674                    .text_size(px(11.0))
1675                    .text_color(theme.fg_text)
1676                    .child(SharedString::from(format!(
1677                        "{}  ·  {:.1}°",
1678                        bodies_text, group.mod90_deg
1679                    ))),
1680            );
1681        }
1682        footer = footer.child(
1683            div()
1684                .flex()
1685                .flex_col()
1686                .items_center()
1687                .gap(px(3.0))
1688                .child(
1689                    div()
1690                        .text_size(px(10.0))
1691                        .text_color(theme.fg_muted)
1692                        .child("Ejes uranianos (90°)"),
1693                )
1694                .child(row),
1695        );
1696    }
1697
1698    // Lista textual de aspectos (top 12 por orb). Compacta, en grid
1699    // de 3 columnas, fonts pequeños. Solo aparece cuando hay aspectos
1700    // computados.
1701    if !render.aspect_summary.is_empty() {
1702        let mut grid = div()
1703            .flex()
1704            .flex_row()
1705            .flex_wrap()
1706            .gap(px(10.0))
1707            .max_w(px(WHEEL_SIZE + 80.0))
1708            .justify_center();
1709        for ap in render.aspect_summary.iter().take(12) {
1710            let kind_sym = aspect_unicode(&ap.kind);
1711            let line = format!(
1712                "{} {} {}  ·  {:.1}°{}",
1713                planet_unicode(&ap.from_body),
1714                kind_sym,
1715                planet_unicode(&ap.to_body),
1716                ap.orb_deg,
1717                match ap.applying {
1718                    Some(true) => " A",
1719                    Some(false) => " S",
1720                    None => "",
1721                }
1722            );
1723            let prefix = if ap.module_id == "natal" {
1724                String::new()
1725            } else {
1726                format!("[{}] ", ap.module_id)
1727            };
1728            grid = grid.child(
1729                div()
1730                    .px(px(6.0))
1731                    .py(px(2.0))
1732                    .text_size(px(11.0))
1733                    .text_color(aspect_color(palette, &ap.kind))
1734                    .child(SharedString::from(format!("{}{}", prefix, line))),
1735            );
1736        }
1737        footer = footer.child(grid);
1738    }
1739
1740    div()
1741        .flex()
1742        .flex_col()
1743        .items_center()
1744        .gap(px(8.0))
1745        .child(header)
1746        .child(wheel)
1747        .child(footer)
1748}
1749
1750/// Pequeña pill con la etiqueta de un overlay activo. El borde toma
1751/// color según el "tipo" del módulo para ayudar a mapear a su anillo
1752/// en el wheel: natal = neutro, outer ring share (transit/synastry/
1753/// planetary_return) = palette.angle_highlight, inner overlays
1754/// (progression/solar_arc) = palette.house_cusp.
1755fn badge(theme: &Theme, palette: &AstroPalette, module_id: &str, label: &str, is_natal: bool) -> gpui::Div {
1756    let border = if is_natal {
1757        theme.border
1758    } else {
1759        match module_id {
1760            "transit" | "synastry" | "planetary_return" => palette.angle_highlight,
1761            "progression" | "solar_arc" => palette.house_cusp,
1762            _ => theme.border,
1763        }
1764    };
1765    div()
1766        .px(px(8.0))
1767        .py(px(2.0))
1768        .rounded(px(10.0))
1769        .bg(theme.bg_panel_alt.clone())
1770        .border_1()
1771        .border_color(border)
1772        .text_size(px(10.0))
1773        .text_color(theme.fg_text)
1774        .child(SharedString::from(label.to_string()))
1775}
1776
1777fn format_offset(minutes: i64) -> String {
1778    if minutes == 0 {
1779        return "⏱ ahora".to_string();
1780    }
1781    let sign = if minutes > 0 { '+' } else { '-' };
1782    let m = minutes.unsigned_abs();
1783    let days = m / (60 * 24);
1784    let hours = (m / 60) % 24;
1785    let mins = m % 60;
1786    if days > 0 {
1787        format!("⏱ {}{}d {:02}h {:02}m", sign, days, hours, mins)
1788    } else if hours > 0 {
1789        format!("⏱ {}{:02}h {:02}m", sign, hours, mins)
1790    } else {
1791        format!("⏱ {}{:02}m", sign, mins)
1792    }
1793}
1794
1795// =====================================================================
1796// Painting
1797// =====================================================================
1798
1799/// Geometría radial canónica de la rueda. Aros nombrados según
1800/// convención del usuario, de afuera hacia adentro:
1801///
1802/// * **Aro A** (`sign_outer`) — externo del zodiaco.
1803/// * **Zona AB** — sign dial: glyphs de signos zodiacales.
1804/// * **Aro B** (`sign_inner` = `topo_houses_outer`) — interno del
1805///   zodiaco / externo del bloque ascensional.
1806/// * **Zona BC** — casas topocéntricas (cusps b→c) + planetas
1807///   topocéntricos, ambos con sus coordenadas.
1808/// * **Aro C** (`topo_houses_inner` = `houses_outer`) — separador
1809///   ascensional / casas geo.
1810/// * **Zona CD** — casas geocéntricas (cusps c→d) + sus coordenadas.
1811/// * **Aro D** (`houses_inner`) — externo de los planetas natales.
1812///   Junto a D, hacia adentro, se posan los planetas natales y sus
1813///   coordenadas.
1814/// * **Aro E** (`aspects`) — el más interno. Desde aquí nacen las
1815///   líneas de aspecto / relaciones / overlays opcionales.
1816///
1817/// Los overlays adicionales (transits, midpoints, progression, solar
1818/// arc, composite) viven INTERIORES al aro E — solo se pintan
1819/// cuando el módulo correspondiente está activo, así no compiten
1820/// con el layout base.
1821#[derive(Clone, Copy)]
1822struct Radii {
1823    sign_outer: f32,          // Aro A
1824    sign_inner: f32,          // Aro B
1825    topo_houses_outer: f32,   // = Aro B
1826    topocentric: f32,         // Zona BC: planetas topo
1827    topo_houses_inner: f32,   // Aro C
1828    houses_outer: f32,        // = Aro C
1829    houses_inner: f32,        // Aro D
1830    bodies: f32,              // Zona D-E: planetas natales (junto a D)
1831    pd_direct: f32,           // GR (cuando activo): exterior al cinturón natal
1832    pd_converse: f32,         // GR (cuando activo): interior al cinturón natal
1833    aspects: f32,             // Aro E (invisible, ancla de líneas)
1834    // Overlays adicionales — todos interiores a E.
1835    transits: f32,
1836    midpoints: f32,
1837    progression: f32,
1838    solar_arc: f32,
1839    composite: f32,
1840}
1841
1842impl Radii {
1843    fn from_outer(r: f32) -> Self {
1844        Self {
1845            // Aro A — externo zodiaco.
1846            sign_outer: r,
1847            // Aro B — interno zodiaco / externo bloque ascensional.
1848            sign_inner: r * 0.92,
1849            topo_houses_outer: r * 0.92,
1850            // Zona BC: planetas topocéntricos centrados.
1851            topocentric: r * 0.85,
1852            // Aro C — separador ascensional / casas geo.
1853            topo_houses_inner: r * 0.78,
1854            houses_outer: r * 0.78,
1855            // Aro D — externo planetas natales.
1856            houses_inner: r * 0.62,
1857            // Planetas natales justo dentro de D.
1858            bodies: r * 0.57,
1859            // GR dual-ring (cuando se activa): abraza el cinturón
1860            // natal por afuera (`pd_direct`) y por adentro
1861            // (`pd_converse`). Si GR está OFF, ninguno de los dos se
1862            // pinta — no compite con el layout base.
1863            pd_direct: r * 0.545,
1864            pd_converse: r * 0.515,
1865            // Aro E — anclaje invisible de las líneas de aspecto.
1866            aspects: r * 0.49,
1867            // Overlays adicionales — todos INTERIORES al aro E. Se
1868            // pintan solo cuando el módulo correspondiente está
1869            // activo, así no compiten con el layout base.
1870            transits: r * 0.43,
1871            midpoints: r * 0.39,
1872            progression: r * 0.33,
1873            solar_arc: r * 0.27,
1874            composite: r * 0.21,
1875        }
1876    }
1877
1878    /// Radio del ring de cuerpos según el `module_id` del Layer.
1879    fn body_ring(&self, module_id: &str) -> f32 {
1880        match module_id {
1881            "progression" => self.progression,
1882            "solar_arc" => self.solar_arc,
1883            "composite" => self.composite,
1884            "midpoints" => self.midpoints,
1885            "topocentric" => self.topocentric,
1886            "pd_direct" => self.pd_direct,
1887            "pd_converse" => self.pd_converse,
1888            _ => self.bodies,
1889        }
1890    }
1891
1892    /// Resuelve qué radios corresponden a una capa de aspectos según el
1893    /// `module_id`: natal-natal en `aspects`, cross con cada overlay
1894    /// desde `bodies` (extremo natal) al ring del módulo. Los módulos
1895    /// del outer ring (OUTER_RING_MODULES) comparten el slot de
1896    /// tránsito (son mutuamente excluyentes a nivel de Shell).
1897    fn aspect_endpoints(&self, module_id: &str) -> (f32, f32) {
1898        if OUTER_RING_MODULES.contains(&module_id) {
1899            return (self.bodies, self.transits);
1900        }
1901        match module_id {
1902            "progression" => (self.bodies, self.progression),
1903            "solar_arc" => (self.bodies, self.solar_arc),
1904            "composite" => (self.bodies, self.composite),
1905            _ => (self.aspects, self.aspects),
1906        }
1907    }
1908}
1909
1910#[allow(clippy::too_many_arguments)]
1911// `hover_focus`: symbol del planeta hovereado en este frame (si lo
1912// hay). Las líneas de aspecto que NO tocan a ese planeta se opacan
1913// para que el usuario lea claramente "qué afecta a qué". Si `None`,
1914// todas las líneas se pintan a alpha plena.
1915fn paint_wheel(
1916    bounds: Bounds<Pixels>,
1917    window: &mut Window,
1918    theme: &Theme,
1919    palette: &AstroPalette,
1920    layers: &[Layer],
1921    ascendant_deg: f32,
1922    midheaven_deg: f32,
1923    rot_offset_deg: f32,
1924    radii: Radii,
1925    visibility: &HashMap<LayerKind, bool>,
1926    hover_focus: Option<&str>,
1927) {
1928    let (cx, cy) = bounds_center(bounds);
1929    let show = |k: LayerKind| visibility.get(&k).copied().unwrap_or(true);
1930
1931    // 1. Sectores zodiacales (parte del SignDial layer).
1932    if show(LayerKind::SignDial) {
1933        paint_sign_sectors(window, cx, cy, &radii, palette, ascendant_deg, rot_offset_deg);
1934
1935        // Anillos del dial con efecto 3D: highlight interior + base +
1936        // shadow exterior. El highlight es 1 px hacia el centro con
1937        // luminancia +0.18; la shadow 1 px hacia afuera con -0.18.
1938        // El bevel central — varios strokes finos con alpha en bell
1939        // curve entre sign_inner y sign_outer — da volumen al dial.
1940        stroke_circle_3d(window, cx, cy, radii.sign_outer, 1.5, palette.dial_ring, theme);
1941        stroke_circle_3d(window, cx, cy, radii.sign_inner, 1.0, palette.dial_ring, theme);
1942        paint_dial_bevel(window, cx, cy, &radii, palette, theme);
1943
1944        // Cusps zodiacales cada 30°.
1945        for i in 0..12 {
1946            let lon = (i as f32) * 30.0;
1947            let color = palette.dial_ring;
1948            paint_radial_line(
1949                window,
1950                cx,
1951                cy,
1952                lon,
1953                ascendant_deg,
1954                rot_offset_deg,
1955                radii.sign_inner,
1956                radii.sign_outer,
1957                color,
1958                1.0,
1959            );
1960        }
1961    }
1962
1963    // 2. Casas — doble anillo (inner + outer) + cusps radiales +
1964    // énfasis Asc/IC/Desc/MC. La doble línea vuelve a la zona de
1965    // casas una "corona" claramente identificable. Color derivado
1966    // de `house_cusp` con un hue shift para que el sistema
1967    // ascensional (casas) se distinga visualmente del eclíptico
1968    // (dial zodiacal) que va en dorado.
1969    if show(LayerKind::Houses) {
1970        let house_base = house_ring_color(palette);
1971        let house_color = with_alpha(house_base, 0.85);
1972        stroke_circle_3d(window, cx, cy, radii.houses_outer, 1.1, house_color, theme);
1973        stroke_circle_3d(window, cx, cy, radii.houses_inner, 1.1, house_color, theme);
1974        // Si hay capa topocéntrica activa, pintar también sus dos
1975        // anillos (con stroke más sutil que el geocéntrico, para que
1976        // se lea como "sistema ascensional" sin competir).
1977        if layers
1978            .iter()
1979            .any(|l| matches!(l.kind, LayerKind::Houses) && l.module_id == "topocentric")
1980        {
1981            let topo_color = with_alpha(house_base, 0.55);
1982            stroke_circle(window, cx, cy, radii.topo_houses_outer, 0.8, topo_color);
1983            stroke_circle(window, cx, cy, radii.topo_houses_inner, 0.8, topo_color);
1984        }
1985
1986        for layer in layers {
1987            if matches!(layer.kind, LayerKind::Houses) {
1988                let is_topo = layer.module_id == "topocentric";
1989                let (r_in, r_out) = if is_topo {
1990                    (radii.topo_houses_inner, radii.topo_houses_outer)
1991                } else {
1992                    (radii.houses_inner, radii.houses_outer)
1993                };
1994                if let Geometry::Ring { cusps_deg } = &layer.geometry {
1995                    for (i, c) in cusps_deg.iter().enumerate() {
1996                        let is_angle = i == 0 || i == 3 || i == 6 || i == 9;
1997                        let color = if is_topo {
1998                            with_alpha(house_base, 0.60)
1999                        } else if is_angle {
2000                            palette.angle_highlight
2001                        } else {
2002                            with_alpha(house_base, 0.75)
2003                        };
2004                        let width = if is_angle && !is_topo { 2.0 } else { 0.8 };
2005                        if is_topo {
2006                            // Topocéntrico: cusp como línea punteada
2007                            // en su propio anillo cercano al sign
2008                            // dial — se distingue del Placidus
2009                            // geocéntrico por el dash pattern y la
2010                            // ubicación más exterior.
2011                            paint_segment(
2012                                window,
2013                                cx
2014                                    + polar_to_screen(
2015                                        *c,
2016                                        ascendant_deg,
2017                                        rot_offset_deg,
2018                                        r_in,
2019                                    )
2020                                    .0,
2021                                cy
2022                                    + polar_to_screen(
2023                                        *c,
2024                                        ascendant_deg,
2025                                        rot_offset_deg,
2026                                        r_in,
2027                                    )
2028                                    .1,
2029                                cx
2030                                    + polar_to_screen(
2031                                        *c,
2032                                        ascendant_deg,
2033                                        rot_offset_deg,
2034                                        r_out,
2035                                    )
2036                                    .0,
2037                                cy
2038                                    + polar_to_screen(
2039                                        *c,
2040                                        ascendant_deg,
2041                                        rot_offset_deg,
2042                                        r_out,
2043                                    )
2044                                    .1,
2045                                color,
2046                                Some((3.0, 2.5)),
2047                                1.0,
2048                            );
2049                        } else {
2050                            paint_radial_line(
2051                                window,
2052                                cx,
2053                                cy,
2054                                *c,
2055                                ascendant_deg,
2056                                rot_offset_deg,
2057                                r_in,
2058                                r_out,
2059                                color,
2060                                width,
2061                            );
2062                        }
2063                    }
2064                }
2065            }
2066        }
2067
2068        // Cruz completa Asc-Desc + MC-IC, alpha bastante visible para
2069        // que orienten la lectura sin competir con cuerpos/aspectos.
2070        // 4 radios desde el centro: ASC, DESC (=asc+180), MC, IC
2071        // (=mc+180). `paint_radial_line` con r_inner=0 pinta un radio
2072        // del centro al borde — la cruz es la unión de los 4.
2073        let axis_color = with_alpha(palette.angle_highlight, 0.55);
2074        for axis_deg in [
2075            ascendant_deg,
2076            ascendant_deg + 180.0,
2077            midheaven_deg,
2078            midheaven_deg + 180.0,
2079        ] {
2080            paint_radial_line(
2081                window,
2082                cx,
2083                cy,
2084                axis_deg,
2085                ascendant_deg,
2086                rot_offset_deg,
2087                0.0,
2088                radii.houses_outer,
2089                axis_color,
2090                1.4,
2091            );
2092        }
2093    }
2094
2095    // Aro D — único anillo visible del bloque de planetas natales
2096    // (la idea del "carril doble" se descartó: confundía con el
2097    // sistema de casas). El aro E (`radii.aspects`) no se pinta por
2098    // diseño; solo es ancla invisible de las líneas.
2099    if show(LayerKind::Bodies) {
2100        let belt_color = with_alpha(palette.dial_ring, 0.55);
2101        stroke_circle_3d(window, cx, cy, radii.houses_inner, 0.9, belt_color, theme);
2102        // GR dual-ring: si las capas de direcciones primarias están
2103        // presentes, marcar sus anillos para que el visual lea como
2104        // "abrazo" del cinturón natal. La directa va punteada,
2105        // la conversa también — la diferencia entre las dos es la
2106        // ubicación radial (afuera vs adentro del cinturón natal).
2107        let has_pd = layers.iter().any(|l| {
2108            matches!(l.kind, LayerKind::Bodies)
2109                && (l.module_id == "pd_direct" || l.module_id == "pd_converse")
2110        });
2111        if has_pd {
2112            let pd_color = with_alpha(palette.angle_highlight, 0.50);
2113            for r in [radii.pd_direct, radii.pd_converse] {
2114                // Pintamos el anillo como tramo punteado fino: 24
2115                // segmentos cortos a lo largo del círculo.
2116                let steps = 96;
2117                for i in 0..steps {
2118                    if i % 2 != 0 {
2119                        continue;
2120                    }
2121                    let a0 = (i as f32) / (steps as f32) * std::f32::consts::TAU;
2122                    let a1 = ((i + 1) as f32) / (steps as f32) * std::f32::consts::TAU;
2123                    let x0 = cx + r * a0.cos();
2124                    let y0 = cy + r * a0.sin();
2125                    let x1 = cx + r * a1.cos();
2126                    let y1 = cy + r * a1.sin();
2127                    paint_segment(window, x0, y0, x1, y1, pd_color, None, 0.6);
2128                }
2129            }
2130        }
2131    }
2132
2133    // 3. Aspectos. Cada module_id usa su par de radios — natal-natal
2134    // ambos en `aspects`, cross con transit en `bodies → transits`,
2135    // cross con progression en `bodies → progression`.
2136    if show(LayerKind::Aspects) {
2137        let mono = palette.is_monochrome();
2138        for layer in layers {
2139            if matches!(layer.kind, LayerKind::Aspects) {
2140                if let Geometry::Lines(segs) = &layer.geometry {
2141                    let (r_from, r_to) = radii.aspect_endpoints(&layer.module_id);
2142                    let is_cross = r_from != r_to;
2143                    for seg in segs {
2144                        // Filtro minors con orbe ancho: los aspectos
2145                        // menores (quincunx, semi-square, quintile…)
2146                        // solo se trazan si están MUY apretados
2147                        // (orbe ≤ 3°). Sobre 3° ensucian sin aportar.
2148                        if !is_major_aspect(&seg.kind) && seg.orb_deg.abs() > 3.0 {
2149                            continue;
2150                        }
2151                        let base = aspect_color(palette, &seg.kind);
2152                        let base = with_alpha(base, base.a * seg.opacity);
2153                        // Hover focus: si hay un planeta hovereado y
2154                        // este segmento NO lo toca, lo atenuamos al
2155                        // 18%; si lo toca o no hay hover, va pleno.
2156                        let touches_hover = hover_focus
2157                            .map(|sym| seg.from_body == sym || seg.to_body == sym)
2158                            .unwrap_or(true);
2159                        let factor = if touches_hover { 1.0 } else { 0.18 };
2160                        let color = with_alpha(base, base.a * factor);
2161                        let dash = if mono {
2162                            dash_pattern_for_kind(&seg.kind)
2163                        } else {
2164                            None
2165                        };
2166                        // Width inverso al orbe: orbes cerrados se ven
2167                        // gruesos (aspecto "fuerte"), orbes amplios
2168                        // finos. Mayores van un escalón más gruesos
2169                        // que menores en su mismo orbe.
2170                        let width = aspect_width(&seg.kind, seg.orb_deg, mono);
2171                        if is_cross {
2172                            paint_cross_aspect_line(
2173                                window,
2174                                cx,
2175                                cy,
2176                                seg.from_deg,
2177                                seg.to_deg,
2178                                ascendant_deg,
2179                                rot_offset_deg,
2180                                r_from,
2181                                r_to,
2182                                color,
2183                                dash,
2184                            );
2185                        } else {
2186                            paint_aspect_line(
2187                                window,
2188                                cx,
2189                                cy,
2190                                seg.from_deg,
2191                                seg.to_deg,
2192                                ascendant_deg,
2193                                rot_offset_deg,
2194                                r_from,
2195                                color,
2196                                dash,
2197                                width,
2198                            );
2199                        }
2200                    }
2201                }
2202            }
2203        }
2204    }
2205
2206    // 4. Marcadores de posición exacta. Antes el dot era "el planeta";
2207    // ahora el glyph (con halo, en DOM) lo es. El círculo acá queda
2208    // como marker de precisión angular — chico, alpha alta, sobre el
2209    // anillo correspondiente. Glow se mantiene para Sol/Luna como
2210    // toque místico, pero también reducido.
2211    if show(LayerKind::Bodies) {
2212        let dot_r = (radii.sign_outer * 0.009).max(1.5);
2213        for layer in layers {
2214            if matches!(layer.kind, LayerKind::Bodies) {
2215                let ring = radii.body_ring(&layer.module_id);
2216                let is_natal = layer.module_id == "natal";
2217                let alpha = if is_natal { 1.0 } else { 0.85 };
2218                for g in &layer.glyphs {
2219                    let color = with_alpha(planet_color(palette, &g.symbol), alpha);
2220                    let (x, y) = polar_to_screen(g.deg, ascendant_deg, rot_offset_deg, ring);
2221                    if is_natal && (g.symbol == "sun" || g.symbol == "moon") {
2222                        paint_glow(window, cx + x, cy + y, dot_r * 1.8, color);
2223                    }
2224                    fill_circle(window, cx + x, cy + y, dot_r, color);
2225                }
2226            }
2227        }
2228    }
2229
2230    // Anillos guía para los overlays internos (progression, solar_arc).
2231    let guide_inset = radii.sign_outer * 0.03;
2232    for (module_id, ring) in [
2233        ("progression", radii.progression),
2234        ("solar_arc", radii.solar_arc),
2235    ] {
2236        let active = layers
2237            .iter()
2238            .any(|l| matches!(l.kind, LayerKind::Bodies) && l.module_id == module_id);
2239        if active {
2240            stroke_circle(
2241                window,
2242                cx,
2243                cy,
2244                ring + guide_inset,
2245                0.5,
2246                with_alpha(palette.house_cusp, 0.35),
2247            );
2248            stroke_circle(
2249                window,
2250                cx,
2251                cy,
2252                ring - guide_inset,
2253                0.5,
2254                with_alpha(palette.house_cusp, 0.35),
2255            );
2256        }
2257    }
2258
2259    // 5. Outer ring (transit o synastry overlay): anillo guía + dots
2260    // de la capa activa. Son mutuamente excluyentes a nivel de Shell;
2261    // si alguno de los dos está prendido, pintamos el slot.
2262    let outer_active = layers.iter().any(|l| {
2263        matches!(l.kind, LayerKind::Outer)
2264            && OUTER_RING_MODULES.contains(&l.module_id.as_str())
2265    });
2266    if outer_active && show(LayerKind::Outer) {
2267        let band = radii.sign_outer * 0.035;
2268        stroke_circle_3d(
2269            window,
2270            cx,
2271            cy,
2272            radii.transits + band,
2273            0.7,
2274            with_alpha(palette.dial_ring, 0.55),
2275            theme,
2276        );
2277        stroke_circle_3d(
2278            window,
2279            cx,
2280            cy,
2281            radii.transits - band,
2282            0.7,
2283            with_alpha(palette.dial_ring, 0.55),
2284            theme,
2285        );
2286
2287        let dot_r = (radii.sign_outer * 0.008).max(1.5);
2288        for layer in layers {
2289            if matches!(layer.kind, LayerKind::Outer)
2290                && (OUTER_RING_MODULES.contains(&layer.module_id.as_str()))
2291            {
2292                for g in &layer.glyphs {
2293                    let color = with_alpha(planet_color(palette, &g.symbol), 0.85);
2294                    let (x, y) =
2295                        polar_to_screen(g.deg, ascendant_deg, rot_offset_deg, radii.transits);
2296                    fill_circle(window, cx + x, cy + y, dot_r, color);
2297                }
2298            }
2299        }
2300    }
2301}
2302
2303fn paint_sign_sectors(
2304    window: &mut Window,
2305    cx: f32,
2306    cy: f32,
2307    radii: &Radii,
2308    palette: &AstroPalette,
2309    ascendant_deg: f32,
2310    rot_offset_deg: f32,
2311) {
2312    const SUBDIVISIONS: usize = 18;
2313    for i in 0..12 {
2314        let lon_start = (i as f32) * 30.0;
2315        let lon_end = lon_start + 30.0;
2316        let element = sign_element_by_index(i);
2317        let color = with_alpha(palette.element(element), 0.10);
2318
2319        let mut builder = PathBuilder::fill();
2320        let (x0, y0) = polar_to_screen(lon_start, ascendant_deg, rot_offset_deg, radii.sign_inner);
2321        builder.move_to(point(px(cx + x0), px(cy + y0)));
2322
2323        for k in 1..=SUBDIVISIONS {
2324            let t = lon_start + (lon_end - lon_start) * (k as f32) / (SUBDIVISIONS as f32);
2325            let (x, y) = polar_to_screen(t, ascendant_deg, rot_offset_deg, radii.sign_inner);
2326            builder.line_to(point(px(cx + x), px(cy + y)));
2327        }
2328        let (xe, ye) = polar_to_screen(lon_end, ascendant_deg, rot_offset_deg, radii.sign_outer);
2329        builder.line_to(point(px(cx + xe), px(cy + ye)));
2330
2331        for k in (0..SUBDIVISIONS).rev() {
2332            let t = lon_start + (lon_end - lon_start) * (k as f32) / (SUBDIVISIONS as f32);
2333            let (x, y) = polar_to_screen(t, ascendant_deg, rot_offset_deg, radii.sign_outer);
2334            builder.line_to(point(px(cx + x), px(cy + y)));
2335        }
2336        builder.close();
2337        if let Ok(path) = builder.build() {
2338            window.paint_path(path, color);
2339        }
2340    }
2341}
2342
2343fn stroke_circle(window: &mut Window, cx: f32, cy: f32, r: f32, width: f32, color: Hsla) {
2344    const SEGMENTS: usize = 96;
2345    let mut builder = PathBuilder::stroke(px(width));
2346    for i in 0..=SEGMENTS {
2347        let t = (i as f32) / (SEGMENTS as f32) * (2.0 * PI);
2348        let x = cx + r * t.cos();
2349        let y = cy + r * t.sin();
2350        if i == 0 {
2351            builder.move_to(point(px(x), px(y)));
2352        } else {
2353            builder.line_to(point(px(x), px(y)));
2354        }
2355    }
2356    if let Ok(path) = builder.build() {
2357        window.paint_path(path, color);
2358    }
2359}
2360
2361/// Pinta 3 halos concéntricos con alpha decreciente alrededor de un
2362/// punto — usado para Sol/Luna natales. El radio crece, la opacidad
2363/// cae: el ojo lo lee como "esto irradia". Sin glow real (GPUI 0.2 no
2364/// tiene radial gradient), pero el shading concéntrico convence.
2365fn paint_glow(window: &mut Window, cx: f32, cy: f32, base_r: f32, color: Hsla) {
2366    const HALOS: [(f32, f32); 3] = [(5.0, 0.05), (3.0, 0.12), (1.8, 0.22)];
2367    for (mult, alpha) in HALOS {
2368        let r = base_r * mult;
2369        let halo = hsla(color.h, color.s, color.l, alpha);
2370        fill_circle(window, cx, cy, r, halo);
2371    }
2372}
2373
2374fn fill_circle(window: &mut Window, cx: f32, cy: f32, r: f32, color: Hsla) {
2375    const SEGMENTS: usize = 32;
2376    let mut builder = PathBuilder::fill();
2377    builder.move_to(point(px(cx + r), px(cy)));
2378    for i in 1..=SEGMENTS {
2379        let t = (i as f32) / (SEGMENTS as f32) * (2.0 * PI);
2380        let x = cx + r * t.cos();
2381        let y = cy + r * t.sin();
2382        builder.line_to(point(px(x), px(y)));
2383    }
2384    builder.close();
2385    if let Ok(path) = builder.build() {
2386        window.paint_path(path, color);
2387    }
2388}
2389
2390#[allow(clippy::too_many_arguments)]
2391fn paint_radial_line(
2392    window: &mut Window,
2393    cx: f32,
2394    cy: f32,
2395    longitude_deg: f32,
2396    ascendant_deg: f32,
2397    rot_offset_deg: f32,
2398    r_inner: f32,
2399    r_outer: f32,
2400    color: Hsla,
2401    width: f32,
2402) {
2403    let (xi, yi) = polar_to_screen(longitude_deg, ascendant_deg, rot_offset_deg, r_inner);
2404    let (xo, yo) = polar_to_screen(longitude_deg, ascendant_deg, rot_offset_deg, r_outer);
2405    let mut builder = PathBuilder::stroke(px(width));
2406    builder.move_to(point(px(cx + xi), px(cy + yi)));
2407    builder.line_to(point(px(cx + xo), px(cy + yo)));
2408    if let Ok(path) = builder.build() {
2409        window.paint_path(path, color);
2410    }
2411}
2412
2413#[allow(clippy::too_many_arguments)]
2414fn paint_aspect_line(
2415    window: &mut Window,
2416    cx: f32,
2417    cy: f32,
2418    a_deg: f32,
2419    b_deg: f32,
2420    ascendant_deg: f32,
2421    rot_offset_deg: f32,
2422    r: f32,
2423    color: Hsla,
2424    dash: Option<(f32, f32)>,
2425    width: f32,
2426) {
2427    let (xa, ya) = polar_to_screen(a_deg, ascendant_deg, rot_offset_deg, r);
2428    let (xb, yb) = polar_to_screen(b_deg, ascendant_deg, rot_offset_deg, r);
2429    paint_segment(window, cx + xa, cy + ya, cx + xb, cy + yb, color, dash, width);
2430}
2431
2432/// Línea de aspecto natal ↔ tránsito: extremos en radios distintos.
2433/// El `from_deg` cae sobre el ring de cuerpos natales (`r_from`); el
2434/// `to_deg` sobre el ring de tránsito (`r_to`). Trazo más fino que el
2435/// natal-natal para no competir visualmente.
2436#[allow(clippy::too_many_arguments)]
2437fn paint_cross_aspect_line(
2438    window: &mut Window,
2439    cx: f32,
2440    cy: f32,
2441    natal_deg: f32,
2442    transit_deg: f32,
2443    ascendant_deg: f32,
2444    rot_offset_deg: f32,
2445    r_from: f32,
2446    r_to: f32,
2447    color: Hsla,
2448    dash: Option<(f32, f32)>,
2449) {
2450    let (xa, ya) = polar_to_screen(natal_deg, ascendant_deg, rot_offset_deg, r_from);
2451    let (xb, yb) = polar_to_screen(transit_deg, ascendant_deg, rot_offset_deg, r_to);
2452    paint_segment(window, cx + xa, cy + ya, cx + xb, cy + yb, color, dash, 0.7);
2453}
2454
2455/// Pinta un segmento entre dos puntos. Si `dash` es `Some((on, off))`,
2456/// itera el vector pintando trechos de `on` px con gaps de `off` px.
2457/// Si `None`, una sola línea continua. Usado por todos los aspect
2458/// painters — el dash pattern es la forma de distinguir kinds en
2459/// el theme BW (donde el color no sirve).
2460fn paint_segment(
2461    window: &mut Window,
2462    x0: f32,
2463    y0: f32,
2464    x1: f32,
2465    y1: f32,
2466    color: Hsla,
2467    dash: Option<(f32, f32)>,
2468    width: f32,
2469) {
2470    let Some((on, off)) = dash else {
2471        let mut b = PathBuilder::stroke(px(width));
2472        b.move_to(point(px(x0), px(y0)));
2473        b.line_to(point(px(x1), px(y1)));
2474        if let Ok(p) = b.build() {
2475            window.paint_path(p, color);
2476        }
2477        return;
2478    };
2479    let dx = x1 - x0;
2480    let dy = y1 - y0;
2481    let len = (dx * dx + dy * dy).sqrt();
2482    if len < 0.1 {
2483        return;
2484    }
2485    let ux = dx / len;
2486    let uy = dy / len;
2487    let step = on + off;
2488    if step < 0.1 {
2489        return;
2490    }
2491    let mut t = 0.0;
2492    while t < len {
2493        let t_end = (t + on).min(len);
2494        let sx = x0 + ux * t;
2495        let sy = y0 + uy * t;
2496        let ex = x0 + ux * t_end;
2497        let ey = y0 + uy * t_end;
2498        let mut b = PathBuilder::stroke(px(width));
2499        b.move_to(point(px(sx), px(sy)));
2500        b.line_to(point(px(ex), px(ey)));
2501        if let Ok(p) = b.build() {
2502            window.paint_path(p, color);
2503        }
2504        t += step;
2505    }
2506}
2507
2508/// `true` para los 5 aspectos Ptoloméicos (conjunction, sextile,
2509/// square, trine, opposition). Cualquier otro `kind` se considera
2510/// menor — quincunx, semi-square, quintile, sesquiquadrate, etc.
2511fn is_major_aspect(kind: &str) -> bool {
2512    matches!(
2513        kind,
2514        "conjunction" | "sextile" | "square" | "trine" | "opposition"
2515    )
2516}
2517
2518/// Grosor de línea de aspecto inverso al orbe. La idea: a orbe 0°
2519/// (aspecto exacto) la línea va gruesa porque "pesa" más; a orbe
2520/// amplio se afina. Los mayores arrancan en un techo más alto que
2521/// los menores. En BW se le suma un poquito a todos porque las
2522/// líneas competen con sus dash patterns.
2523fn aspect_width(kind: &str, orb_deg: f32, mono: bool) -> f32 {
2524    let orb = orb_deg.abs();
2525    let major = is_major_aspect(kind);
2526    // Orbe de referencia para normalizar: ~8° para mayores, ~3° para
2527    // menores. Más allá la línea ya está afinada al mínimo.
2528    let max_orb = if major { 8.0 } else { 3.0 };
2529    let t = (1.0 - (orb / max_orb)).clamp(0.0, 1.0);
2530    let (min_w, max_w) = if major { (0.7, 2.1) } else { (0.5, 1.2) };
2531    let w = min_w + (max_w - min_w) * t;
2532    if mono { w + 0.2 } else { w }
2533}
2534
2535/// Dash pattern por aspecto, para modo monocromático. En modo color
2536/// el caller pasa `None` y las líneas van sólidas. Patterns elegidos
2537/// para que cada kind sea distinguible a ojo:
2538/// - conjunction/opposition: sólido (más peso visual, son los
2539///   aspectos "fuertes")
2540/// - square: dash medio (4 on / 3 off)
2541/// - trine: dash largo (8 on / 2 off) — casi sólido pero distinguible
2542/// - sextile: dotted (1.5 on / 3 off)
2543/// - minor: dotted finísimo (1 on / 4 off)
2544fn dash_pattern_for_kind(kind: &str) -> Option<(f32, f32)> {
2545    match kind {
2546        "conjunction" | "opposition" => None,
2547        "square" => Some((4.0, 3.0)),
2548        "trine" => Some((8.0, 2.0)),
2549        "sextile" => Some((1.5, 3.0)),
2550        _ => Some((1.0, 4.0)),
2551    }
2552}
2553
2554// =====================================================================
2555// Helpers
2556// =====================================================================
2557
2558/// Distancia mínima entre un punto y un segmento de recta. Usado por
2559/// hover_check para detectar proximity a líneas de aspectos.
2560fn dist_point_segment(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32) -> f32 {
2561    let dx = bx - ax;
2562    let dy = by - ay;
2563    let len_sq = dx * dx + dy * dy;
2564    if len_sq < f32::EPSILON {
2565        // Segmento degenerado → distancia al punto a.
2566        let pdx = px - ax;
2567        let pdy = py - ay;
2568        return (pdx * pdx + pdy * pdy).sqrt();
2569    }
2570    let t = (((px - ax) * dx + (py - ay) * dy) / len_sq).clamp(0.0, 1.0);
2571    let proj_x = ax + t * dx;
2572    let proj_y = ay + t * dy;
2573    let dx2 = px - proj_x;
2574    let dy2 = py - proj_y;
2575    (dx2 * dx2 + dy2 * dy2).sqrt()
2576}
2577
2578fn polar_to_screen(
2579    longitude_deg: f32,
2580    ascendant_deg: f32,
2581    rot_offset_deg: f32,
2582    radius: f32,
2583) -> (f32, f32) {
2584    let deg = 180.0 - (longitude_deg - ascendant_deg + rot_offset_deg);
2585    let rad = deg * PI / 180.0;
2586    (radius * rad.cos(), radius * rad.sin())
2587}
2588
2589fn centered_glyph(
2590    x: f32,
2591    y: f32,
2592    box_size: f32,
2593    font_size: f32,
2594    text: SharedString,
2595    color: Hsla,
2596) -> gpui::Div {
2597    div()
2598        .absolute()
2599        .left(px(x - box_size / 2.0))
2600        .top(px(y - box_size / 2.0))
2601        .w(px(box_size))
2602        .h(px(box_size))
2603        .flex()
2604        .items_center()
2605        .justify_center()
2606        .text_size(px(font_size))
2607        .text_color(color)
2608        .child(text)
2609}
2610
2611/// Glyph de planeta con disco-halo detrás del char. El disco viene en
2612/// `disk_bg` (semi-opaco para que se vea a través el fondo del wheel)
2613/// y `disk_border` (típicamente el color del planeta). El char por
2614/// dentro va en `text_color` — recomendado el color del planeta sobre
2615/// disco neutro, o color contrastante sobre disco coloreado.
2616fn planet_glyph(
2617    x: f32,
2618    y: f32,
2619    disk_size: f32,
2620    font_size: f32,
2621    text: SharedString,
2622    text_color: Hsla,
2623    disk_bg: Hsla,
2624    disk_border: Hsla,
2625) -> gpui::Div {
2626    div()
2627        .absolute()
2628        .left(px(x - disk_size / 2.0))
2629        .top(px(y - disk_size / 2.0))
2630        .w(px(disk_size))
2631        .h(px(disk_size))
2632        .rounded_full()
2633        .bg(disk_bg)
2634        .border_1()
2635        .border_color(disk_border)
2636        .flex()
2637        .items_center()
2638        .justify_center()
2639        .text_size(px(font_size))
2640        .text_color(text_color)
2641        .child(text)
2642}
2643
2644/// Reposiciona angularmente un conjunto de longitudes para que pares
2645/// adyacentes mantengan al menos `min_sep_deg` de separación, **sin
2646/// que ningún glyph se aleje más de `max_shift_deg` de su posición
2647/// real**. La acotación es clave para evitar que un cluster denso
2648/// "empuje" a planetas que estaban lejos.
2649///
2650/// Algoritmo: iteramos hasta 60 veces; en cada pasada re-ordenamos
2651/// los displays para mantener el orden circular, y en cada par
2652/// adyacente que esté muy cerca empujamos los dos extremos en
2653/// sentidos opuestos. Tras cada empuje clampeamos `displays[i]` al
2654/// rango `[raw[i] - max_shift, raw[i] + max_shift]` (circular).
2655/// Si el cluster es tan denso que el clamp impide alcanzar el
2656/// `min_sep`, el residual queda alto y el caller encoge los discos.
2657///
2658/// Devuelve `(displays, residual)` con `residual ∈ [0, 1]` =
2659/// fracción de presión no resuelta tras el clamp.
2660fn spread_angles(angles_deg: &[f32], min_sep_deg: f32, max_shift_deg: f32) -> (Vec<f32>, f32) {
2661    let n = angles_deg.len();
2662    if n <= 1 {
2663        return (angles_deg.to_vec(), 0.0);
2664    }
2665    if (n as f32) * min_sep_deg >= 360.0 {
2666        return (angles_deg.to_vec(), 1.0);
2667    }
2668    let raw: Vec<f32> = angles_deg.iter().map(|a| a.rem_euclid(360.0)).collect();
2669    let mut displays: Vec<f32> = raw.clone();
2670    let mut last_residual = 0.0_f32;
2671
2672    // Clamp circular: ajusta `display` a estar dentro de
2673    // `raw ± max_shift_deg`, midiendo distancia mínima circular.
2674    let clamp_to_raw = |display: f32, raw: f32, max_shift: f32| -> f32 {
2675        let mut delta = display - raw;
2676        if delta > 180.0 {
2677            delta -= 360.0;
2678        }
2679        if delta < -180.0 {
2680            delta += 360.0;
2681        }
2682        let clamped = delta.clamp(-max_shift, max_shift);
2683        (raw + clamped).rem_euclid(360.0)
2684    };
2685
2686    // Loop tipo "physics": acumulamos fuerzas sobre TODOS los pares
2687    // adyacentes en una pasada, luego aplicamos un step con damping.
2688    // Esto evita las oscilaciones del empuje inmediato (que reordenaba
2689    // los displays a mitad de la pasada y nunca convergía).
2690    let damping: f32 = 0.6;
2691    for _ in 0..80 {
2692        let mut order: Vec<usize> = (0..n).collect();
2693        order.sort_by(|&a, &b| {
2694            displays[a]
2695                .partial_cmp(&displays[b])
2696                .unwrap_or(std::cmp::Ordering::Equal)
2697        });
2698        let mut forces = vec![0.0_f32; n];
2699        let mut max_residual: f32 = 0.0;
2700        for k in 0..n {
2701            let i = order[k];
2702            let j = order[(k + 1) % n];
2703            let diff = (displays[j] - displays[i]).rem_euclid(360.0);
2704            if diff < min_sep_deg {
2705                let push = (min_sep_deg - diff) / 2.0;
2706                forces[i] -= push;
2707                forces[j] += push;
2708                let r = (min_sep_deg - diff) / min_sep_deg;
2709                if r > max_residual {
2710                    max_residual = r;
2711                }
2712            }
2713        }
2714        // Aplicar fuerzas con damping + clamp al rango ±max_shift.
2715        for i in 0..n {
2716            let stepped = (displays[i] + forces[i] * damping).rem_euclid(360.0);
2717            displays[i] = clamp_to_raw(stepped, raw[i], max_shift_deg);
2718        }
2719        last_residual = max_residual;
2720        if max_residual < 0.001 {
2721            break;
2722        }
2723    }
2724
2725    (displays, last_residual)
2726}
2727
2728/// Detecta clusters de longitudes angularmente cercanas. Dos
2729/// elementos están en el mismo cluster si su separación circular es
2730/// menor a `threshold_deg`. Devuelve los índices originales
2731/// agrupados; cada Vec interno representa un cluster (incluso si
2732/// es de tamaño 1). Cluster con wrap-around (último→primero) se
2733/// fusionan correctamente.
2734fn find_clusters(angles_deg: &[f32], threshold_deg: f32) -> Vec<Vec<usize>> {
2735    let n = angles_deg.len();
2736    if n == 0 {
2737        return Vec::new();
2738    }
2739    let mut idxed: Vec<(usize, f32)> = angles_deg
2740        .iter()
2741        .copied()
2742        .map(|a| a.rem_euclid(360.0))
2743        .enumerate()
2744        .collect();
2745    idxed.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
2746    let mut clusters: Vec<Vec<usize>> = Vec::new();
2747    let mut cur: Vec<usize> = vec![idxed[0].0];
2748    let mut last = idxed[0].1;
2749    for (idx, a) in idxed.iter().skip(1).copied() {
2750        if (a - last) < threshold_deg {
2751            cur.push(idx);
2752        } else {
2753            clusters.push(std::mem::take(&mut cur));
2754            cur.push(idx);
2755        }
2756        last = a;
2757    }
2758    clusters.push(cur);
2759    // Wrap-around: si el último cluster y el primero "tocan" a través
2760    // de 0° (la diferencia circular < threshold), mergearlos.
2761    if clusters.len() >= 2 {
2762        let first_a = angles_deg[clusters[0][0]].rem_euclid(360.0);
2763        let last_a = angles_deg[*clusters.last().unwrap().last().unwrap()].rem_euclid(360.0);
2764        let wrap_diff = 360.0 - last_a + first_a;
2765        if wrap_diff < threshold_deg {
2766            let mut tail = clusters.pop().unwrap();
2767            tail.extend(clusters[0].iter().copied());
2768            clusters[0] = tail;
2769        }
2770    }
2771    clusters
2772}
2773
2774/// Formato compacto con precisión de minutos: "DD°MM'{signo}" donde
2775/// el signo es el glyph zodiacal (♈♉♊…). Ej: 14.93° → "14°56'♈".
2776/// Los minutos se redondean al entero más cercano; si el redondeo
2777/// excede 60, bumpea el grado y mantiene la representación canónica
2778/// (29°60' → 30°00', que a su vez = 0° del signo siguiente — lo
2779/// recalculamos para evitar mostrar "30°00'♈" en vez de "0°00'♉").
2780fn format_coord_compact(deg: f32) -> String {
2781    let normalized = deg.rem_euclid(360.0);
2782    let total_minutes = (normalized * 60.0).round() as i64;
2783    // Carry-overs: 60' → siguiente grado; 30° → siguiente signo (eso
2784    // ya está cubierto porque el total_minutes refleja la posición
2785    // ABSOLUTA y volvemos a derivar sign + minutos del entero limpio).
2786    let total_minutes = total_minutes.rem_euclid(360 * 60);
2787    let sign_idx = (total_minutes / (30 * 60)) as usize % 12;
2788    let within_sign = total_minutes - (sign_idx as i64) * 30 * 60;
2789    let deg_int = (within_sign / 60) as i32;
2790    let minutes = (within_sign % 60) as i32;
2791    let sign_glyph = match sign_idx {
2792        0 => "♈",
2793        1 => "♉",
2794        2 => "♊",
2795        3 => "♋",
2796        4 => "♌",
2797        5 => "♍",
2798        6 => "♎",
2799        7 => "♏",
2800        8 => "♐",
2801        9 => "♑",
2802        10 => "♒",
2803        _ => "♓",
2804    };
2805    format!("{}°{:02}'{}", deg_int, minutes, sign_glyph)
2806}
2807
2808#[cfg(test)]
2809mod spread_tests {
2810    use super::spread_angles;
2811
2812    fn assert_min_sep(displays: &[f32], min_sep: f32) {
2813        let n = displays.len();
2814        let mut sorted = displays.to_vec();
2815        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
2816        // Tolerancia: el algoritmo converge dentro del 1% del min_sep.
2817        let tol = min_sep * 0.02;
2818        for i in 0..n {
2819            let nxt = (i + 1) % n;
2820            let diff = (sorted[nxt] - sorted[i]).rem_euclid(360.0);
2821            assert!(
2822                diff + tol >= min_sep,
2823                "vecinos {} y {} a {}° (mínimo {})",
2824                sorted[i],
2825                sorted[nxt],
2826                diff,
2827                min_sep
2828            );
2829        }
2830    }
2831
2832    #[test]
2833    fn empty_and_single_unchanged() {
2834        let (r, residual) = spread_angles(&[], 10.0, 30.0);
2835        assert!(r.is_empty());
2836        assert_eq!(residual, 0.0);
2837        let (r, residual) = spread_angles(&[42.0], 10.0, 30.0);
2838        assert_eq!(r, vec![42.0]);
2839        assert_eq!(residual, 0.0);
2840    }
2841
2842    #[test]
2843    fn spaced_input_left_alone() {
2844        let input = vec![0.0, 30.0, 90.0, 200.0];
2845        let (out, residual) = spread_angles(&input, 10.0, 30.0);
2846        assert!(residual < 0.001);
2847        for (a, b) in input.iter().zip(out.iter()) {
2848            assert!((a - b).abs() < 1e-3, "{} vs {}", a, b);
2849        }
2850    }
2851
2852    #[test]
2853    fn tight_cluster_gets_spread() {
2854        // 3 planetas a 1° con min_sep=10, max_shift=30 — caben.
2855        let input = vec![100.0, 101.0, 102.0];
2856        let (out, residual) = spread_angles(&input, 10.0, 30.0);
2857        assert!(residual < 0.05, "residual {}", residual);
2858        assert_min_sep(&out, 10.0);
2859    }
2860
2861    #[test]
2862    fn shift_is_bounded() {
2863        // Si max_shift=2°, los planetas no pueden alejarse más allá.
2864        let input = vec![100.0, 101.0];
2865        let (out, _) = spread_angles(&input, 10.0, 2.0);
2866        for (raw, disp) in input.iter().zip(out.iter()) {
2867            let mut delta = (disp - raw).abs();
2868            if delta > 180.0 {
2869                delta = 360.0 - delta;
2870            }
2871            assert!(delta <= 2.0 + 0.01, "shift {} > 2°", delta);
2872        }
2873    }
2874
2875    #[test]
2876    fn distant_planet_unaffected_by_dense_cluster() {
2877        // Cluster denso en 100-101° + planeta solo en 200°. El de 200°
2878        // debe quedarse cerca de 200° con max_shift=10°.
2879        let input = vec![100.0, 100.5, 101.0, 200.0];
2880        let (out, _) = spread_angles(&input, 10.0, 10.0);
2881        let mut delta = (out[3] - 200.0).abs();
2882        if delta > 180.0 {
2883            delta = 360.0 - delta;
2884        }
2885        assert!(delta < 5.0, "planeta lejano se movió {}°", delta);
2886    }
2887
2888    #[test]
2889    fn unfeasible_cluster_reports_max_residual() {
2890        let input: Vec<f32> = (0..40).map(|_| 0.0).collect();
2891        let (_out, residual) = spread_angles(&input, 10.0, 30.0);
2892        assert!((residual - 1.0).abs() < 0.01);
2893    }
2894}
2895
2896#[cfg(test)]
2897mod coord_tests {
2898    use super::format_coord_compact;
2899
2900    #[test]
2901    fn zero_aries() {
2902        assert_eq!(format_coord_compact(0.0), "0°00'♈");
2903    }
2904
2905    #[test]
2906    fn fourteen_fiftysix_aries() {
2907        // 14.9333° = 14° 56'
2908        assert_eq!(format_coord_compact(14.933_3), "14°56'♈");
2909    }
2910
2911    #[test]
2912    fn rollover_to_taurus() {
2913        // 29.9995° debería redondear a 30° y caer en 0°00'♉.
2914        assert_eq!(format_coord_compact(29.9995), "0°00'♉");
2915    }
2916
2917    #[test]
2918    fn capricorn_anchor() {
2919        // 270° = inicio de Capricornio.
2920        assert_eq!(format_coord_compact(270.0), "0°00'♑");
2921    }
2922
2923    #[test]
2924    fn negative_wraps() {
2925        // -10° = 350° = 20°00'♓.
2926        assert_eq!(format_coord_compact(-10.0), "20°00'♓");
2927    }
2928}
2929
2930/// Pill pequeña con un coord ("14°♈") junto al glyph de un planeta
2931/// o cusp. Fondo halo + texto fg_muted, padding mínimo para no
2932/// saturar la rueda con etiquetas grandes.
2933fn coord_label(
2934    x: f32,
2935    y: f32,
2936    text: SharedString,
2937    fg: Hsla,
2938    halo_bg: Hsla,
2939    font_size: f32,
2940) -> gpui::Div {
2941    // Estimación del ancho basada en `chars().count()` (NO `text.len()`
2942    // — los chars unicode astronómicos cuentan 3 bytes pero ocupan
2943    // ~1 columna de fuente). Padding lateral muy pequeño en lugar de
2944    // un mínimo grande: pills con 1-3 chars no llevan "espacios en
2945    // negro" que sobrescriben elementos vecinos.
2946    let char_count = text.chars().count() as f32;
2947    let w = (char_count * font_size * 0.62 + font_size * 0.5).max(font_size * 1.4);
2948    let h = font_size + 5.0;
2949    div()
2950        .absolute()
2951        .left(px(x - w / 2.0))
2952        .top(px(y - h / 2.0))
2953        .w(px(w))
2954        .h(px(h))
2955        .flex()
2956        .items_center()
2957        .justify_center()
2958        .rounded(px(h / 2.0))
2959        .bg(halo_bg)
2960        .text_size(px(font_size))
2961        .text_color(fg)
2962        .child(text)
2963}
2964
2965/// Color HSL semi-opaco para los halos de los glyphs — derivado del
2966/// theme. En dark va casi negro; en light casi blanco. Alpha alta para
2967/// que el char quede legible contra cualquier cosa que haya detrás
2968/// (anillo, líneas de aspecto, starfield).
2969fn glyph_halo(theme: &Theme) -> Hsla {
2970    if theme.is_dark {
2971        hsla(0.0, 0.0, 0.07, 0.92)
2972    } else {
2973        hsla(0.0, 0.0, 0.97, 0.92)
2974    }
2975}
2976
2977fn with_alpha(c: Hsla, a: f32) -> Hsla {
2978    hsla(c.h, c.s, c.l, a.clamp(0.0, 1.0))
2979}
2980
2981/// Devuelve `c` con la luminancia modificada por `delta` (clamp 0..1).
2982/// Útil para derivar highlight (+luma) y shadow (-luma) de un color
2983/// base manteniendo hue y saturación — efecto bevel/3D barato.
2984fn adjust_luma(c: Hsla, delta: f32) -> Hsla {
2985    hsla(c.h, c.s, (c.l + delta).clamp(0.0, 1.0), c.a)
2986}
2987
2988/// Devuelve `c` con el hue desplazado `delta_deg` grados sobre el
2989/// círculo cromático (wrap a [0,1] en la escala normalizada de gpui).
2990/// Usado para derivar el color del anillo de casas desde el del dial
2991/// zodiacal — los dos sistemas (eclíptica vs ascensional) deben
2992/// distinguirse a primera vista pero compartir "familia" cromática.
2993fn shift_hue(c: Hsla, delta_deg: f32) -> Hsla {
2994    let new_h = (c.h + delta_deg / 360.0).rem_euclid(1.0);
2995    hsla(new_h, c.s, c.l, c.a)
2996}
2997
2998/// Color para los anillos del sistema de casas (ascensional). En
2999/// paletas con color, lo derivamos de `house_cusp` con un hue shift
3000/// de ~140° para diferenciar de la eclíptica (que va con el dorado
3001/// de `dial_ring`). En BW devolvemos `house_cusp` tal cual — un
3002/// shift cromático en monocromo es ruido sin información.
3003fn house_ring_color(palette: &AstroPalette) -> Hsla {
3004    if palette.is_monochrome() {
3005        palette.house_cusp
3006    } else {
3007        shift_hue(palette.house_cusp, 140.0)
3008    }
3009}
3010
3011/// Stroke con efecto embossed: 3 trazos concéntricos. El highlight va
3012/// 0.7 px hacia el centro con luminancia subida; el principal en `r`;
3013/// el shadow 0.7 px hacia afuera con luminancia bajada. La dirección
3014/// del bevel depende del theme: en dark el highlight es exterior (luz
3015/// "desde arriba"), en light interior (sombra "desde arriba" hacia
3016/// el centro).
3017fn stroke_circle_3d(
3018    window: &mut Window,
3019    cx: f32,
3020    cy: f32,
3021    r: f32,
3022    width: f32,
3023    color: Hsla,
3024    theme: &Theme,
3025) {
3026    let (hl_offset, sh_offset) = if theme.is_dark {
3027        (-0.7, 0.7)
3028    } else {
3029        (0.7, -0.7)
3030    };
3031    let hl = with_alpha(adjust_luma(color, 0.20), color.a * 0.55);
3032    let sh = with_alpha(adjust_luma(color, -0.18), color.a * 0.55);
3033    stroke_circle(window, cx, cy, r + hl_offset, (width * 0.7).max(0.4), hl);
3034    stroke_circle(window, cx, cy, r, width, color);
3035    stroke_circle(window, cx, cy, r + sh_offset, (width * 0.7).max(0.4), sh);
3036}
3037
3038/// Bevel central del anillo de signos: ~10 strokes finos entre
3039/// sign_inner y sign_outer, con alpha en bell curve (máximo en el
3040/// medio, decae hacia los bordes). Genera la sensación de volumen
3041/// sin pintar gradient radial (no soportado en gpui canvas).
3042fn paint_dial_bevel(
3043    window: &mut Window,
3044    cx: f32,
3045    cy: f32,
3046    radii: &Radii,
3047    palette: &AstroPalette,
3048    theme: &Theme,
3049) {
3050    let steps = 10;
3051    let base = if theme.is_dark { 0.07 } else { 0.10 };
3052    let color = palette.dial_ring;
3053    for i in 0..steps {
3054        let t = (i as f32 + 0.5) / steps as f32;
3055        let r = radii.sign_inner + (radii.sign_outer - radii.sign_inner) * t;
3056        // Bell curve simétrica: |t-0.5|*2 da 0..1 desde el centro, lo
3057        // invertimos para que el centro tenga peso máximo.
3058        let bell = 1.0 - ((t - 0.5).abs() * 2.0);
3059        let a = base * bell;
3060        stroke_circle(window, cx, cy, r, 1.0, with_alpha(color, a));
3061    }
3062}
3063
3064fn sign_unicode(name: &str) -> &'static str {
3065    match name {
3066        "aries" => "♈",
3067        "taurus" => "♉",
3068        "gemini" => "♊",
3069        "cancer" => "♋",
3070        "leo" => "♌",
3071        "virgo" => "♍",
3072        "libra" => "♎",
3073        "scorpio" => "♏",
3074        "sagittarius" => "♐",
3075        "capricorn" => "♑",
3076        "aquarius" => "♒",
3077        "pisces" => "♓",
3078        _ => "?",
3079    }
3080}
3081
3082const SIGN_NAMES_ES: [&str; 12] = [
3083    "Aries",
3084    "Tauro",
3085    "Géminis",
3086    "Cáncer",
3087    "Leo",
3088    "Virgo",
3089    "Libra",
3090    "Escorpio",
3091    "Sagitario",
3092    "Capricornio",
3093    "Acuario",
3094    "Piscis",
3095];
3096
3097fn aspect_unicode(kind: &str) -> &'static str {
3098    match kind {
3099        "conjunction" => "☌",
3100        "opposition" => "☍",
3101        "trine" => "△",
3102        "square" => "□",
3103        "sextile" => "⚹",
3104        "quincunx" => "⚻",
3105        "semi_sextile" => "⚺",
3106        "semi_square" => "∠",
3107        "sesquiquadrate" => "⚼",
3108        "quintile" => "Q",
3109        "biquintile" => "bQ",
3110        _ => "·",
3111    }
3112}
3113
3114fn planet_unicode(name: &str) -> &'static str {
3115    match name {
3116        "sun" => "☉",
3117        "moon" => "☽",
3118        "mercury" => "☿",
3119        "venus" => "♀",
3120        "mars" => "♂",
3121        "jupiter" => "♃",
3122        "saturn" => "♄",
3123        "uranus" => "♅",
3124        "neptune" => "♆",
3125        "pluto" => "♇",
3126        "north_node" => "☊",
3127        "south_node" => "☋",
3128        "chiron" => "⚷",
3129        "lilith" => "⚸",
3130        "ceres" => "⚳",
3131        "pallas" => "⚴",
3132        "juno" => "⚵",
3133        "vesta" => "⚶",
3134        _ => "•",
3135    }
3136}
3137
3138fn planet_color(p: &AstroPalette, name: &str) -> Hsla {
3139    let planet = match name {
3140        "sun" => Planet::Sun,
3141        "moon" => Planet::Moon,
3142        "mercury" => Planet::Mercury,
3143        "venus" => Planet::Venus,
3144        "mars" => Planet::Mars,
3145        "jupiter" => Planet::Jupiter,
3146        "saturn" => Planet::Saturn,
3147        "uranus" => Planet::Uranus,
3148        "neptune" => Planet::Neptune,
3149        "pluto" => Planet::Pluto,
3150        "chiron" => Planet::Chiron,
3151        "north_node" => Planet::NorthNode,
3152        "south_node" => Planet::SouthNode,
3153        "lilith" => Planet::Lilith,
3154        _ => return p.fg_text_fallback(),
3155    };
3156    p.planet(planet)
3157}
3158
3159fn sign_element_by_index(i: usize) -> Element {
3160    match i % 4 {
3161        0 => Element::Fire,
3162        1 => Element::Earth,
3163        2 => Element::Air,
3164        _ => Element::Water,
3165    }
3166}
3167
3168fn element_color_for_sign(p: &AstroPalette, name: &str) -> Hsla {
3169    let elem = match name {
3170        "aries" | "leo" | "sagittarius" => Element::Fire,
3171        "taurus" | "virgo" | "capricorn" => Element::Earth,
3172        "gemini" | "libra" | "aquarius" => Element::Air,
3173        "cancer" | "scorpio" | "pisces" => Element::Water,
3174        _ => return p.fg_text_fallback(),
3175    };
3176    p.element(elem)
3177}
3178
3179fn aspect_color(p: &AstroPalette, kind: &str) -> Hsla {
3180    let k = match kind {
3181        "conjunction" => TAspectKind::Conjunction,
3182        "opposition" => TAspectKind::Opposition,
3183        "trine" => TAspectKind::Trine,
3184        "square" => TAspectKind::Square,
3185        "sextile" => TAspectKind::Sextile,
3186        "quincunx" => TAspectKind::Quincunx,
3187        "semi_sextile" => TAspectKind::Semisextile,
3188        "semi_square" => TAspectKind::Semisquare,
3189        "sesquiquadrate" => TAspectKind::Sesquisquare,
3190        "quintile" => TAspectKind::Quintile,
3191        "biquintile" => TAspectKind::Biquintile,
3192        _ => return p.minor_aspect,
3193    };
3194    p.aspect(k)
3195}
3196
3197trait AstroPaletteExt {
3198    fn fg_text_fallback(&self) -> Hsla;
3199}
3200
3201impl AstroPaletteExt for AstroPalette {
3202    fn fg_text_fallback(&self) -> Hsla {
3203        if self.is_dark {
3204            hsla(0.0, 0.0, 0.85, 1.0)
3205        } else {
3206            hsla(0.0, 0.0, 0.25, 1.0)
3207        }
3208    }
3209}