/* global React, CR_DATA, CR_UI */
const { useState } = React;
const { Icons, Btn, Tag, EmptyState, SourceChip, formatRelative } = CR_UI;

// =========================================================================
// Queue Screen
// =========================================================================
const TopicCardPending = ({ topic, onApprove, onReject }) => (
  <div className="topic-card">
    <div className="topic-card__header">
      <h3 className="topic-card__title">{topic.title}</h3>
    </div>
    <p className="topic-card__summary">{topic.summary}</p>
    <div className="topic-card__sources">
      <Icons.Link size={14} style={{ color: "var(--fg-muted)" }} />
      {topic.sources.slice(0, 3).map((s) => <SourceChip key={s} domain={s} />)}
      {topic.sources.length > 3 && <span style={{ color: "var(--fg-muted)" }}>+{topic.sources.length - 3}</span>}
    </div>
    <div className="topic-card__meta">
      {topic.keywords.map((k) => <span key={k} className="tag tag--keyword">{k}</span>)}
      <span className="topic-card__meta-sep">·</span>
      <span>{formatRelative(topic.found_at)}</span>
    </div>
    <div className="topic-card__actions">
      <Btn kind="approve" icon={<Icons.Check size={14} />} onClick={() => onApprove(topic)}>Одобрить</Btn>
      <div className="spacer" />
      <Btn kind="reject" icon={<Icons.X size={14} />} onClick={() => onReject(topic)}>Отклонить</Btn>
    </div>
  </div>
);

const TopicCardApproved = ({ topic, onOpen }) => (
  <div className="topic-card topic-card--approved">
    <div className="topic-card__header">
      <h3 className="topic-card__title">{topic.title}</h3>
      <Tag tone="approved" icon={<Icons.Check size={11} />}>Одобрено</Tag>
    </div>
    <p className="topic-card__summary">{topic.summary}</p>
    <div className="topic-card__sources">
      <Icons.Link size={14} style={{ color: "var(--fg-muted)" }} />
      {topic.sources.slice(0, 3).map((s) => <SourceChip key={s} domain={s} />)}
    </div>
    <div className="topic-card__meta">
      {topic.keywords.slice(0, 3).map((k) => <span key={k} className="tag tag--keyword">{k}</span>)}
      <span className="topic-card__meta-sep">·</span>
      <span>одобрено {formatRelative(topic.found_at)}</span>
    </div>
    <div className="topic-card__actions">
      <div className="spacer" />
      <Btn kind="ghost" icon={<Icons.ChevronRight size={14} />} onClick={() => onOpen(topic)}>Открыть в Статьях</Btn>
    </div>
  </div>
);

const TopicCardRejected = ({ topic, onRestore }) => (
  <div className="topic-card topic-card--rejected">
    <div className="topic-card__header">
      <h3 className="topic-card__title" style={{ color: "var(--fg-secondary)" }}>{topic.title}</h3>
      <Tag tone="rejected" icon={<Icons.X size={11} />}>Отклонено</Tag>
    </div>
    <p className="topic-card__summary">{topic.summary}</p>
    {topic.reason && (
      <div className="topic-card__reject-block">
        <div style={{ flex: "none", marginTop: 1 }}><Icons.Info size={14} /></div>
        <div className="topic-card__reject-quote">«{topic.reason}»</div>
      </div>
    )}
    <div className="topic-card__meta">
      <span>отклонено {formatRelative(topic.rejected_at)}</span>
    </div>
    <div className="topic-card__actions">
      <div className="spacer" />
      <Btn kind="ghost" icon={<Icons.Refresh size={14} />} onClick={() => onRestore(topic)}>Восстановить</Btn>
    </div>
  </div>
);

const SkeletonCard = () => (
  <div className="topic-card skel-card">
    <div className="skel skel-line" style={{ width: "70%", height: 18 }} />
    <div className="skel skel-line" style={{ width: "100%" }} />
    <div className="skel skel-line" style={{ width: "92%" }} />
    <div className="skel skel-line" style={{ width: "60%" }} />
    <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
      <div className="skel" style={{ width: 96, height: 30 }} />
      <div className="skel" style={{ width: 96, height: 30, marginLeft: "auto" }} />
    </div>
  </div>
);

