import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

# Configuração técnica de alta resolução
plt.style.use('seaborn-v0_8-whitegrid' if 'seaborn-v0_8-whitegrid' in plt.style.available else 'default')
fig = plt.figure(figsize=(18, 14), dpi=300)

c_hull = '#1E3A8A'       # Azul Marinho Tradicional
c_bottom = '#B91C1C'     # Vermelho Óxido Fundo
c_wood = '#B45309'       # Madeira (Mastro/Baucot/Pena)
c_sail_main = '#FEF3C7'  # Lona Vela de Içar (Bege claro)
c_sail_jib = '#FDE68A'   # Lona Bujarrona (Amarelo claro)
c_rig = '#1E293B'        # Cabos / Brandais
c_dim = '#DC2626'        # Cotas vermelhas
c_wl = '#0284C7'         # Linha d'Água
c_ce = '#D97706'         # Centro Vélico (CE)
c_clr = '#2563EB'        # Centro de Resistência Lateral (CLR)

# -------------------------------------------------------------------------
# PAINEL 1: PLANO VÉLICO COMPLETO COM COTAS GEOMÉTRICAS E CENTRO VÉLICO
# -------------------------------------------------------------------------
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2, rowspan=2)
ax1.set_title("PLANO VÉLICO COMPLETO — MINI SAVEIRO DE VELA DE IÇAR (6,30 m)\nCotas I, J, P, E, Ve | Centro Vélico (CE), Centro Lateral (CLR) e Lead de Equilíbrio", fontsize=11, fontweight='bold', color='#0F172A', pad=10)

# Casco (LOA = 6,30 m)
xs = np.linspace(0, 6.30, 80)
sheer = 0.65 + 0.35 * (xs / 6.30)**2.2
ax1.fill(np.concatenate([xs, [6.30, 5.5, 3.0, 0, 0]]),
         np.concatenate([sheer, [1.00, -0.20, -0.45, -0.40, 0.65]]),
         color=c_hull, edgecolor='black', lw=1.8, label="Casco Saveiro 6,30 m")
ax1.fill([0, 0, 3.0, 5.5, 5.9, 0], [0, -0.40, -0.45, -0.20, 0, 0], color=c_bottom, alpha=0.85)
ax1.axhline(0, color=c_wl, lw=1.5, linestyle='--', label="Linha d'Água (WL = 0,00 m)")

# Baucot / Gurupés (Avança 1,50 m além da proa -> x = 7,80 m)
ax1.plot([5.50, 7.80], [0.90, 1.15], color=c_wood, lw=4.5, label="Baucot (Gurupés = 2,30 m total)")

# Mastro (Posição x = 4,00 m | H = 5,80 m acima do convés, topo em y = 6,65 m)
mast_x0, mast_y0 = 4.00, -0.40
mast_x1, mast_y1 = 3.80, 6.25
ax1.plot([mast_x0, mast_x1], [mast_y0, mast_y1], color=c_wood, lw=6.5, label="Mastro (H = 5,80 m acima convés)")

# Carangueja / Verga da Vela de Içar (Ve = 3,40 m)
gaff_x0, gaff_y0 = 3.85, 5.05  # Boca / Garganta (Throat)
gaff_x1, gaff_y1 = 1.35, 6.30  # Pico / Penol (Peak)
ax1.plot([gaff_x0, gaff_x1], [gaff_y0, gaff_y1], color='#78350F', lw=4.0, label="Carangueja (Ve = 3,40 m)")

# Retranca / Esteira da Vela Grande (E = 4,50 m)
boom_x0, boom_y0 = 3.95, 0.85
boom_x1, boom_y1 = 0.20, 0.90
ax1.plot([boom_x0, boom_x1], [boom_y0, boom_y1], color=c_wood, lw=3.5)

# Vela Grande de Içar (Quadrangular: 4 vértices)
# V1: Amura (3.95, 0.85) | V2: Garganta (3.85, 5.05) | V3: Penol (1.35, 6.30) | V4: Escota (0.20, 0.90)
sail_main_pts = [[boom_x0, boom_y0], [gaff_x0, gaff_y0], [gaff_x1, gaff_y1], [boom_x1, boom_y1]]
poly_main = patches.Polygon(sail_main_pts, closed=True, facecolor=c_sail_main, edgecolor='#D97706', lw=1.5, label="Vela de Içar (16,5 m²)")
ax1.add_patch(poly_main)

