"use client";
import { useEffect, useRef, useState } from "react";
import { readApiResponse, uploadFileChunks } from "../lib/chunked-upload";
import { MAX_FILE_SIZE, MAX_FILE_SIZE_LABEL } from "../lib/file-limits";
import { disableLiveAlerts, enableLiveAlerts, liveAlertsEnabled, sendLiveAlert } from "../lib/live-alerts";
import { LogoutButton } from "./logout-button";
import { AdminCustomerPanel } from "./admin-customer-panel";
import { AdminBrandSettings } from "./admin-brand-settings";
import { AdminGlobalSearch, type AdminSearchResult } from "./admin-global-search";
import { DiagnosticCenter } from "./diagnostic-center";
import { UpdateCenter } from "./update-center";
type View = "dashboard" | "requests" | "tuners" | "customers" | "services" | "support" | "dtc" | "settings";
type RequestRow = {
    id: string;
    customer: string;
    customerEmail?: string;
    customerPhone?: string;
    vehicle: string;
    motor: string;
    ecu: string;
    services: string[];
    tuner: string;
    credit: number;
    status: string;
    cls: string;
    time: string;
    progress: number;
    incoming?: boolean;
    fileName?: string;
    fileSize?: number;
    vehicleIdName?: string;
    vehicleIdSize?: number;
    vehicleIdAvailable?: boolean;
    createdAt?: number;
    originalAvailable?: boolean;
    resultAvailable?: boolean;
    resultName?: string;
};
type ChatConversation = {
    id: string;
    customer_id: string;
    customer_name: string;
    customer_company: string | null;
    customer_email: string;
    status: string;
    last_message: string | null;
    last_message_at: number;
    staff_unread: number;
    customer_unread: number;
};
type ChatMessage = {
    id: string;
    sender_id: string;
    sender_role: string;
    sender_name: string;
    body: string;
    created_at: number;
    read_at: number | null;
};
type ChatPayload = {
    conversation: ChatConversation | null;
    conversations: ChatConversation[];
    messages: ChatMessage[];
};
type PendingRegistration = {
    id: string;
    name: string;
    email: string;
    phone: string | null;
    company: string | null;
    created_at: number;
};
type BrandSettings = { portal_name: string; logo_key: string | null; updated_at: number };
type AdminCustomer = {
    id: string;
    email: string;
    name: string;
    role: string;
    status: string;
    phone: string | null;
    company: string | null;
    avatar_url: string | null;
    created_at: number;
    updated_at: number;
    available_credits: number;
    reserved_credits: number;
    auth_providers: string;
    request_count: number;
    completed_request_count: number;
    stored_file_count: number;
    stored_file_bytes: number;
    support_count: number;
    open_support_count: number;
    chat_count: number;
    payment_count: number;
    paid_credits: number;
    last_request_at: number | null;
    last_chat_at: number | null;
    last_session_at: number | null;
};
type AdminCustomerSummary = {
    customerCount: number;
    activeCustomerCount: number;
    pendingCustomerCount: number;
    requestCount: number;
    fileCount: number;
    storedBytes: number;
    supportCount: number;
    chatCount: number;
    availableCredits: number;
    reservedCredits: number;
};
const requests: RequestRow[] = [
    { id: "CC-2026-001245", customer: "Atlas Garage", vehicle: "Volkswagen Golf 7", motor: "2.0 TDI · 150 HP", ecu: "EDC17C64", services: ["Stage 1", "DPF OFF"], tuner: "Ahmet K.", credit: 18, status: "İşlemde", cls: "processing", time: "00:42", progress: 58 },
    { id: "CC-2026-001244", customer: "Mert Otomotiv", vehicle: "BMW F30 320d", motor: "2.0d · 184 HP", ecu: "EDC17C50", services: ["Stage 1"], tuner: "Burak T.", credit: 12, status: "Hazır", cls: "ready", time: "01:18", progress: 100 },
    { id: "CC-2026-001243", customer: "Ege Chip", vehicle: "Fiat Egea", motor: "1.3 Multijet · 95 HP", ecu: "MJD9DF", services: ["EGR OFF", "DTC OFF"], tuner: "Atanmadı", credit: 9, status: "Bekliyor", cls: "waiting", time: "00:16", progress: 15 },
    { id: "CC-2026-001242", customer: "RPM Garage", vehicle: "Mercedes C220", motor: "2.1 CDI · 170 HP", ecu: "CRD3", services: ["Stage 2", "AdBlue OFF"], tuner: "Ahmet K.", credit: 24, status: "Öncelikli", cls: "urgent", time: "02:31", progress: 72 },
];
const nav: [
    string,
    {
        label: string;
        view: View;
        icon: string;
        badge?: string;
    }[]
][] = [
    ["GENEL", [{ label: "Dashboard", view: "dashboard", icon: "⌂" }, { label: "Dosya Talepleri", view: "requests", icon: "◆", badge: "12" }]],
    ["OPERASYON", [{ label: "Tuner Yönetimi", view: "tuners", icon: "♟" }, { label: "Müşteriler", view: "customers", icon: "●" }, { label: "Destek Merkezi", view: "support", icon: "◈" }]],
    ["FİNANS", [{ label: "Hizmetler & Krediler", view: "services", icon: "₺" }]],
    ["ARAÇLAR", [{ label: "DTC Veritabanı", view: "dtc", icon: "⌁" }]],
    ["SİSTEM", [{ label: "Ayarlar", view: "settings", icon: "⚙" }]],
];
const titles: Record<View, [
    string,
    string
]> = { dashboard: ["Operasyon Merkezi", "Tüm dosya servis operasyonunuz tek ekranda."], requests: ["Dosya Talepleri", "Tüm ECU/TCU işlerini filtreleyin ve yönetin."], tuners: ["Tuner Yönetimi", "Ekip performansı, uzmanlık ve iş yükü."], customers: ["Müşteriler & Bayiler", "Müşteri hesapları, krediler ve siparişler."], services: ["Hizmetler & Krediler", "Servis kataloğu ve kredi fiyatlandırması."], support: ["Destek Merkezi", "Müşteri taleplerini tek kuyrukta çözün."], dtc: ["DTC & ECU Bilgi Merkezi", "Arıza kodu ve Bosch kontrol ünitesi ailelerinde hızlı teknik arama."], settings: ["Sistem Ayarları", "Marka, modül ve çalışma ayarları."] };
function Badge({ r }: {
    r: RequestRow;
}) { return <span className={`badge ${r.cls}`}>{r.status}</span>; }
function RequestTable({ all = false, items = requests, onOpen }: {
    all?: boolean;
    items?: RequestRow[];
    onOpen: (request: RequestRow) => void;
}) { const rows = all ? [...items, ...requests.map((x, i) => ({ ...x, id: `CC-2026-00123${i + 4}` }))] : items; return <div className="tableWrap"><table className="table"><thead><tr><th>TALEP</th><th>MÜŞTERİ</th><th>ARAÇ</th><th>ECU / TCU</th><th>İSTENEN SERVİSLER</th><th>TUNER</th><th>KREDİ</th><th>DURUM / SLA</th><th></th></tr></thead><tbody>{rows.map(r => <tr key={r.id} className={r.incoming ? "incomingRow" : ""}><td className="id">{r.id}{r.incoming && <small className="newTag">YENİ</small>}</td><td>{r.customer}</td><td className="vehicle">{r.vehicle}<small>{r.motor}</small></td><td>{r.ecu}</td><td>{r.services.map(s => <span className="service" key={s}>{s}</span>)}</td><td>{r.tuner}</td><td>{r.credit}</td><td><Badge r={r}/><div className="progress"><i style={{ width: `${r.progress}%` }}/></div></td><td><button className="iconBtn detailTrigger" aria-label={`${r.id} detay`} onClick={() => onOpen(r)}>›</button></td></tr>)}</tbody></table></div>; }
export function Dashboard({ user }: {
    user: {
        name: string;
        email: string;
    };
}) {
    const [view, setView] = useState<View>("dashboard");
    const [menu, setMenu] = useState(false);
    const [toast, setToast] = useState("");
    const [modal, setModal] = useState(false);
    const [dtc, setDtc] = useState("");
    const [requestRows, setRequestRows] = useState<RequestRow[]>(requests);
    const [selectedRequest, setSelectedRequest] = useState<RequestRow | null>(null);
    const [pendingCount, setPendingCount] = useState(0);
    const [customerFocus, setCustomerFocus] = useState("");
    const [branding, setBranding] = useState<BrandSettings>({ portal_name: "CHIP CENTER", logo_key: null, updated_at: 0 });
    const [alertsEnabled, setAlertsEnabled] = useState(() => typeof window === "undefined" ? true : liveAlertsEnabled());
    const knownRequestState = useRef<Map<string, string> | null>(null);
    const knownRegistrations = useRef<Set<string> | null>(null);
    const title = titles[view];
    const initials = user.name.split(/\s+/).filter(Boolean).slice(0, 2).map(part => part[0]).join("").toUpperCase() || "AD";
    useEffect(() => {
        function applyBranding(event: Event) { setBranding((event as CustomEvent<BrandSettings>).detail); }
        fetch("/api/customer-settings", { cache: "no-store" }).then(response => response.json() as Promise<BrandSettings>).then(setBranding).catch(() => undefined);
        window.addEventListener("portal-branding-updated", applyBranding);
        return () => window.removeEventListener("portal-branding-updated", applyBranding);
    }, []);
    useEffect(() => { let active = true; async function refresh() { try {
        const response = await fetch("/api/requests", { cache: "no-store" });
        const data = await response.json() as {
            requests?: Record<string, unknown>[];
        };
        if (!active)
            return;
        const incoming = (data.requests ?? []).map(row => { const status = String(row.status || "Bekliyor"); return { id: String(row.id), customer: String(row.customer), customerEmail: String(row.customer_email || ""), customerPhone: String(row.customer_phone || ""), vehicle: String(row.car), motor: String(row.engine), ecu: String(row.ecu), services: String(row.services).split(" + "), tuner: "Atanmadı", credit: Number(row.credits) || 0, status, cls: status === "Hazır" ? "ready" : status === "İşlemde" ? "processing" : "waiting", time: "00:00", progress: status === "Hazır" ? 100 : 5, incoming: true, fileName: String(row.file_name), fileSize: Number(row.file_size) || 0, vehicleIdName: String(row.vehicle_id_name || ""), vehicleIdSize: Number(row.vehicle_id_size) || 0, vehicleIdAvailable: Boolean(row.vehicle_id_available), createdAt: Number(row.created_at) || undefined, originalAvailable: Boolean(row.original_available), resultAvailable: Boolean(row.result_available), resultName: String(row.result_name || "") } satisfies RequestRow; });
        const latestState = new Map(incoming.map(item => [item.id, `${Boolean(item.originalAvailable)}:${Boolean(item.resultAvailable)}`]));
        if (knownRequestState.current) {
            for (const item of incoming) {
                const before = knownRequestState.current.get(item.id);
                if (!before)
                    sendLiveAlert("Yeni müşteri dosyası", `${item.customer} · ${item.vehicle} · ${item.fileName}`);
                else if (before.startsWith("false:") && item.originalAvailable)
                    sendLiveAlert("Original dosya geldi", `${item.id} · ${item.customer} · ${item.fileName}`);
            }
        }
        knownRequestState.current = latestState;
        setRequestRows([...incoming, ...requests.filter(base => !incoming.some(item => item.id === base.id))]);
        setSelectedRequest(current => current ? incoming.find(item => item.id === current.id) || current : current);
    }
    catch { } } void refresh(); const timer = window.setInterval(refresh, 5000); return () => { active = false; window.clearInterval(timer); }; }, []);
    useEffect(() => { let active = true; async function refresh() { try {
        const response = await fetch("/api/registrations", { cache: "no-store" });
        const data = await readApiResponse<{
            registrations: PendingRegistration[];
        }>(response);
        if (!active)
            return;
        const next = new Set(data.registrations.map(item => item.id));
        if (knownRegistrations.current) {
            const incoming = data.registrations.find(item => !knownRegistrations.current?.has(item.id));
            if (incoming)
                sendLiveAlert("Yeni müşteri kaydı", `${incoming.name} · Yönetici onayı bekliyor`);
        }
        knownRegistrations.current = next;
        setPendingCount(data.registrations.length);
    }
    catch { } } void refresh(); const timer = window.setInterval(refresh, 5000); return () => { active = false; window.clearInterval(timer); }; }, []);
    useEffect(() => { if (!selectedRequest)
        return; function closeOnEscape(event: KeyboardEvent) { if (event.key === "Escape")
        setSelectedRequest(null); } window.addEventListener("keydown", closeOnEscape); return () => window.removeEventListener("keydown", closeOnEscape); }, [selectedRequest]);
    function notify(s: string) { setToast(s); setTimeout(() => setToast(""), 2400); }
    async function toggleAlerts() { if (alertsEnabled) {
        setAlertsEnabled(false);
        notify(disableLiveAlerts());
        return;
    } const message = await enableLiveAlerts(); setAlertsEnabled(true); notify(message); }
    function updateRequest(updated: RequestRow) { setRequestRows(current => current.map(item => item.id === updated.id ? updated : item)); setSelectedRequest(updated); }
    function go(v: View) { setView(v); setMenu(false); }
    function openSearchResult(result: AdminSearchResult) {
        if (result.kind === "customer") { setCustomerFocus(result.id); go("customers"); return; }
        if (result.kind === "request") { go("requests"); const request = requestRows.find(item => item.id === result.id); if (request) setSelectedRequest(request); return; }
        setDtc(result.query); go("dtc");
    }
    return <div className="app">
  <aside className={`sidebar ${menu ? "open" : ""}`}><div className="brand"><img src={branding.logo_key ? `/api/customer-settings/logo?v=${branding.updated_at}` : "/chipcenter-logo.png"} alt={branding.portal_name}/></div>{nav.map(([group, items]) => <div className="navGroup" key={group}><div className="navTitle">{group}</div>{items.map(n => <button className={`navItem ${view === n.view ? "active" : ""}`} onClick={() => go(n.view)} key={n.view}><span className="navIcon">{n.icon}</span>{n.label}{n.view === "customers" && pendingCount > 0 ? <span className="navBadge">{pendingCount}</span> : n.badge && <span className="navBadge">{n.badge}</span>}</button>)}</div>)}<div className="sidebarFoot"><div className="openNow"><span className="openDot"/>Şu anda açığız</div><div className="hours">Bugün · 08:00—22:00</div></div></aside>
  <main className="main"><header className="header"><button className="iconBtn menuBtn" onClick={() => setMenu(!menu)}>☰</button><AdminGlobalSearch onSelect={openSearchResult}/><div className="headerActions"><button className="iconBtn" aria-pressed={alertsEnabled} onClick={() => void toggleAlerts()}>{alertsEnabled ? "🔔 Bildirimleri kapat" : "🔕 Bildirimleri aç"}</button><LogoutButton /><div className="avatar" title={user.email}>{initials}</div></div></header>
  <div className="content"><div className="pageHead"><div><div className="eyebrow">{branding.portal_name} · ADMIN</div><h1>{title[0]}</h1><p>{title[1]}</p></div><div className="datePill">10 Ağustos 2026 · Pazartesi</div></div>
  <div className="view" key={view}>{view === "dashboard" && <DashboardHome go={go} items={requestRows} onOpen={setSelectedRequest}/>} {view === "requests" && <Requests items={requestRows} onOpen={setSelectedRequest}/>} {view === "tuners" && <Tuners notify={notify}/>} {view === "customers" && <Customers notify={notify} onCount={setPendingCount} focusId={customerFocus}/>} {view === "services" && <Services notify={notify}/>} {view === "support" && <Support notify={notify}/>} {view === "dtc" && <Dtc value={dtc} setValue={setDtc}/>} {view === "settings" && <Settings save={() => notify("Ayarlar başarıyla kaydedildi")} alertsEnabled={alertsEnabled} toggleAlerts={() => void toggleAlerts()}/>}</div></div></main>
  <nav className="mobileNav"><button onClick={() => go("dashboard")}><span>⌂</span>Ana Sayfa</button><button onClick={() => go("requests")}><span>◆</span>Dosyalar</button><button onClick={() => go("services")}><span>₺</span>Krediler</button><button onClick={() => go("support")}><span>◈</span>Destek</button><button onClick={() => go("settings")}><span>●</span>Hesabım</button></nav>
  {toast && <div className="toast">✓ {toast}</div>}{modal && <div className="modalBack"><div className="modal"><h2>Yeni müşteri ekle</h2><p>Müşteri hesabı oluşturulduğunda giriş bilgileri güvenli e-posta ile iletilir.</p><div className="field"><label>Firma / Tam Adı</label><input placeholder="Örn. Atlas Garage"/></div><div className="field" style={{ marginTop: 12 }}><label>E-posta</label><input placeholder="servis@firma.com"/></div><div className="modalActions"><button className="secondaryBtn" onClick={() => setModal(false)}>Vazgeç</button><button className="primaryBtn" onClick={() => { setModal(false); notify("Müşteri hesabı oluşturuldu"); }}>Müşteriyi oluştur</button></div></div></div>}
  <UpdateCenter/>{selectedRequest && <RequestDetail request={selectedRequest} onClose={() => setSelectedRequest(null)} onUpdated={updateRequest} notify={notify}/>}
  </div>;
}
function RequestDetail({ request, onClose, onUpdated, notify }: {
    request: RequestRow;
    onClose: () => void;
    onUpdated: (request: RequestRow) => void;
    notify: (message: string) => void;
}) {
    const resultInput = useRef<HTMLInputElement>(null);
    const [resultFile, setResultFile] = useState<File | null>(null);
    const [sending, setSending] = useState(false);
    const [error, setError] = useState("");
    const [sendPercent, setSendPercent] = useState(0);
    const fileSize = request.fileSize ? `${(request.fileSize / 1024 / 1024).toFixed(2)} MB` : "Boyut bilgisi alınamadı";
    const created = request.createdAt ? new Intl.DateTimeFormat("tr-TR", { dateStyle: "long", timeStyle: "short" }).format(new Date(request.createdAt)) : "10 Ağustos 2026 · Az önce";
    async function sendResult() {
        if (!resultFile)
            return;
        if (resultFile.size > MAX_FILE_SIZE) {
            setError(`Dosya boyutu ${MAX_FILE_SIZE_LABEL} sınırını aşıyor`);
            return;
        }
        setSending(true);
        setError("");
        setSendPercent(0);
        try {
            const upload = await uploadFileChunks(resultFile, request.id, "result", setSendPercent);
            const response = await fetch(`/api/requests/${encodeURIComponent(request.id)}/result`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileName: resultFile.name, fileSize: resultFile.size, mime: resultFile.type || "application/octet-stream", ...upload }) });
            await readApiResponse(response);
            const updated = { ...request, status: "Hazır", cls: "ready", progress: 100, resultAvailable: true, resultName: resultFile.name };
            onUpdated(updated);
            setResultFile(null);
            notify(`${request.id} düzenlenmiş dosyası müşteriye gönderildi`);
        }
        catch (caught) {
            setError(caught instanceof Error ? caught.message : "Dosya gönderilemedi");
        }
        finally {
            setSending(false);
        }
    }
    return <div className="modalBack requestDetailBack" role="presentation" onMouseDown={event => { if (event.target === event.currentTarget)
        onClose(); }}><section className="requestDetailModal" role="dialog" aria-modal="true" aria-labelledby="request-detail-title"><div className="detailHeader"><div><span className="eyebrow">DOSYA TALEBİ</span><h2 id="request-detail-title">{request.id}</h2><p>{created}</p></div><button className="iconBtn detailClose" aria-label="Detayı kapat" onClick={onClose}>×</button></div><div className="detailStatus"><Badge r={request}/><span>{!request.originalAvailable ? "Müşterinin original dosyası bekleniyor" : request.status === "Hazır" ? "Düzenlenmiş dosya müşteriye gönderildi" : request.incoming ? "Müşteriden yeni gönderildi" : "Operasyon kaydı"}</span></div><div className="detailGrid"><div className="detailItem"><span>Müşteri</span><strong>{request.customer}</strong><small>{request.customerEmail || "E-posta yok"} · {request.customerPhone || "Telefon yok"}</small></div><div className="detailItem"><span>Araç</span><strong>{request.vehicle}</strong><small>{request.motor}</small></div><div className="detailItem"><span>ECU / TCU</span><strong>{request.ecu}</strong></div><div className="detailItem"><span>Tuner</span><strong>{request.tuner}</strong></div></div><div className="detailSection"><span className="detailLabel">İstenen servisler</span><div>{request.services.map(service => <span className="service detailService" key={service}>{service}</span>)}</div></div><div className={`detailFile ${request.originalAvailable ? "" : "missingFile"}`}><span className="detailFileIcon">BIN</span><div><span className="detailLabel">Müşterinin original dosyası</span><strong>{request.fileName || "Dosya bilgisi bulunmuyor"}</strong><small>{request.originalAvailable ? `${fileSize} · İndirmeye hazır` : "Bu eski talepte dosyanın içeriği saklanmamış; müşteri panelinden tekrar yüklenmeli."}</small></div>{request.originalAvailable ? <a className="secondaryBtn downloadLink" href={`/api/requests/${encodeURIComponent(request.id)}/file?kind=original`} download>Originali indir</a> : <span className="fileMissing">YENİDEN YÜKLENMELİ</span>}</div><div className={`detailFile ${request.vehicleIdAvailable ? "" : "missingFile"}`}><span className="detailFileIcon">ID</span><div><span className="detailLabel">Araç / motor ID dosyası</span><strong>{request.vehicleIdName || "ID dosyası bulunmuyor"}</strong><small>{request.vehicleIdAvailable ? `${request.vehicleIdSize ? `${(request.vehicleIdSize / 1024 / 1024).toFixed(2)} MB` : "Boyut bilgisi yok"} · İndirmeye hazır` : "Yeni taleplerde ID dosyası zorunludur."}</small></div>{request.vehicleIdAvailable ? <a className="secondaryBtn downloadLink" href={`/api/requests/${encodeURIComponent(request.id)}/file?kind=vehicle-id`} download>ID dosyasını indir</a> : <span className="fileMissing">DOSYA YOK</span>}</div><div className={`resultUpload ${!request.originalAvailable ? "blockedUpload" : ""}`}><div><span className="detailLabel">Düzenlenmiş dosyayı müşteriye gönder</span><p>{request.resultAvailable ? `Son gönderilen: ${request.resultName}` : "Dosyayı düzenledikten sonra buradan yükleyin. Talep ancak gönderim tamamlanınca Hazır olur."}</p></div>{request.resultAvailable && <a className="secondaryBtn downloadLink resultDownload" href={`/api/requests/${encodeURIComponent(request.id)}/file?kind=result`} download>Gönderilen dosyayı indir</a>}{!request.originalAvailable ? <div className="uploadBlocked">Önce müşteri panelindeki <strong>“Originali yeniden yükle”</strong> düğmesiyle gerçek dosya bu talebe eklenmeli.</div> : <><input ref={resultInput} className="hiddenFileInput" type="file" onChange={event => { setResultFile(event.target.files?.[0] || null); setError(""); event.target.value = ""; }}/><div className="resultActions"><button className="secondaryBtn" disabled={sending} onClick={() => resultInput.current?.click()}>{resultFile ? "Dosyayı değiştir" : "Düzenlenmiş dosyayı seç"}</button>{resultFile && <><span className="resultFileName">{resultFile.name}</span><button className="primaryBtn" disabled={sending} onClick={() => void sendResult()}>{sending ? `Müşteriye gönderiliyor… %${sendPercent}` : "Müşteriye gönder"}</button></>}</div></>}{error && <div className="formError">{error}</div>}</div><div className="detailFooter"><div><span className="detailLabel">Rezerve edilen kredi</span><strong>{request.credit} kredi</strong></div><button className="secondaryBtn" onClick={onClose}>Kapat</button></div></section></div>;
}
function DashboardHome({ go, items, onOpen }: {
    go: (v: View) => void;
    items: RequestRow[];
    onOpen: (request: RequestRow) => void;
}) { const incoming = items.filter(item => item.incoming); const vals = [["Bugünkü dosyalar", String(24 + incoming.length), "↑ %18", "◆"], ["Bekleyen dosyalar", String(12 + incoming.length), incoming.length ? `${incoming.length} yeni talep` : "3 öncelikli", "◷"], ["Aylık ciro", "₺184.250", "↑ %12,4", "₺"], ["Aktif müşteriler", "286", "21 çevrimiçi", "●"]]; return <>{incoming[0] && <button className="incomingNotice" onClick={() => onOpen(incoming[0])}><span className="noticeIcon">↓</span><div><strong>Yeni müşteri dosyası geldi</strong><small>{incoming[0].id} · {incoming[0].customer} · {incoming[0].vehicle} · {incoming[0].fileName}</small></div><span className="badge waiting">İNCELE</span></button>}<div className="kpis">{vals.map(v => <div className="kpi" key={v[0]}><div className="kpiTop"><span>{v[0]}</span><span className="kpiIcon">{v[3]}</span></div><div className="kpiValue">{v[1]}</div><div className="delta">{v[2]}</div></div>)}</div><div className="grid2"><div className="card"><div className="cardHead"><div><h2>Son 30 gün dosya talepleri</h2><span className="muted">Toplam 438 talep · %96,2 zamanında</span></div><button className="secondaryBtn">30 gün⌄</button></div><div className="chart">{[32, 46, 41, 66, 53, 74, 62, 88, 58, 78, 92, 71, 95, 83, 100, 76, 91, 64, 86, 73, 94, 79, 88, 68, 96, 84, 72, 90, 81, 98].map((x, i) => <div className="bar" style={{ height: `${x}%` }} key={i}/>)}</div></div><div className="card"><div className="cardHead"><h2>Canlı aktivite</h2><span className="badge ready">CANLI</span></div>{incoming[0] && <div className="activity"><span className="actIcon">↓</span><div className="actText">{incoming[0].customer} yeni dosya yükledi<span className="actTime">Az önce</span></div></div>}{[["⬆", "Ozan yeni bir BMW dosyası yükledi", "14:42"], ["⚙", "Ahmet, CC-001242 talebini işleme aldı", "14:38"], ["✓", "Audi A3 dosyası tamamlandı", "14:31"], ["₺", "Atlas Garage 250 kredi satın aldı", "14:18"]].map(a => <div className="activity" key={a[2]}><span className="actIcon">{a[0]}</span><div className="actText">{a[1]}<span className="actTime">{a[2]}</span></div></div>)}</div></div><div className="card section"><div className="cardHead"><div><h2>Aktif dosya talepleri</h2><span className="muted">Müşteri tarafından gönderilen işler · Öncelik ve SLA durumuna göre sıralı</span></div><div className="pageTools"><button className="secondaryBtn" onClick={() => go("requests")}>Tümünü gör</button></div></div><RequestTable items={items} onOpen={onOpen}/></div></>; }
function Requests({ items, onOpen }: {
    items: RequestRow[];
    onOpen: (request: RequestRow) => void;
}) { return <div className="card"><div className="cardHead"><div><h2>Tüm dosya talepleri</h2><span className="muted">{items.length} kayıt · {items.filter(item => item.status === "Yeni talep" || item.status === "Bekliyor").length} bekleyen</span></div><button className="primaryBtn">Dışa aktar</button></div><div className="filters"><button className="filter">Durum: Tümü⌄</button><button className="filter">Tuner: Tümü⌄</button><button className="filter">Marka: Tümü⌄</button><button className="filter">Servis⌄</button><button className="filter">Tarih aralığı⌄</button></div><RequestTable all items={items} onOpen={onOpen}/></div>; }
function Field({ label, children }: {
    label: string;
    children: React.ReactNode;
}) { return <div className="field"><label>{label}</label>{children}</div>; }
function Tuners({ notify }: {
    notify: (s: string) => void;
}) { return <CardsList data={[["Ahmet Kaya", "Bosch EDC17 · MD1/MG1", "8 aktif iş · %98 SLA"], ["Burak Tunç", "BMW · VAG Simos", "5 aktif iş · %96 SLA"], ["Selin Aras", "TCU · DSG · ZF", "3 aktif iş · %99 SLA"]]} action="Yeni tuner" notify={notify}/>; }
function Customers({ notify, onCount, focusId }: { notify: (s: string) => void; onCount: (count: number) => void; focusId: string }) {
    return <AdminCustomerPanel notify={notify} onCount={onCount} focusId={focusId}/>;
}
function LegacyCustomers({ notify, onCount }: {
    notify: (s: string) => void;
    onCount: (count: number) => void;
}) {
    const [customers, setCustomers] = useState<AdminCustomer[]>([]);
    const [summary, setSummary] = useState<AdminCustomerSummary>({ customerCount: 0, activeCustomerCount: 0, pendingCustomerCount: 0, requestCount: 0, fileCount: 0, storedBytes: 0, supportCount: 0, chatCount: 0, availableCredits: 0, reservedCredits: 0 });
    const [selected, setSelected] = useState<AdminCustomer | null>(null);
    const [search, setSearch] = useState("");
    const [busy, setBusy] = useState("");
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(true);
    async function load() { try {
        const response = await fetch("/api/admin/customers", { cache: "no-store" });
        const data = await readApiResponse<{
            customers: AdminCustomer[];
            summary: AdminCustomerSummary;
        }>(response);
        setCustomers(data.customers);
        setSummary(data.summary);
        setSelected(current => current ? data.customers.find(item => item.id === current.id) || null : null);
        onCount(data.summary.pendingCustomerCount);
        setError("");
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Müşteri veritabanı alınamadı");
    }
    finally {
        setLoading(false);
    } }
    useEffect(() => { void load(); const timer = window.setInterval(load, 5000); return () => window.clearInterval(timer); }, []);
    async function decide(item: AdminCustomer, action: "approve" | "reject") { setBusy(item.id); setError(""); try {
        const response = await fetch("/api/registrations", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: item.id, action }) });
        const data = await readApiResponse<{
            deliveries?: {
                channel: string;
                status: string;
            }[];
        }>(response);
        await load();
        if (action === "approve") {
            const sent = data.deliveries?.filter(delivery => delivery.status === "sent").map(delivery => delivery.channel).join(" + ");
            notify(sent ? `${item.name} onaylandı · ${sent} bildirimi gönderildi` : `${item.name} onaylandı · bildirim sağlayıcısı ayarı bekleniyor`);
        }
        else
            notify(`${item.name} kaydı reddedildi`);
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Kayıt işlemi tamamlanamadı");
    }
    finally {
        setBusy("");
    } }
    const pending = customers.filter(customer => customer.status === "PENDING_APPROVAL");
    const query = search.toLocaleLowerCase("tr");
    const visible = customers.filter(customer => [customer.name, customer.company || "", customer.email, customer.phone || "", customer.status].join(" ").toLocaleLowerCase("tr").includes(query));
    return <div className="customerAdminPage"><section className="databaseOverview"><article><span>MÜŞTERİ HESAPLARI</span><strong>{summary.customerCount}</strong><small>{summary.activeCustomerCount} aktif · {summary.pendingCustomerCount} bekleyen</small></article><article><span>DOSYA TALEPLERİ</span><strong>{summary.requestCount}</strong><small>Tüm müşteri talepleri</small></article><article><span>KAYITLI DOSYALAR</span><strong>{summary.fileCount}</strong><small>{formatDataBytes(summary.storedBytes)} metadata + güvenli depolama</small></article><article><span>KREDİ CÜZDANLARI</span><strong>{summary.availableCredits}</strong><small>{summary.reservedCredits} kredi rezerve</small></article><article><span>DESTEK KAYITLARI</span><strong>{summary.supportCount}</strong><small>{summary.chatCount} canlı sohbet</small></article></section><section className="card dataRegistryInfo"><div><span className="registryIcon">DB</span><div><h2>Merkezi veri kayıt sistemi</h2><p>Hesaplar, krediler, talepler, dosya bilgileri, destek ve sohbetler D1 veritabanında; dosya içerikleri ise büyük dosyalara uygun güvenli R2 deposunda tutulur.</p></div></div><span className="badge ready">SİSTEMATİK KAYIT AKTİF</span></section><section className="card approvalQueue"><div className="cardHead"><div><h2>Yeni kayıt onayları</h2><span className="muted">Onaylanan müşteriler giriş yapabilir; onay sonucu e-posta ile iletilir.</span></div><span className={`badge ${pending.length ? "waiting" : "ready"}`}>{pending.length ? `${pending.length} ONAY BEKLİYOR` : "TÜMÜ TAMAM"}</span></div>{error && <div className="formError">{error}</div>}{pending.length ? <div className="approvalList">{pending.map(item => <article className="approvalRow" key={item.id}><span className="avatar">{item.name.slice(0, 1).toUpperCase()}</span><div className="approvalIdentity"><strong>{item.company || item.name}</strong><small>{item.name} · {item.email}</small><small>{item.phone || "Telefon eklenmemiş"} · {formatCustomerDate(item.created_at)}</small></div><div className="approvalActions"><button className="secondaryBtn rejectApproval" disabled={busy === item.id} onClick={() => void decide(item, "reject")}>Reddet</button><button className="primaryBtn" disabled={busy === item.id} onClick={() => void decide(item, "approve")}>{busy === item.id ? "İşleniyor…" : "Onayla ve bildir"}</button></div></article>)}</div> : <div className="emptyOrders compactEmpty"><span>✓</span><strong>Bekleyen müşteri kaydı yok</strong><p>Yeni kayıtlar burada incelemenize sunulacak.</p></div>}</section><section className="card customerDatabaseCard"><div className="cardHead"><div><h2>Veritabanındaki müşteriler</h2><span className="muted">{customers.length} gerçek hesap · örnek müşteri bulunmuyor</span></div><div className="customerDbTools"><input value={search} onChange={event => setSearch(event.target.value)} placeholder="Ad, e-posta veya telefon ara…"/><button className="secondaryBtn" onClick={() => void load()}>Yenile</button></div></div>{loading ? <div className="chatLoading">Müşteri kayıtları yükleniyor…</div> : visible.length ? <div className="customerDbTable"><div className="customerDbHeader"><span>MÜŞTERİ</span><span>DURUM</span><span>KREDİ</span><span>TALEP / DOSYA</span><span>DESTEK</span><span>SON AKTİVİTE</span><span /></div>{visible.map(customer => { const lastActivity = Math.max(customer.last_request_at || 0, customer.last_chat_at || 0, customer.last_session_at || 0, customer.created_at); return <button className="customerDbRow" key={customer.id} onClick={() => setSelected(customer)}><span className="customerDbIdentity"><i>{customer.name.slice(0, 1).toUpperCase()}</i><span><strong>{customer.company || customer.name}</strong><small>{customer.email}</small><small>{customer.phone || "Telefon eklenmemiş"}</small></span></span><span><b className={`customerStatus ${customer.status.toLowerCase()}`}>{customerStatusLabel(customer.status)}</b><small>{customer.auth_providers || "Hesap sağlayıcısı yok"}</small></span><span><strong>{customer.available_credits}</strong><small>{customer.reserved_credits} rezerve</small></span><span><strong>{customer.request_count} / {customer.stored_file_count}</strong><small>{formatDataBytes(customer.stored_file_bytes)}</small></span><span><strong>{customer.support_count} / {customer.chat_count}</strong><small>talep / sohbet</small></span><span><strong>{formatCustomerDate(lastActivity)}</strong><small>Kayıt: {formatCustomerDate(customer.created_at)}</small></span><span className="rowArrow">›</span></button>; })}</div> : <div className="emptyOrders"><span>◇</span><strong>Müşteri bulunamadı</strong><p>Arama ölçütünü değiştirin.</p></div>}</section>{selected && <div className="modalBack customerDataBack" role="presentation" onMouseDown={event => { if (event.target === event.currentTarget)
        setSelected(null); }}><section className="customerDataModal" role="dialog" aria-modal="true"><div className="detailHeader"><div><span className="eyebrow">VERİTABANI MÜŞTERİ KAYDI</span><h2>{selected.company || selected.name}</h2><p>{selected.email}</p></div><button className="iconBtn detailClose" onClick={() => setSelected(null)}>×</button></div><div className="customerRecordId"><span>Hesap kimliği</span><code>{selected.id}</code></div><div className="customerRecordGrid"><article><span>Hesap durumu</span><strong>{customerStatusLabel(selected.status)}</strong><small>{selected.auth_providers || "Sağlayıcı yok"}</small></article><article><span>Kredi cüzdanı</span><strong>{selected.available_credits} kullanılabilir</strong><small>{selected.reserved_credits} rezerve · {selected.paid_credits} satın alınan</small></article><article><span>Dosya talepleri</span><strong>{selected.request_count} toplam</strong><small>{selected.completed_request_count} tamamlanan</small></article><article><span>Dosya deposu</span><strong>{selected.stored_file_count} dosya</strong><small>{formatDataBytes(selected.stored_file_bytes)} kayıtlı</small></article><article><span>Destek</span><strong>{selected.support_count} talep</strong><small>{selected.open_support_count} açık · {selected.chat_count} sohbet</small></article><article><span>Ödemeler</span><strong>{selected.payment_count} kayıt</strong><small>PayTR ve kredi hareketleri</small></article><article><span>İletişim</span><strong>{selected.phone || "Telefon eklenmemiş"}</strong><small>{selected.email}</small></article><article><span>Tarihler</span><strong>{formatCustomerDate(selected.created_at)}</strong><small>Son giriş: {selected.last_session_at ? formatCustomerDate(selected.last_session_at) : "Henüz yok"}</small></article></div><div className="detailFooter"><div><span className="detailLabel">Dosya içerikleri</span><strong>Güvenli R2 deposu · metadata D1 veritabanı</strong></div><button className="secondaryBtn" onClick={() => setSelected(null)}>Kapat</button></div></section></div>}</div>;
}
function formatDataBytes(value: number) { if (!value)
    return "0 B"; const units = ["B", "KB", "MB", "GB", "TB"]; const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1); return `${(value / 1024 ** index).toFixed(index ? 1 : 0)} ${units[index]}`; }
