/* ═══════════════════════════════════════════════════════════════════════════════
   ReportBuilderTab — Yap-Boz Tarzı Rapor Oluşturucu
   ═══════════════════════════════════════════════════════════════════════════════ */

const { useState, useEffect, useMemo, useCallback, useRef } = React;
const {
    ResponsiveContainer, AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
    XAxis, YAxis, Tooltip, CartesianGrid, Legend,
} = Recharts;

/* ── Widget Registry ─────────────────────────────────────────────────────── */

const WIDGET_REGISTRY = {
    kpi_total_calls: { id: 'kpi_total_calls', label: 'Toplam Çağrı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_today_calls: { id: 'kpi_today_calls', label: 'Bugünkü Çağrı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_avg_duration: { id: 'kpi_avg_duration', label: 'Ort. Süre', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_transfer_rate: { id: 'kpi_transfer_rate', label: 'Transfer Oranı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_qc_rate: { id: 'kpi_qc_rate', label: 'QC Başarı Oranı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_active_calls: { id: 'kpi_active_calls', label: 'Aktif Çağrı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_aht: { id: 'kpi_aht', label: 'Ort. İşlem Süresi (AHT)', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_abandon_rate: { id: 'kpi_abandon_rate', label: 'Terk Oranı', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_avg_wait_time: { id: 'kpi_avg_wait_time', label: 'Ort. Bekleme Süresi', icon: '', category: 'kpi', defaultSize: 'small' },
    kpi_calls_per_hour: { id: 'kpi_calls_per_hour', label: 'Saatlik Çağrı Hızı', icon: '', category: 'kpi', defaultSize: 'small' },
    chart_daily_trend: { id: 'chart_daily_trend', label: 'Günlük Trend (Alan)', icon: '', category: 'chart', defaultSize: 'large' },
    chart_status_dist: { id: 'chart_status_dist', label: 'Durum Dağılımı (Bar)', icon: '', category: 'chart', defaultSize: 'medium' },
    chart_status_pie: { id: 'chart_status_pie', label: 'Durum Dağılımı (Pasta)', icon: '', category: 'chart', defaultSize: 'medium' },
    chart_duration_dist: { id: 'chart_duration_dist', label: 'Süre Dağılımı (Bar)', icon: '', category: 'chart', defaultSize: 'medium' },
    chart_dept_dist: { id: 'chart_dept_dist', label: 'Departman Dağılımı', icon: '', category: 'chart', defaultSize: 'medium' },
    chart_hourly_heatmap: { id: 'chart_hourly_heatmap', label: 'Saatlik Yoğunluk Haritası', icon: '', category: 'chart', defaultSize: 'large' },
    chart_aht_trend: { id: 'chart_aht_trend', label: 'AHT Günlük Trend', icon: '', category: 'chart', defaultSize: 'large' },
    chart_abandon_trend: { id: 'chart_abandon_trend', label: 'Terk Oranı Trendi', icon: '', category: 'chart', defaultSize: 'large' },
    chart_disposition_dist: { id: 'chart_disposition_dist', label: 'Sonuç Kodu Dağılımı', icon: '', category: 'chart', defaultSize: 'medium' },
    table_agent_perf: { id: 'table_agent_perf', label: 'Sanal Temsilci (Basit)', icon: '', category: 'table', defaultSize: 'large' },
    table_ai_agent_perf: { id: 'table_ai_agent_perf', label: 'Sanal Temsilci Performansı', icon: '', category: 'table', defaultSize: 'large' },
    table_human_agent_perf: { id: 'table_human_agent_perf', label: 'İnsan Temsilci Performansı', icon: '', category: 'table', defaultSize: 'large' },
    table_human_agent_status: { id: 'table_human_agent_status', label: 'Temsilci Statü Analizi', icon: '', category: 'table', defaultSize: 'large' },
    table_dept_dist: { id: 'table_dept_dist', label: 'Departman Tablosu', icon: '', category: 'table', defaultSize: 'medium' },
    table_calls: { id: 'table_calls', label: 'Çağrı Listesi (Müşteri Bilgili)', icon: '', category: 'table', defaultSize: 'large' },
    summary_qc: { id: 'summary_qc', label: 'QC Özet Paneli', icon: '', category: 'summary', defaultSize: 'medium' },
};

const WIDGET_CATEGORIES = [
    { id: 'kpi', label: 'KPI Kartları', icon: '' },
    { id: 'chart', label: 'Grafikler', icon: '' },
    { id: 'table', label: 'Tablolar', icon: '' },
    { id: 'summary', label: 'Özet Paneller', icon: '' },
];

const CHART_COLORS = ['#3b6df0', '#22c55e', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#6b7280'];
const STATUS_COLORS = { ended: '#22c55e', transferred: '#3b6df0', active: '#f59e0b', abandoned: '#ef4444', failed: '#6b7280' };

function fmtDur(s) {
    if (!s) return '0s';
    const m = Math.floor(s / 60);
    const sec = Math.round(s % 60);
    return m > 0 ? `${m}dk ${sec}s` : `${sec}s`;
}

// Local timezone'a göre YYYY-MM-DD üretir.
// toISOString() UTC verdiği için TR'de gece 00:00–02:59 arası yanlış gün gönderiyordu.
function localDateISO(d) {
    const pad = n => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}

// Widget cache anahtarı — table_calls için instance bazlı (sütun seçimi farklı
// olabilir), diğer widget tiplerinde type-bazlı (aynı tip aynı veriyi paylaşır).
function widgetCacheKey(w) {
    if (w.type === 'table_calls') {
        const cols = (w.variable_columns || []).slice().sort().join(',');
        return `${w.type}::${w.id}::${cols}::p${w.page || 1}`;
    }
    return w.type;
}

/* ── CSV Export ──────────────────────────────────────────────────────────── */
function exportToCSV(sortedWidgets, widgetData, dateRange, templateName, startDate, endDate) {
    const rows = [];
    const now = new Date().toLocaleString('tr-TR');

    // Başlık bilgisi
    rows.push(['Rapor', templateName || 'Rapor Oluşturucu']);
    const rangeLabel = (startDate || endDate)
        ? ((startDate || endDate) === (endDate || startDate)
            ? (startDate || endDate)                       // tek gün
            : `${startDate || endDate} → ${endDate || startDate}`)
        : `Son ${dateRange} gün`;
    rows.push(['Tarih Aralığı', rangeLabel]);
    rows.push(['Oluşturulma', now]);
    rows.push([]);

    for (const w of sortedWidgets) {
        const data = widgetData[widgetCacheKey(w)];
        const reg = WIDGET_REGISTRY[w.type];
        rows.push([`=== ${reg?.icon || ''} ${w.title} ===`]);

        if (!data) { rows.push(['Veri yok']); rows.push([]); continue; }

        const t = w.type;

        if (t.startsWith('kpi_')) {
            rows.push(['Değer', 'Alt Bilgi']);
            if (t === 'kpi_avg_duration') {
                rows.push([fmtDur(data.value), `Maks: ${fmtDur(data.max)}`]);
            } else if (t === 'kpi_transfer_rate') {
                rows.push([`%${data.value}`, `${data.count}/${data.total}`]);
            } else if (t === 'kpi_qc_rate') {
                rows.push([`%${data.value}`, `${data.completed}/${data.total}`]);
            } else {
                rows.push([data.value ?? 0, '']);
            }
        } else if (t === 'chart_daily_trend') {
            rows.push(['Tarih', 'Çağrı Sayısı']);
            (data || []).forEach(d =>rows.push([d.date, d.count]));
        } else if (t === 'chart_status_dist' || t === 'chart_status_pie') {
            rows.push(['Durum', 'Adet']);
            (data || []).forEach(d =>rows.push([d.status, d.count]));
        } else if (t === 'chart_duration_dist') {
            rows.push(['Süre Aralığı', 'Adet']);
            (data || []).forEach(d =>rows.push([d.range, d.count]));
        } else if (t === 'chart_dept_dist') {
            rows.push(['Departman', 'Adet']);
            (data || []).forEach(d =>rows.push([d.dept, d.count]));
        } else if (t === 'chart_hourly_heatmap') {
            rows.push(['Saat', 'Çağrı Sayısı']);
            (data || []).forEach(d =>rows.push([`${String(d.hour).padStart(2, '0')}:00`, d.count]));
        } else if (t === 'table_agent_perf') {
            rows.push(['Asistan', 'Toplam', 'Tamamlanan', 'Transfer', 'Ort. Süre (sn)']);
            (data || []).forEach(d =>rows.push([d.name, d.total, d.ended, d.transferred, Math.round(d.avg_duration || 0)]));
        } else if (t === 'table_ai_agent_perf') {
            rows.push(['Asistan', 'Toplam', 'Tamamlanan', 'Transfer', 'Ort. Süre', 'Toplam Süre', 'Maks Süre']);
            (data || []).forEach(d =>rows.push([d.name, d.total, d.ended, d.transferred, fmtDur(d.avg_duration), fmtDur(d.total_duration), fmtDur(d.max_dur)]));
        } else if (t === 'table_human_agent_perf') {
            rows.push(['Temsilci', 'Uzantı', 'Dept.', 'Toplam', 'Tamamlanan', 'Terk', 'Konuşma', 'Ort.Konuşma', 'Ort.Bekleme', 'Hold', 'ACW', 'Kap.Süresi', 'Doluluk']);
            (data || []).forEach(d => {
                rows.push([d.name, d.extension, d.department, d.total_calls, d.completed_calls, d.abandoned_calls,
                    fmtDur(d.total_talk_sec), fmtDur(d.avg_talk_sec), fmtDur(d.avg_wait_sec),
                    fmtDur(d.hold_time_sec), fmtDur(d.acw_time_sec), fmtDur(d.handle_time_sec), `%${d.occupancy_pct}`]);
                if (d.queue_stats && d.queue_stats.length > 0) {
                    rows.push([' → Kuyruk', 'Çağrı', 'Tamamlanan', 'Konuşma Süresi']);
                    d.queue_stats.forEach(q =>rows.push([` → ${q.queue_name}`, q.calls, q.completed, fmtDur(q.talk_sec)]));
                }
            });
        } else if (t === 'table_human_agent_status') {
            const statusSet = new Set();
            (data || []).forEach(a =>Object.keys(a.statuses || {}).forEach(s =>statusSet.add(s)));
            const statuses = Array.from(statusSet).sort();
            rows.push(['Temsilci', 'Uzantı', 'Dept.', ...statuses, 'Toplam']);
            (data || []).forEach(a =>rows.push([
                a.agent_name, a.extension, a.department,
                ...statuses.map(s =>a.statuses[s] ? fmtDur(a.statuses[s]) : '—'),
                fmtDur(a.total_sec),
            ]));
        } else if (t === 'table_dept_dist') {
            rows.push(['Departman', 'Çağrı Sayısı']);
            (data || []).forEach(d =>rows.push([d.dept, d.count]));
        } else if (t === 'summary_qc') {
            rows.push(['Metrik', 'Değer']);
            rows.push(['Toplam Değerlendirme', data.total]);
            rows.push(['Başarılı', data.completed]);
            rows.push(['Başarısız', data.failed]);
            rows.push(['Yarıda Kalan', data.abandoned]);
            rows.push(['Başarı Oranı', `%${data.rate}`]);
        } else if (t === 'chart_aht_trend') {
            rows.push(['Tarih', 'Ort. Süre (sn)']);
            (data || []).forEach(d => rows.push([d.date, d.avg_duration]));
        } else if (t === 'chart_abandon_trend') {
            rows.push(['Tarih', 'Terk Oranı (%)', 'Terk Sayısı']);
            (data || []).forEach(d => rows.push([d.date, d.rate, d.count]));
        } else if (t === 'chart_disposition_dist') {
            rows.push(['Sonuç Kodu', 'Adet']);
            (data || []).forEach(d => rows.push([d.disposition, d.count]));
        }

        rows.push([]);
    }

    const csv = rows.map(r =>
        r.map(v => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')
    ).join('\n');

    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `rapor_${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}


/* ── Widget Content Renderers ────────────────────────────────────────────── */

function WidgetKPI({ data, type }) {
    if (!data) return <div className="rb-widget-loading">Yükleniyor...</div>;

    let value = data.value ?? 0;
    let sub = '';

    if (type === 'kpi_total_calls') { sub = 'toplam çağrı'; }
    if (type === 'kpi_today_calls') { sub = `dün: ${data.yesterday ?? 0}`; }
    if (type === 'kpi_avg_duration') { value = fmtDur(data.value); sub = `max: ${fmtDur(data.max)}`; }
    if (type === 'kpi_transfer_rate') { value = `%${data.value}`; sub = `${data.count}/${data.total}`; }
    if (type === 'kpi_qc_rate') { value = `%${data.value}`; sub = `${data.completed}/${data.total}`; }
    if (type === 'kpi_active_calls') { sub = 'anlık'; }
    if (type === 'kpi_aht') { value = fmtDur(data.value); sub = `${data.count ?? 0} çağrı`; }
    if (type === 'kpi_abandon_rate') { value = `%${data.value}`; sub = `${data.count}/${data.total}`; }
    if (type === 'kpi_avg_wait_time') { value = fmtDur(data.value); sub = `max: ${fmtDur(data.max)}`; }
    if (type === 'kpi_calls_per_hour') { value = data.value; sub = `${data.total ?? 0} çağrı / ${data.hours ?? 0} saat`; }

    return (
        <div className="rb-kpi">
            <div className="rb-kpi-value">{value}</div>
            <div className="rb-kpi-sub">{sub}</div>
        </div>
    );
}

function WidgetAreaChartComp({ data }) {
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    return (
        <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={data}>
                <defs>
                    <linearGradient id="rbGrad" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#3b6df0" stopOpacity={0.3} />
                        <stop offset="95%" stopColor="#3b6df0" stopOpacity={0} />
                    </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,.06)" />
                <XAxis dataKey="date" tick={{ fontSize: 11 }} tickFormatter={v =>v.slice(5)} />
                <YAxis tick={{ fontSize: 11 }} allowDecimals={false} />
                <Tooltip contentStyle={{ borderRadius: 10, fontSize: 12 }} />
                <Area type="monotone" dataKey="count" stroke="#3b6df0" fill="url(#rbGrad)" strokeWidth={2} name="Çağrı" />
            </AreaChart>
        </ResponsiveContainer>
    );
}

function WidgetBarChartComp({ data, dataKeyX, dataKeyY }) {
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    return (
        <ResponsiveContainer width="100%" height={200}>
            <BarChart data={data}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,.06)" />
                <XAxis dataKey={dataKeyX} tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} allowDecimals={false} />
                <Tooltip contentStyle={{ borderRadius: 10, fontSize: 12 }} />
                <Bar dataKey={dataKeyY} radius={[6, 6, 0, 0]} name="Adet">
                    {data.map((_, i) => <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />)}
                </Bar>
            </BarChart>
        </ResponsiveContainer>
    );
}

function WidgetPieChartComp({ data }) {
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    const pieData = data.map(d => ({ name: d.status, value: d.count }));
    return (
        <ResponsiveContainer width="100%" height={220}>
            <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" outerRadius={70} dataKey="value" label={({ name, percent }) => `${name} %${(percent * 100).toFixed(0)}`} labelLine={false}>
                    {pieData.map((d, i) => <Cell key={i} fill={STATUS_COLORS[d.name] || CHART_COLORS[i % CHART_COLORS.length]} />)}
                </Pie>
                <Tooltip contentStyle={{ borderRadius: 10, fontSize: 12 }} />
                <Legend wrapperStyle={{ fontSize: 11 }} />
            </PieChart>
        </ResponsiveContainer>
    );
}

function WidgetHeatmap({ data }) {
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    const max = Math.max(...data.map(d =>d.count), 1);
    return (
        <div>
            <div className="rb-heatmap">
                {data.map(d => {
                    const intensity = d.count / max;
                    const bg = `rgba(59,109,240,${0.08 + intensity * 0.72})`;
                    const color = intensity > 0.5 ? '#fff' : 'var(--text-dim)';
                    return (
                        <div key={d.hour} className="rb-heatmap-cell" style={{ background: bg, color }}
                             title={`${String(d.hour).padStart(2,'0')}:00 → ${d.count} çağrı`}>
                            {d.count > 0 ? d.count : ''}
                        </div>
                    );
                })}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'var(--text-dim)', fontWeight: 600 }}>
                <span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>23:00</span>
            </div>
        </div>
    );
}

function useSortable(data, defaultKey = null, defaultDir = 'desc') {
    const [sortKey, setSortKey] = useState(defaultKey);
    const [sortDir, setSortDir] = useState(defaultDir);
    const sorted = useMemo(() => {
        if (!data || !sortKey) return data || [];
        return [...data].sort((a, b) => {
            const va = a[sortKey] ?? 0, vb = b[sortKey] ?? 0;
            if (typeof va === 'string') return sortDir === 'asc' ? va.localeCompare(vb) : vb.localeCompare(va);
            return sortDir === 'asc' ? va - vb : vb - va;
        });
    }, [data, sortKey, sortDir]);
    const toggle = (key) => {
        if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
        else { setSortKey(key); setSortDir('desc'); }
    };
    const indicator = (key) => sortKey === key ? (sortDir === 'asc' ? ' ▲' : ' ▼') : '';
    return { sorted, toggle, indicator };
}

function SortableTh({ label, field, toggle, indicator, style }) {
    return (
        <th style={{ cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap', ...style }} onClick={() => toggle(field)}>
            {label}{indicator(field)}
        </th>
    );
}

function WidgetAgentTable({ data }) {
    const { sorted, toggle, indicator } = useSortable(data, 'total');
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    return (
        <table className="dash-table" style={{ width: '100%', fontSize: 12 }}>
            <thead>
                <tr>
                    <SortableTh label="Asistan" field="name" toggle={toggle} indicator={indicator} />
                    <SortableTh label="Toplam" field="total" toggle={toggle} indicator={indicator} />
                    <SortableTh label="Tamamlanan" field="ended" toggle={toggle} indicator={indicator} />
                    <SortableTh label="Transfer" field="transferred" toggle={toggle} indicator={indicator} />
                    <SortableTh label="Ort. Süre" field="avg_duration" toggle={toggle} indicator={indicator} />
                </tr>
            </thead>
            <tbody>
                {sorted.map((a, i) => (
                    <tr key={i}>
                        <td style={{ fontWeight:600 }}>{a.name}</td>
                        <td>{a.total}</td>
                        <td>{a.ended}</td>
                        <td>{a.transferred}</td>
                        <td>{fmtDur(a.avg_duration)}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
}

function WidgetDeptTable({ data }) {
    const { sorted, toggle, indicator } = useSortable(data, 'count');
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    const total = data.reduce((s, d) =>s + d.count, 0);
    return (
        <table className="dash-table" style={{ width: '100%', fontSize: 12 }}>
            <thead><tr>
                <SortableTh label="Departman" field="dept" toggle={toggle} indicator={indicator} />
                <SortableTh label="Çağrı" field="count" toggle={toggle} indicator={indicator} />
                <th>Oran</th>
            </tr></thead>
            <tbody>
                {sorted.map((d, i) => (
                    <tr key={i}>
                        <td style={{ fontWeight:600 }}>{d.dept}</td>
                        <td>{d.count}</td>
                        <td>%{total > 0 ? Math.round(d.count / total * 100) : 0}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
}

function WidgetQCSummary({ data }) {
    if (!data) return <div className="rb-widget-loading">Yükleniyor...</div>;
    return (
        <div>
            <div className="rb-summary-row">
                <span className="rb-summary-label">Toplam Değerlendirme</span>
                <span className="rb-summary-value">{data.total}</span>
            </div>
            <div className="rb-summary-row">
                <span className="rb-summary-label">Başarılı</span>
                <span className="rb-summary-value" style={{ color: 'var(--green)' }}>{data.completed}</span>
            </div>
            <div className="rb-summary-row">
                <span className="rb-summary-label">Başarısız</span>
                <span className="rb-summary-value" style={{ color: 'var(--red)' }}>{data.failed}</span>
            </div>
            <div className="rb-summary-row">
                <span className="rb-summary-label">Yarıda Kalan</span>
                <span className="rb-summary-value">{data.abandoned}</span>
            </div>
            <div className="rb-summary-row">
                <span className="rb-summary-label">Başarı Oranı</span>
                <span className="rb-summary-value" style={{ color: 'var(--blue)' }}>%{data.rate}</span>
            </div>
        </div>
    );
}

function WidgetAIAgentPerf({ data }) {
    const { sorted, toggle, indicator } = useSortable(data, 'total');
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    return (
        <div style={{ overflowX: 'auto' }}>
            <table className="dash-table" style={{ width: '100%', fontSize: 12 }}>
                <thead>
                    <tr>
                        <SortableTh label="Asistan" field="name" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Toplam" field="total" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Tamamlanan" field="ended" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Transfer" field="transferred" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Ort. Süre" field="avg_duration" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Toplam Süre" field="total_duration" toggle={toggle} indicator={indicator} />
                        <SortableTh label="Maks Süre" field="max_dur" toggle={toggle} indicator={indicator} />
                    </tr>
                </thead>
                <tbody>
                    {sorted.map((a, i) => (
                        <tr key={i}>
                            <td style={{ fontWeight:600 }}>{a.name}</td>
                            <td>{a.total}</td>
                            <td style={{ color: 'var(--green)' }}>{a.ended}</td>
                            <td style={{ color: 'var(--blue)' }}>{a.transferred}</td>
                            <td>{fmtDur(a.avg_duration)}</td>
                            <td>{fmtDur(a.total_duration)}</td>
                            <td>{fmtDur(a.max_dur)}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

const HUMAN_STATUS_LABELS = {
    available: 'Müsait', busy: 'Meşgul', acw: 'ACW',
    offline: 'Çevrimdışı', hold: 'Hold', on_hold: 'Hold',
};
const HUMAN_STATUS_COLORS = {
    available: 'var(--green)', busy: 'var(--amber)', acw: 'var(--blue)',
    offline: 'var(--text-dim)', hold: '#f59e0b', on_hold: '#f59e0b',
};

function WidgetHumanAgentPerf({ data }) {
    const [expanded, setExpanded] = useState({});
    const { sorted, toggle: sortToggle, indicator } = useSortable(data, 'total_calls');
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    const toggleRow = name =>setExpanded(prev => ({ ...prev, [name]: !prev[name] }));
    return (
        <div style={{ overflowX: 'auto' }}>
            <table className="dash-table" style={{ width: '100%', fontSize: 12, minWidth: 900 }}>
                <thead>
                    <tr>
                        <SortableTh label="Temsilci" field="name" toggle={sortToggle} indicator={indicator} />
                        <th>Uzantı</th>
                        <SortableTh label="Dept." field="department" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Toplam" field="total_calls" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Tamam" field="completed_calls" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Terk" field="abandoned_calls" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Konuşma" field="total_talk_sec" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Ort.Konuşma" field="avg_talk_sec" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Ort.Bekleme" field="avg_wait_sec" toggle={sortToggle} indicator={indicator} />
                        <th>Hold</th><th>ACW</th>
                        <SortableTh label="Kap.Süresi" field="handle_time_sec" toggle={sortToggle} indicator={indicator} />
                        <SortableTh label="Doluluk" field="occupancy_pct" toggle={sortToggle} indicator={indicator} />
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {sorted.map((a, i) => (
                        <React.Fragment key={i}>
                            <tr>
                                <td style={{ fontWeight:600 }}>{a.name}</td>
                                <td>{a.extension}</td>
                                <td>{a.department}</td>
                                <td>{a.total_calls}</td>
                                <td style={{ color: 'var(--green)' }}>{a.completed_calls}</td>
                                <td style={{ color: 'var(--red)' }}>{a.abandoned_calls}</td>
                                <td>{fmtDur(a.total_talk_sec)}</td>
                                <td>{fmtDur(a.avg_talk_sec)}</td>
                                <td>{fmtDur(a.avg_wait_sec)}</td>
                                <td>{fmtDur(a.hold_time_sec)}</td>
                                <td>{fmtDur(a.acw_time_sec)}</td>
                                <td>{fmtDur(a.handle_time_sec)}</td>
                                <td>
                                    <span style={{ color: a.occupancy_pct > 80 ? 'var(--red)' : 'var(--green)', fontWeight:600 }}>
                                        %{a.occupancy_pct}
                                    </span>
                                </td>
                                <td>
                                    {a.queue_stats && a.queue_stats.length > 0 && (
                                        <button
                                            style={{ fontSize: 10, padding: '2px 6px', cursor: 'pointer', borderRadius: 4, border: '1px solid rgba(59,109,240,.3)', background: 'rgba(59,109,240,.1)', color: 'var(--blue)' }}
                                            onClick={() =>toggleRow(a.name)}
                                        >
                                            {expanded[a.name] ? '▲' : '▼'} Kuyruklar
                                        </button>
                                    )}
                                </td>
                            </tr>
                            {expanded[a.name] && (a.queue_stats || []).map((q, j) => (
                                <tr key={`q_${i}_${j}`} style={{ background: 'rgba(59,109,240,.04)' }}>
                                    <td colSpan={3} style={{ paddingLeft: 24, color: 'var(--text-dim)', fontStyle: 'italic' }}>↳ {q.queue_name}</td>
                                    <td>{q.calls}</td>
                                    <td style={{ color: 'var(--green)' }}>{q.completed}</td>
                                    <td>—</td>
                                    <td>{fmtDur(q.talk_sec)}</td>
                                    <td colSpan={7}></td>
                                </tr>
                            ))}
                        </React.Fragment>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

function WidgetHumanAgentStatus({ data }) {
    const { sorted, toggle, indicator } = useSortable(data, 'total_sec');
    if (!data || !data.length) return <div className="rb-widget-loading">Veri yok</div>;
    const statusSet = new Set();
    data.forEach(a =>Object.keys(a.statuses || {}).forEach(s =>statusSet.add(s)));
    const statuses = Array.from(statusSet).sort();
    return (
        <div style={{ overflowX: 'auto' }}>
            <table className="dash-table" style={{ width: '100%', fontSize: 12 }}>
                <thead>
                    <tr>
                        <SortableTh label="Temsilci" field="agent_name" toggle={toggle} indicator={indicator} />
                        <th>Uzantı</th>
                        <SortableTh label="Dept." field="department" toggle={toggle} indicator={indicator} />
                        {statuses.map(s => <th key={s}>{HUMAN_STATUS_LABELS[s] || s}</th>)}
                        <SortableTh label="Toplam" field="total_sec" toggle={toggle} indicator={indicator} />
                    </tr>
                </thead>
                <tbody>
                    {sorted.map((a, i) => (
                        <tr key={i}>
                            <td style={{ fontWeight:600 }}>{a.agent_name}</td>
                            <td>{a.extension}</td>
                            <td>{a.department}</td>
                            {statuses.map(s => (
                                <td key={s} style={{ color: HUMAN_STATUS_COLORS[s] || 'inherit' }}>
                                    {a.statuses[s] ? fmtDur(a.statuses[s]) : '—'}
                                </td>
                            ))}
                            <td style={{ fontWeight:600 }}>{fmtDur(a.total_sec)}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

// ─── Çağrı Listesi (drill-down: WS metadata sütunlarıyla) ───────────────────
function WidgetCallsTable({ data, widget, onUpdate, variableKeyOptions }) {
    const items = (data && data.items) || [];
    const total = (data && data.total) || 0;
    const page  = (data && data.page) || 1;
    const pages = (data && data.pages) || 1;
    const cols  = (widget && widget.variable_columns) || [];
    const [pickerOpen, setPickerOpen] = useState(false);

    const allKeys = (variableKeyOptions || []).slice().sort();

    function toggleCol(k) {
        if (!onUpdate) return;
        const next = cols.includes(k) ? cols.filter(c => c !== k) : [...cols, k];
        onUpdate({ ...widget, variable_columns: next, page: 1 });
    }

    function setPage(p) {
        if (!onUpdate) return;
        onUpdate({ ...widget, page: p });
    }

    return (
        <div className="rb-widget-content" style={{ padding: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8, fontSize: 12, color: 'var(--text-dim)' }}>
                <span>Toplam: {total} çağrı</span>
                <div style={{ position: 'relative' }}>
                    <button className="rb-btn" style={{ fontSize: 11, padding: '4px 10px' }}
                        onClick={() => setPickerOpen(o => !o)}>
                        Sütun Seç ({cols.length})
                    </button>
                    {pickerOpen && (
                        <div style={{
                            position: 'absolute', right: 0, top: '110%', zIndex: 50,
                            background: 'var(--surface, #1e2329)', border: '1px solid var(--border)', borderRadius: 8,
                            padding: 10, minWidth: 220, maxHeight: 280, overflowY: 'auto',
                            boxShadow: '0 4px 16px rgba(0,0,0,.3)',
                        }}>
                            {allKeys.length === 0 ? (
                                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                                    WS değişkeni bulunamadı. WebServis Entegrasyonlarınızı kontrol edin.
                                </div>
                            ) : allKeys.map(k =>
                                <label key={k} style={{ display: 'flex', gap: 6, alignItems: 'center', padding: '3px 0', fontSize: 12, cursor: 'pointer' }}>
                                    <input type="checkbox" checked={cols.includes(k)} onChange={() => toggleCol(k)} />
                                    <span style={{ fontFamily: 'monospace' }}>{k}</span>
                                </label>
                            )}
                        </div>
                    )}
                </div>
            </div>
            <div style={{ overflowX: 'auto' }}>
                <table className="rb-table" style={{ fontSize: 12, width: '100%' }}>
                    <thead>
                        <tr>
                            <th>Tarih</th>
                            <th>Telefon</th>
                            <th>Agent</th>
                            <th>Süre</th>
                            <th>Durum</th>
                            {cols.map(k => <th key={k} style={{ fontFamily: 'monospace' }}>{k}</th>)}
                        </tr>
                    </thead>
                    <tbody>
                        {items.length === 0 ? (
                            <tr><td colSpan={5 + cols.length} style={{ textAlign: 'center', padding: 20, color: 'var(--text-dim)' }}>Bu kriterlerle çağrı bulunamadı.</td></tr>
                        ) : items.map(c =>
                            <tr key={c.id}>
                                <td style={{ whiteSpace: 'nowrap' }}>{fmtDateTime(c.start_time)}</td>
                                <td style={{ fontFamily: 'monospace' }}>{c.phone_number || '—'}</td>
                                <td>{c.agent_name || '—'}</td>
                                <td style={{ whiteSpace: 'nowrap' }}>{Math.round(c.duration || 0)}s</td>
                                <td>{c.status || '—'}</td>
                                {cols.map(k =>
                                    <td key={k} style={{ fontFamily: 'monospace', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                        {(c.variables && c.variables[k]) || '—'}
                                    </td>
                                )}
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
            {pages > 1 && (
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, marginTop: 10, fontSize: 12 }}>
                    <button className="rb-btn" disabled={page <= 1} onClick={() => setPage(page - 1)}>← Önceki</button>
                    <span style={{ color: 'var(--text-dim)' }}>{page} / {pages}</span>
                    <button className="rb-btn" disabled={page >= pages} onClick={() => setPage(page + 1)}>Sonraki →</button>
                </div>
            )}
        </div>
    );
}

function renderWidgetContent(widget, data, ctx) {
    const t = widget.type;
    if (t.startsWith('kpi_')) return <WidgetKPI data={data} type={t} />;
    if (t === 'chart_daily_trend') return <WidgetAreaChartComp data={data} />;
    if (t === 'chart_status_dist') return <WidgetBarChartComp data={data} dataKeyX="status" dataKeyY="count" />;
    if (t === 'chart_status_pie') return <WidgetPieChartComp data={data} />;
    if (t === 'chart_duration_dist') return <WidgetBarChartComp data={data} dataKeyX="range" dataKeyY="count" />;
    if (t === 'chart_dept_dist') return <WidgetBarChartComp data={data} dataKeyX="dept" dataKeyY="count" />;
    if (t === 'chart_hourly_heatmap') return <WidgetHeatmap data={data} />;
    if (t === 'chart_aht_trend') return <WidgetAreaChartComp data={(data||[]).map(d=>({date:d.date, count:d.avg_duration}))} />;
    if (t === 'chart_abandon_trend') return <WidgetAreaChartComp data={(data||[]).map(d=>({date:d.date, count:d.rate}))} />;
    if (t === 'chart_disposition_dist') return <WidgetBarChartComp data={data} dataKeyX="disposition" dataKeyY="count" />;
    if (t === 'table_agent_perf') return <WidgetAgentTable data={data} />;
    if (t === 'table_ai_agent_perf') return <WidgetAIAgentPerf data={data} />;
    if (t === 'table_human_agent_perf') return <WidgetHumanAgentPerf data={data} />;
    if (t === 'table_human_agent_status') return <WidgetHumanAgentStatus data={data} />;
    if (t === 'table_dept_dist') return <WidgetDeptTable data={data} />;
    if (t === 'table_calls') return <WidgetCallsTable data={data} widget={widget}
        onUpdate={ctx && ctx.updateWidget} variableKeyOptions={ctx && ctx.variableKeyOptions} />;
    if (t === 'summary_qc') return <WidgetQCSummary data={data} />;
    return <div className="rb-widget-loading">Bilinmeyen widget</div>;
}


/* ── Main Component ──────────────────────────────────────────────────────── */

function ReportBuilderTab({ toast }) {
    // ── Templates
    const [templates, setTemplates] = useState([]);
    const [activeTemplateId, setActiveTemplateId] = useState(null);
    const [templateName, setTemplateName] = useState('');

    // ── Canvas state
    const [widgets, setWidgets] = useState([]);
    const [dateRange, setDateRange] = useState(14);
    const [startDate, setStartDate] = useState('');   // YYYY-MM-DD — özel aralık başlangıç
    const [endDate, setEndDate] = useState('');       // YYYY-MM-DD — özel aralık bitiş (dahil)
    const [widgetData, setWidgetData] = useState({});
    const [loadingData, setLoadingData] = useState(false);

    // ── Palette
    const [paletteOpen, setPaletteOpen] = useState(true);

    // ── Gelişmiş filtreler
    const [filterOptions, setFilterOptions] = useState({ agents: [], departments: [], dispositions: [], statuses: [] });
    const [filters, setFilters] = useState({ agent_id: '', department: '', disposition: '', status: '', phone: '' });
    const [filtersOpen, setFiltersOpen] = useState(false);
    const activeFilterCount = Object.values(filters).filter(v => v).length;

    // ── Load templates and filter options on mount
    useEffect(() => {
        loadTemplates();
        authFetch('/api/reports/filter-options')
            .then(r => r.json())
            .then(d => setFilterOptions(d))
            .catch(() => {});
    }, []);

    async function loadTemplates() {
        try {
            const r = await authFetch('/api/reports/templates');
            const data = await r.json();
            setTemplates(data);
            // Auto-load default template
            const def = data.find(t =>t.is_default);
            if (def) loadTemplate(def);
        } catch (e) { console.error('Template load error:', e); }
    }

    function loadTemplate(tpl) {
        setActiveTemplateId(tpl.id);
        setTemplateName(tpl.name);
        const cfg = tpl.config || {};
        setWidgets(cfg.widgets || []);
        if (cfg.dateRange) {
            const d = parseInt(cfg.dateRange);
            if (!isNaN(d)) setDateRange(d);
        }
        setStartDate(cfg.startDate || '');
        setEndDate(cfg.endDate || '');
    }

    // ── Build filter query string
    const filterQS = useMemo(() => {
        let qs = '';
        if (filters.agent_id) qs += `&agent_id=${filters.agent_id}`;
        if (filters.department) qs += `&department=${encodeURIComponent(filters.department)}`;
        if (filters.disposition) qs += `&disposition=${encodeURIComponent(filters.disposition)}`;
        if (filters.status) qs += `&status=${encodeURIComponent(filters.status)}`;
        if (filters.phone) qs += `&phone=${encodeURIComponent(filters.phone)}`;
        return qs;
    }, [filters]);

    // ── Özel tarih aralığı query parçası
    //
    // Sektör standardı (Datadog/Grafana/Mixpanel): tek tarih = tek gün.
    // Kullanıcı yalnızca başlangıç ya da bitiş seçerse, backend single-day
    // olarak yorumlar. Ayrıca kullanıcının IANA timezone'u backend'e gönderilir
    // ki gün sınırları doğru hesaplansın (UTC kaymasından kaynaklı kayıp/eksik
    // kayıt görüntüleme önlenir).
    const userTz = useMemo(() => {
        try {
            return Intl.DateTimeFormat().resolvedOptions().timeZone || '';
        } catch (e) {
            return '';
        }
    }, []);

    const dateQS = useMemo(() => {
        const tzPart = userTz ? `&tz=${encodeURIComponent(userTz)}` : '';
        if (startDate || endDate) {
            const s = startDate || endDate;
            const e = endDate || startDate;
            return `&start_date=${s}&end_date=${e}${tzPart}`;
        }
        return `&days=${dateRange}${tzPart}`;
    }, [startDate, endDate, dateRange, userTz]);

    // ── Fetch widget data when widgets, dateRange/özel tarih or filters change
    //
    // Çoğu widget aynı type için aynı veriyi döndürür (ör. iki kpi_total_calls
    // identik veri çeker), o yüzden type-bazlı cache kullanırız. table_calls ise
    // her instance'ın kendi sütun seçimi (variable_columns) olduğu için instance
    // bazlı (widget.id) cache key kullanılır.
    function _widgetQS(w) {
        let qs = '';
        if (w.type === 'table_calls') {
            const cols = (w.variable_columns || []).join(',');
            if (cols) qs += `&variable_columns=${encodeURIComponent(cols)}`;
            qs += `&page=${w.page || 1}&per_page=${w.per_page || 25}`;
        }
        return qs;
    }

    useEffect(() => {
        if (widgets.length === 0) { setWidgetData({}); return; }
        const seen = new Set();
        const targets = widgets.filter(w => {
            const k = widgetCacheKey(w);
            if (seen.has(k)) return false;
            seen.add(k);
            return true;
        });
        setLoadingData(true);
        Promise.all(
            targets.map(w =>
                authFetch(`/api/reports/widget-data?widget_type=${w.type}${dateQS}${filterQS}${_widgetQS(w)}`)
                    .then(r =>r.json())
                    .then(data => ({ key: widgetCacheKey(w), data }))
                    .catch(() => ({ key: widgetCacheKey(w), data: null }))
            )
        ).then(results => {
            const map = {};
            results.forEach(r => { map[r.key] = r.data; });
            setWidgetData(map);
            setLoadingData(false);
        });
    }, [widgets.length, dateQS, filterQS,
        widgets.map(w => `${w.id}:${w.type}:${(w.variable_columns||[]).join(',')}:${w.page||1}`).join('|')]);

    // ── Widget operations
    function addWidget(typeId) {
        const reg = WIDGET_REGISTRY[typeId];
        if (!reg) return;
        const w = {
            id: 'w_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
            type: typeId,
            title: reg.label,
            size: reg.defaultSize,
            position: widgets.length,
        };
        setWidgets(prev => [...prev, w]);
    }

    function removeWidget(id) {
        setWidgets(prev =>prev.filter(w =>w.id !== id).map((w, i) => ({ ...w, position: i })));
    }

    function moveWidget(id, dir) {
        setWidgets(prev => {
            const list = [...prev].sort((a, b) =>a.position - b.position);
            const idx = list.findIndex(w =>w.id === id);
            if (idx < 0) return prev;
            const target = idx + dir;
            if (target < 0 || target >= list.length) return prev;
            [list[idx], list[target]] = [list[target], list[idx]];
            return list.map((w, i) => ({ ...w, position: i }));
        });
    }

    function resizeWidget(id) {
        const sizes = ['small', 'medium', 'large'];
        setWidgets(prev =>prev.map(w => {
            if (w.id !== id) return w;
            const idx = sizes.indexOf(w.size);
            return { ...w, size: sizes[(idx + 1) % sizes.length] };
        }));
    }

    // ── Save/Delete template
    async function saveTemplate() {
        if (!templateName.trim()) { toast('Şablon adı gerekli', 'error'); return; }
        const config = { dateRange: String(dateRange), startDate, endDate, widgets };
        try {
            if (activeTemplateId) {
                await authFetch(`/api/reports/templates/${activeTemplateId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: templateName, config }),
                });
                toast('Şablon güncellendi', 'success');
            } else {
                const r = await authFetch('/api/reports/templates', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: templateName, config }),
                });
                const data = await r.json();
                setActiveTemplateId(data.id);
                toast('Şablon kaydedildi', 'success');
            }
            loadTemplates();
        } catch (e) { toast('Kaydetme hatası: ' + e.message, 'error'); }
    }

    async function deleteTemplate() {
        if (!activeTemplateId) return;
        if (!confirm('Bu şablonu silmek istediğinize emin misiniz?')) return;
        try {
            await authFetch(`/api/reports/templates/${activeTemplateId}`, { method: 'DELETE' });
            toast('Şablon silindi', 'success');
            setActiveTemplateId(null);
            setTemplateName('');
            setWidgets([]);
            loadTemplates();
        } catch (e) { toast('Silme hatası', 'error'); }
    }

    function newTemplate() {
        setActiveTemplateId(null);
        setTemplateName('');
        setWidgets([]);
    }

    // ── Sorted widgets
    const sortedWidgets = useMemo(() =>
        [...widgets].sort((a, b) =>a.position - b.position),
        [widgets]
    );

    const sizeLabel = { small: 'S', medium: 'M', large: 'L' };

    // ═══════════════════════════ RENDER ═══════════════════════════

    return (
        <div className="fade-in">
            {/* ── Header ── */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
                <div>
                    <h2 style={{ fontSize: 24, fontWeight:600 }}>Rapor Oluşturucu</h2>
                    <p style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 4 }}>
                        Widget'ları seçerek kendi raporunuzu tasarlayın, şablon olarak kaydedin.
                    </p>
                </div>
            </div>

            {/* ── Toolbar ── */}
            <div className="rb-toolbar">
                <div className="rb-toolbar-group">
                    <select
                        className="rb-template-select"
                        value={activeTemplateId || ''}
                        onChange={e => {
                            const id = parseInt(e.target.value);
                            const tpl = templates.find(t =>t.id === id);
                            if (tpl) loadTemplate(tpl);
                        }}
                    >
                        <option value="">— Şablon Seçin —</option>
                        {templates.map(t => (
                            <option key={t.id} value={t.id}>{t.name}{t.is_default ? ' ' : ''}</option>
                        ))}
                    </select>
                    <button className="rb-btn" onClick={newTemplate}>+ Yeni</button>
                </div>

                <div className="rb-toolbar-group">
                    <input
                        className="rb-input"
                        placeholder="Şablon adı..."
                        value={templateName}
                        onChange={e =>setTemplateName(e.target.value)}
                    />
                    <button className="rb-btn rb-btn-primary" onClick={saveTemplate}>Kaydet</button>
                    {activeTemplateId && (
                        <button className="rb-btn rb-btn-danger" onClick={deleteTemplate}>Sil</button>
                    )}
                </div>

                {/* Export butonu — sadece canvas'ta widget varsa göster */}
                {sortedWidgets.length > 0 && (
                    <div className="rb-toolbar-group">
                        <button
                            className="rb-btn"
                            style={{
                                background: 'rgba(34,197,94,.12)',
                                color: 'var(--green)',
                                border: '1px solid rgba(34,197,94,.3)',
                                fontWeight:600,
                            }}
                            onClick={() => {
                                exportToCSV(sortedWidgets, widgetData, dateRange, templateName, startDate, endDate);
                                toast('CSV dosyası indirildi', 'success');
                            }}
                            title="Raporu CSV olarak indir"
                        >
                             CSV İndir
                        </button>
                    </div>
                )}

                <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                    <div className="rb-date-toggle">
                        {[7, 14, 30, 60, 90].map(d => (
                            <button
                                key={d}
                                className={(!startDate && !endDate && dateRange === d) ? 'active' : ''}
                                onClick={() => { setStartDate(''); setEndDate(''); setDateRange(d); }}
                            >
                                {d}g
                            </button>
                        ))}
                    </div>
                    <div className="rb-date-toggle" title="Hızlı aralık">
                        {/* Preset'ler kullanıcının LOCAL timezone'una göre hesaplanır.
                            Önceki kod toISOString() ile UTC günü kullanıyordu; TR'de gece
                            00:00–02:59 arası "Bugün" butonu dünü gönderiyordu. */}
                        <button onClick={() => {
                            const y = localDateISO(new Date(Date.now() - 86400000));
                            setStartDate(y); setEndDate(y);
                        }}>Dün</button>
                        <button onClick={() => {
                            const t = localDateISO(new Date());
                            setStartDate(t); setEndDate(t);
                        }}>Bugün</button>
                        <button onClick={() => {
                            const end = new Date();
                            const start = new Date(end.getTime() - 6 * 86400000);
                            setStartDate(localDateISO(start));
                            setEndDate(localDateISO(end));
                        }}>Son 7g</button>
                        <button onClick={() => {
                            const now = new Date();
                            const start = new Date(now.getFullYear(), now.getMonth(), 1);
                            setStartDate(localDateISO(start)); setEndDate(localDateISO(now));
                        }}>Bu Ay</button>
                    </div>
                    <div style={{ display: 'flex', gap: 4, alignItems: 'center', fontSize: 12 }}>
                        <input
                            type="date"
                            className="form-input"
                            style={{ fontSize: 12, padding: '4px 6px', width: 140 }}
                            value={startDate}
                            max={endDate || undefined}
                            onChange={e => setStartDate(e.target.value)}
                            title="Başlangıç tarihi"
                        />
                        <span style={{ color: 'var(--text-dim)' }}>→</span>
                        <input
                            type="date"
                            className="form-input"
                            style={{ fontSize: 12, padding: '4px 6px', width: 140 }}
                            value={endDate}
                            min={startDate || undefined}
                            onChange={e => setEndDate(e.target.value)}
                            title="Bitiş tarihi (dahil)"
                        />
                        {(startDate || endDate) && (
                            <button
                                className="rb-btn"
                                style={{ fontSize: 11, padding: '4px 8px' }}
                                onClick={() => { setStartDate(''); setEndDate(''); }}
                                title="Özel tarih aralığını temizle"
                            >✕</button>
                        )}
                    </div>
                </div>
            </div>

            {/* ── Filtre Çubuğu ── */}
            <div style={{ marginBottom: 16 }}>
                <button
                    className="rb-btn"
                    style={{
                        background: activeFilterCount > 0 ? 'rgba(59,109,240,.12)' : 'transparent',
                        color: activeFilterCount > 0 ? 'var(--blue)' : 'var(--text-dim)',
                        border: activeFilterCount > 0 ? '1px solid rgba(59,109,240,.3)' : '1px solid var(--border)',
                        fontWeight: 600,
                    }}
                    onClick={() => setFiltersOpen(p => !p)}
                >
                    Filtreler {activeFilterCount > 0 ? `(${activeFilterCount})` : ''}
                    <span style={{ marginLeft: 6, fontSize: 10 }}>{filtersOpen ? '▲' : '▼'}</span>
                </button>
                {activeFilterCount > 0 && (
                    <button
                        className="rb-btn"
                        style={{ marginLeft: 8, fontSize: 11, color: 'var(--red)' }}
                        onClick={() => setFilters({ agent_id: '', department: '', disposition: '', status: '', phone: '' })}
                    >
                        Temizle
                    </button>
                )}
            </div>
            {filtersOpen && (
                <div style={{
                    display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12,
                    background: 'var(--bg-hover)', borderRadius: 12, padding: 16, marginBottom: 16,
                    border: '1px solid var(--border)',
                }}>
                    <div>
                        <label style={{ fontSize: 11, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>AI Asistan</label>
                        <select className="form-select" style={{ fontSize: 12 }} value={filters.agent_id} onChange={e => setFilters(f => ({ ...f, agent_id: e.target.value }))}>
                            <option value="">Tümü</option>
                            {filterOptions.agents.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                        </select>
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>Departman</label>
                        <select className="form-select" style={{ fontSize: 12 }} value={filters.department} onChange={e => setFilters(f => ({ ...f, department: e.target.value }))}>
                            <option value="">Tümü</option>
                            {filterOptions.departments.map(d => <option key={d} value={d}>{d}</option>)}
                        </select>
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>Sonuç Kodu</label>
                        <select className="form-select" style={{ fontSize: 12 }} value={filters.disposition} onChange={e => setFilters(f => ({ ...f, disposition: e.target.value }))}>
                            <option value="">Tümü</option>
                            {filterOptions.dispositions.map(d => <option key={d} value={d}>{d}</option>)}
                        </select>
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>Çağrı Durumu</label>
                        <select className="form-select" style={{ fontSize: 12 }} value={filters.status} onChange={e => setFilters(f => ({ ...f, status: e.target.value }))}>
                            <option value="">Tümü</option>
                            {filterOptions.statuses.map(s => <option key={s} value={s}>{s}</option>)}
                        </select>
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>Telefon No</label>
                        <input className="form-input" style={{ fontSize: 12 }} placeholder="Ara..." value={filters.phone} onChange={e => setFilters(f => ({ ...f, phone: e.target.value }))} />
                    </div>
                </div>
            )}

            {/* ── Layout: Palette + Canvas ── */}
            <div className="rb-layout">
                {/* ── Palette ── */}
                <div className="rb-palette">
                    <div className="rb-palette-title">
                         Widget Paleti
                    </div>
                    {WIDGET_CATEGORIES.map(cat => {
                        const items = Object.values(WIDGET_REGISTRY).filter(w =>w.category === cat.id);
                        return (
                            <div key={cat.id} className="rb-palette-category">
                                <div className="rb-palette-category-title">{cat.label}</div>
                                {items.map(w => (
                                    <div key={w.id} className="rb-palette-item" onClick={() =>addWidget(w.id)}>
                                        {w.icon && <span className="rb-palette-item-icon">{w.icon}</span>}
                                        <span>{w.label}</span>
                                        <span className="rb-palette-item-size">{w.defaultSize[0].toUpperCase()}</span>
                                    </div>
                                ))}
                            </div>
                        );
                    })}
                </div>

                {/* ── Canvas ── */}
                <div className="rb-canvas">
                    <div className="rb-grid">
                        {sortedWidgets.length === 0 ? (
                            <div className="rb-grid-empty">
                                <span className="rb-grid-empty-icon"></span>
                                Soldaki paletten widget'ları tıklayarak raporunuzu oluşturun.
                            </div>
                        ) : sortedWidgets.map((w, idx) => {
                            const reg = WIDGET_REGISTRY[w.type];
                            const data = widgetData[widgetCacheKey(w)];
                            return (
                                <div key={w.id} className={`rb-widget rb-widget-${w.size}`}>
                                    <div className="rb-widget-header">
                                        <div className="rb-widget-title">
                                            {w.title}
                                        </div>
                                        <div className="rb-widget-controls">
                                            <button onClick={() =>moveWidget(w.id, -1)} disabled={idx === 0} title="Yukarı taşı">↑</button>
                                            <button onClick={() =>moveWidget(w.id, 1)} disabled={idx === sortedWidgets.length - 1} title="Aşağı taşı">↓</button>
                                            <button className="size-btn" onClick={() =>resizeWidget(w.id)} title="Boyut değiştir">
                                                {sizeLabel[w.size]}
                                            </button>
                                            <button className="remove" onClick={() =>removeWidget(w.id)} title="Kaldır">X</button>
                                        </div>
                                    </div>
                                    <div className="rb-widget-body">
                                        {loadingData && !data
                                            ? <div className="rb-widget-loading">Yükleniyor...</div>
                                            : renderWidgetContent(w, data)
                                        }
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </div>
    );
}

window.ReportBuilderTab = ReportBuilderTab;
