// screen-sources.jsx — Batch 9: Crawl Jobs + Watchlist
// Brands tab and Campaigns tab already exist (BrandsScreen, CampaignsScreen).
const { useState: useStateSr, useMemo: useMemoSr } = React;

function fmtJobTime(iso) {
  const d = new Date(iso);
  return d.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
}
function fmtJobAgo(iso) {
  const min = (Date.now() - new Date(iso).getTime()) / 60000;
  if (min < 1) return 'vừa xong';
  if (min < 60) return Math.round(min) + ' phút trước';
  if (min < 1440) return Math.round(min / 60) + ' giờ trước';
  return Math.round(min / 1440) + ' ngày trước';
}

/* ============ CRAWL JOBS SCREEN ============ */
function CrawlJobsScreen() {
  const [status, setStatus] = useStateSr('all');
  const [brand, setBrand] = useStateSr('all');
  const [selected, setSelected] = useStateSr(null);

  // Synthesize a few extra running/recent jobs for richness
  const jobs = useMemoSr(() => {
    const synth = [
      { id: 'j-now-1', brand: 'uniqlo', status: 'running', startedAt: new Date(Date.now() - 45000).toISOString(), durationS: 0, productsFound: 12, error: null, artifactUrl: null, pages: 1, progress: 0.34 },
      { id: 'j-now-2', brand: 'gu',     status: 'queued',  startedAt: new Date(Date.now() + 120000).toISOString(), durationS: 0, productsFound: 0, error: null, artifactUrl: null, pages: 0 },
    ];
    return [...synth, ...CRAWL_JOBS];
  }, []);

  const filtered = useMemoSr(() => jobs.filter(j => {
    if (status !== 'all' && j.status !== status) return false;
    if (brand !== 'all' && j.brand !== brand) return false;
    return true;
  }), [jobs, status, brand]);

  const stats = useMemoSr(() => ({
    total: jobs.length,
    ok: jobs.filter(x => x.status === 'ok').length,
    failed: jobs.filter(x => x.status === 'failed').length,
    running: jobs.filter(x => x.status === 'running' || x.status === 'queued').length,
    products: jobs.reduce((a, b) => a + b.productsFound, 0),
  }), [jobs]);

  return (
    <div className="page-pad">
      <div className="row gap-sm" style={{ marginBottom: 14, flexWrap: 'wrap' }}>
        <AnStat label="Tổng job" value={stats.total} icon="rotate" color="var(--accent)" />
        <AnStat label="Thành công" value={stats.ok} icon="check" color="var(--green)" />
        <AnStat label="Đang chạy" value={stats.running} icon="zap" color="var(--blue)" />
        <AnStat label="Thất bại" value={stats.failed} icon="alert" color="var(--red)" />
        <AnStat label="Sản phẩm tìm thấy" value={stats.products} icon="package" color="var(--text-2)" />
      </div>

      <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ả' },
            { value: 'running', label: 'Đang chạy' },
            { value: 'ok', label: 'OK' },
            { value: 'partial', label: 'Một phần' },
            { value: 'failed', label: 'Lỗi' },
          ]} value={status} onChange={setStatus} />
          <select className="input sm" value={brand} onChange={e => setBrand(e.target.value)} style={{ width: 180 }}>
            <option value="all">Tất cả brand/adapter</option>
            {BRANDS.map(b => <option key={b.key} value={b.key}>{b.name}</option>)}
            <option value="rakuten_adidas">rakuten_adidas (fallback)</option>
          </select>
          <div style={{ flex: 1 }}></div>
          <Button variant="ghost" icon="rotate" size="sm">Chạy lại tất cả lỗi</Button>
          <Button variant="primary" icon="plus" size="sm">Trigger crawl mới</Button>
        </div>
      </div>

      <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: 100 }}>Thời điểm</div>
          <div style={{ width: 130 }}>Brand · Adapter</div>
          <div style={{ width: 100 }}>Trạng thái</div>
          <div style={{ flex: 1, minWidth: 0 }}>Kết quả</div>
          <div style={{ width: 70, textAlign: 'right' }}>Thời gian</div>
          <div style={{ width: 100, textAlign: 'right' }}></div>
        </div>
        {filtered.map((j, i) => (
          <CrawlRow key={j.id} job={j} divider={i < filtered.length - 1} onOpen={() => setSelected(j)} />
        ))}
      </div>

      {selected && <CrawlJobDrawer job={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

function CrawlRow({ job, divider, onOpen }) {
  const b = brandOf(job.brand);
  const stColor = job.status === 'ok' ? 'var(--green)' :
                  job.status === 'partial' ? 'var(--yellow)' :
                  job.status === 'failed' ? 'var(--red)' :
                  job.status === 'running' ? 'var(--blue)' :
                  'var(--text-3)';
  const stIcon = job.status === 'ok' ? 'check' :
                 job.status === 'partial' ? 'alert' :
                 job.status === 'failed' ? 'alert' :
                 job.status === 'running' ? 'rotate' :
                 'clock';
  return (
    <div className="row" style={{ padding: '10px 14px', borderBottom: divider ? '1px solid var(--border)' : 'none', alignItems: 'center' }}>
      <div style={{ width: 100 }}>
        <div className="t-xs mono">{fmtJobTime(job.startedAt)}</div>
        <div className="t-2xs dimmer">{fmtJobAgo(job.startedAt)}</div>
      </div>
      <div style={{ width: 130 }} className="row gap-xs">
        {b.key && <BrandLogo brand={b} size={20} />}
        <span className="t-xs">{job.brand}</span>
      </div>
      <div style={{ width: 100 }} className="row gap-xs">
        <Icon name={stIcon} size={12} style={{ color: stColor, animation: job.status === 'running' ? 'spin 1.4s linear infinite' : 'none' }} />
        <span className="t-xs strong" style={{ color: stColor }}>{job.status.toUpperCase()}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="t-xs">{job.productsFound} sản phẩm · {job.pages} page</div>
        {job.error && <div className="t-2xs clip-1" style={{ color: stColor }}>{job.error}</div>}
        {job.status === 'running' && (
          <div style={{ height: 4, borderRadius: 2, background: 'var(--surface-2)', marginTop: 6, overflow: 'hidden' }}>
            <div style={{ width: ((job.progress || 0) * 100) + '%', height: '100%', background: 'var(--blue)', transition: 'width 0.3s' }} />
          </div>
        )}
      </div>
      <div style={{ width: 70, textAlign: 'right' }} className="t-xs mono dimmer">
        {job.durationS > 0 ? job.durationS + 's' : '—'}
      </div>
      <div className="row gap-xs" style={{ width: 100, justifyContent: 'flex-end' }}>
        {job.artifactUrl && <Button variant="ghost" size="sm" icon="image">Artifact</Button>}
        {job.status === 'failed' && <Button variant="ghost" size="sm" icon="rotate">Retry</Button>}
        <Button variant="ghost" size="sm" icon="external" onClick={onOpen}>Mở</Button>
      </div>
    </div>
  );
}

function CrawlJobDrawer({ job, onClose }) {
  const b = brandOf(job.brand);
  return (
    <Drawer title={`Crawl job ${job.id}`} sub={`${job.brand} · ${fmtJobTime(job.startedAt)}`} onClose={onClose}>
      <div className="row gap-sm" style={{ marginBottom: 14 }}>
        <Badge variant={job.status === 'ok' ? 'green' : job.status === 'failed' ? 'red' : 'yellow'} icon={job.status === 'ok' ? 'check' : 'alert'}>
          {job.status.toUpperCase()}
        </Badge>
        {job.triggeredBy === 'fallback' && <Badge variant="neutral" icon="rotate">Fallback</Badge>}
        <Badge variant="neutral" icon="clock">{job.durationS}s</Badge>
        <Badge variant="neutral" icon="package">{job.productsFound} sản phẩm</Badge>
      </div>

      <div className="t-2xs strong dimmer" style={{ marginTop: 16, marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>Chi tiết</div>
      <div className="card card-pad" style={{ marginBottom: 14 }}>
        <InfoRow label="Brand" value={b.name || job.brand} />
        <InfoRow label="Adapter" value={job.brand} mono />
        <InfoRow label="Bắt đầu" value={new Date(job.startedAt).toLocaleString('vi-VN')} mono />
        <InfoRow label="Trang đã quét" value={job.pages} />
        <InfoRow label="Sản phẩm tìm thấy" value={job.productsFound} />
      </div>

      {job.error && (
        <>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>Lỗi</div>
          <div className="banner banner-danger" style={{ marginBottom: 14 }}>
            <Icon name="alert" size={14} style={{ color: 'var(--red)' }} />
            <span className="t-2xs">{job.error}</span>
          </div>
        </>
      )}

      {job.artifactUrl && (
        <>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>Artifact</div>
          <div className="card card-pad" style={{ marginBottom: 14 }}>
            <div className="row gap-sm" style={{ alignItems: 'center' }}>
              <Icon name={job.artifactUrl.endsWith('.png') ? 'image' : 'notepad'} size={18} style={{ color: 'var(--text-2)' }} />
              <div style={{ flex: 1 }}>
                <div className="t-xs mono">{job.artifactUrl}</div>
                <div className="t-2xs dimmer">Screenshot HTML khi adapter bị block. Dùng để debug.</div>
              </div>
              <Button variant="ghost" icon="download" size="sm">Tải</Button>
            </div>
          </div>
        </>
      )}

      <div className="t-2xs strong dimmer" style={{ marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>Hành động</div>
      <div className="row gap-sm">
        <Button variant="ghost" icon="rotate">Chạy lại</Button>
        <Button variant="ghost" icon="bot">Xem log JSON</Button>
        <Button variant="ghost" icon="settings">Sửa adapter</Button>
      </div>
    </Drawer>
  );
}

function InfoRow({ label, value, mono }) {
  return (
    <div className="row" style={{ padding: '6px 0', borderBottom: '1px dashed var(--border)' }}>
      <div className="t-2xs dimmer" style={{ width: 140 }}>{label}</div>
      <div className={'t-xs' + (mono ? ' mono' : '')}>{value}</div>
    </div>
  );
}

/* ============ WATCHLIST SCREEN ============ */
function WatchlistScreen() {
  const [items, setItems] = useStateSr(WATCHLIST);
  const [editing, setEditing] = useStateSr(null);
  const [adding, setAdding] = useStateSr(false);
  const app = useApp();

  const stats = useMemoSr(() => ({
    total: items.length,
    active: items.filter(w => w.active).length,
    hits: items.reduce((a, b) => a + b.hitCount, 0),
    recent: items.filter(w => /phút|giờ/.test(w.lastHit || '')).length,
  }), [items]);

  const toggleActive = (id) => setItems(items.map(w => w.id === id ? { ...w, active: !w.active } : w));
  const remove = (id) => { if (confirm('Xoá keyword này?')) setItems(items.filter(w => w.id !== id)); };
  const save = (w) => {
    if (w.id && items.find(x => x.id === w.id)) {
      setItems(items.map(x => x.id === w.id ? w : x));
      app.toast('Đã cập nhật watchlist', 'check', 'var(--green)');
    } else {
      setItems([...items, { ...w, id: 'wl' + (items.length + 1), hitCount: 0, lastHit: '—' }]);
      app.toast('Đã thêm watchlist', 'check', 'var(--green)');
    }
    setEditing(null); setAdding(false);
  };

  return (
    <div className="page-pad">
      <div className="card card-pad" style={{ marginBottom: 14, background: 'var(--surface-2)' }}>
        <div className="row gap-sm" style={{ alignItems: 'center' }}>
          <div style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--accent-soft)', color: 'var(--yellow)', display: 'grid', placeItems: 'center' }}>
            <Icon name="star" size={20} stroke={1.7} />
          </div>
          <div style={{ flex: 1 }}>
            <div className="t-sm strong">Watchlist sản phẩm</div>
            <div className="t-2xs dim">Theo dõi keyword cố định (Air Max, Heattech, AIRism…). Khi giá rớt xuống ngưỡng, hệ thống auto-alert + boost score <strong>+15</strong>.</div>
          </div>
          <Button variant="primary" icon="plus" size="sm" onClick={() => setAdding(true)}>Thêm keyword</Button>
        </div>
      </div>

      <div className="row gap-sm" style={{ marginBottom: 14, flexWrap: 'wrap' }}>
        <AnStat label="Tổng keyword" value={stats.total} icon="star" color="var(--yellow)" />
        <AnStat label="Đang theo dõi" value={stats.active} icon="check" color="var(--green)" />
        <AnStat label="Tổng lần khớp" value={stats.hits} icon="zap" color="var(--accent)" />
        <AnStat label="Mới khớp gần đây" value={stats.recent} icon="clock" color="var(--blue)" />
      </div>

      <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: 70 }}>Active</div>
          <div style={{ flex: 1 }}>Keyword · Brand</div>
          <div style={{ width: 130, textAlign: 'right' }}>Ngưỡng giá</div>
          <div style={{ width: 100, textAlign: 'right' }}>Lần khớp</div>
          <div style={{ width: 140 }}>Khớp gần nhất</div>
          <div style={{ width: 90, textAlign: 'right' }}></div>
        </div>
        {items.map((w, i) => (
          <WatchlistRow key={w.id} item={w} divider={i < items.length - 1}
            onToggle={() => toggleActive(w.id)}
            onEdit={() => setEditing(w)}
            onRemove={() => remove(w.id)} />
        ))}
      </div>

      {(editing || adding) && (
        <WatchlistDrawer
          item={editing || { keyword: '', brand: 'uniqlo', maxPriceYen: 5000, active: true }}
          onClose={() => { setEditing(null); setAdding(false); }}
          onSave={save} />
      )}
    </div>
  );
}

function WatchlistRow({ item, divider, onToggle, onEdit, onRemove }) {
  const b = brandOf(item.brand);
  return (
    <div className="row" style={{ padding: '10px 14px', borderBottom: divider ? '1px solid var(--border)' : 'none', alignItems: 'center' }}>
      <div style={{ width: 70 }}>
        <Toggle on={item.active} onChange={onToggle} />
      </div>
      <div className="row gap-sm" style={{ flex: 1, minWidth: 0 }}>
        <BrandLogo brand={b} size={22} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="t-sm strong clip-1">{item.keyword}</div>
          <div className="t-2xs dimmer">{b.name}</div>
        </div>
      </div>
      <div style={{ width: 130, textAlign: 'right' }} className="t-xs mono">
        ≤ {item.maxPriceYen.toLocaleString()}¥
      </div>
      <div className="row gap-xs" style={{ width: 100, justifyContent: 'flex-end' }}>
        <Badge variant={item.hitCount > 5 ? 'green' : 'neutral'} icon="zap">{item.hitCount}</Badge>
      </div>
      <div style={{ width: 140 }} className="t-2xs dimmer">{item.lastHit}</div>
      <div className="row gap-xs" style={{ width: 90, justifyContent: 'flex-end' }}>
        <Button variant="ghost" size="sm" icon="edit" onClick={onEdit} />
        <Button variant="ghost" size="sm" icon="trash" onClick={onRemove} />
      </div>
    </div>
  );
}

function WatchlistDrawer({ item, onClose, onSave }) {
  const [form, setForm] = useStateSr({ ...item });
  return (
    <Drawer
      title={item.id ? 'Sửa keyword' : 'Thêm keyword mới'}
      sub={item.id ? item.id : 'Mới'}
      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={() => onSave(form)}>Lưu</Button>
        </div>
      }>
      <Field label="Keyword">
        <input className="input" value={form.keyword} onChange={e => setForm({ ...form, keyword: e.target.value })} placeholder="vd: Air Max" />
      </Field>
      <Field label="Brand">
        <select className="input" value={form.brand} onChange={e => setForm({ ...form, brand: e.target.value })}>
          {BRANDS.map(b => <option key={b.key} value={b.key}>{b.name}</option>)}
        </select>
      </Field>
      <Field label="Ngưỡng giá (¥)" hint="Khớp khi giá ≤ ngưỡng này">
        <input className="input mono" type="number" value={form.maxPriceYen} onChange={e => setForm({ ...form, maxPriceYen: parseInt(e.target.value, 10) || 0 })} />
      </Field>
      <Field label="Active">
        <Toggle on={form.active} onChange={(v) => setForm({ ...form, active: v })} />
      </Field>
      <div className="banner banner-info" style={{ marginTop: 12 }}>
        <Icon name="flag" size={14} style={{ color: 'var(--blue)' }} />
        <span className="t-2xs">Sản phẩm khớp watchlist sẽ được boost score <strong>+15</strong> và đẩy lên đầu Product Pool.</span>
      </div>
    </Drawer>
  );
}

Object.assign(window, { CrawlJobsScreen, WatchlistScreen });
