"use client";

import { DragEvent, useEffect, useRef, useState, type CSSProperties } 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 { DiagnosticCenter } from "./diagnostic-center";
import { UpdateCenter } from "./update-center";

type CustomerView = "home" | "files" | "upload" | "services" | "diagnostics" | "credits" | "support" | "account" | "settings" | "detail";
type PortalUser = { id: string; name: string; email: string; phone: string | null; company: string | null; city: string | null; role: string };
type CustomerSummary = { availableCredits: number; reservedCredits: number; openSupportTickets: number };
type ChatConversation = { id: string; status: string; customer_unread: number; last_message_at: 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[]; emailNotification?: { channel: "email"; recipient: string; status: "sent" | "skipped" | "failed"; reason?: string } };
type SupportTicket = { id: string; subject: string; description: string | null; category: string; priority: string; status: string; created_at: number; updated_at: number };
type CustomerService = { id: string; name: string; category: string; description: string | null; credits: number; estimated_minutes: number; active: number };

type CustomerOrder = {
  id: string;
  car: string;
  engine: string;
  ecu: string;
  services: string;
  status: string;
  cls: string;
  date: string;
  fileName?: string;
  hasOriginal?: boolean;
  vehicleIdName?: string;
  vehicleIdSize?: number;
  hasVehicleId?: boolean;
  hasResult?: boolean;
  resultName?: string;
  persisted?: boolean;
};

type CustomerPageSettings = {
  portal_name: string;
  menu_color: string;
  menu_text_color: string;
  accent_color: string;
  logo_key: string | null;
  panel_notifications: number;
  email_notifications: number;
  support_module: number;
  live_chat: number;
  updated_at: number;
};

const defaultPageSettings: CustomerPageSettings = {
  portal_name: "CHIP CENTER", menu_color: "#0e1117", menu_text_color: "#b2bbc9", accent_color: "#e10600",
  logo_key: null, panel_notifications: 1, email_notifications: 1, support_module: 1, live_chat: 1, updated_at: 0,
};
const emptyCustomerSummary: CustomerSummary = { availableCredits: 0, reservedCredits: 0, openSupportTickets: 0 };
const CAR_BRANDS = [
  "Abarth", "Alfa Romeo", "Alpine", "Aston Martin", "Audi", "Bentley", "BMW", "BYD", "Cadillac", "Chery",
  "Chevrolet", "Chrysler", "Citroën", "Cupra", "Dacia", "Daewoo", "Daihatsu", "Dodge", "DS Automobiles", "Ferrari",
  "Fiat", "Ford", "Geely", "Genesis", "GMC", "Honda", "Hongqi", "Hummer", "Hyundai", "Infiniti", "Isuzu", "Iveco",
  "Jaguar", "Jeep", "KGM (SsangYong)", "Kia", "Lada", "Lamborghini", "Lancia", "Land Rover", "Lexus", "Lincoln",
  "Lotus", "Lucid", "MAN", "Maserati", "Mazda", "McLaren", "Mercedes-Benz", "MG", "MINI", "Mitsubishi", "Nissan",
  "Opel", "Peugeot", "Polestar", "Porsche", "Proton", "RAM", "Renault", "Rolls-Royce", "Rover", "Saab", "Scania",
  "SEAT", "Škoda", "Smart", "Subaru", "Suzuki", "Tata", "Tesla", "Togg", "Toyota", "Volkswagen", "Volvo",
].sort((a, b) => a.localeCompare(b, "tr"));
const MOTORCYCLE_BRANDS = [
  "Aprilia", "Arora", "Bajaj", "Benelli", "Benda", "Beta", "Bimota", "BMW Motorrad", "Brixton", "BRP Can-Am",
  "CFMOTO", "Ducati", "Fantic", "GasGas", "Gilera", "Harley-Davidson", "Hero", "Honda", "Husqvarna", "Indian Motorcycle",
  "Italjet", "Jawa", "Kawasaki", "Keeway", "KTM", "Kuba", "Kymco", "Lambretta", "Lifan", "Malaguti", "Mondial",
  "Moto Guzzi", "Moto Morini", "MV Agusta", "NIU", "Norton", "Peugeot Motocycles", "Piaggio", "QJMotor", "RKS",
  "Royal Enfield", "Segway Powersports", "Sherco", "Silence", "Super Soco", "Suzuki", "SYM", "Triumph", "TVS", "Vespa",
  "Voge", "Yamaha", "Yuki", "Zontes", "Zero Motorcycles", "Diğer",
].sort((a, b) => a.localeCompare(b, "tr"));
const ENGINE_OPTIONS = [
  "Benzin · 1.0", "Benzin · 1.2", "Benzin · 1.3", "Benzin · 1.4", "Benzin · 1.5", "Benzin · 1.6", "Benzin · 1.8", "Benzin · 2.0", "Benzin · 2.3", "Benzin · 2.5", "Benzin · 2.7", "Benzin · 3.0", "Benzin · 3.2", "Benzin · 3.5", "Benzin · 4.0", "Benzin · 4.4", "Benzin · 5.0", "Benzin · 5.5", "Benzin · 6.0+",
  "Dizel · 1.3", "Dizel · 1.4", "Dizel · 1.5", "Dizel · 1.6", "Dizel · 1.9", "Dizel · 2.0", "Dizel · 2.1", "Dizel · 2.2", "Dizel · 2.3", "Dizel · 2.5", "Dizel · 2.7", "Dizel · 2.8", "Dizel · 3.0", "Dizel · 3.2", "Dizel · 4.0", "Dizel · 4.2", "Dizel · 4.5+",
  "Hibrit benzin", "Hibrit dizel", "Plug-in hibrit", "Tam elektrikli", "LPG / CNG", "Motosiklet benzin", "Kamyon / ağır vasıta dizel", "Tarım / iş makinesi dizel", "Deniz motoru", "Diğer",
];
const MOTORCYCLE_ENGINE_OPTIONS = [
  "Benzin · 50 cc", "Benzin · 80 cc", "Benzin · 100 cc", "Benzin · 110 cc", "Benzin · 125 cc", "Benzin · 150 cc",
  "Benzin · 175 cc", "Benzin · 200 cc", "Benzin · 250 cc", "Benzin · 300 cc", "Benzin · 350 cc", "Benzin · 390 cc",
  "Benzin · 400 cc", "Benzin · 450 cc", "Benzin · 500 cc", "Benzin · 600 cc", "Benzin · 650 cc", "Benzin · 700 cc",
  "Benzin · 750 cc", "Benzin · 800 cc", "Benzin · 850 cc", "Benzin · 900 cc", "Benzin · 950 cc", "Benzin · 1000 cc",
  "Benzin · 1100 cc", "Benzin · 1200 cc", "Benzin · 1250 cc", "Benzin · 1300 cc", "Benzin · 1400 cc+",
  "Elektrikli motosiklet", "Elektrikli scooter", "ATV / UTV · 250 cc altı", "ATV / UTV · 250—500 cc", "ATV / UTV · 500—1000 cc", "Diğer",
];

