gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198629 Sutichaykuna

⎇ 121f19b9158e4a8b7f0de5da76bd66268aca6376 crates/modules/tahuantinsuyu/tahuantinsuyu-canvas/src/lib.rs Rust · 3129 siq'ikuna · 114.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

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