// Bookings & Schedule — Calendar (month/week/day) + Booking table + New Booking form
const { useState: useStateBk, useMemo: useMemoBk } = React;

function BookingsPage({ t, lang }) {
  const D = window.MJC_DATA;
  const [view, setView] = useStateBk('month');
  const [showForm, setShowForm] = useStateBk(false);
  const [sortKey, setSortKey] = useStateBk('date');
  const [sortDir, setSortDir] = useStateBk('asc');
  const [statusFilter, setStatusFilter] = useStateBk('all');
  const [search, setSearch] = useStateBk('');

  const monthName = lang === 'zh' ? '2026 年 5 月' : 'May 2026';
  const weekdayLabels = lang === 'zh' ? ['一', '二', '三', '四', '五', '六', '日'] : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  // May 2026: 1st falls on Friday. We'll use Mon-first week
  // Day 1 = Fri (index 4)
  const firstDayCol = 4; // Mon=0, ... Fri=4

  const eventsByDay = {};
  D.CALENDAR_EVENTS.forEach(e => {
    if (!eventsByDay[e.day]) eventsByDay[e.day] = [];
    eventsByDay[e.day].push(e);
  });

  const colorMap = {
    gold: { bg: 'rgba(200,146,42,.15)', text: 'var(--gold)', border: 'var(--gold-soft)' },
    teal: { bg: 'rgba(13,106,122,.12)', text: 'var(--teal)', border: 'rgba(13,106,122,.3)' },
    navy: { bg: 'rgba(27,58,107,.1)', text: 'var(--navy)', border: 'rgba(27,58,107,.3)' }
  };

  // Build month grid: 35 cells (5 weeks) or 42
  const totalDays = 31;
  const totalCells = Math.ceil((firstDayCol + totalDays) / 7) * 7;
  const monthCells = [];
  for (let i = 0; i < totalCells; i++) {
    const day = i - firstDayCol + 1;
    if (day < 1 || day > totalDays) monthCells.push(null);
    else monthCells.push(day);
  }

  // Table filtering & sorting
  const sortedBookings = useMemoBk(() => {
    let rows = [...D.DEPARTURES];
    if (statusFilter !== 'all') rows = rows.filter(r => r.status === statusFilter);
    if (search) {
      const q = search.toLowerCase();
      rows = rows.filter(r =>
        r.id.toLowerCase().includes(q) ||
        (lang === 'zh' ? r.tour_zh : r.tour_en).toLowerCase().includes(q) ||
        (lang === 'zh' ? r.guide_zh : r.guide_en).toLowerCase().includes(q)
      );
    }
    rows.sort((a, b) => {
      const av = a[sortKey];
      const bv = b[sortKey];
      if (av < bv) return sortDir === 'asc' ? -1 : 1;
      if (av > bv) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
    return rows;
  }, [sortKey, sortDir, statusFilter, search, lang]);

  const onSort = (key) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir('asc'); }
  };

  const SortHeader = ({ k, label }) => (
    <th onClick={() => onSort(k)} className={sortKey === k ? 'sorted' : ''}>
      {label}
      <span className="sort-arrow">
        {sortKey === k ? (sortDir === 'asc' ? <Icon.ArrowUp size={11} /> : <Icon.ArrowDown size={11} />) : <Icon.Sort size={11} />}
      </span>
    </th>
  );

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">{t('bookings_title')}</h1>
          <div className="page-subtitle">{t('bookings_sub')}</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost"><Icon.Download size={15} /> {t('export')}</button>
          <button className="btn btn-gold" onClick={() => setShowForm(true)}><Icon.Plus size={15} /> {t('new_booking')}</button>
        </div>
      </div>

      {/* Calendar */}
      <div className="card" style={{ marginBottom: 'var(--gap)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
          <h3 className="card-title" style={{ marginRight: 'auto' }}>{monthName}</h3>
          <button className="btn btn-ghost btn-sm"><Icon.ChevronLeft size={14} /></button>
          <button className="btn btn-ghost btn-sm">{t('today')}</button>
          <button className="btn btn-ghost btn-sm"><Icon.ChevronRight size={14} /></button>
          <div className="chart-tabs">
            <button className={view === 'month' ? 'active' : ''} onClick={() => setView('month')}>{t('month')}</button>
            <button className={view === 'week' ? 'active' : ''} onClick={() => setView('week')}>{t('week')}</button>
            <button className={view === 'day' ? 'active' : ''} onClick={() => setView('day')}>{t('day')}</button>
          </div>
        </div>

        {/* Color legend */}
        <div style={{ display: 'flex', gap: 14, marginBottom: 14, fontSize: 11.5, color: 'var(--muted)' }}>
          <span><span className="status-dot" style={{ background: 'var(--gold)' }}></span>{lang === 'zh' ? '高地团' : 'Highland tours'}</span>
          <span><span className="status-dot" style={{ background: 'var(--teal)' }}></span>{lang === 'zh' ? '海岛 / 文化' : 'Island / Cultural'}</span>
          <span><span className="status-dot" style={{ background: 'var(--navy)' }}></span>{lang === 'zh' ? '城市 / 美食' : 'City / Food'}</span>
        </div>

        {view === 'month' && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 1, background: 'var(--border)', borderRadius: 10, overflow: 'hidden' }}>
              {weekdayLabels.map((d, i) => (
                <div key={i} style={{ background: 'var(--bg)', padding: '8px 10px', fontSize: 11, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em' }}>{d}</div>
              ))}
              {monthCells.map((day, i) => (
                <div key={i} style={{
                  background: '#fff',
                  minHeight: 90,
                  padding: 6,
                  position: 'relative',
                  opacity: day ? 1 : .3
                }}>
                  {day && (
                    <>
                      <div style={{
                        fontSize: 12,
                        fontWeight: day === 21 ? 700 : 500,
                        color: day === 21 ? '#fff' : 'var(--ink)',
                        background: day === 21 ? 'var(--navy)' : 'transparent',
                        width: day === 21 ? 22 : 'auto',
                        height: day === 21 ? 22 : 'auto',
                        borderRadius: '50%',
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        padding: day === 21 ? 0 : '0 2px',
                        marginBottom: 4
                      }}>{day}</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        {(eventsByDay[day] || []).slice(0, 3).map((e, j) => {
                          const c = colorMap[e.color];
                          return (
                            <div key={j} style={{
                              background: c.bg,
                              color: c.text,
                              borderLeft: `2px solid ${c.text}`,
                              padding: '2px 5px',
                              fontSize: 10.5,
                              fontWeight: 600,
                              borderRadius: 3,
                              whiteSpace: 'nowrap',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis'
                            }}>
                              {lang === 'zh' ? e.label_zh : e.label_en}
                            </div>
                          );
                        })}
                        {(eventsByDay[day] || []).length > 3 && (
                          <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 600 }}>+{eventsByDay[day].length - 3}</div>
                        )}
                      </div>
                    </>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {view === 'week' && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', gap: 1, background: 'var(--border)', borderRadius: 10, overflow: 'hidden' }}>
              <div style={{ background: 'var(--bg)' }}></div>
              {[21, 22, 23, 24, 25, 26, 27].map((d, i) => (
                <div key={i} style={{ background: 'var(--bg)', padding: '10px 8px', textAlign: 'center' }}>
                  <div style={{ fontSize: 10.5, color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 600 }}>{weekdayLabels[i]}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2, color: d === 21 ? 'var(--navy)' : 'var(--ink)' }}>{d}</div>
                </div>
              ))}
              {['08:00', '10:00', '12:00', '14:00', '16:00'].map((time, ti) => (
                <React.Fragment key={ti}>
                  <div style={{ background: '#fff', padding: '12px 8px', fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>{time}</div>
                  {[21, 22, 23, 24, 25, 26, 27].map((d, di) => {
                    const events = (eventsByDay[d] || []).slice(0, 1);
                    const show = ti === 0 && events.length;
                    return (
                      <div key={di} style={{ background: '#fff', minHeight: 60, padding: 4, position: 'relative' }}>
                        {show && events.map((e, j) => {
                          const c = colorMap[e.color];
                          return (
                            <div key={j} style={{
                              background: c.bg,
                              color: c.text,
                              borderLeft: `3px solid ${c.text}`,
                              padding: '4px 6px',
                              fontSize: 11,
                              fontWeight: 600,
                              borderRadius: 4
                            }}>
                              {lang === 'zh' ? e.label_zh : e.label_en}
                            </div>
                          );
                        })}
                      </div>
                    );
                  })}
                </React.Fragment>
              ))}
            </div>
          </div>
        )}

        {view === 'day' && (
          <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 1, background: 'var(--border)', borderRadius: 10, overflow: 'hidden' }}>
            {['07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00'].map((time, ti) => (
              <React.Fragment key={ti}>
                <div style={{ background: 'var(--bg)', padding: '14px 10px', fontSize: 11.5, color: 'var(--muted)', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{time}</div>
                <div style={{ background: '#fff', minHeight: 60, padding: 8, position: 'relative' }}>
                  {ti === 1 && (
                    <div style={{ background: colorMap.gold.bg, borderLeft: `3px solid ${colorMap.gold.text}`, padding: '8px 12px', borderRadius: 6 }}>
                      <div style={{ fontWeight: 600, fontSize: 13, color: colorMap.gold.text }}>{lang === 'zh' ? '云顶高原 2D1N · BK-2851' : 'Genting Highlands 2D1N · BK-2851'}</div>
                      <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>24 pax · {lang === 'zh' ? '林伟健' : 'Lim Wei Jian'} · BTM 5821</div>
                    </div>
                  )}
                  {ti === 3 && (
                    <div style={{ background: colorMap.teal.bg, borderLeft: `3px solid ${colorMap.teal.text}`, padding: '8px 12px', borderRadius: 6 }}>
                      <div style={{ fontWeight: 600, fontSize: 13, color: colorMap.teal.text }}>{lang === 'zh' ? '吉隆坡半日游 · BK-2849' : 'KL Half-day City · BK-2849'}</div>
                      <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>8 pax · {lang === 'zh' ? '陈美玲' : 'Tan Mei Ling'} · BKV 2210</div>
                    </div>
                  )}
                </div>
              </React.Fragment>
            ))}
          </div>
        )}
      </div>

      {/* Bookings Table */}
      <div className="table-wrap">
        <div className="table-toolbar">
          <span className="title">{lang === 'zh' ? '全部预订' : 'All Bookings'}</span>
          <div style={{ position: 'relative' }}>
            <input
              type="text"
              placeholder={lang === 'zh' ? '搜索...' : 'Search...'}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{ height: 32, border: '1px solid var(--border)', borderRadius: 8, padding: '0 10px 0 30px', fontSize: 12, width: 200, outline: 'none' }}
            />
            <span style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }}>
              <Icon.Search size={13} />
            </span>
          </div>
          <select className="field-select" style={{ height: 32, fontSize: 12 }} value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
            <option value="all">{lang === 'zh' ? '全部状态' : 'All status'}</option>
            <option value="confirmed">{t('confirmed')}</option>
            <option value="pending">{t('pending')}</option>
          </select>
          <button className="btn btn-ghost btn-sm"><Icon.Filter size={13} /> {t('filter')}</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <SortHeader k="id" label={t('booking_id')} />
              <SortHeader k={lang === 'zh' ? 'tour_zh' : 'tour_en'} label={t('tour')} />
              <SortHeader k="date" label={t('date')} />
              <SortHeader k="pax" label={t('pax')} />
              <th>{t('guide')}</th>
              <th>{t('vehicle')}</th>
              <SortHeader k="total" label={t('total')} />
              <th>{t('status')}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {sortedBookings.map((d, i) => (
              <tr key={i}>
                <td className="strong mono" style={{ fontSize: 12 }}>{d.id}</td>
                <td className="strong">{lang === 'zh' ? d.tour_zh : d.tour_en}</td>
                <td>{d.date}</td>
                <td>{d.pax}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div className="avatar avatar-sm avatar-navy">{(lang === 'zh' ? d.guide_zh : d.guide_en).slice(0, 1)}</div>
                    <span>{lang === 'zh' ? d.guide_zh : d.guide_en}</span>
                  </div>
                </td>
                <td className="mono" style={{ fontSize: 12 }}>{d.bus}</td>
                <td className="strong">{d.total}</td>
                <td><StatusBadge status={d.status} t={t} /></td>
                <td>
                  <div className="row-actions">
                    <button className="icon-btn"><Icon.Eye size={14} /></button>
                    <button className="icon-btn"><Icon.Edit size={14} /></button>
                    <button className="icon-btn"><Icon.More size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showForm && <BookingForm t={t} lang={lang} onClose={() => setShowForm(false)} />}
    </div>
  );
}

function BookingForm({ t, lang, onClose }) {
  const [form, setForm] = useStateBk({
    customer: '', phone: '', email: '', tour: '', date: '', pax: '', total: '', notes: ''
  });
  const [errors, setErrors] = useStateBk({});
  const [submitted, setSubmitted] = useStateBk(false);

  const validate = () => {
    const e = {};
    if (!form.customer.trim()) e.customer = lang === 'zh' ? '请输入客户姓名' : 'Customer name required';
    if (!form.phone.trim()) e.phone = lang === 'zh' ? '请输入联系电话' : 'Phone required';
    else if (!/^[+0-9 \-()]{7,}$/.test(form.phone)) e.phone = lang === 'zh' ? '电话格式无效' : 'Invalid phone';
    if (form.email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = lang === 'zh' ? '邮箱格式无效' : 'Invalid email';
    if (!form.tour) e.tour = lang === 'zh' ? '请选择团游' : 'Select a tour';
    if (!form.date) e.date = lang === 'zh' ? '请选择日期' : 'Pick a date';
    if (!form.pax || +form.pax < 1) e.pax = lang === 'zh' ? '人数 ≥ 1' : 'Pax must be ≥ 1';
    if (!form.total || +form.total < 0) e.total = lang === 'zh' ? '总额无效' : 'Invalid total';
    return e;
  };

  const handleChange = (key, val) => {
    setForm(f => ({ ...f, [key]: val }));
    if (errors[key]) setErrors(e => ({ ...e, [key]: undefined }));
  };

  const handleSubmit = () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) {
      setSubmitted(true);
      setTimeout(onClose, 1500);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(16,37,69,.5)', zIndex: 200,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      animation: 'fadein .2s'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 16, width: 'min(640px, 100%)', maxHeight: '90vh',
        overflow: 'auto', boxShadow: 'var(--shadow-lg)', animation: 'slideUp .25s'
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 18 }}>{t('new_booking')}</h2>
            <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{lang === 'zh' ? '请填写预订详情。' : 'Fill in the booking details.'}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon.X size={18} /></button>
        </div>

        {submitted ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--success-bg)', color: 'var(--success)', display: 'inline-grid', placeItems: 'center', marginBottom: 14 }}>
              <Icon.Check size={28} stroke={2.5} />
            </div>
            <h3 style={{ margin: '0 0 4px' }}>{lang === 'zh' ? '预订已创建!' : 'Booking Created!'}</h3>
            <div className="muted">{lang === 'zh' ? '预订号 BK-2857 已发送至客户邮箱。' : 'Confirmation BK-2857 sent to customer.'}</div>
          </div>
        ) : (
          <>
            <div style={{ padding: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div className="field" style={{ gridColumn: '1 / -1' }}>
                <label className="field-label">{lang === 'zh' ? '客户姓名' : 'Customer Name'}<span className="req">*</span></label>
                <input className={`field-input ${errors.customer ? 'error' : ''}`} value={form.customer} onChange={(e) => handleChange('customer', e.target.value)} placeholder={lang === 'zh' ? '张伟' : 'e.g. Zhang Wei'} />
                {errors.customer && <div className="field-error"><Icon.Alert size={11} /> {errors.customer}</div>}
              </div>
              <div className="field">
                <label className="field-label">{lang === 'zh' ? '联系电话' : 'Phone'}<span className="req">*</span></label>
                <input className={`field-input ${errors.phone ? 'error' : ''}`} value={form.phone} onChange={(e) => handleChange('phone', e.target.value)} placeholder="+60 12-345 6789" />
                {errors.phone && <div className="field-error"><Icon.Alert size={11} /> {errors.phone}</div>}
              </div>
              <div className="field">
                <label className="field-label">{lang === 'zh' ? '邮箱 (可选)' : 'Email (optional)'}</label>
                <input className={`field-input ${errors.email ? 'error' : ''}`} value={form.email} onChange={(e) => handleChange('email', e.target.value)} placeholder="customer@example.com" />
                {errors.email && <div className="field-error"><Icon.Alert size={11} /> {errors.email}</div>}
              </div>
              <div className="field" style={{ gridColumn: '1 / -1' }}>
                <label className="field-label">{t('package')}<span className="req">*</span></label>
                <select className={`field-select ${errors.tour ? 'error' : ''}`} value={form.tour} onChange={(e) => handleChange('tour', e.target.value)}>
                  <option value="">{lang === 'zh' ? '— 选择团游 —' : '— Select a tour —'}</option>
                  <option>Genting Highlands 2D1N — RM 350/pax</option>
                  <option>Penang Heritage Trail 3D2N — RM 750/pax</option>
                  <option>Langkawi Island Hopping 4D3N — RM 980/pax</option>
                  <option>Cameron Highlands Tea Tour — RM 390/pax</option>
                  <option>Malacca City Tour — RM 150/pax</option>
                </select>
                {errors.tour && <div className="field-error"><Icon.Alert size={11} /> {errors.tour}</div>}
              </div>
              <div className="field">
                <label className="field-label">{lang === 'zh' ? '出发日期' : 'Travel Date'}<span className="req">*</span></label>
                <input type="date" className={`field-input ${errors.date ? 'error' : ''}`} value={form.date} onChange={(e) => handleChange('date', e.target.value)} />
                {errors.date && <div className="field-error"><Icon.Alert size={11} /> {errors.date}</div>}
              </div>
              <div className="field">
                <label className="field-label">{t('pax')}<span className="req">*</span></label>
                <input type="number" className={`field-input ${errors.pax ? 'error' : ''}`} value={form.pax} onChange={(e) => handleChange('pax', e.target.value)} placeholder="2" />
                {errors.pax && <div className="field-error"><Icon.Alert size={11} /> {errors.pax}</div>}
              </div>
              <div className="field">
                <label className="field-label">{lang === 'zh' ? '总额 (RM)' : 'Total (RM)'}<span className="req">*</span></label>
                <input type="number" className={`field-input ${errors.total ? 'error' : ''}`} value={form.total} onChange={(e) => handleChange('total', e.target.value)} placeholder="4200" />
                {errors.total && <div className="field-error"><Icon.Alert size={11} /> {errors.total}</div>}
              </div>
              <div className="field">
                <label className="field-label">{t('source')}</label>
                <select className="field-select">
                  <option>WhatsApp</option><option>Website</option><option>WeChat</option><option>Referral</option><option>Walk-in</option>
                </select>
              </div>
              <div className="field" style={{ gridColumn: '1 / -1' }}>
                <label className="field-label">{lang === 'zh' ? '备注' : 'Notes'}</label>
                <textarea className="field-textarea" value={form.notes} onChange={(e) => handleChange('notes', e.target.value)} placeholder={lang === 'zh' ? '特殊要求...' : 'Special requests...'}></textarea>
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid var(--border)', background: 'var(--bg)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <button className="btn btn-ghost" onClick={onClose}>{lang === 'zh' ? '取消' : 'Cancel'}</button>
              <button className="btn btn-gold" onClick={handleSubmit}><Icon.Check size={15} /> {lang === 'zh' ? '创建预订' : 'Create Booking'}</button>
            </div>
          </>
        )}
      </div>
      <style>{`
        @keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
      `}</style>
    </div>
  );
}

window.BookingsPage = BookingsPage;
