gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198629 Definitions

⎇ 1d49b9ff88cdfdf792fa200cabe23e82667a2e65 crates/modules/tahuantinsuyu/tahuantinsuyu-canvas/src/lib.rs Rust · 2725 lines · 97.9 KB History Who touched what raw

feat(tahuantinsuyu): capa "ascensional" topocéntrica completa 1d49b9ff8 · sergio ·

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