/* global React, Icon, Btn, Avatar, Stars, FauxQR, SERVICES, EXPERTS, DAYS, SLOTS */
// Taxai — expert booking flow (overlay). service → expert → time → QR → success.
const { useState: useBkState, useEffect: useBkEffect } = React;

const STEPS = [
  { id: 'service', label: 'Dịch vụ' },
  { id: 'expert', label: 'Chuyên gia' },
  { id: 'time', label: 'Thời gian' },
  { id: 'pay', label: 'Thanh toán' },
];

function money(n) { return n.toLocaleString('vi-VN') + 'đ'; }

function Booking({ initialService, onClose, onConfirm }) {
  const [stepIdx, setStepIdx] = useBkState(0);
  const [service, setService] = useBkState(initialService || 'tax');
  const [expert, setExpert] = useBkState(null);
  const [day, setDay] = useBkState(null);
  const [slot, setSlot] = useBkState(null);
  const [paid, setPaid] = useBkState(false);
  const [code] = useBkState(() => 'TX' + Math.floor(100000 + Math.random() * 899999));

  const step = STEPS[stepIdx].id;
  const go = (i) => setStepIdx(i);
  const next = () => setStepIdx((s) => Math.min(s + 1, STEPS.length - 1));
  const back = () => { if (stepIdx === 0) onClose(); else setStepIdx((s) => s - 1); };

  const experts = EXPERTS.filter((e) => e.svc === service);
  const svcObj = SERVICES.find((s) => s.id === service);
  const dayObj = DAYS.find((d) => d.id === day);

  // success overlay
  if (paid) return <Success code={code} expert={expert} svcObj={svcObj} dayObj={dayObj} slot={slot} onDone={() => onConfirm({ expert: expert.name, day: dayObj.dow + ' ' + dayObj.date, slot, code, service })} />;

  return (
    <div className="af" style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'var(--bg-2)', display: 'flex', flexDirection: 'column', animation: 'taxaiFadeIn .24s var(--ease-out)' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 24px', background: 'var(--surface)', borderBottom: '1px solid var(--border-1)', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={back} className="af-modal__x" style={{ width: 36, height: 36 }}><Icon name={stepIdx === 0 ? 'x' : 'arrow-left'} size={18} /></button>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17 }}>Đặt lịch chuyên gia</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-2)' }}>Tư vấn 1-1 qua video · 30 phút</div>
          </div>
        </div>
        <button onClick={onClose} style={{ border: 0, background: 'none', color: 'var(--fg-3)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Icon name="message-square" size={16} /> Về trò chuyện
        </button>
      </div>

      {/* stepper */}
      <div style={{ background: 'var(--surface)', borderBottom: '1px solid var(--border-1)', padding: '14px 24px', flexShrink: 0 }}>
        <div style={{ maxWidth: 880, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          {STEPS.map((s, i) => (
            <React.Fragment key={s.id}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, opacity: i <= stepIdx ? 1 : 0.5 }}>
                <span style={{ width: 26, height: 26, borderRadius: '50%', flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 12.5, fontWeight: 700, fontFamily: 'var(--font-display)',
                  background: i < stepIdx ? 'var(--brand)' : i === stepIdx ? 'var(--brand)' : 'var(--bg-3)', color: i <= stepIdx ? '#fff' : 'var(--fg-3)' }}>
                  {i < stepIdx ? <Icon name="check" size={15} /> : i + 1}
                </span>
                <span style={{ fontSize: 13, fontWeight: 700, color: i <= stepIdx ? 'var(--fg-1)' : 'var(--fg-3)' }}>{s.label}</span>
              </div>
              {i < STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: i < stepIdx ? 'var(--brand)' : 'var(--border-1)', borderRadius: 999 }} />}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '28px 24px 32px' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>
          {step === 'service' && <ServiceStep service={service} setService={setService} />}
          {step === 'expert' && <ExpertStep experts={experts} svcObj={svcObj} onPick={(e) => { setExpert(e); next(); }} onChangeSvc={() => go(0)} />}
          {step === 'time' && <TimeStep expert={expert} day={day} setDay={setDay} slot={slot} setSlot={setSlot} />}
          {step === 'pay' && <PayStep expert={expert} svcObj={svcObj} dayObj={dayObj} slot={slot} />}
        </div>
      </div>

      {/* footer */}
      {step !== 'expert' && (
        <div style={{ borderTop: '1px solid var(--border-1)', background: 'var(--surface)', padding: '14px 24px', flexShrink: 0 }}>
          <div style={{ maxWidth: 880, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>
              {step === 'pay' && <span>Phí đặt cọc giữ chỗ · <strong style={{ color: 'var(--fg-1)', fontFamily: 'var(--font-mono)' }}>{money(expert.price)}</strong></span>}
              {step === 'time' && expert && <span>{expert.name} · {svcObj.label}</span>}
              {step === 'service' && <span>Chọn loại dịch vụ phù hợp với nhu cầu của bạn</span>}
            </div>
            {step === 'service' && <Btn variant="primary" iconRight="arrow-right" onClick={next}>Chọn chuyên gia</Btn>}
            {step === 'time' && <Btn variant="primary" iconRight="arrow-right" disabled={!day || !slot} onClick={next}>Tới thanh toán</Btn>}
            {step === 'pay' && <Btn variant="primary" icon="shield-check" glow onClick={() => setPaid(true)}>Tôi đã thanh toán</Btn>}
          </div>
        </div>
      )}
    </div>
  );
}

// ---- Step: service -------------------------------------------------------
function ServiceStep({ service, setService }) {
  return (
    <div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, letterSpacing: '-.015em', margin: '0 0 6px' }}>Bạn cần tư vấn về?</h2>
      <p style={{ color: 'var(--fg-2)', fontSize: 14.5, margin: '0 0 22px' }}>Đã chọn sẵn theo nội dung trò chuyện — bạn có thể đổi nếu muốn.</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {SERVICES.map((s) => {
          const active = service === s.id;
          return (
            <button key={s.id} onClick={() => setService(s.id)} style={{
              textAlign: 'left', cursor: 'pointer', background: 'var(--surface)', padding: 22,
              border: '1px solid', borderColor: active ? 'var(--brand)' : 'var(--border-1)',
              boxShadow: active ? '0 0 0 3px var(--danger-bg)' : 'var(--shadow-sm)', borderRadius: 'var(--r-lg)', transition: 'all var(--dur)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <span style={{ width: 46, height: 46, borderRadius: 'var(--r-md)', background: active ? 'var(--brand)' : 'var(--bg-2)', color: active ? '#fff' : 'var(--fg-2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transition: 'all var(--dur)' }}>
                  <Icon name={s.icon} size={24} />
                </span>
                {active && <span style={{ color: 'var(--brand)' }}><Icon name="check-circle-2" size={22} /></span>}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, marginTop: 16 }}>{s.label}</div>
              <div style={{ color: 'var(--fg-2)', fontSize: 13.5, marginTop: 6, lineHeight: 1.5 }}>{s.desc}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---- Step: expert --------------------------------------------------------
function ExpertStep({ experts, svcObj, onPick, onChangeSvc }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
        <div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, letterSpacing: '-.015em', margin: '0 0 6px' }}>Chọn chuyên gia</h2>
          <p style={{ color: 'var(--fg-2)', fontSize: 14.5, margin: 0 }}>{experts.length} chuyên gia cho <strong style={{ color: 'var(--fg-1)' }}>{svcObj.label}</strong></p>
        </div>
        <button onClick={onChangeSvc} className="af-chip" style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="repeat" size={14} /> Đổi dịch vụ</button>
      </div>
      <div style={{ display: 'grid', gap: 14 }}>
        {experts.map((e) => (
          <div key={e.id} style={{ background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', padding: 18, display: 'flex', gap: 16, alignItems: 'center', transition: 'all var(--dur)' }}
            onMouseEnter={(ev) => { ev.currentTarget.style.boxShadow = 'var(--shadow-md)'; ev.currentTarget.style.borderColor = 'var(--border-2)'; }}
            onMouseLeave={(ev) => { ev.currentTarget.style.boxShadow = 'var(--shadow-sm)'; ev.currentTarget.style.borderColor = 'var(--border-1)'; }}>
            <Avatar name={e.name} size={58} bg={e.bg} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17 }}>{e.name}</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12.5, fontWeight: 700, color: 'var(--warning)' }}><Stars value={e.rating} size={13} /> {e.rating} <span style={{ color: 'var(--fg-3)', fontWeight: 500 }}>({e.reviews})</span></span>
              </div>
              <div style={{ color: 'var(--fg-2)', fontSize: 13.5, marginTop: 4 }}>{e.title} · {e.years} năm kinh nghiệm</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 9, flexWrap: 'wrap' }}>
                {e.tags.map((t) => <span key={t} style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-2)', background: 'var(--bg-2)', border: '1px solid var(--border-1)', padding: '3px 9px', borderRadius: 999 }}>{t}</span>)}
              </div>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 16, color: 'var(--fg-1)' }}>{money(e.price)}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>/ buổi 30 phút</div>
              </div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: 'var(--success)' }}><Icon name="clock" size={13} /> {e.next}</div>
              <Btn variant="primary" size="sm" iconRight="arrow-right" onClick={() => onPick(e)}>Chọn</Btn>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Step: time ----------------------------------------------------------
function TimeStep({ expert, day, setDay, slot, setSlot }) {
  return (
    <div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, letterSpacing: '-.015em', margin: '0 0 18px' }}>Chọn thời gian</h2>
      <div style={{ display: 'flex', gap: 14, alignItems: 'center', background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', padding: 16, marginBottom: 22, boxShadow: 'var(--shadow-sm)' }}>
        <Avatar name={expert.name} size={48} bg={expert.bg} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>{expert.name}</div>
          <div style={{ color: 'var(--fg-2)', fontSize: 13 }}>{expert.title}</div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12.5, fontWeight: 700, color: 'var(--warning)' }}><Stars value={expert.rating} size={13} /> {expert.rating}</span>
      </div>

      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Ngày</div>
      <div style={{ display: 'flex', gap: 10, marginBottom: 24, flexWrap: 'wrap' }}>
        {DAYS.map((d) => {
          const active = day === d.id;
          return (
            <button key={d.id} onClick={() => setDay(d.id)} style={{
              minWidth: 78, padding: '11px 14px', borderRadius: 'var(--r-md)', cursor: 'pointer', textAlign: 'center',
              border: '1px solid', borderColor: active ? 'var(--brand)' : 'var(--border-2)', background: active ? 'var(--brand)' : 'var(--surface)', color: active ? '#fff' : 'var(--fg-1)', transition: 'all var(--dur)',
            }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, opacity: active ? 0.85 : 0.7 }}>{d.dow}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, marginTop: 2 }}>{d.date}</div>
            </button>
          );
        })}
      </div>

      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Khung giờ</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(96px, 1fr))', gap: 10 }}>
        {SLOTS.map((s) => {
          const active = slot === s;
          const disabled = !day;
          return (
            <button key={s} disabled={disabled} onClick={() => setSlot(s)} style={{
              padding: '11px 0', borderRadius: 'var(--r-md)', cursor: disabled ? 'not-allowed' : 'pointer', fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 14,
              border: '1px solid', borderColor: active ? 'var(--brand)' : 'var(--border-2)', background: active ? 'var(--brand)' : 'var(--surface)', color: active ? '#fff' : disabled ? 'var(--fg-3)' : 'var(--fg-1)',
              opacity: disabled ? 0.5 : 1, transition: 'all var(--dur)',
            }}>{s}</button>
          );
        })}
      </div>
    </div>
  );
}