# Costuras verticais dos panos na vela grande
for t in np.linspace(0.15, 0.85, 6):
    xt = boom_x0 + t * (boom_x1 - boom_x0)
    yt = boom_y0 + t * (boom_y1 - boom_y0)
    # Ponto correspondente no topo
    if t < 0.5:
        xt_top = gaff_x0 + (t/0.5) * (gaff_x1 - gaff_x0)*0.5
        yt_top = gaff_y0 + (t/0.5) * (gaff_y1 - gaff_y0)*0.5
    else:
        xt_top = gaff_x0 + (gaff_x1 - gaff_x0)*0.5 + ((t-0.5)/0.5) * (gaff_x1 - gaff_x0)*0.5
        yt_top = gaff_y0 + (gaff_y1 - gaff_y0)*0.5 + ((t-0.5)/0.5) * (gaff_y1 - gaff_y0)*0.5
    ax1.plot([xt, xt_top], [yt, yt_top], color='#D97706', lw=0.6, linestyle=':')

# Bujarrona / Vela de Proa (Triangular: 3 vértices)
# V1: Amura no baucot (7.75, 1.15) | V2: Adriça no mastro (3.88, 4.80) | V3: Escota (4.20, 0.90)
sail_jib_pts = [[7.75, 1.15], [3.88, 4.80], [4.20, 0.90]]
poly_jib = patches.Polygon(sail_jib_pts, closed=True, facecolor=c_sail_jib, edgecolor='#B45309', lw=1.2, alpha=0.9, label="Bujarrona (6,0 m²)")
ax1.add_patch(poly_jib)

# Cabos (Estais, adriças e escotas)
ax1.plot([3.88, 7.75], [4.80, 1.15], color=c_rig, lw=1.2) # Estai de proa
ax1.plot([3.85, 3.85], [5.05, 0.85], color=c_rig, lw=1.2) # Testa P
ax1.plot([1.35, 3.82], [6.30, 6.20], color=c_rig, lw=1.5) # Adriça da pena

# -------------------------------------------------------------------------
# CENTROS AERODINÂMICOS E HIDRODINÂMICOS (CE e CLR)
# -------------------------------------------------------------------------
# Centro da Vela Grande: CE_main ≈ (2.35 m, 3.25 m)
# Centro da Buja: CE_jib ≈ (5.28 m, 2.28 m)
# Centro Vélico Combinado (CE_total):
# X_ce = (16.5 * 2.35 + 6.0 * 5.28) / 22.5 = (38.78 + 31.68) / 22.5 = 3.13 m
# Y_ce = (16.5 * 3.25 + 6.0 * 2.28) / 22.5 = (53.63 + 13.68) / 22.5 = 2.99 m
x_ce, y_ce = 3.13, 2.99
ax1.plot(x_ce, y_ce, marker='o', markersize=9, color=c_ce, markeredgecolor='black', markeredgewidth=1.5, zorder=5)
ax1.text(x_ce + 0.15, y_ce, "CE (Centro Vélico)\nx = 3,13 m | y = 2,99 m", fontsize=7.5, fontweight='bold', color=c_ce, zorder=5)

# Centro de Resistência Lateral do Casco (CLR):
# Para LWL = 5,60 m (de x=0 a x=5,60m), CLR fica a ~46% do LWL = x = 2,75 m | y = -0,22 m
x_clr, y_clr = 2.75, -0.22
ax1.plot(x_clr, y_clr, marker='s', markersize=9, color=c_clr, markeredgecolor='black', markeredgewidth=1.5, zorder=5)
ax1.text(x_clr - 0.15, y_clr - 0.25, "CLR (Resistência Lateral)\nx = 2,75 m", fontsize=7.5, fontweight='bold', color=c_clr, ha='right', zorder=5)

# Lead de Equilíbrio (Distância horizontal entre CE e CLR)
# Lead = 3.13 - 2.75 = 0.38 m = 6,8% do LWL (faixa ideal: 5% a 9%)
ax1.annotate('', xy=(x_clr, 0.4), xytext=(x_ce, 0.4), arrowprops=dict(arrowstyle='<->', color='#047857', lw=1.5))
ax1.text((x_clr + x_ce)/2, 0.52, "LEAD = 0,38 m (6,8% LWL)\nEquilíbrio Perfeito de Leme!", ha='center', fontsize=7.2, fontweight='bold', color='#047857')

# -------------------------------------------------------------------------
# COTAS GEOMÉTRICAS OFICIAIS DA PRANCHA (I, J, P, E, Ve)
# -------------------------------------------------------------------------
# Cota P (Testa da Vela Grande ao longo do mastro = 4,20 m)
ax1.annotate('', xy=(3.65, 0.85), xytext=(3.65, 5.05), arrowprops=dict(arrowstyle='<->', color=c_dim, lw=1.8))
ax1.text(3.50, 2.95, "P = 4,20 m\n(Testa)", ha='right', va='center', fontsize=8, fontweight='bold', color=c_dim)

# Cota E (Esteira da Vela Grande = 4,50 m)
ax1.annotate('', xy=(0.20, 0.65), xytext=(3.95, 0.65), arrowprops=dict(arrowstyle='<->', color=c_dim, lw=1.8))
ax1.text(2.07, 0.48, "E = 4,50 m (Esteira)", ha='center', va='top', fontsize=8, fontweight='bold', color=c_dim)