export function CustomerPortal({ user }: { user: PortalUser }) {
  const [profileUser, setProfileUser] = useState(user);
  const [view, setView] = useState<CustomerView>("home");
  const [menu, setMenu] = useState(false);
  const [toast, setToast] = useState("");
  const [orders, setOrders] = useState<CustomerOrder[]>([]);
  const [selectedOrder, setSelectedOrder] = useState<CustomerOrder | null>(null);
  const [pageSettings, setPageSettings] = useState<CustomerPageSettings>(defaultPageSettings);
  const [summary, setSummary] = useState<CustomerSummary>(emptyCustomerSummary);
  const [alertsEnabled, setAlertsEnabled] = useState(() => typeof window === "undefined" ? true : liveAlertsEnabled());
  const knownOrderState = useRef<Map<string, boolean> | null>(null);

  useEffect(() => {
    let active = true;
    async function refreshOrders() {
      try {
        const response = await fetch("/api/requests", { cache: "no-store" });
        const data = await response.json() as { requests?: Record<string, unknown>[] };
        if (!active) return;
        const persisted = (data.requests ?? []).map(row => {
          const rawStatus = String(row.status || "Bekliyor");
          const status = rawStatus === "Hazır" ? "Dosya hazır" : rawStatus;
          const cls = rawStatus === "Hazır" ? "ready" : rawStatus === "İşlemde" ? "processing" : "waiting";
          return {
            id: String(row.id), car: String(row.car), engine: String(row.engine), ecu: String(row.ecu),
            services: String(row.services), status, cls,
            date: Number(row.created_at) ? new Intl.DateTimeFormat("tr-TR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(Number(row.created_at))) : "Az önce",
            fileName: String(row.file_name || ""), hasOriginal: Boolean(row.original_available), vehicleIdName: String(row.vehicle_id_name || ""), vehicleIdSize: Number(row.vehicle_id_size) || 0, hasVehicleId: Boolean(row.vehicle_id_available),
            hasResult: Boolean(row.result_available), resultName: String(row.result_name || ""), persisted: true,
          } satisfies CustomerOrder;
        });
        const latestState = new Map(persisted.map(order => [order.id, Boolean(order.hasResult)]));
        if (knownOrderState.current) {
          for (const order of persisted) {
            if (!knownOrderState.current.get(order.id) && order.hasResult) {
              sendLiveAlert("Düzenlenmiş dosyanız hazır", `${order.id} · ${order.car} · ${order.resultName || "Dosya hazır"}`);
              setToast(`${order.id} düzenlenmiş dosyanız hazır`);
              window.setTimeout(() => setToast(""), 3200);
            }
          }
        }
        knownOrderState.current = latestState;
        setOrders(persisted);
      } catch {
        // Keep the last visible list when a background refresh is unavailable.
      }
    }
    void refreshOrders();
    const timer = window.setInterval(refreshOrders, 5000);
    return () => { active = false; window.clearInterval(timer); };
  }, []);

  useEffect(() => {
    let active = true;
    async function refreshSummary() {
      try {
        const response = await fetch("/api/customer-summary", { cache: "no-store" });
        const nextSummary = await readApiResponse<CustomerSummary>(response);
        if (active) setSummary(nextSummary);
      } catch {
        if (active) setSummary(emptyCustomerSummary);
      }
    }
    void refreshSummary();
    const timer = window.setInterval(refreshSummary, 15_000);
    return () => { active = false; window.clearInterval(timer); };
  }, []);

  useEffect(() => {
    let active = true;
    fetch("/api/customer-settings", { cache: "no-store" }).then(response => readApiResponse<CustomerPageSettings>(response)).then(settings => {
      if (!active) return;
      setPageSettings(settings);
    }).catch(() => undefined);
    return () => { active = false; };
  }, []);

  useEffect(() => {
    const query = new URLSearchParams(window.location.search);
    const payment = query.get("payment");
    if (!payment) return;
    setView("credits");
    setToast(payment === "success" ? "Ödeme sonucu doğrulanıyor; kredileriniz kısa süre içinde görünecek" : "Ödeme tamamlanmadı");
    window.setTimeout(() => setToast(""), 4200);
    window.history.replaceState({}, "", "/customer");
  }, []);

  function go(next: CustomerView) {
    setView(next);
    if (next !== "detail") setSelectedOrder(null);
    setMenu(false);
  }

  function openOrder(order: CustomerOrder) {
    setSelectedOrder(order);
    setView("detail");
    setMenu(false);
  }

  function notify(message: string) {
    setToast(message);
    setTimeout(() => setToast(""), 2200);
  }

  async function toggleAlerts() {
    if (alertsEnabled) {
      setAlertsEnabled(false);
      notify(disableLiveAlerts());
      return;
    }
    const message = await enableLiveAlerts();
    setAlertsEnabled(true);
    notify(message);
  }

  const nav: { id: Exclude<CustomerView, "detail">; label: string; icon: string }[] = [
    { id: "home", label: "Ana Sayfa", icon: "⌂" },
    { id: "files", label: "Dosyalarım", icon: "◆" },
    { id: "upload", label: "Yeni Dosya Talebi", icon: "+" },
    { id: "services", label: "Hizmetler", icon: "⚙" },
    { id: "diagnostics", label: "DTC & ECU Bilgi", icon: "⌕" },
    { id: "credits", label: "Kredi Satın Al", icon: "₺" },
    { id: "support", label: "Destek", icon: "?" },
    { id: "account", label: "Hesabım", icon: "●" },
    { id: "settings", label: "Sayfa Ayarları", icon: "⚙" },
  ].filter(item => (item.id !== "support" || Boolean(pageSettings.support_module)) && (item.id !== "settings" || ["SUPER_ADMIN", "ADMIN", "TUNER", "SUPPORT"].includes(user.role))) as { id: Exclude<CustomerView, "detail">; label: string; icon: string }[];

  const customerStyle = {
    "--customer-menu": pageSettings.menu_color,
    "--customer-menu-text": pageSettings.menu_text_color,
    "--red": pageSettings.accent_color,
    "--red2": pageSettings.accent_color,
  } as CSSProperties;
  const logoUrl = pageSettings.logo_key ? `/api/customer-settings/logo?v=${pageSettings.updated_at}` : "/chipcenter-logo.png";
  const initials = profileUser.name.split(/\s+/).filter(Boolean).slice(0, 2).map(part => part[0]).join("").toUpperCase() || "MU";

  return <div className="app customerApp" style={customerStyle}>
    <aside className={`sidebar ${menu ? "open" : ""}`}>
      <div className="brand"><img src={logoUrl} alt={pageSettings.portal_name} /></div>
      <div className="customerIdentity">
        <span className="avatar">{initials}</span>
        <div><strong>{profileUser.name}</strong><small>{profileUser.company || "Müşteri hesabı"}</small></div>
      </div>
      <div className="navGroup">
        <div className="navTitle">MÜŞTERİ PORTALI</div>
        {nav.map(item => <button key={item.id} className={`navItem ${view === item.id ? "active" : ""}`} onClick={() => go(item.id)}><span className="navIcon">{item.icon}</span>{item.label}{item.id === "files" && <span className="navBadge">{orders.length}</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)} aria-label="Menüyü aç">☰</button>
        <div className="customerHeaderTitle">{pageSettings.portal_name} <span>Müşteri Portalı</span></div>
        <div className="headerActions"><button className="iconBtn" aria-pressed={alertsEnabled} onClick={() => void toggleAlerts()}>{alertsEnabled ? "🔔 Bildirimleri kapat" : "🔕 Bildirimleri aç"}</button><button className="primaryBtn" onClick={() => go("upload")}>+ Dosya yükle</button><LogoutButton/><div className="avatar" title={profileUser.email}>{initials}</div></div>
      </header>

      <div className="content customerContent">
        {view === "home" && <CustomerHome user={profileUser} go={go} notify={notify} orders={orders} onOpen={openOrder} supportEnabled={Boolean(pageSettings.support_module)} summary={summary} />}
        {view === "files" && <CustomerFiles notify={notify} orders={orders} onOpen={openOrder} />}
        {view === "upload" && <CustomerUpload user={profileUser} summary={summary} notify={notify} go={go} onCreated={order => setOrders(current => [order, ...current])} />}
        {view === "services" && <CustomerServices notify={notify} />}
        {view === "diagnostics" && <DiagnosticCenter />}
        {view === "credits" && <CustomerCredits notify={notify} onBalanceRefresh={() => fetch("/api/customer-summary", { cache: "no-store" }).then(response => readApiResponse<CustomerSummary>(response)).then(setSummary).catch(() => undefined)} />}
        {view === "support" && Boolean(pageSettings.support_module) && <CustomerSupport user={profileUser} notify={notify} liveChatEnabled={Boolean(pageSettings.live_chat)} openTickets={summary.openSupportTickets} />}
        {view === "account" && <CustomerAccount user={profileUser} onUpdated={setProfileUser} notify={notify} />}
        {view === "settings" && ["SUPER_ADMIN", "ADMIN", "TUNER", "SUPPORT"].includes(user.role) && <CustomerPageSettingsView settings={pageSettings} onSaved={setPageSettings} notify={notify} />}
        {view === "detail" && selectedOrder && <CustomerRequestDetail order={selectedOrder} back={() => go("files")} notify={notify} />}
      </div>
    </main>

    <nav className="mobileNav">
      <button onClick={() => go("home")}><span>⌂</span>Ana Sayfa</button>
      <button onClick={() => go("files")}><span>◆</span>Dosyalar</button>
      <button onClick={() => go("services")}><span>⚙</span>Hizmetler</button>
      <button onClick={() => go("diagnostics")}><span>⌕</span>DTC/ECU</button>
      <button className="uploadBtn" onClick={() => go("upload")}>+</button>
      <button onClick={() => go("credits")}><span>₺</span>Kredi</button>
      {Boolean(pageSettings.support_module) && <button onClick={() => go("support")}><span>?</span>Destek</button>}
      <button onClick={() => go("account")}><span>●</span>Hesabım</button>
      {["SUPER_ADMIN", "ADMIN", "TUNER", "SUPPORT"].includes(user.role) && <button onClick={() => go("settings")}><span>⚙</span>Ayarlar</button>}
    </nav>
    <UpdateCenter/>{toast && <div className="toast">✓ {toast}</div>}
  </div>;
}

function CustomerHome({ user, go, notify, orders, onOpen, supportEnabled, summary }: { user: PortalUser; go: (v: CustomerView) => void; notify: (s: string) => void; orders: CustomerOrder[]; onOpen: (order: CustomerOrder) => void; supportEnabled: boolean; summary: CustomerSummary }) {
  return <div className="view">
    <section className="customerHero">
      <div><span className="eyebrow">HOŞ GELDİNİZ</span><h1>Merhaba {user.name.split(" ")[0]},</h1><p>Dosyalarınızın durumunu takip edin veya yeni bir kalibrasyon talebi oluşturun.</p><div className="heroActions"><button className="primaryBtn largeBtn" onClick={() => go("upload")}>+ Yeni dosya talebi</button><button className="secondaryBtn largeBtn" onClick={() => go("files")}>Dosyalarımı görüntüle</button></div></div>
      <div className="balanceCard"><span>Kullanılabilir kredi</span><strong>{summary.availableCredits}</strong><small>{summary.reservedCredits ? `${summary.reservedCredits} kredi rezerve edildi` : "Rezerve kredi yok"}</small><button onClick={() => go("credits")}>Kredi satın al →</button></div>
    </section>
    <div className="kpis customerKpis">
      {[["Aktif talepler",String(orders.filter(order => order.status === "Bekliyor" || order.status === "İşlemde").length),"Güncel işler"],["Hazır dosyalar",String(orders.filter(order => order.status === "Dosya hazır" && order.hasResult).length),"İndirmeye hazır"],["Tamamlanan",String(orders.filter(order => order.status === "Tamamlandı").length),"Bu listede"],["Destek talepleri",String(summary.openSupportTickets),summary.openSupportTickets ? "Yanıt bekliyor" : "Açık talep yok"]].map(item => <div className="kpi" key={item[0]}><div className="kpiTop">{item[0]}</div><div className="kpiValue">{item[1]}</div><div className="muted">{item[2]}</div></div>)}
    </div>
    <div className="card section">
      <div className="cardHead"><div><h2>Son dosya talepleriniz</h2><span className="muted">Taleplerinizin güncel durumu</span></div><button className="secondaryBtn" onClick={() => go("files")}>Tümünü gör</button></div>
      <OrderCards orders={orders.slice(0, 3)} notify={notify} onOpen={onOpen} />
    </div>
    {supportEnabled && <div className="supportBanner"><div><span className="actIcon">?</span><div><strong>Teknik desteğe mi ihtiyacınız var?</strong><p>Uzman ekibimiz çalışma saatleri içinde ortalama 6 dakikada yanıt verir.</p></div></div><button className="secondaryBtn" onClick={() => go("support")}>Destek talebi oluştur</button></div>}
  </div>;
}

function OrderCards({ orders, notify, onOpen }: { orders: CustomerOrder[]; notify: (s: string) => void; onOpen: (order: CustomerOrder) => void }) {
  if (!orders.length) return <div className="emptyOrders"><span>◇</span><strong>Henüz dosya talebiniz yok</strong><p>İlk original dosyanızı yüklediğinizde talebiniz burada görünecek.</p></div>;
  return <div className="orderCards">{orders.map(order => <article className="orderCard" key={order.id}>
    <div className="orderTop"><span className="id">{order.id}</span><span className={`badge ${order.cls}`}>{order.status}</span></div>
    <h3>{order.car}</h3><p>{order.engine}</p>
    <div className="orderMeta"><span><small>ECU / TCU</small>{order.ecu}</span><span><small>İşlemler</small>{order.services}</span></div>
    <div className="orderBottom"><span>{order.date}</span><div className="orderActions"><button className="secondaryBtn" onClick={() => onOpen(order)}>Detaylar</button>{order.persisted && !order.hasOriginal ? <RestoreOriginalButton order={order} notify={notify}/> : order.status === "Dosya hazır" && order.hasResult ? <a className="primaryBtn downloadLink" href={`/api/requests/${encodeURIComponent(order.id)}/file?kind=result`} download onClick={() => notify(`${order.resultName || order.id} indiriliyor`)}>Dosyayı indir</a> : null}</div></div>
  </article>)}</div>;
}

function RestoreOriginalButton({order,notify}:{order:CustomerOrder;notify:(message:string)=>void}) {
  const inputRef=useRef<HTMLInputElement>(null);
  const [uploading,setUploading]=useState(false);
  const [done,setDone]=useState(false);
  const [percent,setPercent]=useState(0);
  async function restore(file?:File){
    if(!file)return;
    if(file.size>MAX_FILE_SIZE){notify(`Dosya boyutu ${MAX_FILE_SIZE_LABEL} sınırını aşıyor`);return}
    setUploading(true);setPercent(0);
    try{const upload=await uploadFileChunks(file,order.id,"original",setPercent);const response=await fetch(`/api/requests/${encodeURIComponent(order.id)}/original`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:file.name,fileSize:file.size,mime:file.type||"application/octet-stream",...upload})});await readApiResponse(response);setDone(true);notify(`${file.name} talebe eklendi`)}catch(error){notify(error instanceof Error?error.message:"Dosya gönderilemedi")}finally{setUploading(false)}
  }
  return <><input ref={inputRef} className="hiddenFileInput" type="file" onChange={event=>{void restore(event.target.files?.[0]);event.target.value=""}}/><button className="secondaryBtn" disabled={uploading||done} onClick={()=>inputRef.current?.click()}>{done?"✓ Dosya gönderildi":uploading?`Gönderiliyor… %${percent}`:"Originali yeniden yükle"}</button></>;
}

