// ──── LAB MANAGEMENT ────

const LAB_WORK_TYPES = [
  "Zirkonyum Kron", "Metal Porselen Kron", "Porselen Veneer", "İmplant Üst Yapısı",
  "Tam Protez", "Parsiyel Protez", "Köprü", "İnley / Onley",
  "Geçici Kron", "Gece Koruyucusu", "Retainer", "Diğer",
];

const LAB_STATUSES = ["Gönderildi", "Üretimde", "Kargoda", "Teslim Alındı"];

function labStatusStyle(s) {
  if (s === "Gönderildi")    return { bg: "#dbeafe", color: "#1d4ed8" };
  if (s === "Üretimde")      return { bg: "#dcfce7", color: "#15803d" };
  if (s === "Kargoda")       return { bg: "#e0f2fe", color: "#0369a1" };
  if (s === "Teslim Alındı") return { bg: "#fee2e2", color: "#b91c1c" };
  return { bg: "#f1f5f9", color: "#64748b" };
}

function LabStatusPill({ status }) {
  const s = labStatusStyle(status);
  return (
    <span style={{ display:"inline-flex", alignItems:"center", padding:"2px 9px", borderRadius:99, fontSize:11, fontWeight:600, background:s.bg, color:s.color }}>
      {status}
    </span>
  );
}

// ── Lab Yönetimi Modalı ────────────────────────────────────────────────────

function LabsModal({ labs, onAdd, onDelete, onClose }) {
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");

  const handleAdd = (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    onAdd({ id: "lab_" + Date.now(), name: name.trim(), phone: phone.trim() });
    setName(""); setPhone("");
  };

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{ maxWidth: 420 }}>
        <div className="modal__head">
          <span className="modal__title">Laboratuvarlar</span>
          <button className="icon-btn" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div className="modal__body">
          {labs.length === 0 && <p style={{ fontSize:13, color:"var(--text-mute)", marginBottom:14 }}>Henüz laboratuvar eklenmedi.</p>}
          {labs.map(l => (
            <div key={l.id} style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"8px 0", borderBottom:"1px solid var(--line)" }}>
              <div>
                <div style={{ fontWeight:600, fontSize:13, color:"var(--ink)" }}>{l.name}</div>
                {l.phone && <div style={{ fontSize:12, color:"var(--text-mute)" }}>{l.phone}</div>}
              </div>
              <button className="icon-btn" onClick={() => onDelete(l.id)} title="Sil">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
              </button>
            </div>
          ))}
          <hr className="divider"/>
          <form onSubmit={handleAdd}>
            <div className="form-row">
              <div className="form-field">
                <label>Lab Adı *</label>
                <input value={name} onChange={e => setName(e.target.value)} placeholder="Dental-X Lab" required autoFocus/>
              </div>
              <div className="form-field">
                <label>Telefon</label>
                <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="0212 000 00 00"/>
              </div>
            </div>
            <div style={{ marginTop:10, display:"flex", justifyContent:"flex-end" }}>
              <button type="submit" className="btn btn--accent btn--sm">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Ekle
              </button>
            </div>
          </form>
        </div>
        <div className="modal__foot">
          <button className="btn btn--ghost" onClick={onClose}>Kapat</button>
        </div>
      </div>
    </div>
  );
}

// ── Yeni Sipariş Modalı ────────────────────────────────────────────────────