// ---- Step: pay -----------------------------------------------------------
function PayStep({ expert, svcObj, dayObj, slot }) {
  return (
    <div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, letterSpacing: '-.015em', margin: '0 0 18px' }}>Thanh toán đặt cọc</h2>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, alignItems: 'start' }}>
        {/* summary */}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-1)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15.5 }}>Chi tiết lịch hẹn</div>
          <div style={{ padding: 20, display: 'grid', gap: 14 }}>
            <SummaryRow icon="user-round" label="Chuyên gia" value={expert.name} sub={expert.title} />
            <SummaryRow icon={svcObj.icon} label="Dịch vụ" value={svcObj.label} />
            <SummaryRow icon="calendar" label="Thời gian" value={`${dayObj.dow}, ${dayObj.date} · ${slot}`} sub="Tư vấn video 30 phút" />
            <div style={{ height: 1, background: 'var(--border-1)' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 14, color: 'var(--fg-2)' }}>Phí tư vấn</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14 }}>{money(expert.price)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 15, fontWeight: 700 }}>Đặt cọc giữ chỗ</span>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--brand)' }}>{money(expert.price)}</span>
            </div>
            <div className="af-alert af-alert--info" style={{ fontSize: 12.5 }}>
              <Icon name="info" size={16} /><span>Hoàn 100% nếu hủy trước 2 giờ. Đặt cọc được trừ vào phí buổi tư vấn.</span>
            </div>
          </div>
        </div>

        {/* QR */}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', padding: 20, textAlign: 'center' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 4 }}>Quét mã VietQR để thanh toán</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>Mở app ngân hàng & quét mã</div>
          <div style={{ display: 'inline-block', padding: 12, border: '1px solid var(--border-2)', borderRadius: 'var(--r-md)', position: 'relative' }}>
            <FauxQR size={172} seed={expert.id.charCodeAt(1) * 13 + slot.charCodeAt(0)} />
            <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 40, height: 40, borderRadius: 8, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 0 0 4px #fff' }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17 }}>T<span style={{ color: 'var(--brand)' }}>a</span></span>
            </div>
          </div>
          <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--fg-2)' }}>Chủ tài khoản</div>
          <div style={{ fontWeight: 700, fontSize: 14 }}>CTY CP CONG NGHE TAXAI</div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginTop: 8, fontFamily: 'var(--font-mono)', fontSize: 12.5, color: 'var(--fg-2)' }}>
            <span>NOI DUNG:</span><span style={{ color: 'var(--brand)', fontWeight: 600 }}>TAXAI {expert.id.toUpperCase()}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ icon, label, value, sub }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <span style={{ width: 34, height: 34, borderRadius: 'var(--r-sm)', background: 'var(--bg-2)', color: 'var(--fg-2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={icon} size={17} /></span>
      <div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', fontWeight: 600 }}>{label}</div>
        <div style={{ fontSize: 14.5, fontWeight: 700, marginTop: 1 }}>{value}</div>
        {sub && <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 1 }}>{sub}</div>}
      </div>
    </div>
  );
}