const QueueScreen = ({ state, onOpenJobLog, onApprove, onReject, onRestore, onOpenArticle, onFindNew, onRefresh, topicsOverride, brand, runningJobKind, runningJobElapsed }) => {
  const [tab, setTab] = useState("pending");

  // Real data from backend only — no CR_DATA fallback. An empty backend
  // state is shown as an honest empty state, not as design-preview mocks.
  const data = topicsOverride || { pending: [], approved: [], rejected: [] };
  const { pending, approved, rejected } = data;

  return (
    <div className="screen">
      <div className="screen__header">
        <div className="screen__header-row">
          <div style={{ flex: 1 }}>
            <div className="section-label" style={{ marginBottom: 6 }}>Триаж · {brand || "—"}</div>
            <h1 className="screen__title">
              Очередь — Новые
              <span className="screen__title-count">{pending.length}</span>
            </h1>
            <div className="screen__subtitle">
              Одобрить → запустится ресерч. Отклонить → причина сохраняется в истории.
              {" · "}
              <span className="kbd">A</span> одобрить {" "}
              <span className="kbd">R</span> отклонить {" "}
              <span className="kbd">→</span> следующая
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", paddingTop: 8 }}>
            <Btn kind="secondary" size="sm" icon={<Icons.Refresh size={13} />} onClick={onRefresh}>Обновить</Btn>
            <Btn kind="primary" icon={<Icons.Plus size={14} />} onClick={onFindNew} disabled={!brand || state === "loading"}>
              {state === "loading" ? "Ищу…" : "Найти новые темы"}
            </Btn>
          </div>
        </div>
        <div className="tabs">
          <button className={"tab " + (tab === "pending" ? "is-active" : "")} onClick={() => setTab("pending")}>
            Новые <span className="tab__count">{pending.length}</span>
          </button>
          <button className={"tab " + (tab === "approved" ? "is-active" : "")} onClick={() => setTab("approved")}>
            Одобренные <span className="tab__count">{approved.length}</span>
          </button>
          <button className={"tab " + (tab === "rejected" ? "is-active" : "")} onClick={() => setTab("rejected")}>
            Отклонённые <span className="tab__count">{rejected.length}</span>
          </button>
          <div style={{ flex: 1 }} />
        </div>
      </div>

      <div className="queue-body">
        {state === "loading" && runningJobKind === "find_topics" && (
          <div className="job-banner">
            <Icons.Spinner size={16} />
            <span style={{ fontWeight: 500 }}>Поиск новых тем</span>
            {runningJobElapsed != null && (
              <span style={{ opacity: 0.7 }}>{Math.floor(runningJobElapsed / 60)}:{String(runningJobElapsed % 60).padStart(2, "0")}</span>
            )}
            <div className="job-banner__progress"><div className="job-banner__progress-bar" style={{ width: "30%" }} /></div>
            <span className="job-banner__link" onClick={onOpenJobLog}>Журнал →</span>
          </div>
        )}

        {state === "error" && (
          <div className="error-banner">
            <Icons.AlertTriangle size={18} />
            <div style={{ flex: 1 }}>
              <div className="error-banner__title">Поиск не удался</div>
              <div className="error-banner__body">
                Последний job find_topics завершился с ошибкой. Откройте журнал — там стек/лог.
              </div>
            </div>
            <Btn kind="secondary" size="sm" icon={<Icons.Refresh size={13} />} onClick={onFindNew}>Повторить</Btn>
            <Btn kind="ghost" size="sm" onClick={onOpenJobLog}>Журнал →</Btn>
          </div>
        )}

        {tab === "pending" && pending.length === 0 && state !== "loading" && (
          <EmptyState
            icon={<Icons.Inbox size={26} />}
            title="Очередь пуста"
            body={<>Нажмите <strong>Найти новые темы</strong>, чтобы Claude собрал свежие новости по конфигу бренда. Если бренд только создан — сначала прогоните «Прочитать 100 постов» в Настройках.</>}
            actions={<Btn kind="primary" icon={<Icons.Plus size={14} />} onClick={onFindNew} disabled={!brand}>Найти новые темы</Btn>}
          />
        )}

        {tab === "pending" && pending.length > 0 && state === "loading" && (
          <div className="queue-list">
            {pending.map((t) => <TopicCardPending key={t.id} topic={t} onApprove={onApprove} onReject={onReject} />)}
            <SkeletonCard />
          </div>
        )}

        {tab === "pending" && pending.length > 0 && state !== "loading" && (
          <div className="queue-list">
            {pending.map((t) => <TopicCardPending key={t.id} topic={t} onApprove={onApprove} onReject={onReject} />)}
          </div>
        )}

        {tab === "approved" && (
          approved.length === 0 ? (
            <EmptyState
              icon={<Icons.Doc size={26} />}
              title="Нет одобренных тем"
              body="Одобрите тему во вкладке «Новые» — она автоматически появится здесь и попадёт в Статьи."
            />
          ) : (
            <div className="queue-list">
              {approved.map((t) => <TopicCardApproved key={t.id} topic={t} onOpen={onOpenArticle} />)}
            </div>
          )
        )}

        {tab === "rejected" && (
          rejected.length === 0 ? (
            <EmptyState
              icon={<Icons.X size={26} />}
              title="Нет отклонённых тем"
              body="Отклонённые темы хранятся здесь — на случай, если решите вернуть тему обратно в очередь."
            />
          ) : (
            <div className="queue-list">
              {rejected.map((t) => <TopicCardRejected key={t.id} topic={t} onRestore={onRestore} />)}
            </div>
          )
        )}
      </div>
    </div>
  );
};

window.CR_QUEUE = { QueueScreen };