# Cota Ve (Carangueja / Verga = 3,40 m)
ax1.annotate('', xy=(gaff_x0 - 0.15, gaff_y0 + 0.15), xytext=(gaff_x1 - 0.15, gaff_y1 + 0.15), arrowprops=dict(arrowstyle='<->', color='#059669', lw=1.8))
ax1.text(2.45, 5.95, "Ve = 3,40 m (Carangueja)", ha='center', va='bottom', fontsize=8, fontweight='bold', color='#059669', rotation=-27)

# Cota I (Altura Triângulo de Proa = 4,80 m)
ax1.annotate('', xy=(4.15, 0.90), xytext=(4.15, 4.80), arrowprops=dict(arrowstyle='<->', color='#2563EB', lw=1.8))
ax1.text(4.25, 2.85, "I = 4,80 m\n(Altura Buja)", ha='left', va='center', fontsize=8, fontweight='bold', color='#2563EB')

# Cota J (Base Triângulo de Proa no Baucot = 3,80 m)
ax1.annotate('', xy=(3.95, 1.35), xytext=(7.75, 1.35), arrowprops=dict(arrowstyle='<->', color='#2563EB', lw=1.8))
ax1.text(5.85, 1.50, "J = 3,80 m (Base Buja c/ Baucot)", ha='center', va='bottom', fontsize=8, fontweight='bold', color='#2563EB')

ax1.set_xlim(-0.8, 8.5)
ax1.set_ylim(-1.0, 7.5)
ax1.set_aspect('equal')
ax1.axis('off')

# -------------------------------------------------------------------------
# PAINEL 2: PLANO DE CORTE E COSTURA DOS PANOS (GEOMETRIA DAS VELAS)
# -------------------------------------------------------------------------
ax2 = plt.subplot2grid((3, 3), (0, 2))
ax2.set_title("2. GEOMETRIA DOS PANOS DE LONA", fontsize=9.5, fontweight='bold', color='#0F172A', pad=6)

# Vela Grande em escala reduzida
pts_m_box = [[0.5, 0.5], [0.5, 3.8], [2.6, 4.8], [3.8, 0.5], [0.5, 0.5]]
poly_box_m = patches.Polygon(pts_m_box, closed=True, facecolor=c_sail_main, edgecolor='#D97706', lw=1.5)
ax2.add_patch(poly_box_m)
ax2.text(1.8, 2.2, "VELA DE IÇAR\n16,5 m²\n4 lados", ha='center', va='center', fontsize=7.5, fontweight='bold', color='#78350F')
ax2.text(0.3, 2.15, "P = 4,20 m", rotation=90, ha='center', va='center', fontsize=6.8, fontweight='bold', color=c_dim)
ax2.text(2.15, 0.25, "E = 4,50 m", ha='center', fontsize=6.8, fontweight='bold', color=c_dim)
ax2.text(1.55, 4.50, "Ve = 3,40 m", rotation=25, ha='center', fontsize=6.8, fontweight='bold', color='#059669')
ax2.text(3.45, 2.80, "Valuma = 4,80 m", rotation=-72, ha='center', fontsize=6.8, fontweight='bold', color='#475569')

# Buja em escala reduzida
pts_j_box = [[4.5, 0.5], [4.5, 3.8], [7.2, 0.5], [4.5, 0.5]]
poly_box_j = patches.Polygon(pts_j_box, closed=True, facecolor=c_sail_jib, edgecolor='#B45309', lw=1.5)
ax2.add_patch(poly_box_j)
ax2.text(5.3, 1.6, "BUJARRONA\n6,0 m²\nTriangular", ha='center', va='center', fontsize=7.2, fontweight='bold', color='#B45309')
ax2.text(4.3, 2.15, "I = 4,80 m", rotation=90, ha='center', va='center', fontsize=6.8, fontweight='bold', color='#2563EB')
ax2.text(5.85, 0.25, "Esteira = 2,70 m", ha='center', fontsize=6.8, fontweight='bold', color='#2563EB')
ax2.text(6.05, 2.45, "Testa = 5,10 m", rotation=-50, ha='center', fontsize=6.8, fontweight='bold', color='#2563EB')

ax2.set_xlim(-0.2, 7.8)
ax2.set_ylim(0, 5.4)
ax2.set_aspect('equal')
ax2.axis('off')

# -------------------------------------------------------------------------
# PAINEL 3: EQUILÍBRIO HIDRODINÂMICO E DIAGRAMA DE FORÇAS
# -------------------------------------------------------------------------
ax3 = plt.subplot2grid((3, 3), (1, 2))
ax3.axis('off')
ax3.set_title("3. BALANÇO DE EQUILÍBRIO VÉLICO (LEAD)", fontsize=9.5, fontweight='bold', color='#0F172A', pad=6)

