// screen-schedule.jsx — Batch 7: Queue + Publish Log
// Calendar tab is already provided by screen-calendar-brands.jsx (CalendarScreen).
const { useState: useStateSc, useMemo: useMemoSc } = React;

/* ============ helpers ============ */
function fmtClock(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
}
function fmtDay(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const today = new Date();
  const sameDay = d.toDateString() === today.toDateString();
  const tmr = new Date(today); tmr.setDate(today.getDate() + 1);
  const sameTmr = d.toDateString() === tmr.toDateString();
  if (sameDay) return 'Hôm nay';
  if (sameTmr) return 'Ngày mai';
  return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit' });
}
function diffMin(a, b) {
  return Math.round(Math.abs(new Date(a) - new Date(b)) / 60000);
}
function fmtAgo(iso) {
  if (!iso) return '—';
  const diff = (Date.now() - new Date(iso).getTime()) / 60000;
  if (diff < 1) return 'vừa xong';
  if (diff < 60) return Math.round(diff) + ' phút trước';
  if (diff < 1440) return Math.round(diff / 60) + ' giờ trước';
  return Math.round(diff / 1440) + ' ngày trước';
}
function channelMeta(key) {
  return SOCIAL_CHANNELS.find(c => c.key === key) || { label: key, icon: 'globe', color: 'var(--text-2)' };
}

/* ============ QUEUE SCREEN ============ */
function QueueScreen() {
  const app = useApp();
  // Build queue list from POSTS with scheduledAt in future, sorted by time
  const initialQueue = useMemoSc(() => {
    const now = Date.now();
    return POSTS
      .filter(p => p.scheduledAt && new Date(p.scheduledAt).getTime() > now - 3600000)
      .map(p => ({ ...p, paused: false }))
      .sort((a, b) => new Date(a.scheduledAt) - new Date(b.scheduledAt));
  }, []);

  const [queue, setQueue] = useStateSc(initialQueue);
  const [selected, setSelected] = useStateSc(new Set());
  const [editing, setEditing] = useStateSc(null);

  const conflicts = useMemoSc(() => {
    const flags = {};
    for (let i = 0; i < queue.length - 1; i++) {
      const a = queue[i], b = queue[i + 1];
      if (a.channel === b.channel && diffMin(a.scheduledAt, b.scheduledAt) < 15) {
        flags[a.id] = true; flags[b.id] = true;
      }
    }
    return flags;
  }, [queue]);

  const grouped = useMemoSc(() => {
    const g = {};
    queue.forEach(p => {
      const day = fmtDay(p.scheduledAt);
      g[day] = g[day] || [];
      g[day].push(p);
    });
    return g;
  }, [queue]);

  const stats = useMemoSc(() => ({
    total: queue.length,
    next: queue[0] ? queue[0].scheduledAt : null,
    paused: queue.filter(p => p.paused).length,
    conflict: Object.keys(conflicts).length,
  }), [queue, conflicts]);

  const toggleSel = (id) => {
    const s = new Set(selected);
    if (s.has(id)) s.delete(id); else s.add(id);
    setSelected(s);
  };

  const bulkPause = () => {
    const wasPaused = queue.find(p => selected.has(p.id))?.paused;
    setQueue(queue.map(p => selected.has(p.id) ? { ...p, paused: !p.paused } : p));
    app.toast(`Đã ${wasPaused ? 'bỏ tạm dừng' : 'tạm dừng'} ${selected.size} bài`, 'pause', 'var(--yellow)');
  };

  const bulkReschedule = () => {
    const offsetMin = parseInt(prompt('Dời thêm bao nhiêu phút? (số âm để đẩy sớm)') || '0', 10);
    if (!offsetMin) return;
    const n = selected.size;
    setQueue(queue.map(p => {
      if (!selected.has(p.id)) return p;
      const d = new Date(p.scheduledAt);
      d.setMinutes(d.getMinutes() + offsetMin);
      return { ...p, scheduledAt: d.toISOString() };
    }).sort((a, b) => new Date(a.scheduledAt) - new Date(b.scheduledAt)));
    setSelected(new Set());
    app.toast(`Đã dời ${n} bài`, 'clock', 'var(--accent)');
  };

  const saveEdit = (newIso) => {
    if (!editing) return;
    setQueue(queue.map(p => p.id === editing.id ? { ...p, scheduledAt: newIso } : p)
                  .sort((a, b) => new Date(a.scheduledAt) - new Date(b.scheduledAt)));
    setEditing(null);
    app.toast('Đã đổi giờ đăng', 'check', 'var(--green)');
  };

  return (
    <div className="page-pad">
      {/* Stats row */}
      <div className="row gap-sm" style={{ marginBottom: 14, flexWrap: 'wrap' }}>
        <QueueStat label="Trong hàng đợi" value={stats.total} icon="clock" color="var(--accent)" />
        <QueueStat label="Bài kế tiếp" value={stats.next ? fmtClock(stats.next) + ' · ' + fmtDay(stats.next) : '—'} icon="rocket" color="var(--blue)" />
        <QueueStat label="Đang tạm dừng" value={stats.paused} icon="pause" color="var(--yellow)" />
        <QueueStat label="Xung đột < 15p" value={stats.conflict} icon="alert" color={stats.conflict > 0 ? 'var(--red)' : 'var(--green)'} />
      </div>

      {/* Bulk actions bar */}
      {selected.size > 0 && (
        <div className="card card-pad" style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-2)' }}>
          <span className="t-sm strong">{selected.size} bài đang chọn</span>
          <div style={{ flex: 1 }}></div>
          <Button variant="ghost" icon="pause" size="sm" onClick={bulkPause}>Tạm dừng</Button>
          <Button variant="ghost" icon="clock" size="sm" onClick={bulkReschedule}>Dời giờ</Button>
          <Button variant="ghost" icon="x" size="sm" onClick={() => setSelected(new Set())}>Bỏ chọn</Button>
        </div>
      )}

      {/* Queue grouped by day */}
      {Object.keys(grouped).length === 0 ? (
        <div className="card card-pad" style={{ textAlign: 'center', padding: 48 }}>
          <Icon name="clock" size={36} stroke={1.4} style={{ color: 'var(--text-3)', marginBottom: 8 }} />
          <div className="t-h2">Hàng đợi rỗng</div>
          <div className="t-sm dim">Lên lịch bài đăng ở tab Lịch hoặc Content Review.</div>
        </div>
      ) : (
        Object.entries(grouped).map(([day, items]) => (
          <div key={day} style={{ marginBottom: 18 }}>
            <div className="t-2xs strong dimmer" style={{ marginBottom: 8, textTransform: 'uppercase', letterSpacing: 0.6 }}>{day} · {items.length} bài</div>
            <div className="card" style={{ overflow: 'hidden' }}>
              {items.map((p, i) => (
                <QueueRow key={p.id}
                  post={p}
                  selected={selected.has(p.id)}
                  conflict={conflicts[p.id]}
                  onToggle={() => toggleSel(p.id)}
                  onEdit={() => setEditing(p)}
                  divider={i < items.length - 1}
                />
              ))}
            </div>
          </div>
        ))
      )}

      {editing && <RescheduleDrawer post={editing} onClose={() => setEditing(null)} onSave={saveEdit} />}
    </div>
  );
}

