gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198629 Definiciones

⎇ a92fa1577700a5cb28c6bb96872300ce99a7e5f8 crates/modules/tahuantinsuyu/tahuantinsuyu-canvas/src/lib.rs Rust · 3082 líneas · 113.3 KB Historia Quién tocó qué crudo

feat(tahuantinsuyu): anti-solapamiento de glyphs + selector Naibod/Ptolomeo a92fa1577 · sergio ·

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