// screen-calendar-brands.jsx
const { useState: useStateCB } = React;

/* ============ CALENDAR ============ */
const DOW = ['T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'CN'];
const EVT_COLOR = { scheduled: 'var(--violet)', posted: 'var(--green)', failed: 'var(--red)', text_pending: 'var(--yellow)', image_pending: 'var(--orange)', approved: 'var(--blue)', draft: 'var(--text-2)' };

function CalendarScreen() {
  const app = useApp();
  const [view, setView] = useStateCB('month');
  // build events from posts onto a fake May 2026 grid
  const events = POSTS.map((p, i) => {
    const prod = PRODUCTS.find(x => x.id === p.productId);
    const day = p.status === 'posted' ? 26 + (i % 3) : 29 + (i % 3);
    const hour = 9 + (i * 3) % 12;
    return { ...p, prod, day, hour, status: p.status };
  });
  const eventsByDay = {};
  events.forEach(e => { (eventsByDay[e.day] = eventsByDay[e.day] || []).push(e); });

  // May 2026 starts on Friday (T6); 31 days
  const firstDow = 4; // 0=T2 ... May 1 2026 is Friday => index 4
  const days = 31;
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);

  return (
    <div className="page-pad wide">
      <div className="between" style={{ marginBottom: 14 }}>
        <div>
          <div className="t-h1">Lịch đăng</div>
          <div className="t-sm dim">Tháng 5, 2026 · {events.length} bài</div>
        </div>
        <div className="row gap-sm">
          <div className="row gap-sm desktop-only t-2xs dimmer">
            {Object.entries({ scheduled: 'Đặt lịch', posted: 'Đã đăng', failed: 'Lỗi', text_pending: 'Chờ duyệt text', image_pending: 'Chờ duyệt ảnh' }).map(([k, l]) => (
              <span key={k} className="row" style={{ gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: EVT_COLOR[k] }}></span>{l}</span>
            ))}
          </div>
          <Seg value={view} options={[{ value: 'month', label: 'Tháng' }, { value: 'week', label: 'Tuần' }, { value: 'list', label: 'List' }]} onChange={setView} />
        </div>
      </div>

      {view === 'list' || (typeof window !== 'undefined' && window.innerWidth < 860) ? (
        <CalList events={events} app={app} />
      ) : (
        <div className="card desktop-only" style={{ overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
            {DOW.map(d => <div key={d} className="t-2xs strong dimmer" style={{ padding: '10px 12px', textAlign: 'center', borderBottom: '1px solid var(--border)' }}>{d}</div>)}
            {cells.map((d, i) => (
              <div key={i} style={{ minHeight: view === 'week' ? 160 : 112, borderRight: (i % 7 !== 6) ? '1px solid var(--border)' : 'none', borderBottom: '1px solid var(--border)', padding: 6, background: d === 29 ? 'var(--accent-soft)' : undefined }}>
                {d && <div className="t-2xs mono dimmer" style={{ marginBottom: 4, fontWeight: d === 29 ? 700 : 400, color: d === 29 ? 'var(--accent)' : undefined }}>{d}</div>}
                <div className="col" style={{ gap: 3 }}>
                  {(eventsByDay[d] || []).slice(0, 3).map(e => (
                    <div key={e.id} onClick={() => app.go('review', e.productId)} title={e.prod.titleVn}
                         style={{ display: 'flex', gap: 5, alignItems: 'center', padding: '3px 5px', borderRadius: 5, background: 'var(--surface)', cursor: 'pointer', borderLeft: '2px solid ' + EVT_COLOR[e.status] }}>
                      <span className="t-2xs mono dimmer" style={{ minWidth: 26 }}>{String(e.hour).padStart(2, '0')}:00</span>
                      <span className="t-2xs clip-1">{e.prod.titleVn}</span>
                    </div>
                  ))}
                  {(eventsByDay[d] || []).length > 3 && <div className="t-2xs dimmer" style={{ paddingLeft: 5 }}>+{eventsByDay[d].length - 3} nữa</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      <div className="mobile-only"><CalList events={events} app={app} /></div>
    </div>
  );
}

function CalList({ events, app }) {
  const sorted = [...events].sort((a, b) => a.day - b.day || a.hour - b.hour);
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      {sorted.map((e, i) => {
        const b = brandOf(e.prod.brand);
        return (
          <div key={e.id} className="row" style={{ gap: 12, padding: 12, borderBottom: i < sorted.length - 1 ? '1px solid var(--border)' : 'none', cursor: 'pointer' }} onClick={() => app.go('review', e.productId)}>
            <div className="col" style={{ minWidth: 56, alignItems: 'center' }}>
              <div className="t-sm strong mono">{e.day}/5</div>
              <div className="t-2xs dimmer mono">{String(e.hour).padStart(2, '0')}:00</div>
            </div>
            <Placeholder label="" brand={b} ratio="1" style={{ width: 44, height: 44 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-sm strong clip-1">{e.prod.titleVn}</div>
              <div className="t-2xs dimmer clip-1">{e.caption.split('\n')[0]}</div>
            </div>
            <div className="col gap-sm" style={{ alignItems: 'flex-end' }}>
              <StatusPill status={e.status} />
              {e.postUrl && <a className="t-2xs row gap-sm" style={{ color: 'var(--accent)' }} href={'https://' + e.postUrl} target="_blank" onClick={ev => ev.stopPropagation()}>Xem bài <Icon name="external" size={11} /></a>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ============ BRANDS ============ */
function BrandsScreen() {
  const app = useApp();
  const [filter, setFilter] = useStateCB('all');
  const [open, setOpen] = useStateCB(null);
  const [adding, setAdding] = useStateCB(false);
  const list = BRANDS.filter(b => filter === 'all' ? true : filter === 'enabled' ? b.enabled : filter === 'disabled' ? !b.enabled : b.rate24 < 70);

  return (
    <div className="page-pad wide">
      <div className="between" style={{ marginBottom: 14 }}>
        <div>
          <div className="t-h1">Nguồn brand</div>
          <div className="t-sm dim">Cấu hình site Nhật để hệ thống tự scrape. Tự thêm brand mới không cần gọi MADIAD.</div>
        </div>
        <Button variant="primary" icon="plus" onClick={() => setAdding(true)}>Thêm source brand</Button>
      </div>

      <div className="row gap-sm" style={{ marginBottom: 14 }}>
        <Seg value={filter} options={[{ value: 'all', label: 'Tất cả' }, { value: 'enabled', label: 'Đang chạy' }, { value: 'disabled', label: 'Tạm dừng' }, { value: 'errors', label: 'Có lỗi' }]} onChange={setFilter} />
      </div>

      <div className="card desktop-only" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr>
            <th>Brand</th><th>Host patterns</th><th style={{ width: 110 }}>Kiểu</th><th style={{ width: 120 }}>Trạng thái</th><th style={{ width: 130 }}>Scrape cuối</th><th style={{ width: 150 }}>Success 24h</th><th style={{ width: 44 }}></th>
          </tr></thead>
          <tbody>
            {list.map(b => (
              <tr key={b.key} onClick={() => setOpen(b)}>
                <td>
                  <div className="row gap-sm"><BrandLogo brand={b} size={28} /><div><div className="t-sm strong">{b.name}</div><div className="t-2xs dimmer mono">{b.key} · {b.jp}</div></div></div>
                </td>
                <td><span className="t-xs mono dimmer">{b.hosts.join(', ')}</span></td>
                <td><Badge variant={b.kind === 'manual' ? 'neutral' : 'brand'}>{b.kind}</Badge></td>
                <td>{b.enabled ? <Badge variant="green" icon="play">Active</Badge> : <Badge variant="neutral" icon="pause">Paused</Badge>}</td>
                <td><span className="t-xs dimmer">{b.lastScrape}</span></td>
                <td>
                  {b.rate24 < 70 && b.enabled ? <Badge variant="red" icon="alert">Cần kiểm tra</Badge> : (
                    <div className="row gap-sm">
                      <div style={{ flex: 1, height: 6, background: 'var(--surface-2)', borderRadius: 99, overflow: 'hidden' }}><div style={{ width: b.rate24 + '%', height: '100%', background: b.rate24 >= 90 ? 'var(--green)' : b.rate24 >= 70 ? 'var(--yellow)' : 'var(--red)' }}></div></div>
                      <span className="t-2xs mono dimmer">{b.rate24}%</span>
                    </div>
                  )}
                </td>
                <td onClick={e => e.stopPropagation()}><Button variant="ghost" size="sm" icon="dots" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* mobile cards */}
      <div className="mobile-only col" style={{ gap: 10 }}>
        {list.map(b => (
          <div key={b.key} className="card card-pad" onClick={() => setOpen(b)}>
            <div className="between"><div className="row gap-sm"><BrandLogo brand={b} size={30} /><div><div className="t-sm strong">{b.name}</div><div className="t-2xs dimmer mono">{b.key}</div></div></div>{b.enabled ? <Badge variant="green">Active</Badge> : <Badge variant="neutral">Paused</Badge>}</div>
            <div className="between" style={{ marginTop: 10 }}><span className="t-2xs dimmer">{b.lastScrape}</span><span className="t-2xs mono dimmer">{b.rate24}% · {b.rateN}</span></div>
          </div>
        ))}
      </div>

      {open && <BrandDrawer b={open} onClose={() => setOpen(null)} app={app} />}
      {adding && <BrandForm onClose={() => setAdding(false)} app={app} />}
    </div>
  );
}

function BrandDrawer({ b, onClose, app }) {
  const [tab, setTab] = useStateCB('config');
  const logs = Array.from({ length: 8 }, (_, i) => ({ code: i === 0 && b.rate24 < 70 ? 500 : 200, dur: 800 + i * 120, time: (i + 1) * 12 + ' phút trước', ok: !(i === 0 && b.rate24 < 70) }));
  return (
    <Drawer title={b.name} sub={`${b.key} · ${b.jp}`} onClose={onClose}
      head={<><BrandLogo brand={b} size={34} /><div style={{ flex: 1, minWidth: 0 }}><div className="t-h2">{b.name}</div><div className="t-xs dimmer mono">{b.key}</div></div></>}
      foot={<><Button variant={b.enabled ? 'danger' : 'primary'} icon={b.enabled ? 'pause' : 'play'} onClick={() => { app.toast(b.enabled ? 'Đã tạm dừng brand' : 'Đã kích hoạt brand', 'check'); onClose(); }}>{b.enabled ? 'Tạm dừng' : 'Kích hoạt'}</Button><Button variant="default" icon="mail">Liên hệ MADIAD</Button></>}>
      <Tabs active={tab} onChange={setTab} tabs={[{ value: 'config', label: 'Cấu hình' }, { value: 'stats', label: 'Thống kê' }, { value: 'logs', label: 'Logs' }, { value: 'test', label: 'Test' }]} />
      <div style={{ paddingTop: 16 }}>
        {tab === 'config' && (
          <div className="col" style={{ gap: 14 }}>
            <Field label="Tên hiển thị"><input className="input" defaultValue={b.name} /></Field>
            <Field label="Brand-safe name" hint="Tên dùng trong caption để né kiểm duyệt FB"><input className="input mono" defaultValue={b.safe} /></Field>
            <Field label="Host patterns" hint="Mỗi dòng 1 host"><textarea className="textarea mono" defaultValue={b.hosts.join('\n')} /></Field>
            <Field label="Kiểu scraper"><select className="select" defaultValue={b.kind}><option value="json_api">json_api</option><option value="html_parse">html_parse</option><option value="manual">manual</option></select></Field>
            <Field label="Crawl interval (phút)"><input className="input mono" type="number" defaultValue={b.interval} /></Field>
          </div>
        )}
        {tab === 'stats' && (
          <div className="col" style={{ gap: 12 }}>
            <div className="grid-2"><div className="stat"><div className="stat-top t-xs">Success 24h</div><div className="stat-val" style={{ fontSize: 26 }}>{b.rate24}%</div></div><div className="stat"><div className="stat-top t-xs">Tổng scrape</div><div className="stat-val" style={{ fontSize: 26 }}>{b.rateN.split('/')[1] || 0}</div></div></div>
            <div className="card card-pad"><div className="t-2xs strong dimmer" style={{ marginBottom: 10 }}>7 NGÀY QUA</div><div className="row" style={{ gap: 4, alignItems: 'flex-end', height: 80 }}>{[80, 92, 75, 100, 88, b.rate24, b.rate24].map((v, i) => <div key={i} style={{ flex: 1, height: v + '%', background: i === 6 ? 'var(--accent)' : 'var(--surface-2)', borderRadius: 4 }} title={v + '%'}></div>)}</div></div>
          </div>
        )}
        {tab === 'logs' && (
          <div className="col" style={{ gap: 2 }}>
            {logs.map((l, i) => (
              <div key={i} className="row" style={{ gap: 10, padding: '9px 8px', borderBottom: '1px solid var(--border)' }}>
                <Badge variant={l.ok ? 'green' : 'red'}>{l.code}</Badge>
                <span className="t-xs mono dimmer" style={{ flex: 1 }}>{l.dur}ms</span>
                <span className="t-2xs dimmer">{l.time}</span>
              </div>
            ))}
          </div>
        )}
        {tab === 'test' && (
          <div className="col" style={{ gap: 12 }}>
            <Field label="URL test" hint="Dán 1 URL sản phẩm để thử scrape ngay"><textarea className="textarea mono" placeholder={'https://' + b.hosts[0] + '/...'} /></Field>
            <Button variant="primary" icon="scan" onClick={() => app.toast('Đang test scrape…', 'loader', 'var(--blue)')}>Test scrape ngay</Button>
            <div className="panel" style={{ padding: 12 }}><div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>OUTPUT</div><pre className="t-xs mono dimmer" style={{ whiteSpace: 'pre-wrap' }}>{`{\n  "title_jp": "...",\n  "price_jpy": 0,\n  "images": [],\n  "status": "chờ test"\n}`}</pre></div>
          </div>
        )}
      </div>
    </Drawer>
  );
}

function BrandForm({ onClose, app }) {
  const [step, setStep] = useStateCB(1);
  return (
    <Modal title="Thêm source brand" sub={`Bước ${step}/2 · ${step === 1 ? 'Thông tin cơ bản' : 'Cấu hình scraper'}`} onClose={onClose}
      foot={<>{step === 2 && <Button variant="ghost" onClick={() => setStep(1)} icon="arrowL">Quay lại</Button>}<div className="topbar-spacer"></div><Button variant="ghost" onClick={onClose}>Hủy</Button>{step === 1 ? <Button variant="primary" iconR="arrowR" onClick={() => setStep(2)}>Tiếp tục</Button> : <Button variant="primary" icon="check" onClick={() => { app.toast('Đã thêm source brand mới', 'check'); onClose(); }}>Thêm brand</Button>}</>}>
      {step === 1 ? (
        <div className="col" style={{ gap: 14 }}>
          <div className="grid-2"><Field label="Key (slug)"><input className="input mono" placeholder="vd: gu" /></Field><Field label="Brand-safe name"><input className="input mono" placeholder="G.U" /></Field></div>
          <Field label="Tên tiếng Nhật"><input className="input" placeholder="ジーユー" /></Field>
          <Field label="Tên hiển thị"><input className="input" placeholder="GU" /></Field>
          <Field label="Host patterns" hint="Mỗi dòng 1 host"><textarea className="textarea mono" placeholder={'gu-global.com\ngu.jp'} /></Field>
        </div>
      ) : (
        <div className="col" style={{ gap: 14 }}>
          <Field label="Kiểu scraper"><select className="select"><option>json_api</option><option>html_parse</option><option>manual</option></select></Field>
          <Field label="Config JSON" hint="Để trống nếu kind = manual"><textarea className="textarea mono" style={{ minHeight: 120 }} placeholder={`{\n  "list_selector": ".product-tile",\n  "price_selector": ".price"\n}`} /></Field>
          <div className="grid-2"><Field label="Crawl interval (phút)"><input className="input mono" type="number" defaultValue={1440} /></Field><Field label="Sale page URL (tùy chọn)"><input className="input mono" placeholder="https://…/sale" /></Field></div>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { CalendarScreen, BrandsScreen });