function formatCustomerDate(value: number) { return new Intl.DateTimeFormat("tr-TR", { dateStyle: "short", timeStyle: "short" }).format(new Date(value)); }
function customerStatusLabel(value: string) { return value === "ACTIVE" ? "Aktif" : value === "PENDING_APPROVAL" ? "Onay bekliyor" : value === "REJECTED" ? "Reddedildi" : value; }
function CardsList({ data, action, notify }: {
    data: string[][];
    action: string;
    notify: (s: string) => void;
}) { return <div className="card"><div className="cardHead"><div><h2>{action.replace("Yeni ", "")} listesi</h2><span className="muted">Aktif kayıtlar ve operasyon özeti</span></div><button className="primaryBtn" onClick={() => notify(`${action} formu hazır`)}>＋ {action}</button></div>{data.map(d => <div className="activity" key={d[0]}><span className="avatar">{d[0][0]}</span><div className="actText"><b>{d[0]}</b><span className="actTime">{d[1]}</span></div><span style={{ marginLeft: "auto" }} className="muted">{d[2]}</span><button className="iconBtn">›</button></div>)}</div>; }
type CatalogService = {
    id: string;
    name: string;
    category: string;
    credits: number;
    estimated_minutes: number;
    active: number;
};
function Services({ notify }: {
    notify: (s: string) => void;
}) {
    const [items, setItems] = useState<CatalogService[]>([]);
    const [name, setName] = useState("");
    const [credits, setCredits] = useState("4");
    const [category, setCategory] = useState("Motor Yazılımı");
    const [search, setSearch] = useState("");
    const [busy, setBusy] = useState("");
    const [error, setError] = useState("");
    const [draftCredits, setDraftCredits] = useState<Record<string, string>>({});
    async function load() { try {
        const response = await fetch("/api/services", { cache: "no-store" });
        const data = await readApiResponse<{
            services: CatalogService[];
        }>(response);
        setItems(data.services);
        setDraftCredits(Object.fromEntries(data.services.map(service => [service.id, String(service.credits)])));
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Hizmetler alınamadı");
    } }
    useEffect(() => { void load(); }, []);
    async function add() { if (!name.trim())
        return; setBusy("add"); setError(""); try {
        const response = await fetch("/api/services", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, credits: Number(credits), category }) });
        const data = await readApiResponse<{
            service: CatalogService;
        }>(response);
        setItems(current => [...current.filter(item => item.id !== data.service.id), data.service].sort((a, b) => a.name.localeCompare(b.name, "tr")));
        setDraftCredits(current => ({ ...current, [data.service.id]: String(data.service.credits) }));
        setName("");
        setCredits("4");
        notify(`${data.service.name} hizmeti eklendi`);
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Hizmet eklenemedi");
    }
    finally {
        setBusy("");
    } }
    async function saveCredit(service: CatalogService) { const value = Number(draftCredits[service.id]); setBusy(service.id); setError(""); try {
        const response = await fetch(`/api/services/${encodeURIComponent(service.id)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ credits: value }) });
        const data = await readApiResponse<{
            service: CatalogService;
        }>(response);
        setItems(current => current.map(item => item.id === service.id ? data.service : item));
        setDraftCredits(current => ({ ...current, [service.id]: String(data.service.credits) }));
        notify(`${service.name} kredisi ${data.service.credits} olarak güncellendi`);
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Kredi güncellenemedi");
    }
    finally {
        setBusy("");
    } }
    async function remove(service: CatalogService) { if (!window.confirm(`${service.name} hizmetini kaldırmak istiyor musunuz?`))
        return; setBusy(service.id); setError(""); try {
        const response = await fetch(`/api/services/${encodeURIComponent(service.id)}`, { method: "DELETE" });
        await readApiResponse(response);
        setItems(current => current.filter(item => item.id !== service.id));
        notify(`${service.name} hizmeti kaldırıldı`);
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Hizmet kaldırılamadı");
    }
    finally {
        setBusy("");
    } }
    const visible = items.filter(service => service.name.toLocaleLowerCase("tr").includes(search.toLocaleLowerCase("tr")) || service.category.toLocaleLowerCase("tr").includes(search.toLocaleLowerCase("tr")));
    return <div className="serviceAdminPage"><section className="card addServiceCard"><div className="serviceSectionTitle"><span>⊕</span><div><h2>Yeni hizmet ekle</h2><p>Müşterilerin seçebileceği ECU/TCU, motor veya motosiklet yazılım hizmeti oluşturun.</p></div></div><div className="addServiceForm"><div className="field"><label>Hizmet adı</label><input value={name} onChange={event => setName(event.target.value)} placeholder="Örn. Lambda OFF" onKeyDown={event => { if (event.key === "Enter")
        void add(); }}/></div><div className="field"><label>Kategori</label><select value={category} onChange={event => setCategory(event.target.value)}><option>Motor Yazılımı</option><option>Motosiklet Yazılımı</option><option>Performance</option><option>Emission</option><option>Gearbox</option><option>Utility</option><option>Custom</option></select></div><div className="field"><label>Kredi</label><input type="number" min="1" max="999" value={credits} onChange={event => setCredits(event.target.value)} onKeyDown={event => { if (event.key === "Enter")
        void add(); }}/></div><button className="primaryBtn addServiceButton" disabled={busy === "add" || !name.trim()} onClick={() => void add()}>{busy === "add" ? "Ekleniyor…" : "＋ Hizmeti ekle"}</button></div></section><section className="card serviceListCard"><div className="cardHead serviceCatalogHead"><div><h2>Tüm hizmetler</h2><span className="muted">{items.length} aktif hizmet · Otomobil ve motosiklet hizmetlerinin kredi değerlerini düzenleyebilirsiniz.</span></div><input className="serviceSearch" value={search} onChange={event => setSearch(event.target.value)} placeholder="Hizmet veya kategori ara…"/></div>{error && <div className="formError serviceError">{error}</div>}<div className="serviceAdminTable"><div className="serviceAdminHeader"><span>HİZMET ADI</span><span>KATEGORİ</span><span>KREDİ</span><span>İŞLEM</span></div>{visible.map(service => <div className="serviceAdminRow" key={service.id}><div><strong>{service.name}</strong><small>Ortalama {service.estimated_minutes} dakika</small></div><span className={`serviceCategory ${service.category === "Motor Yazılımı" ? "motorCategory" : service.category === "Motosiklet Yazılımı" ? "motoCategory" : ""}`}>{service.category}</span><div className="creditEditor"><input aria-label={`${service.name} kredi`} type="number" min="1" max="999" value={draftCredits[service.id] ?? service.credits} onChange={event => setDraftCredits(current => ({ ...current, [service.id]: event.target.value }))} onKeyDown={event => { if (event.key === "Enter")
        void saveCredit(service); }}/><button className="secondaryBtn" disabled={busy === service.id || Number(draftCredits[service.id]) === service.credits} onClick={() => void saveCredit(service)}>{busy === service.id ? "…" : "Kaydet"}</button></div><button className="deleteServiceBtn" disabled={busy === service.id} aria-label={`${service.name} hizmetini sil`} onClick={() => void remove(service)}>⌫</button></div>)}{!visible.length && <div className="emptyServices">Aramanıza uygun hizmet bulunamadı.</div>}</div></section></div>;
}
function Support({ notify }: {
    notify: (s: string) => void;
}) {
    const [conversations, setConversations] = useState<ChatConversation[]>([]);
    const [conversation, setConversation] = useState<ChatConversation | null>(null);
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [activeId, setActiveId] = useState("");
    const [draft, setDraft] = useState("");
    const [loading, setLoading] = useState(true);
    const [sending, setSending] = useState(false);
    const [error, setError] = useState("");
    const messagesEnd = useRef<HTMLDivElement>(null);
    const knownConversationState = useRef<Map<string, string> | null>(null);
    async function applyPayload(response: Response, announce = true) { const payload = await readApiResponse<ChatPayload>(response); const nextState = new Map(payload.conversations.map(item => [item.id, `${item.last_message_at}:${item.staff_unread}`])); if (announce && knownConversationState.current) {
        const incoming = payload.conversations.find(item => item.staff_unread > 0 && knownConversationState.current?.get(item.id) !== nextState.get(item.id));
        if (incoming) {
            sendLiveAlert("Yeni canlı destek mesajı", `${incoming.customer_company || incoming.customer_name}: ${incoming.last_message || "Yeni mesaj"}`);
            notify("Müşteriden yeni canlı destek mesajı geldi");
        }
    } knownConversationState.current = nextState; setConversations(payload.conversations); setConversation(payload.conversation); setMessages(payload.messages); if (payload.conversation) {
        if (!activeId)
            setActiveId(payload.conversation.id);
        if (payload.conversation.staff_unread)
            void fetch("/api/live-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "read", conversationId: payload.conversation.id }) });
    } }
    useEffect(() => { let active = true; async function refresh() { try {
        const query = activeId ? `?conversationId=${encodeURIComponent(activeId)}` : "";
        const response = await fetch(`/api/live-chat${query}`, { cache: "no-store" });
        if (!active)
            return;
        await applyPayload(response);
        setError("");
    }
    catch (caught) {
        if (active)
            setError(caught instanceof Error ? caught.message : "Canlı destek bağlantısı kurulamadı");
    }
    finally {
        if (active)
            setLoading(false);
    } } void refresh(); const timer = window.setInterval(refresh, 2000); return () => { active = false; window.clearInterval(timer); }; }, [activeId]);
    useEffect(() => { messagesEnd.current?.scrollIntoView({ behavior: "smooth", block: "end" }); }, [messages.length]);
    async function action(actionName: "message" | "close") { if (!conversation || (actionName === "message" && !draft.trim()))
        return; setSending(true); setError(""); try {
        const response = await fetch("/api/live-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: actionName, conversationId: conversation.id, message: draft }) });
        await applyPayload(response, false);
        if (actionName === "message") {
            setDraft("");
            notify("Mesajınız müşteriye gönderildi");
        }
        else {
            notify("Canlı destek görüşmesi kapatıldı");
            setActiveId("");
        }
    }
    catch (caught) {
        setError(caught instanceof Error ? caught.message : "Mesaj gönderilemedi");
    }
    finally {
        setSending(false);
    } }
    const openCount = conversations.filter(item => item.status === "OPEN").length;
    const unread = conversations.reduce((sum, item) => sum + item.staff_unread, 0);
    return <div className="adminChatLayout"><section className="card chatInbox"><div className="cardHead"><div><h2>Canlı destek görüşmeleri</h2><span className="muted">{openCount} açık görüşme · {unread} okunmamış mesaj</span></div><span className="onlineState"><i /> ÇEVRİMİÇİ</span></div><div className="chatConversationList">{loading && !conversations.length ? <div className="chatLoading">Görüşmeler yükleniyor…</div> : conversations.length ? conversations.map(item => <button key={item.id} className={`chatConversation ${conversation?.id === item.id ? "active" : ""}`} onClick={() => setActiveId(item.id)}><span className="avatar">{item.customer_name.slice(0, 1).toUpperCase()}</span><span><strong>{item.customer_company || item.customer_name}</strong><small>{item.last_message || "Yeni görüşme başlatıldı"}</small></span><time>{chatListTime(item.last_message_at)}</time>{item.staff_unread > 0 && <b>{item.staff_unread}</b>}</button>) : <div className="emptyOrders compactEmpty"><span>✓</span><strong>Bekleyen canlı destek yok</strong><p>Müşteri görüşme başlattığında burada görünecek.</p></div>}</div></section><section className="card liveChatCard adminChatCard">{!conversation ? <div className="chatStart"><span>◈</span><strong>Bir görüşme seçin</strong><p>Müşteriyle aynı ekran üzerinden canlı mesajlaşın.</p></div> : <><div className="liveChatHead"><div><span className="onlineState"><i /> {conversation.status === "OPEN" ? "AKTİF GÖRÜŞME" : "KAPALI GÖRÜŞME"}</span><h2>{conversation.customer_company || conversation.customer_name}</h2><p>{conversation.customer_name} · {conversation.customer_email}</p></div>{conversation.status === "OPEN" && <button className="secondaryBtn chatCloseBtn" disabled={sending} onClick={() => void action("close")}>Görüşmeyi kapat</button>}</div><div className="chatMessages" aria-live="polite">{!messages.length && <div className="chatWelcome"><strong>Henüz mesaj yok</strong><span>Müşteri mesaj gönderdiğinde burada görünecek.</span></div>}{messages.map(message => <div key={message.id} className={`chatBubbleRow ${isStaffRole(message.sender_role) ? "mine" : "theirs"}`}><div className="chatBubble"><div><strong>{isStaffRole(message.sender_role) ? "Siz" : message.sender_name}</strong><time>{formatAdminChatTime(message.created_at)}</time></div><p>{message.body}</p>{isStaffRole(message.sender_role) && <span className={`chatReceipt ${message.read_at ? "read" : "sent"}`}>{message.read_at ? "✓✓ Müşteri okudu" : "✓ Gönderildi"}</span>}</div></div>)}<div ref={messagesEnd}/></div>{conversation.status === "OPEN" ? <form className="chatComposer" onSubmit={event => { event.preventDefault(); void action("message"); }}><textarea value={draft} maxLength={4000} onChange={event => setDraft(event.target.value)} onKeyDown={event => { if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        void action("message");
    } }} placeholder="Müşteriye yanıt yazın…" aria-label="Müşteriye canlı destek mesajı"/><button type="submit" className="primaryBtn" disabled={sending || !draft.trim()}>{sending ? "…" : "Gönder"}</button></form> : <div className="chatClosedNotice">Bu görüşme kapatıldı.</div>}</>}{error && <div className="formError">{error}</div>}</section></div>;
}
function isStaffRole(role: string) { return ["SUPER_ADMIN", "ADMIN", "TUNER", "SUPPORT"].includes(role); }
function formatAdminChatTime(value: number) { return new Intl.DateTimeFormat("tr-TR", { hour: "2-digit", minute: "2-digit" }).format(new Date(value)); }
function chatListTime(value: number) { const date = new Date(value); const today = new Date(); return date.toDateString() === today.toDateString() ? formatAdminChatTime(value) : new Intl.DateTimeFormat("tr-TR", { day: "2-digit", month: "2-digit" }).format(date); }
function Dtc({ value, setValue }: { value: string; setValue: (s: string) => void }) { return <DiagnosticCenter value={value} setValue={setValue}/>; }
function Settings({ save, alertsEnabled, toggleAlerts }: { save: () => void; alertsEnabled: boolean; toggleAlerts: () => void }) {
    return <AdminBrandSettings notify={() => save()} alertsEnabled={alertsEnabled} toggleAlerts={toggleAlerts}/>;
}
function LegacySettings({ save, alertsEnabled, toggleAlerts }: {
    save: () => void;
    alertsEnabled: boolean;
    toggleAlerts: () => void;
}) { return <div className="split"><div className="card"><div className="cardHead"><h2>Marka ve iletişim</h2></div><div className="formGrid"><Field label="Firma adı"><input defaultValue="CHIP CENTER"/></Field><Field label="Admin e-postası"><input defaultValue="dirlikozan@gmail.com"/></Field><Field label="Varsayılan dil"><select><option>Türkçe</option><option>English</option><option>Deutsch</option></select></Field><Field label="Maksimum dosya boyutu"><input defaultValue={MAX_FILE_SIZE_LABEL} readOnly/></Field><Field label="Ana renk"><input defaultValue="#E10600"/></Field></div><div className="modalActions"><button className="primaryBtn" onClick={save}>Değişiklikleri kaydet</button></div></div><div><div className="card"><h2>Panel bildirimleri</h2><p className="muted">Yeni müşteri dosyasında ses çalar ve izin verirseniz masaüstü bildirimi gösterir.</p><button className="primaryBtn notificationEnable" aria-pressed={alertsEnabled} onClick={toggleAlerts}>{alertsEnabled ? "🔔 Bildirimleri kapat" : "🔕 Bildirimleri aç"}</button></div><div className="card notificationExternal"><h2>E-posta bildirimleri</h2><p className="muted"><strong>Admin:</strong><br />dirlikozan@gmail.com</p><p className="muted">Yeni dosya, kayıt onayı ve düzenlenmiş dosya bildirimleri yapılandırılmış e-posta sağlayıcısı üzerinden gönderilir.</p><span className="badge ready">E-POSTA AKTİF</span></div></div></div>; }