function CustomerFiles({ notify, orders, onOpen }: { notify: (s: string) => void; orders: CustomerOrder[]; onOpen: (order: CustomerOrder) => void }) {
  return <div className="view"><div className="pageHead"><div><span className="eyebrow">DOSYALARIM</span><h1>Dosya talepleri</h1><p>Tüm aktif ve tamamlanan işlemlerinizi takip edin.</p></div></div><div className="filters"><button className="filter">Tümü · {orders.length}</button><button className="filter">Aktif · {orders.filter(order => order.status === "Bekliyor" || order.status === "İşlemde").length}</button><button className="filter">Hazır · {orders.filter(order => order.status === "Dosya hazır").length}</button><button className="filter">Tamamlanan · {orders.filter(order => order.status === "Tamamlandı").length}</button></div><OrderCards orders={orders} notify={notify} onOpen={onOpen} /></div>;
}

function CustomerRequestDetail({ order, back, notify }: { order: CustomerOrder; back: () => void; notify: (message: string) => void }) {
  const isReady = Boolean(order.hasResult);
  const isProcessing = order.status === "İşlemde" || order.status === "Dosya hazır" || order.status === "Tamamlandı";
  const timeline = [
    { title: "Talep oluşturuldu", text: `${order.date} · Talebiniz sisteme kaydedildi.`, done: true },
    { title: "Original dosya alındı", text: order.hasOriginal === false ? "Dosyanın yeniden yüklenmesi bekleniyor." : order.fileName || "Original dosya güvenli şekilde kaydedildi.", done: order.hasOriginal !== false },
    { title: "Araç/motor ID dosyası alındı", text: order.hasVehicleId ? order.vehicleIdName || "ID dosyası güvenli şekilde kaydedildi." : "Bu eski talepte ayrı ID dosyası bulunmuyor.", done: Boolean(order.hasVehicleId) },
    { title: "Kalibrasyon işlemi", text: isProcessing ? "Dosyanız uzman tuner tarafından işleniyor." : "Tuner sırasına alınmayı bekliyor.", done: isProcessing },
    { title: "Düzenlenmiş dosya hazır", text: isReady ? order.resultName || "Dosyanız indirilmeye hazır." : "İşlem tamamlanınca burada görünecek.", done: isReady },
  ];
  return <div className="view customerDetailPage">
    <div className="detailPageTop"><button className="secondaryBtn backToFiles" onClick={back}>← Dosyalarıma dön</button><span className={`badge ${order.cls}`}>{order.status}</span></div>
    <div className="pageHead customerDetailHead"><div><span className="eyebrow">DOSYA TALEBİ</span><h1>{order.id}</h1><p>{order.car} için talep ayrıntıları ve güncel işlem durumu.</p></div></div>
    <div className="customerDetailLayout">
      <section className="card customerDetailMain">
        <div className="cardHead"><div><h2>Araç ve dosya bilgileri</h2><span className="muted">Talebinizde kayıtlı bilgiler</span></div></div>
        <div className="detailGrid customerInfoGrid"><div className="detailItem"><span>Araç</span><strong>{order.car}</strong><small>{order.engine}</small></div><div className="detailItem"><span>ECU / TCU</span><strong>{order.ecu}</strong></div><div className="detailItem"><span>İstenen servisler</span><strong>{order.services}</strong></div><div className="detailItem"><span>Talep tarihi</span><strong>{order.date}</strong></div></div>
        <div className={`detailFile customerOriginalFile ${order.hasOriginal === false ? "missingFile" : ""}`}><span className="detailFileIcon">ORI</span><div><span className="detailLabel">Gönderilen original dosya</span><strong>{order.fileName || "Original dosya"}</strong><small>{order.hasOriginal === false ? "Dosya içeriği yeniden yüklenmeli." : "Dosya CHIP CENTER sisteminde güvenli şekilde saklanıyor."}</small></div><span className={order.hasOriginal === false ? "fileMissing" : "fileReady"}>{order.hasOriginal === false ? "BEKLENİYOR" : "KAYDEDİLDİ"}</span></div>
        <div className={`detailFile customerOriginalFile ${order.hasVehicleId ? "" : "missingFile"}`}><span className="detailFileIcon">ID</span><div><span className="detailLabel">Araç / motor ID dosyası</span><strong>{order.vehicleIdName || "ID dosyası bulunmuyor"}</strong><small>{order.hasVehicleId ? `${order.vehicleIdSize ? formatBytes(order.vehicleIdSize) : "Dosya"} · Güvenli şekilde saklanıyor.` : "Yeni taleplerde bu dosya zorunludur."}</small></div>{order.hasVehicleId ? <a className="secondaryBtn downloadLink" href={`/api/requests/${encodeURIComponent(order.id)}/file?kind=vehicle-id`} download>ID dosyasını indir</a> : <span className="fileMissing">YOK</span>}</div>
        {isReady ? <div className="customerResultBox"><div><span className="detailLabel">Düzenlenmiş dosya</span><strong>{order.resultName || `${order.id}-modified.bin`}</strong><small>Dosyanız indirilmeye hazır.</small></div><a className="primaryBtn downloadLink" href={`/api/requests/${encodeURIComponent(order.id)}/file?kind=result`} download onClick={() => notify(`${order.resultName || order.id} indiriliyor`)}>Dosyayı indir</a></div> : <div className="customerWaitingBox"><span className="noticeIcon">⌁</span><div><strong>Dosyanız işlem sırasında</strong><p>Dosya tamamlandığında bu ekranda indirme düğmesi açılacak ve bildirim gösterilecek.</p></div></div>}
      </section>
      <aside className="card customerTimeline"><div className="cardHead"><div><h2>İşlem geçmişi</h2><span className="muted">Talebinizin adımları</span></div></div><div className="timelineList">{timeline.map((item, index) => <div className={`timelineItem ${item.done ? "done" : ""}`} key={item.title}><span className="timelineDot">{item.done ? "✓" : index + 1}</span><div><strong>{item.title}</strong><p>{item.text}</p></div></div>)}</div><button className="secondaryBtn detailSupportBtn" onClick={() => notify(`${order.id} için destek talebi açıldı`)}>Bu taleple ilgili destek al</button></aside>
    </div>
  </div>;
}

