// Core pages: Login, Reception Dashboard, Doctor Dashboard, New X-ray wizard

/* =========================================================
   LOGIN
   ========================================================= */
function LoginPage({ onLogin }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const submit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const data = await window.API.login(username, password);
      onLogin(data.user);
    } catch (err) {
      setError(err.message || 'Login muvaffaqiyatsiz');
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      <div className="login-bg"></div>
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 24 }}>
        <div className="page-in" style={{ width: 400, maxWidth: '100%' }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 28 }}>
            <LogoMark size={56} />
            <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--fg-1)', margin: '16px 0 4px', letterSpacing: '-0.02em' }}>
              Your <span style={{ color: 'var(--brand-secondary)' }}>Smile</span> Rentgen
            </h1>
            <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: 0, textAlign: 'center' }}>3D rentgen markazi tizimi</p>
          </div>

          <Card className="card--glass" style={{ padding: 28 }}>
            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Field label="Foydalanuvchi nomi" icon="user">
                <Input value={username} onChange={e => setUsername(e.target.value)} placeholder="username" icon autoFocus />
              </Field>
              <Field label="Parol" icon="lock">
                <Input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" icon />
              </Field>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <label className="checkbox">
                  <input type="checkbox" defaultChecked />
                  <span className="checkbox__box"></span>
                  <span className="checkbox__label" style={{ fontSize: 13 }}>Meni eslab qol</span>
                </label>
                <a href="#" style={{ fontSize: 13 }}>Parolni unutdingizmi?</a>
              </div>
              {error && <div className="field__error" style={{ background: 'var(--color-danger-soft)', padding: 10, borderRadius: 8 }}>{error}</div>}
              <Button variant="primary" size="lg" loading={loading} iconRight="arrow-right">Kirish</Button>
            </form>
          </Card>

          <div style={{ textAlign: 'center', marginTop: 24, fontSize: 12, color: 'var(--fg-4)' }}>
            © 2026 Your Smile Rentgen. Barcha huquqlar himoyalangan.
          </div>
        </div>
      </div>
    </>
  );
}

/* =========================================================
   RECEPTION DASHBOARD
   ========================================================= */