balance_text = """
• CÁLCULO DOS CENTROS DE ESFORÇO:
  - Área Vela Grande (S1): 16,5 m² (73,3% do total)
  - Área Bujarrona (S2):    6,0 m² (26,7% do total)
  - Área Vélica Total (At): 22,5 m²

• POSIÇÃO LONGITUDINAL (X a partir da popa):
  - CE da Vela Grande:  X1 = 2,35 m | Y1 = 3,25 m
  - CE da Bujarrona:    X2 = 5,28 m | Y2 = 2,28 m
  - CE Total Combinado: X_ce = 3,13 m | Y_ce = 2,99 m

• CENTRO LATERAL DO CASCO (CLR):
  - LWL = 5,60 m (Popa x=0 a x=5,60 m)
  - CLR do Casco Chato: X_clr = 2,75 m (a 46% do LWL)

• LEAD DE EQUILÍBRIO (X_ce - X_clr):
  - Lead = 3,13 m - 2,75 m = 0,38 metro
  - Lead em % do LWL = (0,38 / 5,60) * 100 = 6,8%
  - FAIXA RECOMENDADA NAVAL: 5% a 9%
  -> RESULTADO: EQUILÍBRIO NEUTRO PERFEITO!
  (Leme macio, sem puxar na mão do timoneiro)
"""
ax3.text(0.02, 0.98, balance_text, ha='left', va='top', fontsize=6.8, family='monospace', color='#1E293B', linespacing=1.3)

# -------------------------------------------------------------------------
# PAINEL 4: PLANO DE RIZOS E COMPORTAMENTO COM DIFERENTES FORÇAS DE VENTO
# -------------------------------------------------------------------------
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=3)
ax4.set_title("4. TABELA DE PLANO DE RIZOS E POLAR DE NAVEGAÇÃO CONFORME A VELOCIDADE DO VENTO", fontsize=9.5, fontweight='bold', color='#0F172A', pad=6)

reefing_data = [
    ["Condição de Mar / Vento (Beaufort)", "Velocidade Vento", "Configuração de Velame", "Área Ativa", "Comportamento do Barco", "Velocidade Esperada"],
    ["Força 1 a 2 (Brisa Muito Leve)", "1 a 6 nós", "Pano Total: Vela de Içar + Buja Aberta", "22,5 m² (100%)", "Empuxo leve constante; navega suave sem adernar.", "2,5 a 4,0 nós"],
    ["Força 3 (Brisa Fraca a Moderada)", "7 a 10 nós", "Pano Total: Vela de Içar + Buja Aberta", "22,5 m² (100%)", "Velocidade de cruzeiro ideal para passeio de família; adernamento ~6°.", "5,0 a 5,5 nós"],
    ["Força 4 (Brisa Moderada a Fresca)", "11 a 16 nós", "1º Rizo na Vela de Içar + Buja Aberta", "17,5 m² (78%)", "Casco apoiado firme no bojo chato; leme equilibrado; spray agradável.", "5,8 a 6,2 nós (Vel. Casco)"],
    ["Força 5 (Brisa Forte / Ventania)", "17 a 21 nós", "2º Rizo na Vela de Içar + Buja Rizante", "12,5 m² (55%)", "Reduz centro vélico; mantém segurança total sem forçar o mastro.", "5,5 a 5,8 nós"],
    ["Força 6 (Vento Muito Forte / Temporal)", "22 a 27 nós", "Somente Buja Encurtada ou Sob Motor Diesel", "5,0 m² (ou Motor)", "Recolhe a vela grande; liga o diesel 12 CV para voltar ao porto em segurança.", "4,5 a 5,0 nós (Diesel)"]
]

ax4.axis('off')
# Renderizar tabela no ax4
cell_text = reefing_data
table_plot = ax4.table(cellText=cell_text[1:], colLabels=cell_text[0], loc='center', cellLoc='center')
table_plot.auto_set_font_size(False)
table_plot.set_fontsize(7.2)
table_plot.scale(1.0, 1.4)
# Estilizar cabeçalho da tabela do matplotlib
for (r, c), cell in table_plot.get_celld().items():
    if r == 0:
        cell.set_facecolor('#0F2B48')
        cell.set_text_props(color='white', weight='bold')
    else:
        cell.set_facecolor('#F8FAFC' if r % 2 == 1 else 'white')

plt.tight_layout()
output_velico_master = "/home/magdalena/eee/alunos/alberico-de-carvalho-santiago/estudo_completo_area_velica_saveiro.png"
plt.savefig(output_velico_master, dpi=300, bbox_inches='tight')
plt.close()
print("Prancha Master da Área Vélica gerada com sucesso!")
