// §3.17 HR daily inbox — one-screen surface of what HR should act on today.
// Pulls /api/inbox every 30s. Each section is collapsible-conceptually but we
// just stack them top-to-bottom with the most-actionable bucket first.

function InboxView({ openCandidate, go, candidates }) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  const load = React.useCallback(async () => {
    try {
      const r = await window.TalentirAPI.get('/api/inbox');
      setData(r); setError(null);
    } catch (e) { setError(e?.message || 'Gagal memuat inbox.'); }
    setLoading(false);
  }, []);

  React.useEffect(() => {
    load();
    const iv = setInterval(load, 30_000);
    return () => clearInterval(iv);
  }, [load]);

  if (loading && !data) {
    return <div className="empty" style={{ padding: 40 }}>Memuat inbox…</div>;
  }
  if (error) {
    return (
      <div className="empty" style={{ padding: 40 }}>
        <Icon name="x" size={28}/>
        <div style={{ fontWeight: 700, marginTop: 10 }}>Gagal memuat</div>
        <div style={{ fontSize: 13 }}>{error}</div>
        <Btn size="sm" onClick={load} style={{ marginTop: 12 }}>Coba lagi</Btn>
      </div>
    );
  }

  const totalActionable = (data?.counts?.actionable ?? 0);
  const totalAll =
    (data?.counts?.needsResponse ?? 0) +
    (data?.counts?.todayInterviews ?? 0) +
    (data?.counts?.staleInterviews ?? 0) +
    (data?.counts?.newCandidates ?? 0);

  // Fully empty inbox = quietest possible "all clear" — recruiter can move on.
  if (totalAll === 0) {
    return (
      <div className="empty" style={{ padding: '60px 20px', textAlign: 'center' }}>
        <Icon name="check" size={32}/>
        <div style={{ fontWeight: 700, marginTop: 12, fontSize: 16 }}>Semua beres untuk hari ini ✨</div>
        <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
          Tidak ada kandidat butuh respon, interview hari ini, atau lamaran baru dalam 24 jam terakhir.
        </div>
        <Btn size="sm" onClick={() => go({ view: 'jobs' })} icon="briefcase" style={{ marginTop: 20 }}>
          Buka Lowongan
        </Btn>
      </div>
    );
  }

  const onItemClick = (item) => {
    if (item.action.kind === 'open-chat' || item.action.kind === 'open-candidate') {
      const cand = candidates.find((c) => c.id === item.candidateId);
      if (cand) openCandidate(cand);
    } else if (item.action.kind === 'open-interview') {
      const cand = candidates.find((c) => c.id === item.candidateId);
      if (cand) openCandidate(cand);
      // (Calendar tab in drawer would be ideal; until §3.15 ships, drawer is OK)
    }
  };

  return (
    <div className="col-flex" style={{ gap: 18, padding: '4px 0 30px' }}>
      <div className="row-flex" style={{ gap: 10, alignItems: 'baseline' }}>
        <h2 style={{ fontSize: 22, letterSpacing: '-0.02em', margin: 0 }}>Inbox HR</h2>
        <span style={{ fontSize: 13, color: 'var(--muted)' }}>
          {totalActionable > 0 ? `${totalActionable} hal butuh perhatian sekarang` : 'Tidak ada yang mendesak'}
        </span>
        <div style={{ flex: 1 }}/>
        <Btn size="sm" onClick={load} icon="refresh">Refresh</Btn>
      </div>

      <InboxSection
        title="Butuh respon"
        kind="danger"
        hint="Bot sudah menyerah dan menunggu HR ambil alih chat."
        items={data.needsResponse}
        onItemClick={onItemClick}
        ctaLabel="Ambil alih chat"
      />

      <InboxSection
        title="Wawancara hari ini"
        kind="accent"
        hint="Pastikan link meeting siap dan kandidat sudah konfirmasi."
        items={data.todayInterviews}
        onItemClick={onItemClick}
        ctaLabel="Buka kandidat"
      />

      <InboxSection
        title="Sudah lama tidak di-follow-up"
        kind="warn"
        hint="Kandidat di stage Wawancara HR/User tanpa kontak >3 hari. Kirim pesan reminder atau pindah stage."
        items={data.staleInterviews}
        onItemClick={onItemClick}
        ctaLabel="Lihat kandidat"
      />

      <InboxSection
        title="Lamaran baru (24 jam)"
        kind=""
        hint="Urut dari skor AI tertinggi — biasa-nya mereka yang paling layak diundang."
        items={data.newCandidates}
        onItemClick={onItemClick}
        ctaLabel="Buka profil"
      />
    </div>
  );
}

function InboxSection({ title, kind, hint, items, onItemClick, ctaLabel }) {
  if (!items || items.length === 0) return null;
  const accent =
    kind === 'danger' ? 'oklch(0.55 0.18 25)'
    : kind === 'accent' ? 'var(--accent, #3a6df0)'
    : kind === 'warn' ? 'oklch(0.72 0.14 75)'
    : 'var(--ink-2, #475569)';
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div className="row-flex" style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', gap: 10 }}>
        <span style={{ width: 8, height: 8, borderRadius: 99, background: accent, flexShrink: 0 }}/>
        <strong style={{ fontSize: 13.5 }}>{title}</strong>
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)', background: 'var(--surface)', border: '1px solid var(--border)', padding: '1px 7px', borderRadius: 99 }}>{items.length}</span>
        <span style={{ flex: 1 }}/>
        <span style={{ fontSize: 11.5, color: 'var(--muted)', textAlign: 'right', maxWidth: '50%' }}>{hint}</span>
      </div>
      <div className="col-flex" style={{ gap: 0 }}>
        {items.map((it) => (
          <div key={it.id} className="row-flex"
               onClick={() => onItemClick(it)}
               style={{ gap: 12, padding: '10px 16px', cursor: 'pointer', borderBottom: '1px solid var(--border)', alignItems: 'center' }}>
            <Avatar name={it.title} size="sm"/>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {it.jobTitle ? <>{it.jobTitle} · </> : null}
                {it.subtitle}
              </div>
            </div>
            {it.hrName && <span style={{ fontSize: 11, color: 'var(--muted)' }}>{it.hrName.split(' ')[0]}</span>}
            <Btn size="sm" icon="arrow">{ctaLabel}</Btn>
          </div>
        ))}
      </div>
    </div>
  );
}

window.InboxView = InboxView;