function CustomerUpload({ user, summary, notify, go, onCreated }: { user: PortalUser; summary: CustomerSummary; notify: (s: string) => void; go: (v: CustomerView) => void; onCreated: (order: CustomerOrder) => void }) {
  const inputRef = useRef<HTMLInputElement>(null);
  const vehicleIdInputRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);
  const [vehicleIdFile, setVehicleIdFile] = useState<File | null>(null);
  const [dragging, setDragging] = useState(false);
  const [vehicleIdDragging, setVehicleIdDragging] = useState(false);
  const [progress, setProgress] = useState(0);
  const [vehicleIdProgress, setVehicleIdProgress] = useState(0);
  const [step, setStep] = useState(1);
  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [uploadPercent, setUploadPercent] = useState(0);
  const [customerEmail, setCustomerEmail] = useState(user.email);
  const [vehicleKind, setVehicleKind] = useState<"car" | "motorcycle">("car");
  const [brand, setBrand] = useState("");
  const [model, setModel] = useState("");
  const [engineType, setEngineType] = useState("");
  const [engine, setEngine] = useState("");
  const [ecu, setEcu] = useState("");
  const customerPhone = user.phone || "";
  const [serviceOptions, setServiceOptions] = useState<CustomerService[]>([]);

  useEffect(() => {
    fetch("/api/services", { cache: "no-store" }).then(response => readApiResponse<{ services: CustomerService[] }>(response)).then(data => {
      if (!data.services.length) return;
      setServiceOptions(data.services);
      setSelectedServices(current => {
        const available = new Set(data.services.map(service => service.name));
        const retained = current.filter(name => available.has(name));
        return retained;
      });
    }).catch(() => undefined);
  }, []);

  useEffect(() => {
    setSelectedServices(current => {
      const relevant = serviceOptions.filter(service => vehicleKind === "motorcycle"
        ? service.category !== "Motor Yazılımı"
        : service.category !== "Motosiklet Yazılımı");
      const names = new Set(relevant.map(service => service.name));
      const retained = current.filter(name => names.has(name));
      return retained;
    });
  }, [serviceOptions, vehicleKind]);

  const totalCredits = serviceOptions.filter(service => selectedServices.includes(service.name)).reduce((sum, service) => sum + service.credits, 0);
  const remainingCredits = summary.availableCredits - totalCredits;
  const hasEnoughCredits = remainingCredits >= 0;
  const motorServices = serviceOptions.filter(service => service.category === "Motor Yazılımı");
  const motorcycleServices = serviceOptions.filter(service => service.category === "Motosiklet Yazılımı");
  const ecuServices = serviceOptions.filter(service => service.category !== "Motor Yazılımı" && service.category !== "Motosiklet Yazılımı");
  const vehicleBrands = vehicleKind === "motorcycle" ? MOTORCYCLE_BRANDS : CAR_BRANDS;
  const engineOptions = vehicleKind === "motorcycle" ? MOTORCYCLE_ENGINE_OPTIONS : ENGINE_OPTIONS;

  function changeVehicleKind(nextKind: "car" | "motorcycle") {
    setVehicleKind(nextKind);
    setBrand("");
    setModel("");
    setEngineType("");
    setEngine("");
    setEcu("");
    setSelectedServices([]);
    setSubmitError("");
  }

  function prepareFile(selected: File | undefined, kind: "original" | "vehicle-id") {
    if (!selected) return;
    if (!selected.size || selected.size > MAX_FILE_SIZE) {
      notify(`Dosya boyutu geçersiz veya ${MAX_FILE_SIZE_LABEL} sınırını aşıyor`);
      return;
    }
    const setTargetFile = kind === "original" ? setFile : setVehicleIdFile;
    const setTargetProgress = kind === "original" ? setProgress : setVehicleIdProgress;
    setTargetFile(selected);
    setSubmitError("");
    setTargetProgress(8);
    let value = 8;
    const timer = window.setInterval(() => {
      value = Math.min(100, value + Math.ceil(Math.random() * 17));
      setTargetProgress(value);
      if (value >= 100) {
        window.clearInterval(timer);
        notify(`${selected.name} gönderime hazır`);
      }
    }, 150);
  }

  function onDrop(event: DragEvent<HTMLDivElement>, kind: "original" | "vehicle-id") {
    event.preventDefault();
    if (kind === "original") setDragging(false); else setVehicleIdDragging(false);
    prepareFile(event.dataTransfer.files[0], kind);
  }

  function toggleService(service: string) {
    setSelectedServices(current => current.includes(service) ? current.filter(item => item !== service) : [...current, service]);
    setSubmitError("");
  }

  async function submitRequest() {
    if (!file || !vehicleIdFile || selectedServices.length === 0 || !brand.trim() || !model.trim() || !engineType.trim() || !engine.trim() || !ecu.trim()) {
      setSubmitError("Marka, model, motor, ECU, original dosya ve araç/motor ID dosyasının tamamı zorunludur");
      return;
    }
    if (!hasEnoughCredits) {
      setSubmitError(`Yetersiz kredi: ${totalCredits} kredi gerekli, mevcut bakiyeniz ${summary.availableCredits} kredi`);
      return;
    }
    const nextId = `CC-2026-${String(Date.now()).slice(-6)}`;
    setSubmitting(true);
    setSubmitError("");
    setUploadPercent(0);
    try {
      const originalUpload = await uploadFileChunks(file, nextId, "original", percent => setUploadPercent(Math.round(percent / 2)));
      const vehicleIdUpload = await uploadFileChunks(vehicleIdFile, nextId, "vehicle-id", percent => setUploadPercent(50 + Math.round(percent / 2)));
      const response = await fetch("/api/requests", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({
        id: nextId, customer: user.company || user.name, customerEmail, customerPhone,
        car: `${vehicleKind === "motorcycle" ? "Motosiklet" : "Otomobil"} · ${brand.trim()} ${model.trim()}`, engine: `${engineType.trim()} · ${engine.trim()}`, ecu: ecu.trim(),
        services: selectedServices.join(" + "), fileName: file.name, fileSize: file.size, mime: file.type || "application/octet-stream",
        uploadId: originalUpload.uploadId, chunkCount: originalUpload.chunkCount,
        vehicleIdFileName: vehicleIdFile.name, vehicleIdFileSize: vehicleIdFile.size, vehicleIdMime: vehicleIdFile.type || "application/octet-stream",
        vehicleIdUploadId: vehicleIdUpload.uploadId, vehicleIdChunkCount: vehicleIdUpload.chunkCount,
      }) });
      await readApiResponse(response);
      onCreated({
        id: nextId, car: `${vehicleKind === "motorcycle" ? "Motosiklet" : "Otomobil"} · ${brand.trim()} ${model.trim()}`, engine: `${engineType.trim()} · ${engine.trim()}`, ecu: ecu.trim(),
        services: selectedServices.join(" + "), status: "Bekliyor", cls: "waiting", date: "Az önce",
        fileName: file.name, hasOriginal: true, vehicleIdName: vehicleIdFile.name, vehicleIdSize: vehicleIdFile.size, hasVehicleId: true,
        hasResult: false, persisted: true,
      });
      notify(`${nextId} talebi, original ve ID dosyaları başarıyla gönderildi`);
      go("files");
    } catch (error) {
      const message = error instanceof Error ? error.message : "Talep gönderilemedi";
      setSubmitError(message);
      notify(message);
    } finally {
      setSubmitting(false);
    }
  }

  function serviceGrid(items: CustomerService[]) {
    return <div className="serviceCards customerServiceCards">{items.map(service => <button type="button" key={service.id} className={`serviceChoice ${selectedServices.includes(service.name) ? "selected" : ""}`} onClick={() => toggleService(service.name)}><span><strong>{service.name}</strong><small>{service.credits} kredi · {service.category}</small></span><span className="serviceCheck">{selectedServices.includes(service.name) ? "✓" : "+"}</span></button>)}</div>;
  }

  const stepOneIncomplete = !file || !vehicleIdFile || progress < 100 || vehicleIdProgress < 100 || !customerEmail.trim() || !brand.trim() || !model.trim() || !engineType.trim() || !engine.trim() || !ecu.trim();
  return <div className="view">
    <div className="pageHead"><div><span className="eyebrow">YENİ TALEP · ADIM {step}/3</span><h1>{step === 1 ? "Dosyalarınızı gönderin" : step === 2 ? "Hizmetleri seçin" : "Talebi kontrol edin"}</h1><p>{step === 1 ? `${vehicleKind === "motorcycle" ? "Motosiklet" : "Araç"} bilgileriyle birlikte original ve ID dosyasını yükleyin.` : step === 2 ? "ECU/TCU, motor ve motosiklet yazılım hizmetlerini belirleyin." : "Bakiyenizi ve tüm bilgileri kontrol edip talebinizi gönderin."}</p></div><div className="uploadBalanceTop"><span>Mevcut kredi</span><strong>{summary.availableCredits}</strong><small>{summary.reservedCredits ? `${summary.reservedCredits} kredi işlemde` : "Kullanıma hazır"}</small></div></div>
    <div className="stepper customerStepper"><i className="step on"/><i className={`step ${step >= 2 ? "on" : ""}`}/><i className={`step ${step >= 3 ? "on" : ""}`}/></div>
    <div className="split"><div className="card">
      {step === 1 && <><div className="requestKindSelector"><button type="button" className={`kindChoice ${vehicleKind === "car" ? "active" : ""}`} onClick={() => changeVehicleKind("car")}><span>OTOMOBİL</span><strong>Otomobil / ticari araç</strong><small>ECU, TCU ve motor dosyaları</small></button><button type="button" className={`kindChoice motorcycleChoice ${vehicleKind === "motorcycle" ? "active" : ""}`} onClick={() => changeVehicleKind("motorcycle")}><span>MOTOSİKLET</span><strong>Motosiklet / scooter / ATV</strong><small>EMS, ECU ve özel kalibrasyonlar</small></button></div><div className="formGrid"><CustomerField label={`${vehicleKind === "motorcycle" ? "Motosiklet" : "Araç"} markası *`}><select value={brand} onChange={event => setBrand(event.target.value)} required><option value="" disabled>{vehicleKind === "motorcycle" ? "Motosiklet markası seçin" : "Marka seçin"}</option>{vehicleBrands.map(item => <option value={item} key={item}>{item}</option>)}</select></CustomerField><CustomerField label={`${vehicleKind === "motorcycle" ? "Model / seri" : "Model"} *`}><input value={model} onChange={event => setModel(event.target.value)} placeholder={vehicleKind === "motorcycle" ? "Örn. MT-07, S1000RR, Forza 250" : "Örn. Corolla, Focus, 320d"} required /></CustomerField><CustomerField label={`${vehicleKind === "motorcycle" ? "Motor hacmi / türü" : "Motor türü"} *`}><select value={engineType} onChange={event => setEngineType(event.target.value)} required><option value="" disabled>{vehicleKind === "motorcycle" ? "Motor hacmini seçin" : "Motor türünü seçin"}</option>{engineOptions.map(item => <option value={item} key={item}>{item}</option>)}</select></CustomerField><CustomerField label="Motor / motor kodu *"><input value={engine} onChange={event => setEngine(event.target.value)} placeholder={vehicleKind === "motorcycle" ? "Örn. CP2 · 73.4 HP · Euro 5" : "Örn. 2.0 TDI 150 HP · CUNA"} required /></CustomerField><CustomerField label={`${vehicleKind === "motorcycle" ? "ECU / EMS" : "ECU / TCU"} *`}><input value={ecu} onChange={event => setEcu(event.target.value)} placeholder={vehicleKind === "motorcycle" ? "Örn. Keihin, Denso, Bosch ME17" : "Örn. Bosch EDC17C64"} required /></CustomerField><CustomerField label="Bildirim e-postası"><input type="email" value={customerEmail} onChange={event => setCustomerEmail(event.target.value)} required /></CustomerField></div>
      <input ref={inputRef} className="hiddenFileInput" type="file" onChange={event => { prepareFile(event.target.files?.[0], "original"); event.target.value = ""; }} /><div className={`upload interactiveUpload ${dragging ? "dragging" : ""} ${file ? "hasFile" : ""}`} style={{ marginTop: 16 }} role="button" tabIndex={0} onClick={() => inputRef.current?.click()} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") inputRef.current?.click(); }} onDragEnter={event => { event.preventDefault(); setDragging(true); }} onDragOver={event => event.preventDefault()} onDragLeave={event => { if (event.currentTarget === event.target) setDragging(false); }} onDrop={event => onDrop(event, "original")}>
        {!file ? <div><b className="uploadArrow">↑</b><strong>Original dosyayı buraya bırakın *</strong><span>veya seçmek için tıklayın</span><small>Tüm dosya türleri kabul edilir · Maks. {MAX_FILE_SIZE_LABEL}</small></div> : <div className="selectedFile"><span className="fileIcon">{fileExtension(file.name)}</span><div><strong>{file.name}</strong><span>{formatBytes(file.size)} · {progress < 100 ? "Dosya hazırlanıyor" : "Gönderime hazır"}</span><div className="uploadProgress"><i style={{ width: `${progress}%` }} /></div><small>%{progress}</small></div></div>}
      </div>{file && <button className="changeFileBtn" onClick={() => inputRef.current?.click()}>Original dosyayı değiştir</button>}
      <input ref={vehicleIdInputRef} className="hiddenFileInput" type="file" onChange={event => { prepareFile(event.target.files?.[0], "vehicle-id"); event.target.value = ""; }} /><div className={`upload interactiveUpload vehicleIdUpload ${vehicleIdDragging ? "dragging" : ""} ${vehicleIdFile ? "hasFile" : ""}`} role="button" tabIndex={0} onClick={() => vehicleIdInputRef.current?.click()} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") vehicleIdInputRef.current?.click(); }} onDragEnter={event => { event.preventDefault(); setVehicleIdDragging(true); }} onDragOver={event => event.preventDefault()} onDragLeave={event => { if (event.currentTarget === event.target) setVehicleIdDragging(false); }} onDrop={event => onDrop(event, "vehicle-id")}>
        {!vehicleIdFile ? <div><b className="uploadArrow idArrow">ID</b><strong>Aracın veya motorun ID dosyasını buraya yükleyin *</strong><span>Bu ikinci dosya zorunludur; seçmek için tıklayabilir veya sürükleyebilirsiniz.</span><small>Tüm dosya türleri kabul edilir · Maks. {MAX_FILE_SIZE_LABEL}</small></div> : <div className="selectedFile"><span className="fileIcon">ID</span><div><strong>{vehicleIdFile.name}</strong><span>{formatBytes(vehicleIdFile.size)} · {vehicleIdProgress < 100 ? "ID dosyası hazırlanıyor" : "Gönderime hazır"}</span><div className="uploadProgress"><i style={{ width: `${vehicleIdProgress}%` }} /></div><small>%{vehicleIdProgress}</small></div></div>}
      </div>{vehicleIdFile && <button className="changeFileBtn" onClick={() => vehicleIdInputRef.current?.click()}>ID dosyasını değiştir</button>}</>}
      {step === 2 && <div className="requestServiceSections"><section><div className="serviceGroupHead"><div><h3>{vehicleKind === "motorcycle" ? "ECU / EMS temel hizmetleri" : "ECU / TCU hizmetleri"}</h3><p>Kalibrasyon, emisyon ve kontrol ünitesi işlemleri</p></div><span>{ecuServices.length} hizmet</span></div>{serviceGrid(ecuServices)}</section>{vehicleKind === "car" && <section><div className="serviceGroupHead motorGroupHead"><div><h3>Motor yazılım hizmetleri</h3><p>Motor davranışı, limitler, gaz tepkisi ve yardımcı fonksiyonlar</p></div><span>{motorServices.length} hizmet</span></div>{serviceGrid(motorServices)}</section>}{vehicleKind === "motorcycle" && <section className="motorcycleServiceSection"><div className="serviceGroupHead motorcycleGroupHead"><div><h3>Motosiklet yazılım hizmetleri</h3><p>Motosiklet, scooter ve ATV için ECU/EMS kalibrasyonları</p></div><span>{motorcycleServices.length} hizmet</span></div>{serviceGrid(motorcycleServices)}</section>}</div>}
      {step === 3 && <><div className={`creditCheckPanel ${hasEnoughCredits ? "enough" : "insufficient"}`}><div><span>Mevcut kredi</span><strong>{summary.availableCredits}</strong></div><b>−</b><div><span>Bu talep</span><strong>{totalCredits}</strong></div><b>=</b><div><span>Kalan kredi</span><strong>{remainingCredits}</strong></div></div>{!hasEnoughCredits && <div className="creditInsufficientNotice"><strong>Yetersiz kredi</strong><span>Bu talep için {totalCredits} kredi gerekiyor. Mevcut bakiyeniz {summary.availableCredits} kredi. Önce kredi satın alın veya seçili hizmetleri azaltın.</span></div>}<div className="requestSummary"><div><span>{vehicleKind === "motorcycle" ? "Motosiklet" : "Araç"}</span><strong>{brand} {model} · {engineType} · {engine}</strong></div><div><span>{vehicleKind === "motorcycle" ? "ECU / EMS" : "ECU / TCU"}</span><strong>{ecu}</strong></div><div><span>Original dosya</span><strong>{file?.name}</strong></div><div><span>Araç / motor ID dosyası</span><strong>{vehicleIdFile?.name}</strong></div><div><span>Seçilen hizmetler</span><strong>{selectedServices.join(" · ")}</strong></div><div><span>E-posta bildirimi</span><strong>{customerEmail}</strong></div><div className="summaryTotal"><span>Toplam</span><strong>{totalCredits} kredi</strong></div></div></>}
      {submitError && <div className="formError">{submitError}</div>}
      <div className="modalActions"><button className="secondaryBtn" disabled={submitting} onClick={() => step === 1 ? go("home") : setStep(step - 1)}>{step === 1 ? "Vazgeç" : "Geri"}</button>{step === 3 && !hasEnoughCredits && <button className="secondaryBtn" disabled={submitting} onClick={() => go("credits")}>Kredi satın al</button>}<button className="primaryBtn" disabled={submitting || (step === 1 && stepOneIncomplete) || (step === 2 && selectedServices.length === 0)} onClick={() => { if (step < 3) { setSubmitError(""); setStep(step + 1); } else void submitRequest(); }}>{submitting ? `İki dosya gönderiliyor… %${uploadPercent}` : step === 1 ? "Hizmet seçimine geç" : step === 2 ? "Talebi kontrol et" : "Talebi ve dosyaları gönder"}</button></div>
    </div><div className="card uploadCreditSidebar"><h2>Kredi özeti</h2><div className="uploadCreditValue"><span>Mevcut bakiyeniz</span><strong>{summary.availableCredits}</strong><small>kredi</small></div><div className="activity"><span className="actIcon">−</span><div className="actText">Seçili hizmetler<span className="actTime">Talep gönderilince rezerve edilir</span></div><strong>{totalCredits}</strong></div><div className="activity"><span className="actIcon">=</span><div className="actText">Talep sonrası<span className="actTime">{selectedServices.length ? "Tahmini kullanılabilir bakiye" : "Hizmet seçildikten sonra hesaplanır"}</span></div><strong className={selectedServices.length && remainingCredits < 0 ? "negativeCredit" : ""}>{selectedServices.length ? remainingCredits : "—"}</strong></div>{!hasEnoughCredits && <button className="primaryBtn" onClick={() => go("credits")}>Kredi satın al</button>}<p className="muted secureUploadNote">Original ve ID dosyalarınız şifreli bağlantıyla parçalı yüklenir ve yalnızca yetkili tuner tarafından görüntülenir.</p></div></div>
  </div>;
}