function QueueStat({ label, value, icon, color }) {
  return (
    <div className="card card-pad" style={{ flex: '1 1 200px', minWidth: 180 }}>
      <div className="row gap-xs" style={{ alignItems: 'center', marginBottom: 4 }}>
        <Icon name={icon} size={14} stroke={1.6} style={{ color }} />
        <span className="t-2xs strong dimmer" style={{ textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</span>
      </div>
      <div className="t-h2" style={{ color, fontSize: 22 }}>{value}</div>
    </div>
  );
}

function QueueRow({ post, selected, conflict, onToggle, onEdit, divider }) {
  const product = PRODUCTS.find(x => x.id === post.productId);
  const ch = channelMeta(post.channel === 'fb' ? 'facebook' : post.channel);
  return (
    <div className="row gap-sm"
      style={{
        padding: '12px 14px',
        borderBottom: divider ? '1px solid var(--border)' : 'none',
        background: selected ? 'rgba(255,184,0,0.06)' : (post.paused ? 'var(--surface-2)' : 'transparent'),
        opacity: post.paused ? 0.6 : 1,
      }}>
      <input type="checkbox" checked={selected} onChange={onToggle} style={{ width: 16, height: 16, accentColor: 'var(--accent)' }} />
      <div style={{ minWidth: 64, textAlign: 'center' }}>
        <div className="t-h2 mono" style={{ fontSize: 18, lineHeight: 1 }}>{fmtClock(post.scheduledAt)}</div>
        <div className="t-2xs dimmer mono">{ch.label}</div>
      </div>
      <div style={{
        width: 4, alignSelf: 'stretch', borderRadius: 2,
        background: conflict ? 'var(--red)' : post.paused ? 'var(--text-3)' : ch.color,
      }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="t-sm strong clip-1">{product ? product.titleVn : post.id}</div>
        <div className="t-2xs dimmer clip-1">{post.caption.split('\n')[0]}</div>
        <div className="row gap-xs" style={{ marginTop: 6 }}>
          {post.format !== 'single' && <Badge variant="neutral" icon="layers">{post.format}</Badge>}
          {post.tone && <Badge variant="neutral" icon="palette">{post.tone}</Badge>}
          {post.paused && <Badge variant="yellow" icon="pause">tạm dừng</Badge>}
          {conflict && <Badge variant="red" icon="alert">xung đột &lt; 15p</Badge>}
        </div>
      </div>
      <Button variant="ghost" size="sm" icon="clock" onClick={onEdit}>Đổi giờ</Button>
    </div>
  );
}

function RescheduleDrawer({ post, onClose, onSave }) {
  const initial = post.scheduledAt ? new Date(post.scheduledAt) : new Date();
  const [date, setDate] = useStateSc(initial.toISOString().slice(0, 10));
  const [time, setTime] = useStateSc(initial.toTimeString().slice(0, 5));
  const apply = () => {
    const iso = new Date(date + 'T' + time + ':00').toISOString();
    onSave(iso);
  };
  const chLabel = channelMeta(post.channel === 'fb' ? 'facebook' : post.channel).label;
  return (
    <Drawer
      title="Đổi giờ đăng"
      sub={`${post.id} · ${chLabel}`}
      onClose={onClose}
      foot={
        <div className="row gap-sm" style={{ justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose}>Huỷ</Button>
          <Button variant="primary" icon="check" onClick={apply}>Lưu lịch mới</Button>
        </div>
      }>
      <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div>
          <label className="t-2xs strong dimmer">Ngày</label>
          <input type="date" value={date} onChange={e => setDate(e.target.value)} className="input" />
        </div>
        <div>
          <label className="t-2xs strong dimmer">Giờ</label>
          <input type="time" value={time} onChange={e => setTime(e.target.value)} className="input" />
        </div>
      </div>
      <div className="banner banner-info" style={{ marginTop: 12 }}>
        <Icon name="flag" size={14} style={{ color: 'var(--blue)' }} />
        <span className="t-2xs">Hệ thống sẽ cảnh báo nếu có bài cùng kênh trong khoảng 15 phút.</span>
      </div>
    </Drawer>
  );
}

/* ============ PUBLISH LOG SCREEN ============ */
function PublishLogScreen() {
  const [chFilter, setChFilter] = useStateSc('all');
  const [stFilter, setStFilter] = useStateSc('all');
  const [search, setSearch] = useStateSc('');

  // Extend the sample log to look richer (add 4 more synthetic entries from POSTS posted history)
  const log = useMemoSc(() => {
    const extra = POSTS.filter(p => p.status === 'posted' && p.postUrl).slice(0, 5).map((p, i) => ({
      id: 'plx' + i,
      postId: p.id,
      channel: 'facebook',
      status: 'ok',
      publishedAt: new Date(Date.now() - (i + 1) * 3600000 * 6).toISOString(),
      latencyMs: 1500 + i * 220,
      platformPostId: '376516022211741_' + (8800 + i),
      canonicalUrl: p.postUrl,
      error: null,
    }));
    return [...PUBLISH_LOG, ...extra]
      .sort((a, b) => new Date(b.publishedAt || 0) - new Date(a.publishedAt || 0));
  }, []);

  const filtered = useMemoSc(() => log.filter(x => {
    if (chFilter !== 'all' && x.channel !== chFilter) return false;
    if (stFilter !== 'all' && x.status !== stFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      if (!(x.postId + ' ' + (x.canonicalUrl || '') + ' ' + (x.error || '')).toLowerCase().includes(s)) return false;
    }
    return true;
  }), [log, chFilter, stFilter, search]);

  const stats = useMemoSc(() => ({
    total: log.length,
    ok: log.filter(x => x.status === 'ok').length,
    retry: log.filter(x => x.status === 'retry').length,
    pending: log.filter(x => x.status === 'pending').length,
    avgLatency: Math.round(log.filter(x => x.latencyMs > 0).reduce((a, b) => a + b.latencyMs, 0) / log.filter(x => x.latencyMs > 0).length),
  }), [log]);

  return (
    <div className="page-pad">
      {/* Stats */}
      <div className="row gap-sm" style={{ marginBottom: 14, flexWrap: 'wrap' }}>
        <QueueStat label="Tổng publish" value={stats.total} icon="upload" color="var(--accent)" />
        <QueueStat label="Thành công" value={stats.ok} icon="check" color="var(--green)" />
        <QueueStat label="Đang retry" value={stats.retry} icon="rotate" color="var(--yellow)" />
        <QueueStat label="Đang chờ" value={stats.pending} icon="clock" color="var(--blue)" />
        <QueueStat label="Độ trễ TB" value={stats.avgLatency + ' ms'} icon="zap" color="var(--text-2)" />
      </div>

      {/* Filter bar */}
      <div className="card card-pad" style={{ marginBottom: 14 }}>
        <div className="row gap-sm" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
          <Seg options={[
            { value: 'all', label: 'Tất cả kênh' },
            { value: 'facebook', label: 'FB' },
            { value: 'instagram', label: 'IG' },
            { value: 'tiktok', label: 'TT' },
          ]} value={chFilter} onChange={setChFilter} />
          <Seg options={[
            { value: 'all', label: 'Mọi trạng thái' },
            { value: 'ok', label: 'OK' },
            { value: 'retry', label: 'Retry' },
            { value: 'pending', label: 'Pending' },
          ]} value={stFilter} onChange={setStFilter} />
          <div style={{ flex: 1, minWidth: 200, position: 'relative' }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
            <input className="input" placeholder="Tìm post ID / URL / error..." value={search} onChange={e => setSearch(e.target.value)} style={{ paddingLeft: 30 }} />
          </div>
          <Button variant="ghost" icon="download" size="sm">Export CSV</Button>
          <Button variant="ghost" icon="archive" size="sm">Archive 90d</Button>
        </div>
      </div>

      {/* Log table */}
      <div className="card" style={{ overflow: 'hidden' }}>
        <div className="row" style={{
          padding: '10px 14px', background: 'var(--surface-2)',
          borderBottom: '1px solid var(--border)', fontSize: 11, fontWeight: 600, color: 'var(--text-2)', textTransform: 'uppercase', letterSpacing: 0.4
        }}>
          <div style={{ width: 78 }}>Thời điểm</div>
          <div style={{ width: 92 }}>Kênh</div>
          <div style={{ width: 100 }}>Trạng thái</div>
          <div style={{ flex: 1, minWidth: 0 }}>Post · URL canonical</div>
          <div style={{ width: 80, textAlign: 'right' }}>Latency</div>
          <div style={{ width: 100, textAlign: 'right' }}></div>
        </div>
        {filtered.length === 0 ? (
          <div style={{ padding: 32, textAlign: 'center' }} className="t-sm dim">Không có log phù hợp.</div>
        ) : (
          filtered.map((x, i) => <LogRow key={x.id} row={x} divider={i < filtered.length - 1} />)
        )}
      </div>
    </div>
  );
}

function LogRow({ row, divider }) {
  const ch = channelMeta(row.channel);
  const stColor = row.status === 'ok' ? 'var(--green)' : row.status === 'retry' ? 'var(--yellow)' : row.status === 'pending' ? 'var(--blue)' : 'var(--red)';
  const stIcon = row.status === 'ok' ? 'check' : row.status === 'retry' ? 'rotate' : row.status === 'pending' ? 'clock' : 'alert';
  return (
    <div className="row" style={{ padding: '10px 14px', borderBottom: divider ? '1px solid var(--border)' : 'none', alignItems: 'center' }}>
      <div style={{ width: 78 }}>
        <div className="t-xs mono">{row.publishedAt ? fmtClock(row.publishedAt) : '—'}</div>
        <div className="t-2xs dimmer">{fmtAgo(row.publishedAt)}</div>
      </div>
      <div style={{ width: 92 }} className="row gap-xs">
        <Icon name={ch.icon} size={14} style={{ color: ch.color }} />
        <span className="t-xs">{ch.label}</span>
      </div>
      <div style={{ width: 100 }} className="row gap-xs">
        <Icon name={stIcon} size={12} style={{ color: stColor }} />
        <span className="t-xs strong" style={{ color: stColor }}>{row.status.toUpperCase()}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="t-xs mono clip-1">{row.postId}</div>
        {row.canonicalUrl
          ? <div className="t-2xs dimmer mono clip-1" style={{ color: 'var(--accent)' }}>{row.canonicalUrl}</div>
          : row.error
            ? <div className="t-2xs clip-1" style={{ color: stColor }}>{row.error}</div>
            : <div className="t-2xs dimmer">—</div>}
      </div>
      <div style={{ width: 80, textAlign: 'right' }} className="t-xs mono dimmer">
        {row.latencyMs > 0 ? row.latencyMs + ' ms' : '—'}
      </div>
      <div style={{ width: 100, textAlign: 'right' }}>
        {row.status === 'retry' && <Button variant="ghost" size="sm" icon="rotate">Retry</Button>}
        {row.status === 'ok' && row.canonicalUrl && <Button variant="ghost" size="sm" icon="external">Mở</Button>}
        {row.status === 'pending' && <Button variant="ghost" size="sm" icon="x">Huỷ</Button>}
      </div>
    </div>
  );
}

Object.assign(window, { QueueScreen, PublishLogScreen });
