// Relative "x menit lalu" from an ISO timestamp.
function relTime(v) {
  if (!v) return '';
  const m = Math.round((Date.now() - new Date(v).getTime()) / 60000);
  if (m < 1) return 'baru saja';
  if (m < 60) return `${m} menit lalu`;
  const h = Math.round(m / 60);
  if (h < 24) return `${h} jam lalu`;
  const d = Math.round(h / 24);
  return d === 1 ? 'kemarin' : `${d} hari lalu`;
}

// Dashboard view
function DashboardView({ go, openCandidate }) {
  const { JOBS, CANDIDATES, USER } = window.TalentirData;
  const [dash, setDash] = useState(null);
  useEffect(() => {
    window.TalentirAPI.get('/api/dashboard').then(setDash).catch(err => console.error('Gagal memuat dashboard:', err));
  }, []);

  // Client-side fallbacks for instant first paint; backend values override.
  const newCount = dash ? dash.byStatus.baru : CANDIDATES.filter(c => c.status === 'baru').length;
  // Interview metric combines both new sub-stages so the dashboard tile stays
  // a single "Wawancara" count even though the pipeline column is split.
  const isInterview = (s) => s === 'wawancara-hr' || s === 'wawancara-user';
  const interviewCount = dash
    ? (dash.byStatus['wawancara-hr'] || 0) + (dash.byStatus['wawancara-user'] || 0)
    : CANDIDATES.filter(c => isInterview(c.status)).length;
  const activeJobs = dash ? dash.openJobs : JOBS.filter(j => j.status === 'Buka').length;
  const totalCands = dash ? dash.totalCandidates : CANDIDATES.length;
  const screened = dash ? dash.screenedCount : CANDIDATES.filter(c => c.score > 0).length;
  const topCands = dash?.topCandidates
    ? dash.topCandidates.map(window.TalentirAPI.mapCandidate)
    : [...CANDIDATES].sort((a, b) => b.score - a.score).slice(0, 5);

  const firstName = ((USER && USER.name) || 'Anda').split(' ')[0];
  const hour = new Date().getHours();
  const greet = hour < 11 ? 'Selamat pagi' : hour < 15 ? 'Selamat siang' : hour < 18 ? 'Selamat sore' : 'Selamat malam';

  return (
    <div className="view">
      <div className="view-head">
        <div>
          <div className="title">{greet}, {firstName} 👋</div>
          <div className="subtitle">{newCount} lamaran baru menunggu, {interviewCount} kandidat siap diundang wawancara. AI sudah selesai menyaring semuanya.</div>
        </div>
        <div className="row-flex">
          <Btn icon="download" onClick={() => go({ view: 'import' })}>Import Kandidat</Btn>
          <Btn kind="primary" icon="plus" onClick={() => go({ view: 'jobs', subview: 'new' })}>Posisi Baru</Btn>
        </div>
      </div>

      {/* Stats */}
      <div className="stats">
        <div className="card stat-card">
          <div className="lbl"><Icon name="briefcase" size={12}/>Lowongan Aktif</div>
          <div className="val tnum">{activeJobs}</div>
          <div className="delta">{dash ? dash.closedJobs : (JOBS.length - activeJobs)} ditutup</div>
        </div>
        <div className="card stat-card">
          <div className="lbl"><Icon name="users" size={12}/>Total Pelamar</div>
          <div className="val tnum">{totalCands}</div>
          <div className="delta up"><Icon name="arrow" size={11}/>+{dash ? dash.newThisWeek : '…'} minggu ini</div>
        </div>
        <div className="card stat-card">
          <div className="lbl"><Icon name="sparkles" size={12}/>Auto-screened AI</div>
          <div className="val tnum">{screened}</div>
          <div className="delta">{dash ? dash.screenedPct : 0}% pelamar terproses</div>
        </div>
        <div className="card stat-card">
          <div className="lbl"><Icon name="message" size={12}/>WA Bot Aktif</div>
          <div className="val tnum">{dash ? dash.waBotJobs : '…'}<span style={{ fontSize: 18, color: 'var(--muted)' }}>/{dash ? dash.totalJobs : JOBS.length}</span></div>
          <div className="delta">{dash ? dash.waMsgToday : 0} pesan terkirim hari ini</div>
        </div>
      </div>

      {/* Main grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginTop: 18 }}>
        {/* Top candidates */}
        <div className="card">
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <h3 style={{ margin: 0, fontSize: 14 }}>Kandidat Teratas Minggu Ini</h3>
            <Badge kind="accent"><Icon name="sparkles" size={10}/>Diurutkan AI</Badge>
            <div style={{ flex: 1 }}/>
            <button className="btn ghost sm" onClick={() => go({ view: 'jobs' })}>Lihat semua <Icon name="chevron" size={12}/></button>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: '32%' }}>Kandidat</th>
                <th>Posisi</th>
                <th style={{ width: 110 }}>Sumber</th>
                <th style={{ width: 100 }}>Status</th>
                <th style={{ width: 120 }}>Skor AI</th>
              </tr>
            </thead>
            <tbody>
              {topCands.map(c => {
                const job = JOBS.find(j => j.id === c.jobId);
                return (
                  <tr key={c.id} style={{ cursor: 'pointer' }} onClick={() => openCandidate(c)}>
                    <td>
                      <div className="row-flex">
                        <Avatar name={c.name}/>
                        <div>
                          <div style={{ fontWeight: 700 }}>{c.name}</div>
                          <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{c.location} · {c.experience} exp</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ fontSize: 13 }}>{job?.title || '—'}</td>
                    <td><Source src={c.source}/></td>
                    <td><StatusBadge status={c.status}/></td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className="mono" style={{ fontWeight: 700, fontSize: 13, width: 24 }}>{c.score}</span>
                        <div style={{ flex: 1 }}><ScoreBar value={c.score}/></div>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Activity */}
        <div className="card card-pad">
          <h3 style={{ margin: 0, fontSize: 14 }}>Aktivitas Terbaru</h3>
          <div className="divider"/>
          <div className="feed">
            {!dash && <div style={{ fontSize: 12.5, color: 'var(--muted)', padding: '8px 0' }}>Memuat aktivitas…</div>}
            {dash && dash.activity.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)', padding: '8px 0' }}>Belum ada aktivitas.</div>}
            {dash && dash.activity.map((a, i) => <FeedRow key={i} tone={a.tone} txt={a.text} t={relTime(a.at)}/>)}
          </div>
        </div>
      </div>

      {/* AI insights */}
      <div className="ai-block" style={{ marginTop: 18, padding: 20 }}>
        <div className="lbl"><Icon name="sparkles" size={12}/>AI Insight Mingguan</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 18, marginTop: 6 }}>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>{dash ? dash.highQualityPct : '…'}%</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>kandidat berkualitas tinggi (skor AI ≥ 75) dari {totalCands} total pelamar.</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>{dash ? dash.avgScore : '…'}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>skor AI rata-rata seluruh pelamar yang sudah disaring.</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>{dash ? dash.staleAlerts : '…'} posisi</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>lowongan terbuka belum punya kandidat skor ≥ 75 — saran: longgarkan filter atau tambah sumber.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

const FeedRow = ({ tone, txt, t }) => {
  const color = tone === 'wa' ? 'var(--wa)' :
                tone === 'good' ? 'var(--good)' :
                tone === 'warn' ? 'var(--warn)' :
                tone === 'accent' ? 'var(--accent)' :
                'var(--muted)';
  return (
    <div className="row">
      <div className="dot" style={{ background: color }}/>
      <div className="txt">
        {txt}
        <div className="t">{t}</div>
      </div>
    </div>
  );
};

window.DashboardView = DashboardView;