function NewLabOrderModal({ labs, patients, clinics, initial, onSave, onClose }) {
  const today = new Date().toISOString().slice(0, 10);
  const empty = {
    patientId: "", patientName: "", labId: labs[0]?.id || "",
    clinicId: clinics[0]?.id || "", workType: LAB_WORK_TYPES[0],
    sentDate: today, expectedDate: "", returnDate: "",
    status: "Gönderildi", cost: "", notes: "",
  };
  const [form, setForm] = React.useState(initial ? { ...empty, ...initial, cost: String(initial.cost ?? "") } : empty);
  const [patientMode, setPatientMode] = React.useState(initial?.patientId ? "existing" : "name");
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const { DatePicker } = window.DentUI;

  const handleSubmit = (e) => {
    e.preventDefault();
    const pName = patientMode === "existing"
      ? (patients.find(p => p.id === form.patientId)?.name || "")
      : form.patientName;
    if (!pName.trim()) return;
    onSave({
      ...form,
      id: form.id || "lo_" + Date.now(),
      patientName: pName,
      patientId: patientMode === "existing" ? form.patientId : "",
      cost: parseFloat(form.cost) || 0,
    });
  };

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{ maxWidth: 500 }}>
        <div className="modal__head">
          <span className="modal__title">{initial ? "Siparişi Düzenle" : "Yeni Lab Siparişi"}</span>
          <button className="icon-btn" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal__body">
            {/* Hasta */}
            <div className="form-field" style={{ marginBottom:14 }}>
              <label>Hasta *</label>
              <div className="radio-group" style={{ marginBottom:8 }}>
                <button type="button" className={`radio-opt ${patientMode==="existing"?"is-on":""}`} onClick={() => setPatientMode("existing")}>Kayıtlı hasta</button>
                <button type="button" className={`radio-opt ${patientMode==="name"?"is-on":""}`} onClick={() => setPatientMode("name")}>İsim yaz</button>
              </div>
              {patientMode === "existing"
                ? <select value={form.patientId} onChange={e => set("patientId", e.target.value)} required>
                    <option value="">— Seçin —</option>
                    {patients.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                  </select>
                : <input value={form.patientName} onChange={e => set("patientName", e.target.value)} placeholder="Hasta adı soyadı" required autoFocus/>
              }
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Laboratuvar *</label>
                {labs.length > 0
                  ? <select value={form.labId} onChange={e => set("labId", e.target.value)} required>
                      {labs.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
                    </select>
                  : <input value={form.labId} onChange={e => set("labId", e.target.value)} placeholder="Lab adı" required/>
                }
              </div>
              <div className="form-field">
                <label>Klinik</label>
                <select value={form.clinicId} onChange={e => set("clinicId", e.target.value)}>
                  {clinics.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>İş Türü</label>
                <select value={form.workType} onChange={e => set("workType", e.target.value)}>
                  {LAB_WORK_TYPES.map(w => <option key={w}>{w}</option>)}
                </select>
              </div>
              <div className="form-field">
                <label>Durum</label>
                <select value={form.status} onChange={e => set("status", e.target.value)}>
                  {LAB_STATUSES.map(s => <option key={s}>{s}</option>)}
                </select>
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Gönderim Tarihi</label>
                <DatePicker value={form.sentDate} onChange={v => set("sentDate", v)}/>
              </div>
              <div className="form-field">
                <label>Beklenen Teslim</label>
                <DatePicker value={form.expectedDate} onChange={v => set("expectedDate", v)}/>
              </div>
            </div>
            {(form.status === "Teslim Alındı" || form.status === "Hastaya Takıldı") && (
              <div className="form-row">
                <div className="form-field">
                  <label>Teslim Alınan Tarih</label>
                  <DatePicker value={form.returnDate} onChange={v => set("returnDate", v)}/>
                </div>
                <div className="form-field">
                  <label>Maliyet (₺)</label>
                  <input type="number" min="0" value={form.cost} onChange={e => set("cost", e.target.value)} placeholder="0"/>
                </div>
              </div>
            )}
            {form.status === "Gönderildi" || form.status === "Üretimde" ? (
              <div className="form-field">
                <label>Maliyet (₺)</label>
                <input type="number" min="0" value={form.cost} onChange={e => set("cost", e.target.value)} placeholder="0"/>
              </div>
            ) : null}
            <div className="form-field">
              <label>Not</label>
              <textarea value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="İsteğe bağlı not..." style={{ minHeight:56 }}/>
            </div>
          </div>
          <div className="modal__foot">
            <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
            <button type="submit" className="btn btn--accent">{initial ? "Kaydet" : "Sipariş Ekle"}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Ana Lab Görünümü ───────────────────────────────────────────────────────

function LabView({ data, labs, labOrders, onUpdateLabs, onUpdateLabOrders }) {
  const { Card, fmtTRY, fmtDate } = window.DentUI;
  const I = window.DentIcons;

  const [statusFilter, setStatusFilter] = React.useState("all");
  const [labFilter, setLabFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [showNewOrder, setShowNewOrder] = React.useState(false);
  const [editOrder, setEditOrder] = React.useState(null);
  const [showLabs, setShowLabs] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [linkCopied, setLinkCopied] = React.useState(null);
  const [linkLoading, setLinkLoading] = React.useState(null);
  const { ConfirmModal } = window.DentUI;

  const findLab = id => labs.find(l => l.id === id);
  const findClinic = id => data.CLINICS.find(c => c.id === id);

  // Sync status from lab_tracking on mount
  React.useEffect(() => {
    const ordersWithTokens = labOrders.filter(o => o.trackingToken);
    if (!ordersWithTokens.length || !window._sb) return;
    (async () => {
      const { data: rows } = await window._sb.from('lab_tracking')
        .select('token,status')
        .in('token', ordersWithTokens.map(o => o.trackingToken));
      if (!rows?.length) return;
      const map = Object.fromEntries(rows.map(r => [r.token, r.status]));
      let changed = false;
      const updated = labOrders.map(o => {
        if (o.trackingToken && map[o.trackingToken] && map[o.trackingToken] !== o.status) {
          changed = true;
          return { ...o, status: map[o.trackingToken] };
        }
        return o;
      });
      if (changed) onUpdateLabOrders(updated);
    })();
  }, []);

  // Realtime: lab_tracking güncellemelerini anlık al
  React.useEffect(() => {
    const sb = window._sb;
    const user = window._dentUser;
    if (!sb || !user) return;
    const channel = sb.channel('lab-tracking-' + user.id)
      .on('postgres_changes', {
        event: 'UPDATE',
        schema: 'public',
        table: 'lab_tracking',
        filter: `user_id=eq.${user.id}`,
      }, (payload) => {
        const { order_id, status } = payload.new;
        onUpdateLabOrders(prev =>
          prev.map(o => o.id === order_id && o.status !== status ? { ...o, status } : o)
        );
      })
      .subscribe();
    return () => sb.removeChannel(channel);
  }, []);

  const sendLabLink = async (order) => {
    setLinkLoading(order.id);
    try {
      const sb = window._sb;
      const user = window._dentUser;
      let token = order.trackingToken;
      if (!token) {
        const patientCode = "DS-" + order.id.slice(-6).toUpperCase();
        const { data: inserted, error } = await sb.from('lab_tracking').insert({
          user_id: user.id,
          order_id: order.id,
          work_type: order.workType,
          patient_code: patientCode,
          clinic_name: findClinic(order.clinicId)?.name || "",
          sent_date: order.sentDate,
          expected_date: order.expectedDate,
          notes: order.notes,
          status: order.status,
        }).select('token').single();
        if (error || !inserted) { alert("Bağlantı oluşturulamadı."); return; }
        token = inserted.token;
        onUpdateLabOrders(labOrders.map(o => o.id === order.id ? { ...o, trackingToken: token } : o));
      } else {
        await sb.from('lab_tracking').update({
          status: order.status, expected_date: order.expectedDate,
          notes: order.notes, updated_at: new Date().toISOString(),
        }).eq('token', token);
      }
      const url = `https://dentsideapp.com/lab.html?t=${token}`;
      try { await navigator.clipboard.writeText(url); }
      catch { window.prompt("Bu linki kopyalayın:", url); }
      setLinkCopied(order.id);
      setTimeout(() => setLinkCopied(null), 2500);
    } finally {
      setLinkLoading(null);
    }
  };

  const pending = labOrders.filter(o => o.status === "Gönderildi" || o.status === "Üretimde" || o.status === "Kargoda");
  const returned = labOrders.filter(o => o.status === "Teslim Alındı");
  const totalCost = labOrders.reduce((a, o) => a + (o.cost || 0), 0);
  const avgDays = (() => {
    const completed = labOrders.filter(o => o.sentDate && o.returnDate);
    if (!completed.length) return null;
    const avg = completed.reduce((a, o) => {
      const diff = (new Date(o.returnDate) - new Date(o.sentDate)) / 86400000;
      return a + diff;
    }, 0) / completed.length;
    return Math.round(avg);
  })();

  // Gecikme kontrolü
  const today = new Date().toISOString().slice(0, 10);
  const overdue = labOrders.filter(o =>
    (o.status === "Gönderildi" || o.status === "Üretimde" || o.status === "Kargoda") &&
    o.expectedDate && o.expectedDate < today
  );

  let list = labOrders;
  if (statusFilter !== "all") list = list.filter(o => o.status === statusFilter);
  if (labFilter !== "all") list = list.filter(o => o.labId === labFilter);
  if (search) list = list.filter(o => o.patientName?.toLowerCase().includes(search.toLowerCase()) || o.workType?.toLowerCase().includes(search.toLowerCase()));
  list = [...list].sort((a, b) => (b.sentDate || "").localeCompare(a.sentDate || ""));

  const handleSaveOrder = (order) => {
    if (editOrder) {
      onUpdateLabOrders(labOrders.map(o => o.id === order.id ? order : o));
      setEditOrder(null);
    } else {
      onUpdateLabOrders([...labOrders, order]);
    }
    setShowNewOrder(false);
  };

  const handleStatusChange = async (id, status) => {
    const order = labOrders.find(o => o.id === id);
    onUpdateLabOrders(labOrders.map(o => o.id === id ? { ...o, status } : o));
    if (order?.trackingToken && window._sb) {
      await window._sb.from('lab_tracking')
        .update({ status, updated_at: new Date().toISOString() })
        .eq('token', order.trackingToken);
    }
  };

  const handleDelete = (id) => {
    onUpdateLabOrders(labOrders.filter(o => o.id !== id));
    setConfirmDel(null);
  };

  return (
    <div className="view">
      <div className="page-head">
        <div>
          <h1 className="page-title">Laboratuvar</h1>
          <p className="page-sub">{labOrders.length} sipariş · {pending.length} bekliyor</p>
        </div>
        <div className="page-actions">
          <button className="btn btn--ghost" onClick={() => setShowLabs(true)}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M8 3h8M8 3v8L3 19a2 2 0 0 0 1.8 2.8h14.4A2 2 0 0 0 21 19l-5-8V3"/><path d="M6.5 15h11"/></svg>
            Laboratuvarlar ({labs.length})
          </button>
          <button className="btn btn--accent" onClick={() => { setEditOrder(null); setShowNewOrder(true); }}>
            <I.Plus size={15}/>Yeni Sipariş
          </button>
        </div>
      </div>

      {/* KPI kartları */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))", gap:12, marginBottom:20 }}>
        {[
          { label:"Toplam Sipariş", value: labOrders.length, unit:"adet", color:"var(--ink)" },
          { label:"Bekleyen",       value: pending.length,   unit:"adet", color:"#1d4ed8" },
          { label:"Teslim Alınan",  value: returned.length,  unit:"adet", color:"#15803d" },
          { label:"Lab Maliyeti",   value: fmtTRY(totalCost), unit:null,  color:"var(--accent)" },
        ].map(k => (
          <Card key={k.label} padding={16}>
            <div style={{ fontSize:11, fontWeight:600, color:"var(--text-mute)", textTransform:"uppercase", letterSpacing:".04em", marginBottom:6 }}>{k.label}</div>
            <div style={{ fontSize:22, fontWeight:800, color:k.color }}>{k.value}{k.unit ? <span style={{ fontSize:13, fontWeight:500, color:"var(--text-mute)", marginLeft:4 }}>{k.unit}</span> : ""}</div>
          </Card>
        ))}
      </div>

      {/* Gecikme uyarısı */}
      {overdue.length > 0 && (
        <div style={{ background:"#fff7ed", border:"1px solid #fed7aa", borderRadius:10, padding:"10px 16px", marginBottom:16, display:"flex", alignItems:"center", gap:8, fontSize:13, color:"#b45309", fontWeight:600 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          {overdue.length} sipariş beklenen teslim tarihini geçti: {overdue.map(o => o.patientName).join(", ")}
        </div>
      )}

      {/* Filtreler */}
      <div className="filters-bar" style={{ marginBottom:16 }}>
        <input className="search-box" value={search} onChange={e => setSearch(e.target.value)} placeholder="Hasta adı veya iş türü ara..." style={{ padding:"7px 12px", border:"1px solid var(--line-strong)", borderRadius:8, fontSize:13, fontFamily:"inherit", outline:"none", width:220 }}/>
        <div className="seg">
          <button className={`seg__opt ${statusFilter==="all"?"is-on":""}`} onClick={() => setStatusFilter("all")}>Tümü</button>
          {LAB_STATUSES.map(s => (
            <button key={s} className={`seg__opt ${statusFilter===s?"is-on":""}`} onClick={() => setStatusFilter(s)}>{s}</button>
          ))}
        </div>
        {labs.length > 0 && (
          <select value={labFilter} onChange={e => setLabFilter(e.target.value)}
            style={{ border:"1px solid var(--line-strong)", borderRadius:8, padding:"7px 10px", fontSize:13, fontFamily:"inherit", outline:"none" }}>
            <option value="all">Tüm Lablar</option>
            {labs.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
          </select>
        )}
      </div>

      {/* Tablo */}
      <Card padding={0}>
        <div style={{ overflowX:"auto" }}>
          <table style={{ width:"100%", borderCollapse:"collapse", fontSize:13 }}>
            <thead>
              <tr style={{ background:"var(--surface-2)", borderBottom:"1px solid var(--line)" }}>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Hasta</th>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>İş Türü</th>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Laboratuvar</th>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Gönderim</th>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Beklenen</th>
                <th style={{ padding:"10px 14px", textAlign:"left", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Durum</th>
                <th style={{ padding:"10px 14px", textAlign:"right", fontWeight:600, fontSize:12, color:"var(--ink)" }}>Maliyet</th>
                <th style={{ width:32 }}></th>
              </tr>
            </thead>
            <tbody>
              {list.length === 0 && (
                <tr><td colSpan={8} style={{ textAlign:"center", padding:40, color:"var(--text-mute)", fontSize:13 }}>
                  {labOrders.length === 0 ? "Henüz sipariş eklenmedi" : "Sonuç bulunamadı"}
                </td></tr>
              )}
              {list.map(o => {
                const lab = findLab(o.labId);
                const isOverdue = (o.status === "Gönderildi" || o.status === "Üretimde") && o.expectedDate && o.expectedDate < today;
                return (
                  <tr key={o.id} style={{ borderBottom:"1px solid var(--line)", background: isOverdue ? "#fff7ed" : undefined }}>
                    <td style={{ padding:"10px 14px", fontWeight:600, color:"var(--ink)" }}>{o.patientName || "—"}</td>
                    <td style={{ padding:"10px 14px" }}>{o.workType}</td>
                    <td style={{ padding:"10px 14px", color:"var(--text-mute)" }}>{lab?.name || o.labId || "—"}</td>
                    <td style={{ padding:"10px 14px", color:"var(--text-mute)" }}>{o.sentDate ? fmtDate(o.sentDate) : "—"}</td>
                    <td style={{ padding:"10px 14px" }}>
                      {o.expectedDate
                        ? <span style={{ color: isOverdue ? "#b45309" : "var(--text)", fontWeight: isOverdue ? 600 : 400 }}>
                            {fmtDate(o.expectedDate)}{isOverdue ? " ⚠" : ""}
                          </span>
                        : <span className="muted">—</span>
                      }
                    </td>
                    <td style={{ padding:"10px 14px" }}>
                      <div style={{ position:"relative", display:"inline-block" }}>
                        <LabStatusPill status={o.status}/>
                        <select value={o.status} onChange={e => handleStatusChange(o.id, e.target.value)}
                          style={{ position:"absolute", inset:0, opacity:0, cursor:"pointer", width:"100%", height:"100%" }}>
                          {LAB_STATUSES.map(s => <option key={s}>{s}</option>)}
                        </select>
                      </div>
                    </td>
                    <td style={{ padding:"10px 14px", textAlign:"right", fontWeight:600 }}>
                      {o.cost ? fmtTRY(o.cost) : <span className="muted">—</span>}
                    </td>
                    <td style={{ padding:"4px 8px" }}>
                      <div className="row-actions">
                        <button className="icon-btn" title="Lab takip linki gönder"
                          onClick={() => sendLabLink(o)}
                          style={{ color: linkCopied === o.id ? "#15803d" : o.trackingToken ? "#2B47E8" : undefined }}>
                          {linkLoading === o.id
                            ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{animation:"spin 1s linear infinite"}}><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                            : linkCopied === o.id
                              ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>
                              : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                          }
                        </button>
                        <button className="icon-btn" title="Düzenle" onClick={() => { setEditOrder(o); setShowNewOrder(true); }}>
                          <I.Edit size={14}/>
                        </button>
                        <button className="icon-btn" title="Sil" onClick={() => setConfirmDel(o)}>
                          <I.Trash size={14}/>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      {showNewOrder && (
        <NewLabOrderModal
          labs={labs} patients={data.PATIENTS} clinics={data.CLINICS}
          initial={editOrder}
          onSave={handleSaveOrder}
          onClose={() => { setShowNewOrder(false); setEditOrder(null); }}
        />
      )}

      {showLabs && (
        <LabsModal
          labs={labs}
          onAdd={l => onUpdateLabs([...labs, l])}
          onDelete={id => onUpdateLabs(labs.filter(l => l.id !== id))}
          onClose={() => setShowLabs(false)}
        />
      )}

      {confirmDel && (
        <ConfirmModal
          title="Siparişi Sil"
          message={`"${confirmDel.patientName} — ${confirmDel.workType}" siparişi kalıcı olarak silinecek.`}
          confirmLabel="Sil"
          danger
          onConfirm={() => handleDelete(confirmDel.id)}
          onCancel={() => setConfirmDel(null)}
        />
      )}
    </div>
  );
}

window._dsLab = LabView;

// Inject spin keyframe for link loading spinner
(function() {
  if (!document.getElementById('ds-lab-spin')) {
    const s = document.createElement('style');
    s.id = 'ds-lab-spin';
    s.textContent = '@keyframes spin{to{transform:rotate(360deg)}}';
    document.head.appendChild(s);
  }
})();
