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92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
Visualization module for Dubai HomeIQ Dashboard
Contains Plotly chart components
"""

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from typing import Optional, List, Dict
from config import COLORS


def plot_price_trend(df: pd.DataFrame, area_name: str = None, 
                     price_column: str = 'MEDIAN_RATE_PER_SQFT') -> go.Figure:
    """
    Plot price trend over time
    
    Args:
        df: DataFrame with YEAR and price data
        area_name: Optional area name for title
        price_column: Column name for price data
        
    Returns:
        Plotly figure
    """
    if df.empty or 'YEAR' not in df.columns or price_column not in df.columns:
        return go.Figure()
    
    df = df.sort_values('YEAR')
    
    fig = go.Figure()
    
    if area_name:
        title = f"Price Trend: {area_name.title()}"
        # Single area line
        fig.add_trace(go.Scatter(
            x=df['YEAR'],
            y=df[price_column],
            mode='lines+markers',
            name=area_name.title(),
            line=dict(color=COLORS['primary'], width=3),
            marker=dict(size=8, color=COLORS['primary'])
        ))
    else:
        title = "Price Trends by Area"
        # Multiple areas
        areas = df['AREA_EN'].unique()[:10]  # Limit to 10 areas
        colors = px.colors.qualitative.Set3
        
        for i, area in enumerate(areas):
            area_data = df[df['AREA_EN'] == area].sort_values('YEAR')
            fig.add_trace(go.Scatter(
                x=area_data['YEAR'],
                y=area_data[price_column],
                mode='lines+markers',
                name=area.title(),
                line=dict(color=colors[i % len(colors)], width=2),
                marker=dict(size=6)
            ))
    
    fig.update_layout(
        title=title,
        xaxis_title="Year",
        yaxis_title="Price per sqft (AED)",
        hovermode='closest',
        template='plotly_white',
        height=500,
        showlegend=True if not area_name else False
    )
    
    return fig


def plot_rental_yield_distribution(df: pd.DataFrame) -> go.Figure:
    """
    Plot rental yield distribution histogram
    
    Args:
        df: DataFrame with yield data
        
    Returns:
        Plotly figure
    """
    if df.empty or 'yield' not in df.columns:
        return go.Figure()
    
    fig = go.Figure()
    
    fig.add_trace(go.Histogram(
        x=df['yield'],
        nbinsx=30,
        marker_color=COLORS['info'],
        opacity=0.7,
        name='Rental Yield Distribution'
    ))
    
    fig.update_layout(
        title="Rental Yield Distribution",
        xaxis_title="Yield (%)",
        yaxis_title="Frequency",
        template='plotly_white',
        height=400
    )
    
    return fig


def plot_buyer_score_ranking(df: pd.DataFrame, top_n: int = 10) -> go.Figure:
    """
    Plot top areas by buyer score (horizontal bar chart)
    
    Args:
        df: DataFrame with area and buyer_score columns
        top_n: Number of top areas to show
        
    Returns:
        Plotly figure
    """
    if df.empty or 'buyer_score' not in df.columns:
        return go.Figure()
    
    top_areas = df.nlargest(top_n, 'buyer_score')
    
    fig = go.Figure()
    
    # Color bars based on score
    colors = [COLORS['success'] if score >= 70 else 
              COLORS['warning'] if score >= 50 else 
              COLORS['danger'] 
              for score in top_areas['buyer_score']]
    
    fig.add_trace(go.Bar(
        y=top_areas['area'].str.title(),
        x=top_areas['buyer_score'],
        orientation='h',
        marker=dict(color=colors),
        text=[f"{score:.1f}" for score in top_areas['buyer_score']],
        textposition='auto',
        name='Buyer Score'
    ))
    
    fig.update_layout(
        title=f"Top {top_n} Areas by Buyer Score",
        xaxis_title="Buyer Score",
        yaxis_title="Area",
        template='plotly_white',
        height=400,
        yaxis={'categoryorder': 'total ascending'}
    )
    
    return fig


def plot_supply_vs_demand(supply_df: pd.DataFrame, sales_df: pd.DataFrame) -> go.Figure:
    """
    Plot supply vs demand bubble chart
    
    Args:
        supply_df: Supply data with units
        sales_df: Sales data with transactions
        
    Returns:
        Plotly figure
    """
    if supply_df.empty or sales_df.empty:
        return go.Figure()
    
    # Aggregate by area
    supply_agg = supply_df.groupby('area_name_en')['no_of_units'].sum().reset_index()
    sales_agg = sales_df.groupby('AREA_EN')['SALE_TRANSACTIONS'].sum().reset_index()
    
    # Merge
    merged = supply_agg.merge(
        sales_agg,
        left_on='area_name_en',
        right_on='AREA_EN',
        how='inner'
    )
    
    if merged.empty:
        return go.Figure()
    
    fig = go.Figure()
    
    fig.add_trace(go.Scatter(
        x=merged['SALE_TRANSACTIONS'],
        y=merged['no_of_units'],
        mode='markers',
        marker=dict(
            size=merged['no_of_units'] / 100,
            color=merged['no_of_units'],
            colorscale='Viridis',
            showscale=True,
            sizemode='diameter',
            sizeref=merged['no_of_units'].max() / 100
        ),
        text=merged['area_name_en'].str.title(),
        hovertemplate='<b>%{text}</b><br>Transactions: %{x}<br>Units: %{y}<extra></extra>',
        name='Supply vs Demand'
    ))
    
    fig.update_layout(
        title="Supply vs Demand Analysis",
        xaxis_title="Sales Transactions",
        yaxis_title="Supply Units",
        template='plotly_white',
        height=500
    )
    
    return fig


def plot_market_health_heatmap(df: pd.DataFrame) -> go.Figure:
    """
    Plot market health heatmap by area and year
    
    Args:
        df: DataFrame with area, year, and health_index columns
        
    Returns:
        Plotly figure
    """
    if df.empty or 'health_index' not in df.columns:
        return go.Figure()
    
    # Pivot for heatmap
    pivot_df = df.pivot_table(
        values='health_index',
        index='AREA_EN',
        columns='YEAR',
        aggfunc='mean'
    )
    
    fig = go.Figure(data=go.Heatmap(
        z=pivot_df.values,
        x=pivot_df.columns,
        y=[area.title() for area in pivot_df.index],
        colorscale='RdYlGn',
        text=pivot_df.values,
        texttemplate='%{text:.1f}',
        textfont={"size": 10},
        colorbar=dict(title="Health Index")
    ))
    
    fig.update_layout(
        title="Market Health Index Heatmap",
        xaxis_title="Year",
        yaxis_title="Area",
        template='plotly_white',
        height=600
    )
    
    return fig


def plot_roi_comparison(df: pd.DataFrame, areas: List[str] = None) -> go.Figure:
    """
    Plot ROI comparison chart
    
    Args:
        df: DataFrame with ROI data
        areas: List of areas to compare
        
    Returns:
        Plotly figure
    """
    if df.empty:
        return go.Figure()
    
    if areas:
        df = df[df['area'].isin(areas)]
    
    fig = go.Figure()
    
    fig.add_trace(go.Bar(
        x=df['area'].str.title(),
        y=df.get('capital_appreciation', df.get('roi', 0)),
        name='Capital Appreciation',
        marker_color=COLORS['primary']
    ))
    
    if 'rental_yield' in df.columns:
        fig.add_trace(go.Bar(
            x=df['area'].str.title(),
            y=df['rental_yield'],
            name='Rental Yield',
            marker_color=COLORS['success']
        ))
    
    fig.update_layout(
        title="ROI Comparison",
        xaxis_title="Area",
        yaxis_title="Return (%)",
        barmode='group',
        template='plotly_white',
        height=400
    )
    
    return fig


def plot_forecast_with_confidence(historical: pd.DataFrame, 
                                 forecast: pd.DataFrame,
                                 area_name: str) -> go.Figure:
    """
    Plot forecast with confidence intervals
    
    Args:
        historical: Historical data
        forecast: Forecast data with confidence intervals
        area_name: Area name for title
        
    Returns:
        Plotly figure
    """
    fig = go.Figure()
    
    # Historical data
    fig.add_trace(go.Scatter(
        x=historical['YEAR'],
        y=historical['MEDIAN_RATE_PER_SQFT'],
        mode='lines+markers',
        name='Historical',
        line=dict(color=COLORS['primary'], width=2)
    ))
    
    # Forecast
    if not forecast.empty and 'ds' in forecast.columns:
        fig.add_trace(go.Scatter(
            x=forecast['ds'],
            y=forecast['yhat'],
            mode='lines',
            name='Forecast',
            line=dict(color=COLORS['success'], width=2, dash='dash')
        ))
        
        # Confidence intervals
        if 'yhat_lower' in forecast.columns and 'yhat_upper' in forecast.columns:
            fig.add_trace(go.Scatter(
                x=forecast['ds'],
                y=forecast['yhat_upper'],
                mode='lines',
                name='Upper Bound',
                line=dict(width=0),
                showlegend=False
            ))
            
            fig.add_trace(go.Scatter(
                x=forecast['ds'],
                y=forecast['yhat_lower'],
                mode='lines',
                name='Confidence Interval',
                fill='tonexty',
                fillcolor='rgba(33, 150, 243, 0.2)',
                line=dict(width=0)
            ))
    
    fig.update_layout(
        title=f"Price Forecast: {area_name.title()}",
        xaxis_title="Year",
        yaxis_title="Price per sqft (AED)",
        template='plotly_white',
        height=500,
        hovermode='x unified'
    )
    
    return fig


def create_kpi_cards(metrics: Dict[str, float]) -> List[go.Figure]:
    """
    Create KPI card visualizations
    
    Args:
        metrics: Dictionary of metric names and values
        
    Returns:
        List of Plotly figures (one per metric)
    """
    cards = []
    
    for metric_name, value in metrics.items():
        fig = go.Figure()
        
        # Determine color based on value
        if 'score' in metric_name.lower() or 'health' in metric_name.lower():
            color = COLORS['success'] if value >= 70 else \
                   COLORS['warning'] if value >= 50 else \
                   COLORS['danger']
        else:
            color = COLORS['primary']
        
        fig.add_trace(go.Indicator(
            mode="number+delta",
            value=value,
            title={"text": metric_name},
            delta={'reference': 50},
            number={'font': {'size': 40}, 'valueformat': '.1f'},
            domain={'x': [0, 1], 'y': [0, 1]}
        ))
        
        fig.update_layout(
            height=200,
            paper_bgcolor='white',
            font={'color': color}
        )
        
        cards.append(fig)
    
    return cards