function CustomerServices({ notify }: { notify: (message: string) => void }) {
  const [services, setServices] = useState<CustomerService[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  async function load() {
    setLoading(true);
    try {
      const response = await fetch("/api/services", { cache: "no-store" });
      const payload = await readApiResponse<{ services: CustomerService[] }>(response);
      setServices(payload.services);
      setError("");
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Hizmetler alınamadı");
    } finally { setLoading(false); }
  }
  useEffect(() => { void load(); }, []);
  const categoryPriority = (category: string) => category === "Motosiklet Yazılımı" ? 0 : category === "Motor Yazılımı" ? 1 : 2;
  const categories = Array.from(new Set(services.map(service => service.category))).sort((a, b) => categoryPriority(a) - categoryPriority(b) || a.localeCompare(b, "tr"));
  return <div className="view customerServicesPage"><div className="pageHead"><div><span className="eyebrow">HİZMET KATALOĞU</span><h1>Tuner hizmetleri ve krediler</h1><p>Otomobil ve motosiklet dosyaları için sunulan ECU/TCU/EMS işlemlerini güncel kredi değerleriyle inceleyin.</p></div><button className="secondaryBtn" onClick={() => { void load(); notify("Hizmet listesi yenileniyor"); }}>Listeyi yenile</button></div>{loading ? <section className="card paymentLoading">Hizmetler yükleniyor…</section> : error ? <div className="formError">{error}</div> : categories.map(category => { const isMotorcycle = category === "Motosiklet Yazılımı"; const isMotor = category === "Motor Yazılımı"; return <section className={`card customerServiceCatalog ${isMotor ? "motorCatalog" : ""} ${isMotorcycle ? "motorcycleCatalog" : ""}`} key={category}><div className="cardHead"><div><h2>{isMotorcycle ? "Motosiklet yazılım hizmetleri" : isMotor ? "Motor yazılım hizmetleri" : category}</h2><span className="muted">{services.filter(service => service.category === category).length} aktif hizmet</span></div>{(isMotor || isMotorcycle) && <span className={`badge ready ${isMotorcycle ? "motoBadge" : ""}`}>{isMotorcycle ? "MOTOSİKLET" : "MOTOR"}</span>}</div><div className="customerCatalogGrid">{services.filter(service => service.category === category).map(service => <article className="customerCatalogItem" key={service.id}><span className="catalogServiceIcon">{isMotorcycle ? "MOTO" : isMotor ? "M" : "ECU"}</span><div><strong>{service.name}</strong><small>Ortalama işlem: {service.estimated_minutes} dakika</small></div><b>{service.credits}<small> kredi</small></b></article>)}</div></section>; })}</div>;
}

type CreditPackage = { credits: number; amountUsd: number; amountMinor: number; label: string };
type CreditPayment = { id: string; credits: number; amountUsd: number; currency: string; provider: string; status: string; testMode: boolean; failureMessage: string | null; createdAt: number; paidAt: number | null };
type CreditPaymentPayload = { configuration: { provider: string; configured: boolean; testMode: boolean; currency: string }; packages: CreditPackage[]; payments: CreditPayment[] };

function CustomerCredits({ notify, onBalanceRefresh }: { notify: (message: string) => void; onBalanceRefresh: () => void }) {
  const [payload, setPayload] = useState<CreditPaymentPayload | null>(null);
  const [selected, setSelected] = useState(50);
  const [iframeUrl, setIframeUrl] = useState("");
  const [activePaymentId, setActivePaymentId] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  async function load(silent = false) {
    try {
      const response = await fetch("/api/payments", { cache: "no-store" });
      const next = await readApiResponse<CreditPaymentPayload>(response);
      setPayload(next);
      const active = next.payments.find(payment => payment.id === activePaymentId);
      if (active?.status === "SUCCEEDED") {
        setIframeUrl("");
        setActivePaymentId("");
        notify(`${active.credits} kredi hesabınıza eklendi`);
        onBalanceRefresh();
      } else if (active?.status === "FAILED") {
        setIframeUrl("");
        setActivePaymentId("");
        setError(active.failureMessage || "Ödeme tamamlanmadı");
      }
    } catch (caught) {
      if (!silent) setError(caught instanceof Error ? caught.message : "Kredi paketleri alınamadı");
    } finally { if (!silent) setLoading(false); }
  }

  useEffect(() => { void load(); }, []);
  useEffect(() => {
    if (!activePaymentId) return;
    const timer = window.setInterval(() => void load(true), 4000);
    return () => window.clearInterval(timer);
  }, [activePaymentId]);

  async function startPayment() {
    setBusy(true);
    setError("");
    try {
      const response = await fetch("/api/payments", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ credits: selected }) });
      const result = await readApiResponse<{ paymentId: string; iframeUrl: string }>(response);
      setActivePaymentId(result.paymentId);
      setIframeUrl(result.iframeUrl);
      notify("Güvenli PayTR ödeme ekranı açıldı");
      await load(true);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Ödeme başlatılamadı");
    } finally { setBusy(false); }
  }

  const selectedPackage = payload?.packages.find(item => item.credits === selected);
  return <div className="view creditPurchasePage">
    <div className="pageHead creditPageHead"><div><span className="eyebrow">GÜVENLİ ÖDEME</span><h1>Kredi paketleri</h1><p>İhtiyacınız kadar kredi alın; kredileriniz ödeme onayından hemen sonra hesabınıza eklenir.</p></div><div className="paytrTrust"><span>Güvenli ödeme</span><strong>PayTR</strong><small>3D Secure destekli</small></div></div>
    {loading ? <section className="card paymentLoading">Kredi paketleri hazırlanıyor…</section> : <>
      {!payload?.configuration.configured && <div className="paymentSetupNotice"><span>◈</span><div><strong>Ödeme sistemi aktivasyon bekliyor</strong><p>PayTR mağaza bilgileri bağlandığında bu sayfadaki güvenli ödeme düğmesi otomatik olarak canlı çalışacak. Paket seçimi ve ödeme altyapısı hazırdır.</p></div></div>}
      <div className="creditPackageGrid">{payload?.packages.map((item, index) => <button type="button" className={`creditPackageCard ${selected === item.credits ? "selected" : ""} ${index === 1 ? "popular" : ""}`} key={item.credits} onClick={() => setSelected(item.credits)}>
        {index === 1 && <span className="packageRibbon">EN ÇOK TERCİH EDİLEN</span>}<span className="packageIcon">CC</span><strong>{item.credits}</strong><small>KREDİ</small><div className="packagePrice"><b>${item.amountUsd}</b><span>USD</span></div><i>{selected === item.credits ? "✓ Seçildi" : "Paketi seç"}</i>
      </button>)}</div>
      <section className="card paymentCheckoutBar"><div><span>Seçilen paket</span><strong>{selectedPackage?.credits || selected} kredi</strong><small>Tek seferlik ödeme · Abonelik yok</small></div><div className="checkoutTotal"><span>Toplam</span><strong>${selectedPackage?.amountUsd || selected}.00</strong></div><button className="primaryBtn paymentButton" disabled={busy || !payload?.configuration.configured} onClick={() => void startPayment()}>{busy ? "Ödeme hazırlanıyor…" : "Güvenli ödemeye geç →"}</button></section>
      {error && <div className="formError paymentError">{error}</div>}
      <section className="card paymentHistory"><div className="cardHead"><div><h2>Ödeme geçmişi</h2><span className="muted">Son kredi hareketleriniz</span></div><button className="secondaryBtn" onClick={() => void load()}>Yenile</button></div>{payload?.payments.length ? <div className="paymentRows">{payload.payments.map(payment => <div className="paymentRow" key={payment.id}><span className="paymentRef"><strong>{payment.credits} kredi</strong><small>{payment.id}</small></span><span><strong>${payment.amountUsd.toFixed(2)}</strong><small>{new Intl.DateTimeFormat("tr-TR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(payment.createdAt))}</small></span><span className={`paymentStatus ${payment.status.toLowerCase()}`}>{payment.status === "SUCCEEDED" ? "Tamamlandı" : payment.status === "FAILED" ? "Başarısız" : "Bekliyor"}</span></div>)}</div> : <div className="emptyOrders compactEmpty"><span>◇</span><strong>Henüz kredi ödemesi yok</strong><p>İlk satın alımınız burada görüntülenecek.</p></div>}</section>
    </>}
    {iframeUrl && <div className="paymentModal" role="dialog" aria-modal="true" aria-label="PayTR güvenli ödeme"><div className="paymentModalPanel"><div className="paymentModalHead"><div><strong>Güvenli ödeme</strong><span>{selected} kredi · ${selected}.00</span></div><button className="iconBtn" aria-label="Ödeme penceresini kapat" onClick={() => { setIframeUrl(""); setActivePaymentId(""); }}>×</button></div><iframe src={iframeUrl} title="PayTR güvenli ödeme" allow="payment" /><div className="paymentModalFoot"><span>🔒 Kart bilgileriniz CHIP CENTER sunucularında saklanmaz.</span><button className="secondaryBtn" onClick={() => void load()}>Ödeme durumunu kontrol et</button></div></div></div>}
  </div>;
}

function formatBytes(bytes: number) {
  if (bytes === 0) return "0 B";
  const units = ["B", "KB", "MB", "GB"];
  const unit = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
  return `${(bytes / Math.pow(1024, unit)).toFixed(unit ? 1 : 0)} ${units[unit]}`;
}

function fileExtension(name: string) {
  const extension = name.includes(".") ? name.split(".").pop() : "DOSYA";
  return (extension || "DOSYA").slice(0, 5).toUpperCase();
}

function CustomerPageSettingsView({ settings, onSaved, notify }: { settings: CustomerPageSettings; onSaved: (settings: CustomerPageSettings) => void; notify: (message: string) => void }) {
  const [draft, setDraft] = useState(settings);
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoPreview, setLogoPreview] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const logoInput = useRef<HTMLInputElement>(null);

  useEffect(() => setDraft(settings), [settings]);
  useEffect(() => {
    if (!logoFile) { setLogoPreview(""); return; }
    const url = URL.createObjectURL(logoFile);
    setLogoPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [logoFile]);

  function toggle(key: "panel_notifications" | "email_notifications" | "support_module" | "live_chat") {
    setDraft(current => ({ ...current, [key]: current[key] ? 0 : 1 }));
  }

  function chooseLogo(file?: File) {
    if (!file) return;
    if (!new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]).has(file.type)) { setError("Logo PNG, JPG, WEBP veya GIF olmalı"); return; }
    if (file.size > 1024 * 1024) { setError("Logo en fazla 1 MB olabilir"); return; }
    setLogoFile(file);
    setError("");
  }

  async function save() {
    setSaving(true);
    setError("");
    try {
      const response = await fetch("/api/customer-settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({
        portalName: draft.portal_name, menuColor: draft.menu_color, menuTextColor: draft.menu_text_color, accentColor: draft.accent_color,
        panelNotifications: Boolean(draft.panel_notifications), emailNotifications: Boolean(draft.email_notifications),
        supportModule: Boolean(draft.support_module), liveChat: Boolean(draft.live_chat),
      }) });
      let saved = await readApiResponse<CustomerPageSettings>(response);
      if (logoFile) {
        const logoResponse = await fetch("/api/customer-settings/logo", { method: "PUT", headers: { "Content-Type": logoFile.type }, body: logoFile });
        saved = await readApiResponse<CustomerPageSettings>(logoResponse);
      }
      window.localStorage.setItem("chipcenter:live-alerts", saved.panel_notifications ? "on" : "off");
      if (saved.panel_notifications) await enableLiveAlerts();
      onSaved(saved);
      setLogoFile(null);
      notify("Sayfa ayarları kaydedildi ve uygulandı");
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Ayarlar kaydedilemedi");
    } finally { setSaving(false); }
  }

  const currentLogo = logoPreview || (settings.logo_key ? `/api/customer-settings/logo?v=${settings.updated_at}` : "/chipcenter-logo.png");
  return <div className="view customerSettingsPage">
    <div className="pageHead"><div><span className="eyebrow">SAYFA AYARLARI</span><h1>Müşteri portalını özelleştirin</h1><p>Marka görünümü, renkler, modüller ve bildirim tercihlerini yönetin.</p></div></div>
    <section className="card settingsPanel">
      <div className="settingsTitle"><span className="settingsTitleIcon">✎</span><div><h2>Sayfa Ayarları</h2><p>Değişiklikler kaydedildiğinde müşteri portalına anında uygulanır.</p></div></div>
      <div className="settingsRows">
        <div className="settingsRow"><label htmlFor="portal-name">Firma adı</label><input id="portal-name" className="settingsTextInput" value={draft.portal_name} onChange={event => setDraft(current => ({ ...current, portal_name: event.target.value }))} /></div>
        <div className="settingsRow settingsLogoRow"><label>Firma logosu</label><div className="logoPicker"><div className="logoPreview"><img src={currentLogo} alt="Firma logosu önizleme" /></div><input ref={logoInput} className="hiddenFileInput" type="file" accept="image/png,image/jpeg,image/webp,image/gif" onChange={event => { chooseLogo(event.target.files?.[0]); event.target.value = ""; }} /><button className="secondaryBtn" type="button" onClick={() => logoInput.current?.click()}>Dosya seç</button><span>{logoFile?.name || "PNG, JPG, WEBP veya GIF · Maks. 1 MB"}</span></div></div>
        <SettingsColor label="Menü rengi" value={draft.menu_color} onChange={value => setDraft(current => ({ ...current, menu_color: value }))} />
        <SettingsColor label="Menü yazı rengi" value={draft.menu_text_color} onChange={value => setDraft(current => ({ ...current, menu_text_color: value }))} />
        <SettingsColor label="Vurgu ve ikon rengi" value={draft.accent_color} onChange={value => setDraft(current => ({ ...current, accent_color: value }))} />
      </div>
      <div className="settingsDivider" />
      <div className="settingsSwitchGrid">
        <SettingsToggle label="Panelde sesli bildirim" value={Boolean(draft.panel_notifications)} onChange={() => toggle("panel_notifications")} />
        <SettingsToggle label="Hazır dosya e-posta bildirimi" value={Boolean(draft.email_notifications)} onChange={() => toggle("email_notifications")} />
        <SettingsToggle label="Destek modülü" value={Boolean(draft.support_module)} onChange={() => toggle("support_module")} />
        <SettingsToggle label="Canlı sohbet" value={Boolean(draft.live_chat)} onChange={() => toggle("live_chat")} />
      </div>
      <p className="settingsHint">E-posta bildirim tercihiniz kaydedilir. Hazır dosya ve ödeme bildirimleri e-posta ile gönderilir.</p>
      {error && <div className="formError">{error}</div>}
      <div className="settingsSave"><button className="primaryBtn" disabled={saving} onClick={() => void save()}>{saving ? "Kaydediliyor…" : "✓ Değişiklikleri kaydet"}</button></div>
    </section>
  </div>;
}