// ---- Success -------------------------------------------------------------
function Success({ code, expert, svcObj, dayObj, slot, onDone }) {
  useBkEffect(() => { const t = setTimeout(() => {}, 0); return () => clearTimeout(t); }, []);
  return (
    <div className="af" style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, animation: 'taxaiFadeIn .24s var(--ease-out)' }}>
      <div style={{ width: 460, maxWidth: '100%', background: 'var(--surface)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-xl)', boxShadow: 'var(--shadow-lg)', padding: 36, textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--success-bg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20, animation: 'taxaiPop .4s var(--ease-out)' }}>
          <span style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--success)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={30} /></span>
        </div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, letterSpacing: '-.015em', margin: '0 0 8px' }}>Thanh toán thành công!</h2>
        <p style={{ color: 'var(--fg-2)', fontSize: 14.5, margin: '0 0 22px', lineHeight: 1.55 }}>Lịch hẹn của bạn đã được xác nhận. Chúng tôi đã gửi chi tiết qua email & SMS.</p>
        <div style={{ background: 'var(--bg-2)', border: '1px solid var(--border-1)', borderRadius: 'var(--r-md)', padding: 18, textAlign: 'left', display: 'grid', gap: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={expert.name} size={42} bg={expert.bg} />
            <div><div style={{ fontWeight: 700, fontSize: 15 }}>{expert.name}</div><div style={{ fontSize: 12.5, color: 'var(--fg-2)' }}>{svcObj.label}</div></div>
          </div>
          <div style={{ height: 1, background: 'var(--border-1)' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}><span style={{ color: 'var(--fg-2)' }}>Thời gian</span><span style={{ fontWeight: 700 }}>{dayObj.dow}, {dayObj.date} · {slot}</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}><span style={{ color: 'var(--fg-2)' }}>Mã đặt lịch</span><span className="mono" style={{ fontWeight: 600, color: 'var(--brand)' }}>{code}</span></div>
        </div>
        <div style={{ marginTop: 24 }}>
          <Btn variant="primary" icon="message-square" glow style={{ width: '100%', padding: 13 }} onClick={onDone}>Về cuộc trò chuyện</Btn>
        </div>
      </div>
    </div>
  );
}

window.Booking = Booking;
