/* screens-auth-home.jsx — /login and / home dashboard */

function LoginScreen({ onLogin }) {
  const [email, setEmail] = React.useState('linh.tran@boxme.tech');
  const [password, setPassword] = React.useState('••••••••••');
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const { isMobile, vw } = useViewport();
  const stacked = vw < 900;

  function validate() {
    const e = {};
    if (!email) e.email = 'Bắt buộc';
    else if (!/.+@.+\..+/.test(email)) e.email = 'Email không hợp lệ';
    if (!password) e.password = 'Bắt buộc';
    else if (password.length < 6) e.password = 'Tối thiểu 6 ký tự';
    return e;
  }
  function submit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setSubmitting(true);
    setTimeout(() => onLogin({ name: 'Linh Tran', email }), 700);
  }
  const valid = Object.keys(validate()).length === 0;

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bx-page-bg)',
      display: 'grid', gridTemplateColumns: stacked ? '1fr' : '1fr 1fr', overflow: 'auto',
    }}>
      {/* Left: form */}
      <div style={{ display: 'flex', alignItems: stacked ? 'flex-start' : 'center', justifyContent: 'center', padding: stacked ? '32px 20px' : 24, background: '#fff', order: stacked ? 2 : 1 }}>
        <form onSubmit={submit} style={{ width: '100%', maxWidth: 380, display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--bx-primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 16 }}>W</div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--bx-text-heading)' }}>Kế hoạch nhân sự</div>
              <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>v2 · Boxme vận hành nội bộ</div>
            </div>
          </div>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 600, color: 'var(--bx-text-heading)', margin: 0 }}>Đăng nhập</h1>
            <p style={{ fontSize: 13, color: 'var(--bx-text-muted)', marginTop: 6, marginBottom: 0 }}>
              Dùng tài khoản <span style={{ fontFamily: 'var(--bx-font-mono)' }}>@boxme.tech</span>. SSO qua Google Workspace.
            </p>
          </div>

          <Field label="Email công việc" required error={errors.email}>
            <Input icon="mail" value={email} onChange={e => setEmail(e.target.value)} placeholder="ban@boxme.tech" error={errors.email}/>
          </Field>
          <Field label="Mật khẩu" required error={errors.password}>
            <Input icon="lock" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" error={errors.password}/>
          </Field>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: 'var(--bx-text-muted)' }}>
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
              <input type="checkbox" style={{ accentColor: 'var(--bx-primary)' }}/> Giữ đăng nhập (8 giờ)
            </label>
            <a href="#" onClick={e => e.preventDefault()}>Quên mật khẩu</a>
          </div>

          <Button type="submit" variant="primary" disabled={!valid || submitting} size="lg">
            {submitting ? 'Đang đăng nhập…' : 'Đăng nhập'}
          </Button>

          <div style={{ position: 'relative', textAlign: 'center', margin: '4px 0' }}>
            <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 1, background: 'var(--bx-border-muted)' }}></div>
            <span style={{ position: 'relative', background: '#fff', padding: '0 10px', fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>hoặc</span>
          </div>
          <Button type="button" variant="outline" icon="globe" onClick={() => onLogin({ name: 'Linh Tran', email: 'linh.tran@boxme.tech' })}>
            Tiếp tục với Google Workspace
          </Button>
          <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textAlign: 'center' }}>
            Cần cấp quyền? Liên hệ quản lý vận hành theo quốc gia.
          </div>
        </form>
      </div>

      {/* Right: brand panel */}
      <div style={{
        background: 'linear-gradient(180deg, #f7f8ff 0%, #ececec 100%)',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        padding: stacked ? '32px 20px 24px' : 40, position: 'relative',
        order: stacked ? 1 : 2,
        minHeight: stacked ? 'auto' : '100vh',
      }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          {['VN','TH','PH'].map(c => (
            <span key={c} style={{
              fontFamily: 'var(--bx-font-mono)', fontSize: 11, fontWeight: 600,
              padding: '4px 8px', background: '#fff', border: '1px solid var(--bx-border-muted)',
              borderRadius: 9999, color: 'var(--bx-text-body)',
            }}>{c}</span>
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>Phiên bản v2 có gì</div>
          <h2 style={{ fontSize: stacked ? 20 : 28, fontWeight: 600, color: 'var(--bx-text-heading)', margin: 0, lineHeight: 1.2, letterSpacing: '-0.01em' }}>
            Biến dự báo đơn hàng ngày mai thành kế hoạch ca và yêu cầu tuyển dụng rõ ràng.
          </h2>
          <p style={{ fontSize: 13, color: 'var(--bx-text-body)', lineHeight: 1.55, margin: 0, maxWidth: 480 }}>
            5 lớp tính toán chạy thành một luồng rõ ràng. Điều chỉnh ở bước nào cũng được, xem chên lệch và chốt kế hoạch khi đã ưng ý.
          </p>
          <div style={{ display: 'flex', gap: 24, marginTop: 8 }}>
            {[
              { n: '5', l: 'Lớp tính toán' },
              { n: '3', l: 'Quốc gia' },
              { n: '17', l: 'Tham số có lịch sử' },
            ].map(s => (
              <div key={s.l}>
                <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--bx-text-heading)', fontVariantNumeric: 'tabular-nums' }}>{s.n}</div>
                <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>© Boxme Asia · Kế hoạch nhân sự v2 · bản dựng 0.8.1</div>
      </div>
    </div>
  );
}

// ---------- Home ----------
function HomeScreen({ role, warehouseId, country, navigate }) {
  const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId) || WFP.WAREHOUSES[0];
  const k = WFP.HOME_KPIS;
  const trend = WFP.TREND;
  const hiring = WFP.HIRING.filter(h => h.warehouseId === warehouseId);
  const planWarn = WFP.SHIFT_PLAN.warnings.filter(w => w.level === 'CRITICAL' || w.level === 'WARNING').length;
  const open = hiring.filter(h => h.status === 'DRAFT' || h.status === 'APPROVED' || h.status === 'SENT').length;
  const { isMobile, vw } = useViewport();

  // Role-aware tile config
  const tiles = [
    { role: ['PLANNER','OPS','ADMIN','AUDITOR'], comp: (
      <Metric label="Dự báo · ngày mai" value={fmt.int(k.forecastTomorrow)} sublabel="đơn"
        delta="+8,2%" deltaTone="up" hint="Nguồn: ghi đè · chốt 08:01"/>
    )},
    { role: ['PLANNER','OPS','ADMIN','AUDITOR'], comp: (
      <Metric label="Nhân sự cần" value={k.requiredHeadcount} sublabel="người · mọi ca"
        delta={'−' + (k.requiredHeadcount - k.assignedHeadcount) + ' thiếu'} deltaTone="down"
        hint={'đã xếp ' + k.assignedHeadcount}/>
    )},
    { role: ['PLANNER','OPS','ADMIN'], comp: (
      <Metric label="Yêu cầu tuyển đang mở" value={open} sublabel="chờ gửi"
        delta={planWarn ? planWarn + ' cảnh báo' : 'ổn'} deltaTone={planWarn ? 'down' : 'up'}
        hint="Tạo tự động từ kế hoạch 19/05"/>
    )},
    { role: ['OPS','ADMIN','AUDITOR'], comp: (
      <Metric label="Ngân sách OT đã dùng" value={k.otBudgetUsedPct + '%'} sublabel="từ đầu tháng · trần 40h/tháng"
        delta="+12% theo tuần" deltaTone="flat" hint="Luật lao động VN · trần 40h"/>
    )},
  ].filter(t => t.role.includes(role));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <PageHeader
        breadcrumb={['Trang chủ']}
        title={'Chào buổi sáng, ' + (role === 'AUDITOR' ? 'kiểm toán viên' : 'Linh')}
        subtitle={'Ngày mai là ' + fmt.date('2026-05-19') + ' · ' + wh.code + ' · loại ngày ' + WFP.SHIFT_PLAN.dayType}
        actions={
          <>
            {!isMobile && <Button variant="outline" icon="refresh">Chạy lại tính toán</Button>}
            <Button variant="primary" icon="plan" onClick={() => navigate('/planner/shift-plan')}>
              {isMobile ? "Kế hoạch ngày mai" : "Mở kế hoạch ngày mai"}
            </Button>
          </>
        }
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20 }}>
        {/* KPI row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: vw < 560 ? 'repeat(2, 1fr)' : vw < 900 ? 'repeat(2, 1fr)' : 'repeat(' + tiles.length + ', 1fr)',
          gap: isMobile ? 10 : 16,
        }}>
          {tiles.map((t, i) => <React.Fragment key={i}>{t.comp}</React.Fragment>)}
        </div>

        {/* Trend + plan summary */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: vw < 1100 ? '1fr' : '2fr 1fr',
          gap: isMobile ? 12 : 16, marginTop: isMobile ? 12 : 16,
        }}>
          <Card title="Xu hướng đơn 14 ngày" subtitle={'Dự báo so với thực tế · trần năng lực 12.500'}
            actions={
              <Tabs value="14d" onChange={() => {}} tabs={[
                { id: '7d', label: '7N' }, { id: '14d', label: '14N' }, { id: '30d', label: '30N' },
              ]} dense/>
            }>
            <ChartLegend items={[
              { label: 'Dự báo',    color: '#0b43ea' },
              { label: 'Thực tế',   color: '#00af4e' },
              { label: 'Năng lực',  color: '#99a1af', dashed: true },
            ]} style={{ marginBottom: 8 }}/>
            <LineChart data={trend} lines={[
              { key: 'forecast', label: 'Dự báo',   color: '#0b43ea' },
              { key: 'actual',   label: 'Thực tế',  color: '#00af4e' },
              { key: 'capacity', label: 'Năng lực', color: '#99a1af', width: 1.5, dashed: true },
            ]}/>
          </Card>

          <Card title="Tổng quan ngày mai" subtitle={'Kế hoạch ' + WFP.SHIFT_PLAN.id}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <KV label="Trạng thái"   value={<Badge kind={WFP.SHIFT_PLAN.status}>{WFP.SHIFT_PLAN.status}</Badge>}/>
              <KV label="Loại ngày"    value={<Badge kind="WARNING">{WFP.SHIFT_PLAN.dayType}</Badge>}/>
              <KV label="Dự báo"       mono value={fmt.int(WFP.SHIFT_PLAN.forecastQty) + ' đơn'}/>
              <KV label="Nhân sự"      mono value={WFP.SHIFT_PLAN.layer3.netHeadcount + ' thực · đã xếp ' + WFP.SHIFT_PLAN.layer5.assigned.total}/>
              <KV label="OT dự kiến"   mono value={fmt.hrs(WFP.SHIFT_PLAN.layer5.otHours) + ' / ' + fmt.hrs(WFP.SHIFT_PLAN.layer5.otCapHours) + ' trần'}/>
              <KV label="Chi phí"      mono value={fmt.vnd(WFP.SHIFT_PLAN.layer5.cost.laborVND)}/>
              <KV label="Cảnh báo"     value={<span style={{ display: 'inline-flex', gap: 6 }}>
                <Badge kind="CRITICAL" size="sm">1 nghiêm trọng</Badge>
                <Badge kind="WARNING" size="sm">1 cảnh báo</Badge>
                <Badge kind="INFO" size="sm">1 thông tin</Badge>
              </span>}/>
            </div>
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--bx-border-muted)', display: 'flex', gap: 8 }}>
              <Button variant="outline" size="sm" icon="eye" onClick={() => navigate('/planner/shift-plan')}>Mở kế hoạch</Button>
              <Button variant="ghost-primary" size="sm" icon="hiring" onClick={() => navigate('/planner/hiring')}>Xem tuyển dụng</Button>
            </div>
          </Card>
        </div>

        {/* Bottom row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: vw < 1100 ? '1fr' : '1fr 1fr 1fr',
          gap: isMobile ? 12 : 16, marginTop: isMobile ? 12 : 16,
        }}>
          <Card title="Hoạt động gần đây" subtitle="24 giờ qua · toàn hệ thống" padding={0}>
            <div style={{ padding: '4px 0' }}>
              {WFP.ACTIVITY.slice(0, 6).map((a, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 14px',
                  borderTop: i === 0 ? 'none' : '1px solid var(--bx-border-muted)',
                }}>
                  <ActivityDot kind={a.kind}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, color: 'var(--bx-text-dark)', lineHeight: 1.45 }}>{a.what}</div>
                    <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', marginTop: 4 }}>
                      <span style={{ fontFamily: 'var(--bx-font-mono)' }}>{fmt.dateTime(a.ts)}</span>
                      <span style={{ margin: '0 6px' }}>·</span>
                      <span>{a.who}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card title="Tuyển dụng · đang mở" subtitle={open + ' chờ gửi'} padding={0}>
            <Table dense columns={[
              { header: 'Ca',       key: 'shiftCode', mono: true },
              { header: 'Vị trí',   key: 'role', render: r => r.role.toLowerCase() + ' · ' + r.level },
              { header: 'Số lượng', key: 'count', mono: true, align: 'right' },
              { header: 'Trạng thái', render: r => <Badge kind={r.status}>{r.status}</Badge> },
            ]} rows={hiring.slice(0, 5)} getRowKey={r => r.id} emptyText="Không có yêu cầu tuyển dụng"/>
            <div style={{ padding: 12, borderTop: '1px solid var(--bx-border-muted)' }}>
              <Button variant="ghost-primary" size="sm" iconRight="arrowRight" onClick={() => navigate('/planner/hiring')}>Xem tất cả</Button>
            </div>
          </Card>

          <Card title="Cấu hình · cập nhật mới" subtitle="Tham số có phiên bản" padding={0}>
            <Table dense columns={[
              { header: 'Khóa', render: r => <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 11 }}>{r.key.length > 28 ? r.key.slice(0, 26) + '…' : r.key}</span> },
              { header: 'v',   mono: true, align: 'right', render: r => 'v' + r.versions[0].version, priority: 2 },
              { header: 'Bởi', priority: 2, render: r => <span style={{ fontSize: 11.5, color: 'var(--bx-text-muted)' }}>{r.versions[0].updatedBy}</span> },
            ]} rows={WFP.CONFIG_KEYS.slice(0, 5)} getRowKey={r => r.key + '-' + (r.warehouseId || 'g')}/>
            <div style={{ padding: 12, borderTop: '1px solid var(--bx-border-muted)' }}>
              <Button variant="ghost-primary" size="sm" iconRight="arrowRight" onClick={() => navigate('/admin/config')}>Mở kho cấu hình</Button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function KV({ label, value, mono }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, width: 100 }}>{label}</div>
      <div style={{ flex: 1, fontSize: 13, color: 'var(--bx-text-dark)', fontFamily: mono ? 'var(--bx-font-mono)' : 'inherit', fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );
}

function ActivityDot({ kind }) {
  const map = {
    APPROVED:  { bg: '#eef2ff', fg: '#0b43ea', icon: 'check' },
    PROMOTED:  { bg: '#f0fdf4', fg: '#15803d', icon: 'rocket' },
    IMPORTED:  { bg: '#fefce8', fg: '#92400e', icon: 'upload' },
    GENERATED: { bg: '#f5f5f5', fg: '#525252', icon: 'spark' },
    AUTOTUNE:  { bg: '#eff6ff', fg: '#1e40af', icon: 'sliders' },
    EDITED:    { bg: '#f5f5f5', fg: '#525252', icon: 'edit' },
  };
  const c = map[kind] || map.GENERATED;
  return (
    <div style={{ width: 26, height: 26, borderRadius: 8, background: c.bg, color: c.fg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <Icon name={c.icon} size={12}/>
    </div>
  );
}

Object.assign(window, { LoginScreen, HomeScreen, KV, ActivityDot });