function ReceptionDashboard({ onNav, me }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [notifs, setNotifs] = useState([]);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    window.API.receptionDashboard()
      .then(d => { if (mounted) { setData(d); setLoading(false); } })
      .catch(() => { if (mounted) setLoading(false); });
    window.API.listNotifications(false)
      .then(rows => { if (mounted) setNotifs(Array.isArray(rows) ? rows.slice(0, 8) : []); })
      .catch(() => { if (mounted) setNotifs([]); });
    return () => { mounted = false; };
  }, []);

  const k = data?.kpis || { registered: 0, revenue: 0, debt: 0, pending: 0 };
  const recent = data?.recent || [];
  const weekData = data?.week_revenue || [];
  const hourly = data?.hourly_load || [];

  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Xayrli tong' : hour < 18 ? 'Xayrli kun' : 'Xayrli kech';
  const firstName = me?.full_name?.trim()?.split(/\s+/)?.[0] || me?.full_name || 'foydalanuvchi';

  // Sparklines from week revenue
  const spark1 = makeSpark(weekData.length ? weekData.map(w => w.value / 100000) : [4, 7, 6, 8, 11, 9, 14]);
  const spark2 = makeSpark(weekData.length ? weekData.map(w => w.value) : [1.2, 1.4, 1.1, 1.8, 1.6, 2.2, 1.35]);
  const spark3 = makeSpark([8, 6, 9, 7, 5, 6, 4]);
  const spark4 = makeSpark([3, 5, 4, 6, 4, 7, 5]);

  return (
    <div className="page-in" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {/* Aurora hero */}
      <div className="hero-aurora">
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 32, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.16em', color: 'rgba(56,189,248,0.9)', textTransform: 'uppercase', marginBottom: 8 }}>
              {uzDate(new Date())} · Reception
            </div>
            <h1 className="hero-aurora__title">{greeting}, {firstName} 👋</h1>
            <p className="hero-aurora__sub">{loading ? "Ma'lumot yuklanmoqda..." : `Bugun ${k.registered} ta bemor ro'yxatga olindi, ${k.pending} ta rentgen tayyorlanmoqda.`}</p>
          </div>
          <Button variant="gradient" size="lg" icon="plus-circle" onClick={() => onNav('new-visit')}>
            Yangi rentgen
          </Button>
        </div>
      </div>

      {/* KPI cards */}
      <div className="grid-cards-4 anim-stagger">
        <StatCard icon="user-plus" iconTone="" label="Bugun ro'yxatga olingan" value={k.registered}
          delta={12} sparkline={spark1} />
        <StatCard icon="wallet" iconTone="success" label="Bugungi tushum" value={k.revenue}
          format={(v) => uzMoneyShort(v)} delta={8} sparkline={spark2} />
        <StatCard icon="clock-counter-clockwise" iconTone="warning" label="Qarz qoldig'i" value={k.debt}
          format={(v) => uzMoneyShort(v)} delta={-4} sparkline={spark3} />
        <StatCard icon="upload-simple" iconTone="info" label="Yuklanmoqda" value={k.pending}
          delta={2} sparkline={spark4} />
      </div>

      {/* Two-column: today's records + activity */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 360px', gap: 24 }}>
        <Card style={{ padding: 0 }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div className="t-h5" style={{ marginBottom: 2 }}>Bugungi yozuvlar</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Oxirgi 8 ta vizit</div>
            </div>
            <Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => onNav('kassa')}>Hammasini ko'rish</Button>
          </div>
          <table className="table">
            <thead>
              <tr>
                <th>Vaqt</th>
                <th>Bemor</th>
                <th>Xizmat</th>
                <th className="text-right">Summa</th>
                <th>Holat</th>
              </tr>
            </thead>
            <tbody>
              {recent.length === 0 && !loading && (
                <tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--fg-4)', padding: 24 }}>Bugun yozuvlar yo'q</td></tr>
              )}
              {recent.map(v => (
                <tr key={v.id} onClick={() => onNav('patient-detail', { patientId: v.patient.id })}>
                  <td className="td-mono">{uzDateTime(v.created_at).split(', ')[1]}</td>
                  <td className="td-primary">{v.patient.full_name}</td>
                  <td>{v.doctor ? v.doctor.full_name : '—'}</td>
                  <td className="text-right td-primary">{uzMoneyShort(v.total_amount)}</td>
                  <td><StatusBadge status={v.payment_status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card style={{ padding: 0 }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div className="t-h5">So'nggi xabarlar</div>
              <span style={{ fontSize: 11, color: 'var(--fg-4)' }}>{notifs.length} ta</span>
            </div>
            <div style={{ padding: '6px 18px 14px' }}>
              {notifs.length === 0 && (
                <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--fg-4)', fontSize: 13 }}>
                  Hozircha xabar yo'q
                </div>
              )}
              {notifs.map(n => (
                <div key={n.id} className="activity-item" style={{ opacity: n.is_read ? 0.6 : 1 }}>
                  <div className="activity-item__dot activity-item__dot--info"><Icon name={(window.NOTIF_ICONS && window.NOTIF_ICONS[n.type]) || 'bell'} /></div>
                  <div className="activity-item__body">
                    <p className="activity-item__text"><strong>{n.title}</strong></p>
                    <span className="activity-item__meta">{window.uzDateTime ? window.uzDateTime(n.created_at) : n.created_at}</span>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <div className="row row-between" style={{ marginBottom: 12 }}>
              <div className="t-h5">Soatlik yuklanish</div>
              <span style={{ fontSize: 11, color: 'var(--fg-4)' }}>{new Date().toLocaleDateString('uz-UZ')}</span>
            </div>
            <HourlyLoadChart hourly={hourly} />
          </Card>
        </div>
      </div>
    </div>
  );
}

function HourlyLoadChart({ hourly }) {
  // Show 8h-22h
  const source = (hourly && hourly.length) ? hourly : Array.from({ length: 24 }, (_, h) => ({ hour: h, count: 0 }));
  const data = source.slice(8, 22);
  const max = Math.max(...data.map(d => d.count), 1);
  const now = new Date().getHours();
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 90 }}>
      {data.map(d => {
        const isNow = d.hour === now;
        return (
          <div key={d.hour} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
            <div style={{
              width: '100%',
              height: `${(d.count / max) * 100}%`,
              minHeight: 4,
              background: isNow ? 'var(--brand-gradient)' : 'var(--brand-primary-soft)',
              borderRadius: '4px 4px 0 0',
              transition: 'height 600ms var(--ease-out)',
            }}></div>
            <div style={{ fontSize: 9, color: isNow ? 'var(--brand-primary)' : 'var(--fg-4)', fontWeight: isNow ? 600 : 400 }}>{d.hour}</div>
          </div>
        );
      })}
    </div>
  );
}

/* =========================================================
   NEW X-RAY VISIT — the most important screen
   ========================================================= */
function normalizePatient(p) {
  if (!p) return p;
  return {
    ...p,
    name: p.full_name || p.name,
    fullName: p.full_name || p.fullName,
    birth: p.birth_date ? window.uzDate(p.birth_date) : (p.birth || '\u2014'),
    birthDate: p.birth_date ? new Date(p.birth_date) : (p.birthDate || null),
  };
}

function normalizeDoctor(d) {
  if (!d) return d;
  return {
    ...d,
    name: d.full_name || d.name,
    speciality: d.specialty || d.speciality || '\u2014',
    clinic: d.clinic || '\u2014',
    telegram: d.telegram_username || d.telegram,
  };
}

function normalizeService(s) {
  return { ...s, price: Number(s.price), cat: s.category || s.cat };
}

function NewVisitPage({ onNav, toast }) {
  const [patient, setPatient] = useState(null);
  const [doctor, setDoctor] = useState(null);
  const [noDoctor, setNoDoctor] = useState(false);
  const [selectedSvcs, setSelectedSvcs] = useState([]);
  const [payType, setPayType] = useState('cash');
  const [paymentStatus, setPaymentStatus] = useState('full');
  const [paidAmount, setPaidAmount] = useState('');
  const [showNewPatient, setShowNewPatient] = useState(false);
  const [showNewDoctor, setShowNewDoctor] = useState(false);
  const [saving, setSaving] = useState(false);

  // Data from API
  const [services, setServices] = useState([]);
  const [doctors, setDoctors] = useState([]);
  const [patients, setPatients] = useState([]);

  useEffect(() => {
    let mounted = true;
    Promise.all([
      window.API.listServices(),
      window.API.listDoctors(),
      window.API.listPatients({ limit: 200 }),
    ]).then(([svc, docs, pts]) => {
      if (!mounted) return;
      setServices(svc.map(normalizeService));
      setDoctors(docs.map(normalizeDoctor));
      setPatients(pts.map(normalizePatient));
    }).catch(err => {
      console.error('Load failed', err);
      toast({ kind: 'danger', title: "Ma'lumot yuklanmadi", msg: err.message });
    });
    return () => { mounted = false; };
  }, [toast]);

  const total = selectedSvcs.reduce((s, x) => s + Number(x.price), 0);
  const paid = paymentStatus === 'full' ? total
             : paymentStatus === 'debt' ? 0
             : parseInt((paidAmount || '0').replace(/\D/g,'')) || 0;
  const debt = Math.max(0, total - paid);

  const toggleSvc = (s) => {
    setSelectedSvcs(prev => prev.find(x => x.id === s.id) ? prev.filter(x => x.id !== s.id) : [...prev, s]);
  };

  const canSave = patient && selectedSvcs.length > 0 && !saving;

  const handleSave = async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      const payload = {
        services: selectedSvcs.map(s => ({ service_id: s.id, quantity: 1 })),
        payment_method: paymentStatus === 'debt' ? 'debt' : payType,
        paid_amount: paid,
      };
      if (typeof patient.id === 'number') {
        payload.patient_id = patient.id;
      } else {
        // New patient (created via modal \u2014 has temp shape)
        payload.patient_new = {
          full_name: patient.full_name || patient.name,
          phone: patient.phone || null,
          birth_date: patient.birth_date || (patient.birthDate ? patient.birthDate.toISOString().slice(0,10) : null),
          passport: patient.passport || null,
        };
      }
      if (doctor && typeof doctor.id === 'number' && String(doctor.id).match(/^\d+$/)) {
        payload.doctor_id = Number(doctor.id);
      } else if (doctor && !noDoctor) {
        payload.doctor_new = {
          full_name: doctor.full_name || doctor.name,
          phone: doctor.phone || null,
          specialty: doctor.specialty || doctor.speciality || null,
          clinic: doctor.clinic || null,
        };
      }
      const result = await window.API.createXrayRecord(payload);
      toast({ kind: 'success', title: 'Rentgen yozildi!', msg: `${result.patient.full_name} \u2014 ${uzMoney(total)}` });
      setTimeout(() => onNav('dashboard'), 700);
    } catch (err) {
      toast({ kind: 'danger', title: 'Saqlash xato', msg: err.message });
    } finally {
      setSaving(false);
    }
  };

  const grouped = useMemo(() => groupServicesByCat(services), [services]);

  return (
    <div className="page-in">
      <PageHeader
        title="Yangi rentgen ro'yxati"
        sub="Bemorni qidiring, xizmatlarni tanlang, to'lov qabul qiling"
        breadcrumbs={["Reception", "Yangi rentgen"]}
        actions={<Button variant="ghost" icon="x" onClick={() => onNav('dashboard')}>Bekor qilish</Button>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 340px', gap: 24 }}>
        {/* Left — sections */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* 1. Bemor */}
          <Card>
            <div className="row row-between" style={{ marginBottom: 16 }}>
              <div className="row row-3">
                <SectionNum n={1} done={!!patient} />
                <div>
                  <div className="t-h5">Bemor</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>F.I.O. yoki telefon orqali qidiring</div>
                </div>
              </div>
              {patient && (
                <Button variant="ghost" size="sm" icon="x" onClick={() => setPatient(null)}>O'zgartirish</Button>
              )}
            </div>

            {!patient ? (
              <>
                <Combobox
                  placeholder="Bemor F.I.O. yoki +998 90..."
                  items={patients}
                  displayKey="name"
                  secondaryKey="phone"
                  onChange={setPatient}
                  onCreate={() => setShowNewPatient(true)}
                  createLabel="+ Yangi bemor qo'shish"
                />
                <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, color: 'var(--fg-4)' }}>
                  <span>{patients.length ? `Bazada: ${patients.length} ta bemor` : "Bemorlar yuklanmoqda..."}</span>
                  <button className="btn btn--secondary btn--sm" onClick={() => setShowNewPatient(true)}>
                    <Icon name="user-plus" /> Yangi bemor
                  </button>
                </div>
              </>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: 'var(--brand-primary-soft)', border: '1px solid var(--brand-primary)', borderRadius: 12 }}>
                <Avatar name={patient.name || patient.full_name || '?'} size="lg" />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)' }}>{patient.fullName || patient.full_name || patient.name || '—'}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>
                    {[patient.phone, patient.birth, patient.birthDate ? `${age(patient.birthDate)} yosh` : null].filter(Boolean).join(' · ') || 'Ma\'lumot kiritilmagan'}
                  </div>
                </div>
                <Icon name="check-circle" weight="fill" style={{ color: 'var(--brand-primary)', fontSize: 22 }} />
              </div>
            )}
          </Card>

          {/* 2. Shifokor */}
          <Card>
            <div className="row row-between" style={{ marginBottom: 16 }}>
              <div className="row row-3">
                <SectionNum n={2} done={!!doctor || noDoctor} optional />
                <div>
                  <div className="t-h5">Shifokor <span style={{ color: 'var(--fg-4)', fontWeight: 400, fontSize: 13 }}>(ixtiyoriy)</span></div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Yo'naltirgan shifokor</div>
                </div>
              </div>
              {doctor && (
                <Button variant="ghost" size="sm" icon="x" onClick={() => setDoctor(null)}>O'zgartirish</Button>
              )}
            </div>

            {!doctor && !noDoctor ? (
              <>
                <Combobox
                  placeholder="Shifokor ismi yoki klinika..."
                  items={doctors}
                  displayKey="name"
                  secondaryKey="clinic"
                  onChange={setDoctor}
                  onCreate={() => setShowNewDoctor(true)}
                  createLabel="+ Yangi shifokor qo'shish"
                />
                <label className="checkbox" style={{ marginTop: 12 }}>
                  <input type="checkbox" checked={noDoctor} onChange={e => setNoDoctor(e.target.checked)} />
                  <span className="checkbox__box"></span>
                  <span className="checkbox__label" style={{ fontSize: 13 }}>Shifokor tanlanmagan</span>
                </label>
              </>
            ) : doctor ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: 'var(--surface-2)', border: '1px solid var(--border-1)', borderRadius: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--color-info-soft)', color: 'var(--color-info)', display: 'grid', placeItems: 'center' }}><Icon name="stethoscope" /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>{doctor.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{doctor.speciality} · {doctor.clinic}</div>
                </div>
                {doctor.telegram && <Badge tone="info" icon="paper-plane-tilt">Telegram</Badge>}
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: 'var(--surface-2)', border: '1px dashed var(--border-1)', borderRadius: 12 }}>
                <Icon name="info" style={{ color: 'var(--fg-3)' }} />
                <div style={{ flex: 1, fontSize: 13, color: 'var(--fg-3)' }}>Shifokorsiz — to'g'ridan-to'g'ri bemor.</div>
                <button className="btn btn--ghost btn--sm" onClick={() => setNoDoctor(false)}>Bekor qil</button>
              </div>
            )}
          </Card>

          {/* 3. Services */}
          <Card>
            <div className="row row-between" style={{ marginBottom: 16 }}>
              <div className="row row-3">
                <SectionNum n={3} done={selectedSvcs.length > 0} />
                <div>
                  <div className="t-h5">Xizmatlar</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Kamida 1 ta xizmat tanlang</div>
                </div>
              </div>
              {selectedSvcs.length > 0 && (
                <Badge tone="primary">{selectedSvcs.length} ta tanlandi</Badge>
              )}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {SERVICE_CATEGORIES.map(cat => (
                <div key={cat.id}>
                  <div className="t-eyebrow" style={{ marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name={cat.icon} style={{ fontSize: 14 }} />
                    {cat.label}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 8 }}>
                    {(grouped[cat.id] || []).map(s => {
                      const sel = selectedSvcs.find(x => x.id === s.id);
                      return (
                        <div key={s.id} className={`svc-card ${sel ? 'is-selected' : ''}`} onClick={() => toggleSvc(s)}>
                          <div className="svc-card__check">{sel && <Icon name="check" style={{ fontSize: 14 }} />}</div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div className="svc-card__name">{s.name}</div>
                            <div className="svc-card__price">{uzMoneyShort(s.price)} so'm</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* 4. Payment */}
          <Card>
            <div className="row row-3" style={{ marginBottom: 16 }}>
              <SectionNum n={4} done={paymentStatus !== 'partial' || paid > 0} />
              <div>
                <div className="t-h5">To'lov</div>
                <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>To'lov turi va holatini tanlang</div>
              </div>
            </div>

            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Holati</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
              {[
                { id: 'full', label: "To'landi", tone: 'success' },
                { id: 'partial', label: 'Qisman', tone: 'warning' },
                { id: 'debt', label: 'Qarzga', tone: 'danger' },
              ].map(s => (
                <button key={s.id}
                  className={`chip ${paymentStatus === s.id ? 'is-active' : ''}`}
                  style={{ padding: '10px 16px' }}
                  onClick={() => setPaymentStatus(s.id)}>{s.label}</button>
              ))}
            </div>

            {/* To'lov turi faqat pul olinganda kerak (qarzga bo'lsa — yashiriladi) */}
            {paymentStatus !== 'debt' && (
              <>
                <div className="t-eyebrow" style={{ marginBottom: 10 }}>To'lov turi</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 18 }}>
                  {[
                    { id: 'cash', label: 'Naqd', icon: 'money' },
                    { id: 'card', label: 'Karta', icon: 'credit-card' },
                    { id: 'transfer', label: "O'tkazma", icon: 'arrows-left-right' },
                  ].map(t => (
                    <button key={t.id}
                      className={`svc-card ${payType === t.id ? 'is-selected' : ''}`}
                      style={{ padding: 12, flexDirection: 'column', gap: 6, justifyContent: 'center', textAlign: 'center' }}
                      onClick={() => setPayType(t.id)}>
                      <Icon name={t.icon} style={{ fontSize: 20, color: payType === t.id ? 'var(--brand-primary)' : 'var(--fg-3)' }} />
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{t.label}</span>
                    </button>
                  ))}
                </div>
              </>
            )}

            {paymentStatus === 'partial' && (
              <Field label="Olingan summa">
                <div style={{ position: 'relative' }}>
                  <Input
                    placeholder="0"
                    value={paidAmount}
                    onChange={e => setPaidAmount(e.target.value.replace(/\D/g,''))}
                    style={{ paddingRight: 60 }}
                  />
                  <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-4)', fontSize: 13 }}>so'm</span>
                </div>
                {paidAmount && (
                  <div style={{ fontSize: 12, color: 'var(--color-danger)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Icon name="warning" style={{ fontSize: 13 }} />
                    Qarz: {uzMoney(total - paid)}
                  </div>
                )}
              </Field>
            )}
          </Card>
        </div>

        {/* Right — sticky summary */}
        <div className="summary-card">
          <Card style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-2)', background: 'var(--surface-2)' }}>
              <div className="t-eyebrow">Yig'indi</div>
            </div>
            <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>

              <div>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Bemor</div>
                <div style={{ fontSize: 14, fontWeight: 600, color: patient ? 'var(--fg-1)' : 'var(--fg-4)' }}>
                  {patient?.name || 'Tanlanmagan'}
                </div>
              </div>

              <div>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Shifokor</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: doctor ? 'var(--fg-1)' : 'var(--fg-4)' }}>
                  {doctor?.name || (noDoctor ? "Tanlanmagan" : '\u2014')}
                </div>
              </div>

              <div style={{ borderTop: '1px solid var(--border-2)', paddingTop: 14 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8 }}>
                  Xizmatlar ({selectedSvcs.length})
                </div>
                {selectedSvcs.length === 0 ? (
                  <div style={{ fontSize: 13, color: 'var(--fg-4)' }}>Hech narsa tanlanmagan</div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {selectedSvcs.map(s => (
                      <div key={s.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', fontSize: 13 }}>
                        <span style={{ color: 'var(--fg-2)', flex: 1, paddingRight: 8 }}>{s.name}</span>
                        <span style={{ fontWeight: 500, fontVariantNumeric: 'tabular-nums', color: 'var(--fg-1)' }}>{uzMoneyShort(s.price)}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <div style={{ borderTop: '1px solid var(--border-2)', paddingTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>Jami</span>
                  <span style={{ fontSize: 22, fontWeight: 700, color: 'var(--fg-1)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>
                    {uzMoneyShort(total)}
                  </span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--fg-3)' }}>
                  <span>To'landi</span>
                  <span style={{ color: 'var(--color-success)', fontWeight: 600 }}>{uzMoneyShort(paid)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                  <span style={{ color: 'var(--fg-3)' }}>Qarz</span>
                  <span style={{ color: debt > 0 ? 'var(--color-danger)' : 'var(--fg-4)', fontWeight: 600 }}>{uzMoneyShort(debt)}</span>
                </div>
              </div>

              <Button variant="primary" size="lg" icon="check-circle" disabled={!canSave} loading={saving} onClick={handleSave}>
                {saving ? "Saqlanmoqda..." : "Tugatish va saqlash"}
              </Button>
              {!canSave && (
                <div style={{ fontSize: 11, color: 'var(--fg-4)', textAlign: 'center' }}>
                  Bemor va kamida 1 xizmat kerak
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>

      {/* New patient modal */}
      <NewPatientModal open={showNewPatient} onClose={() => setShowNewPatient(false)}
        onCreate={(p) => { setPatient(p); setShowNewPatient(false); toast({ kind: 'success', title: 'Bemor qo\'shildi', msg: p.name }); }} />
      <NewDoctorModal open={showNewDoctor} onClose={() => setShowNewDoctor(false)}
        onCreate={(d) => { setDoctor(d); setShowNewDoctor(false); toast({ kind: 'success', title: 'Shifokor qo\'shildi', msg: d.name }); }} />
    </div>
  );
}

function SectionNum({ n, done, optional }) {
  return (
    <div style={{
      width: 28, height: 28, borderRadius: '50%',
      background: done ? 'var(--color-success)' : optional ? 'var(--surface-2)' : 'var(--brand-primary)',
      color: done || !optional ? '#fff' : 'var(--fg-3)',
      border: optional && !done ? '1.5px dashed var(--border-strong)' : 'none',
      display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12,
      flexShrink: 0,
    }}>
      {done ? <Icon name="check" /> : n}
    </div>
  );
}

function NewPatientModal({ open, onClose, onCreate }) {
  const [form, setForm] = useState({ name: '', birth: '', phone: '+998 ', passport: '' });
  const [saving, setSaving] = useState(false);
  if (!open) return null;
  const valid = form.name.trim() && form.phone.length > 8;

  const save = async () => {
    setSaving(true);
    try {
      const bd = form.birth ? parseUzDate(form.birth) : null;
      const isoBirth = bd ? bd.toISOString().slice(0, 10) : null;
      const created = await window.API.createPatient({
        full_name: form.name.trim(),
        phone: form.phone || null,
        birth_date: isoBirth,
        passport: form.passport || null,
      });
      const norm = window.normalizePatient ? window.normalizePatient(created) : {
        ...created,
        name: created.full_name,
        fullName: created.full_name,
        birth: isoBirth ? form.birth : '—',
        birthDate: bd,
      };
      onCreate(norm);
    } catch (err) {
      alert("Xato: " + err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Yangi bemor"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Bekor qilish</Button>
          <Button variant="primary" disabled={!valid || saving} loading={saving} icon="user-plus" onClick={save}>Qo'shish</Button>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="F.I.O." hint="To'liq familiya, ism, otasining ismi">
          <Input placeholder="Aliyev Akmal Rustamovich" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} autoFocus />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Tug'ilgan sana">
            <Input placeholder="dd.mm.yyyy" value={form.birth} onChange={e => setForm({ ...form, birth: e.target.value })} />
          </Field>
          <Field label="Telefon">
            <Input placeholder="+998 90 123 45 67" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
          </Field>
        </div>
        <Field label="Pasport / ID" hint="Ixtiyoriy">
          <Input placeholder="AA 1234567" value={form.passport} onChange={e => setForm({ ...form, passport: e.target.value })} />
        </Field>
      </div>
    </Modal>
  );
}

function NewDoctorModal({ open, onClose, onCreate }) {
  const [form, setForm] = useState({ name: '', speciality: '', clinic: '', phone: '+998 ', telegram: '' });
  const [saving, setSaving] = useState(false);
  if (!open) return null;
  const valid = form.name.trim();

  const save = async () => {
    setSaving(true);
    try {
      const created = await window.API.createDoctorShort({
        full_name: form.name.trim(),
        phone: form.phone || null,
        specialty: form.speciality || null,
        clinic: form.clinic || null,
        telegram_username: form.telegram || null,
      });
      const norm = window.normalizeDoctor ? window.normalizeDoctor(created) : {
        ...created,
        name: created.full_name,
        speciality: created.specialty,
      };
      onCreate(norm);
    } catch (err) {
      alert("Xato: " + err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Yangi shifokor"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Bekor qilish</Button>
          <Button variant="primary" disabled={!valid || saving} loading={saving} icon="plus" onClick={save}>Qo'shish</Button>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="F.I.O.">
          <Input placeholder="Karimov Sherzod" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} autoFocus />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Mutaxassisligi">
            <Input placeholder="Stomatolog" value={form.speciality} onChange={e => setForm({ ...form, speciality: e.target.value })} />
          </Field>
          <Field label="Klinika">
            <Input placeholder="DentaMed" value={form.clinic} onChange={e => setForm({ ...form, clinic: e.target.value })} />
          </Field>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Telefon">
            <Input placeholder="+998 90 123 45 67" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
          </Field>
          <Field label="Telegram" hint="Ixtiyoriy">
            <Input placeholder="@username" value={form.telegram} onChange={e => setForm({ ...form, telegram: e.target.value })} />
          </Field>
        </div>
      </div>
    </Modal>
  );
}

function parseUzDate(s) {
  const m = s.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
  if (!m) return new Date(1990, 0, 1);
  return new Date(+m[3], +m[2] - 1, +m[1]);
}

Object.assign(window, { LoginPage, ReceptionDashboard, NewVisitPage, SectionNum, NewPatientModal, NewDoctorModal, parseUzDate, normalizePatient, normalizeDoctor, normalizeService });