function SettingsColor({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
  return <div className="settingsRow"><label>{label}</label><div className="colorControl"><input className="settingsTextInput" value={value} maxLength={7} onChange={event => onChange(event.target.value)} /><input type="color" value={/^#[0-9a-f]{6}$/i.test(value) ? value : "#000000"} onChange={event => onChange(event.target.value)} aria-label={`${label} seç`} /></div></div>;
}

function SettingsToggle({ label, value, onChange }: { label: string; value: boolean; onChange: () => void }) {
  return <div className="settingsToggleRow"><span>{label}</span><button type="button" className={`settingsToggle ${value ? "on" : "off"}`} role="switch" aria-checked={value} onClick={onChange}><span>{value ? "Evet" : "Hayır"}</span><i /></button></div>;
}

function CustomerSupport({ user, notify, liveChatEnabled, openTickets }: { user: PortalUser; notify: (s: string) => void; liveChatEnabled: boolean; openTickets: number }) {
  const [conversation, setConversation] = useState<ChatConversation | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [draft, setDraft] = useState("");
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [tickets, setTickets] = useState<SupportTicket[]>([]);
  const [ticketFormOpen, setTicketFormOpen] = useState(false);
  const [ticketSubject, setTicketSubject] = useState("");
  const [ticketDescription, setTicketDescription] = useState("");
  const [ticketCategory, setTicketCategory] = useState("Teknik");
  const [ticketSending, setTicketSending] = useState(false);
  const messagesEnd = useRef<HTMLDivElement>(null);
  const knownLastMessage = useRef<string | null>(null);
  const chatInitialized = useRef(false);

  async function applyPayload(response: Response, announce = true) {
    const payload = await readApiResponse<ChatPayload>(response);
    const last = payload.messages.at(-1);
    if (announce && chatInitialized.current && last && last.id !== knownLastMessage.current && last.sender_id !== user.id) {
      sendLiveAlert("Canlı destek yanıtı", `${last.sender_name}: ${last.body}`);
      notify("Canlı destekten yeni mesaj geldi");
    }
    knownLastMessage.current = last?.id || null;
    chatInitialized.current = true;
    setConversation(payload.conversation);
    setMessages(payload.messages);
    if (payload.conversation?.customer_unread) {
      void fetch("/api/live-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "read", conversationId: payload.conversation.id }) });
    }
    return payload;
  }

  useEffect(() => {
    if (!liveChatEnabled) return;
    let active = true;
    async function refresh() {
      try {
        const response = await fetch("/api/live-chat", { 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); };
  }, [liveChatEnabled]);

  useEffect(() => { messagesEnd.current?.scrollIntoView({ behavior: "smooth", block: "end" }); }, [messages.length]);

  useEffect(() => {
    let active = true;
    async function refreshTickets() {
      try {
        const response = await fetch("/api/support-tickets", { cache: "no-store" });
        const payload = await readApiResponse<{ tickets: SupportTicket[] }>(response);
        if (active) setTickets(payload.tickets);
      } catch {
        // Canlı sohbet, normal destek listesi geçici olarak alınamasa da çalışmaya devam eder.
      }
    }
    void refreshTickets();
    const timer = window.setInterval(refreshTickets, 15_000);
    return () => { active = false; window.clearInterval(timer); };
  }, []);

  async function createTicket() {
    if (ticketSubject.trim().length < 4 || ticketDescription.trim().length < 10) {
      setError("Normal destek talebi için konu ve en az 10 karakterlik açıklama yazın");
      return;
    }
    setTicketSending(true);
    setError("");
    try {
      const response = await fetch("/api/support-tickets", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ subject: ticketSubject, description: ticketDescription, category: ticketCategory }),
      });
      const payload = await readApiResponse<{ ticket: SupportTicket }>(response);
      setTickets(current => [payload.ticket, ...current]);
      setTicketSubject("");
      setTicketDescription("");
      setTicketFormOpen(false);
      notify(`${payload.ticket.id} normal destek talebi oluşturuldu`);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Destek talebi oluşturulamadı");
    } finally { setTicketSending(false); }
  }

  async function action(actionName: "start" | "message" | "close") {
    if (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 }),
      });
      const payload = await applyPayload(response, false);
      if (actionName === "message") {
        setDraft("");
        if (payload.emailNotification?.status === "sent") notify("Mesajınız gönderildi · Yönetici e-postası Resend tarafından kabul edildi");
        else if (payload.emailNotification?.status === "failed") notify("Mesajınız gönderildi · Yönetici e-posta bildirimi başarısız oldu");
        else notify("Mesajınız gönderildi");
      }
      if (actionName === "start") notify("Canlı destek görüşmesi başladı");
      if (actionName === "close") notify("Canlı destek görüşmesi kapatıldı");
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "İşlem tamamlanamadı");
    } finally { setSending(false); }
  }

  const visibleTicketCount = tickets.filter(ticket => !["CLOSED", "RESOLVED", "KAPALI", "ÇÖZÜLDÜ"].includes(ticket.status.toUpperCase())).length || openTickets;
  return <div className="view"><div className="pageHead"><div><span className="eyebrow">DESTEK</span><h1>Size nasıl yardımcı olabiliriz?</h1><p>Canlı sohbet anlık görüşme içindir; normal destek talebi kayıt altında takip edilir.</p></div><button className="primaryBtn" onClick={() => setTicketFormOpen(current => !current)}>+ Normal destek talebi</button></div>
    {ticketFormOpen && <section className="card normalTicketForm"><div className="cardHead"><div><h2>Normal destek talebi oluştur</h2><span className="muted">Talebiniz kayıt altına alınır ve destek ekibinin kuyruğuna düşer.</span></div><button className="iconBtn" aria-label="Formu kapat" onClick={() => setTicketFormOpen(false)}>×</button></div><div className="formGrid"><CustomerField label="Kategori"><select value={ticketCategory} onChange={event => setTicketCategory(event.target.value)}><option>Teknik</option><option>Dosya</option><option>Ödeme</option><option>Hesap</option><option>Diğer</option></select></CustomerField><CustomerField label="Konu *"><input value={ticketSubject} maxLength={120} onChange={event => setTicketSubject(event.target.value)} placeholder="Kısaca sorununuzu yazın" /></CustomerField></div><CustomerField label="Açıklama *"><textarea value={ticketDescription} maxLength={4000} onChange={event => setTicketDescription(event.target.value)} placeholder="Sorununuzu ayrıntılı olarak açıklayın…" /></CustomerField><div className="modalActions"><button className="secondaryBtn" disabled={ticketSending} onClick={() => setTicketFormOpen(false)}>Vazgeç</button><button className="primaryBtn" disabled={ticketSending || ticketSubject.trim().length < 4 || ticketDescription.trim().length < 10} onClick={() => void createTicket()}>{ticketSending ? "Gönderiliyor…" : "Destek talebini gönder"}</button></div></section>}
    <div className="supportLayout"><div className="card"><div className="cardHead"><div><h2>Normal destek talepleri</h2><span className="muted">{visibleTicketCount} açık talep</span></div><span className="badge waiting">KAYITLI DESTEK</span></div>{tickets.length ? <div className="normalTicketList">{tickets.map(ticket => <article className="normalTicketRow" key={ticket.id}><span className="actIcon">?</span><div><strong>{ticket.subject}</strong><small>{ticket.id} · {ticket.category} · {new Intl.DateTimeFormat("tr-TR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(ticket.created_at))}</small><p>{ticket.description}</p></div><span className={`badge ${ticket.status === "OPEN" ? "waiting" : "ready"}`}>{ticket.status === "OPEN" ? "Açık" : ticket.status}</span></article>)}</div> : <div className="emptyOrders compactEmpty"><span>✓</span><strong>Açık normal destek talebiniz yok</strong><p>Yeni bir talep oluşturduğunuzda burada görünecek.</p></div>}</div>
      {liveChatEnabled && <section className="card liveChatCard"><div className="liveChatHead"><div><span className="onlineState"><i /> CANLI · ÇEVRİMİÇİ</span><h2>{conversation ? "Chip Center ile canlı görüşmeniz" : "Canlı destek ekibi hazır"}</h2><p>{conversation ? "Bu ekrandan ayrılmadan anlık mesajlaşabilirsiniz." : "Canlı görüşme mesajları doğrudan admin ekranına düşer."}</p></div>{conversation && <button className="secondaryBtn chatCloseBtn" disabled={sending} onClick={() => void action("close")}>Görüşmeyi bitir</button>}</div>
        {loading ? <div className="chatLoading">Canlı destek bağlanıyor…</div> : !conversation ? <div className="chatStart"><span>◈</span><strong>Destek ekibi şu anda çevrimiçi</strong><p>Canlı görüşmeyi başlatın; yazışma bu sayfada anlık açılacak.</p><button className="primaryBtn" disabled={sending} onClick={() => void action("start")}>{sending ? "Bağlanıyor…" : "Canlı sohbeti başlat"}</button></div> : <><div className="chatMessages" aria-live="polite">{!messages.length && <div className="chatWelcome"><strong>Canlı görüşme başladı</strong><span>Sorununuzu aşağıya yazın. Destek ekibi bu konuşmayı admin panelinden anlık görebilir.</span></div>}{messages.map(message => <div key={message.id} className={`chatBubbleRow ${message.sender_id === user.id ? "mine" : "theirs"}`}><div className="chatBubble"><div><strong>{message.sender_id === user.id ? "Siz" : message.sender_name}</strong><time>{formatChatTime(message.created_at)}</time></div><p>{message.body}</p>{message.sender_id === user.id && <span className={`chatReceipt ${message.read_at ? "read" : "sent"}`}>{message.read_at ? "✓✓ Okundu" : "✓ Gönderildi"}</span>}</div></div>)}<div ref={messagesEnd} /></div><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="Canlı mesajınızı yazın…" aria-label="Canlı destek mesajı"/><button className="primaryBtn" disabled={sending || !draft.trim()} type="submit">{sending ? "…" : "Gönder"}</button></form></>}
        {error && <div className="formError">{error}</div>}
      </section>}
    </div></div>;
}

function formatChatTime(value: number) {
  return new Intl.DateTimeFormat("tr-TR", { hour: "2-digit", minute: "2-digit" }).format(new Date(value));
}

function CustomerAccount({ user, notify, onUpdated }: { user: PortalUser; notify: (s: string) => void; onUpdated: (user: PortalUser) => void }) {
  const [name, setName] = useState(user.name);
  const [company, setCompany] = useState(user.company || "");
  const [phone, setPhone] = useState(user.phone || "");
  const [city, setCity] = useState(user.city || "");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  async function save() {
    setSaving(true);
    setError("");
    try {
      const response = await fetch("/api/profile", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, company, phone, city }) });
      const payload = await readApiResponse<{ user: PortalUser }>(response);
      onUpdated(payload.user);
      setPhone(payload.user.phone || "");
      notify("Profiliniz ve telefon numaranız veritabanına kaydedildi");
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Profil güncellenemedi");
    } finally { setSaving(false); }
  }

  return <div className="view accountSettingsPage"><div className="pageHead"><div><span className="eyebrow">HESABIM</span><h1>Hesap ayarları</h1><p>Firma ve iletişim bilgilerinizi yönetin.</p></div></div><div className="card accountSettingsCard"><div className="accountProfileIntro"><span>{user.name.slice(0, 1).toUpperCase()}</span><div><strong>{user.company || user.name}</strong><small>{user.email}</small></div><b>DOĞRULANMIŞ HESAP</b></div><div className="formGrid"><CustomerField label="Firma adı"><input value={company} onChange={event => setCompany(event.target.value)} /></CustomerField><CustomerField label="Yetkili kişi"><input value={name} onChange={event => setName(event.target.value)} /></CustomerField><CustomerField label="E-posta"><input value={user.email} readOnly /></CustomerField><CustomerField label="Telefon *"><input inputMode="tel" value={phone} onChange={event => setPhone(event.target.value)} placeholder="0532 123 45 67 veya +905321234567" /></CustomerField><CustomerField label="Şehir"><input value={city} onChange={event => setCity(event.target.value)} placeholder="Örn. İstanbul" /></CustomerField></div><div className="phoneFormatNote"><span>✓</span><div><strong>Türkiye numaralarını doğrudan yazabilirsiniz</strong><small>0532… veya 532… biçimi otomatik olarak +90 ülke koduna çevrilir.</small></div></div>{error && <div className="formError">{error}</div>}<div className="modalActions"><button className="primaryBtn" disabled={saving || !name.trim() || !phone.trim()} onClick={() => void save()}>{saving ? "Kaydediliyor…" : "Değişiklikleri kaydet"}</button></div></div></div>;
}

function CustomerField({ label, children }: { label: string; children: React.ReactNode }) {
  return <div className="field"><label>{label}</label>{children}</div>;
}
