import math
import random
from js import document, window
from pyodide.ffi import create_proxy

def get_random_color():
    h = random.randint(30, 60)
    s = random.randint(45, 75)
    l = random.randint(65, 85)
    return f"hsl({h}, {s}%, {l}%)"

def draw_polygon(ctx, pts, fill_color, stroke_color="#1f2937"):
    ctx.beginPath()
    ctx.moveTo(pts[0][0], pts[0][1])
    for p in pts[1:]:
        ctx.lineTo(p[0], p[1])
    ctx.closePath()
    ctx.fillStyle = fill_color
    ctx.fill()
    ctx.lineWidth = 1.2
    ctx.strokeStyle = stroke_color
    ctx.stroke()

def calculate_and_draw(event=None):
    try:
        wall_len_m = float(document.getElementById("wall-len").value)
        wall_h_m = float(document.getElementById("wall-h").value)
        base_size = float(document.getElementById("tile-base").value)
        shape = document.getElementById("tile-shape").value
    except ValueError:
        window.alert("لطفاً مقادیر عددی معتبر وارد کنید.")
        return

    wall_w = wall_len_m * 100
    wall_h = wall_h_m * 100
    wall_area = wall_w * wall_h

    tile_area = 0
    formula_latex = ""

    if shape == "square":
        tile_area = base_size ** 2
        formula_latex = r"A = a^2"
    elif shape == "triangle":
        tile_area = (math.sqrt(3) / 4) * (base_size ** 2)
        formula_latex = r"A = \frac{\sqrt{3}}{4} a^2"
    elif shape == "hexagon":
        tile_area = (3 * math.sqrt(3) / 2) * (base_size ** 2)
        formula_latex = r"A = \frac{3\sqrt{3}}{2} a^2"

    if tile_area <= 0:
        return

    pure_count = math.ceil(wall_area / tile_area)
    waste_count = math.ceil(pure_count * 1.10)

    document.getElementById("main-answer").innerText = f"پروژه آماده رسم. تعداد کاشی مورد نیاز: {waste_count} عدد"
    document.getElementById("res-wall-area").innerText = f"{wall_area:,.2f} سانتی‌متر مربع"
    document.getElementById("res-tile-area").innerText = f"{tile_area:,.2f} سانتی‌متر مربع"
    document.getElementById("res-tile-count").innerText = f"{pure_count} عدد (خالص)"
    document.getElementById("res-waste-count").innerText = f"{waste_count} عدد (با ۱۰٪ پرتی)"
    
    window.renderFormula(formula_latex, "formula-container")

    canvas = document.getElementById("tiling-canvas")
    ctx = canvas.getContext("2d")
    cw = canvas.width
    ch = canvas.height
    
    ctx.clearRect(0, 0, cw, ch)
    ctx.save()
    
    margin = 20
    scale = min((cw - 2*margin) / wall_w, (ch - 2*margin) / wall_h)
    
    tx = (cw - wall_w * scale) / 2
    ty = (ch - wall_h * scale) / 2
    ctx.translate(tx, ty)
    ctx.scale(scale, scale)
    
    ctx.fillStyle = "#e5e7eb"
    ctx.fillRect(0, 0, wall_w, wall_h)
    
    ctx.beginPath()
    ctx.rect(0, 0, wall_w, wall_h)
    ctx.clip()

    a = base_size

    if shape == "square":
        cols = int(wall_w / a) + 2
        rows = int(wall_h / a) + 2
        for col in range(0, cols):
            for row in range(0, rows):
                x, y = col * a, row * a
                poly = [(x, y), (x+a, y), (x+a, y+a), (x, y+a)]
                draw_polygon(ctx, poly, get_random_color())

    elif shape == "triangle":
        h = a * math.sqrt(3) / 2
        cols = int(wall_w / a) + 3
        rows = int(wall_h / h) + 3
        for r_idx in range(-1, rows):
            y = r_idx * h
            shift = (a / 2) if r_idx % 2 != 0 else 0
            for c_idx in range(-2, cols):
                cx = c_idx * a + shift
                t_up = [(cx, y+h), (cx+a/2, y), (cx+a, y+h)]
                draw_polygon(ctx, t_up, get_random_color())
                t_down = [(cx+a/2, y), (cx+a, y+h), (cx+1.5*a, y)]
                draw_polygon(ctx, t_down, get_random_color())

    elif shape == "hexagon":
        hex_h = math.sqrt(3) * a
        cols = int(wall_w / (1.5 * a)) + 4
        rows = int(wall_h / hex_h) + 4
        
        for col in range(-2, cols):
            cx = col * 1.5 * a
            y_shift = 0.5 * hex_h if col % 2 != 0 else 0
            for row in range(-2, rows):
                cy = row * hex_h + y_shift
                poly = []
                for k in range(6):
                    angle = k * math.pi / 3
                    px = cx + a * math.cos(angle)
                    py = cy + a * math.sin(angle)
                    poly.append((px, py))
                draw_polygon(ctx, poly, get_random_color())

    ctx.restore()

document.getElementById("calc-btn").addEventListener("click", create_proxy(calculate_and_draw))