/* home.jsx — Главная: дайджест недели + статистика + быстрые действия. */

function HomeScreen({ user, onNav, onNew, onOpenNote }) {
  const cats = Store.useCategories();
  const [digest, setDigest] = React.useState(null);

  React.useEffect(() => {
    api.getDigest().then(setDigest);
  }, []);

  const hour = new Date().getHours();
  const greet = hour < 5 ? "Доброй ночи" : hour < 12 ? "Доброе утро" : hour < 18 ? "Добрый день" : "Добрый вечер";
  const catLabel = (k) => (cats.find((c) => c.key === k) || { label: k }).label;
  const catColor = (k) => (cats.find((c) => c.key === k) || { color: "gray" }).color;

  return (
    <div>
      <div className="mb-5">
        <h1 className="text-[22px] sm:text-[26px] font-extrabold tracking-tight text-[var(--text)]">
          {greet}, {user.name || "друг"} 👋
        </h1>
        <p className="mt-1 text-[13px] sm:text-sm text-[var(--muted)]">Коротко о том, что происходит в блокноте</p>
      </div>

      {/* ДАЙДЖЕСТ НЕДЕЛИ */}
      <div className="answer-card card-in rounded-2xl p-4 sm:p-5 mb-4">
        <div className="flex items-center gap-2 mb-2 text-[var(--accent)]">
          <Icon name="sparkles" size={17} />
          <span className="text-[12px] font-bold uppercase tracking-wide whitespace-nowrap">Дайджест недели</span>
        </div>
        {!digest ? (
          <div className="space-y-2"><div className="sk h-4 w-3/4 rounded" /><div className="sk h-4 w-1/2 rounded" /></div>
        ) : (
          <>
            <p className="text-[15px] leading-relaxed text-[var(--text)]" style={{ textWrap: "pretty" }}>{digest.headline}</p>
            {Object.keys(digest.by_category).length > 0 && (
              <div className="mt-3.5 space-y-2">
                {Object.entries(digest.by_category).sort((a, b) => b[1] - a[1]).map(([k, v]) => {
                  const max = Math.max(...Object.values(digest.by_category));
                  return (
                    <div key={k} className="flex items-center gap-2.5">
                      <span className="text-[12px] text-[var(--muted)] w-16 shrink-0 truncate">{catLabel(k)}</span>
                      <div className="flex-1 h-2 rounded-full bg-[var(--surface-2)] overflow-hidden">
                        <div className={`h-full rounded-full sw-${catColor(k)}`} style={{ width: `${(v / max) * 100}%` }} />
                      </div>
                      <span className="text-[12px] font-bold text-[var(--text)] w-5 text-right mono">{v}</span>
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </div>

      {/* БЛИЖАЙШИЕ НАПОМИНАНИЯ */}
      {digest && digest.next_reminders && digest.next_reminders.length > 0 && (
        <Block title="Ближайшие напоминания" action={{ label: "Все", onClick: () => onNav("reminders") }}>
          <div className="grid gap-2">
            {digest.next_reminders.map((r) => {
              const f = formatRemind(r.remind_at);
              return (
                <div key={r.id} className="flex items-center gap-3 rounded-xl border border-[var(--border)] bg-[var(--surface)] px-3.5 py-2.5">
                  <span className={`grid place-items-center w-8 h-8 rounded-lg shrink-0 reminder-icon-${f.tone}`}><Icon name="bell" size={15} /></span>
                  <span className="text-[14px] text-[var(--text)] truncate flex-1">{r.text}</span>
                  <span className={`text-[12px] font-semibold reminder-tone-${f.tone} shrink-0`}>{f.text}</span>
                </div>
              );
            })}
          </div>
        </Block>
      )}

      {/* БЫСТРЫЕ ДЕЙСТВИЯ */}
      <Block title="Быстрые действия">
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5">
          <QuickAction icon="plus" label="Новая запись" onClick={onNew} primary />
          <QuickAction icon="sparkles" label="Спросить ИИ" onClick={() => onNav("search")} />
          <QuickAction icon="bell" label="Напоминания" onClick={() => onNav("reminders")} />
          <QuickAction icon="lock" label="Пароли" onClick={() => onNav("passwords")} />
        </div>
      </Block>
    </div>
  );
}

function Block({ title, action, children }) {
  return (
    <section className="mb-5">
      <div className="flex items-center gap-2 mb-2.5">
        <h2 className="text-[13px] font-bold uppercase tracking-wide text-[var(--muted)]">{title}</h2>
        {action && <button onClick={action.onClick} className="ml-auto text-[12px] font-semibold text-[var(--accent)] hover:underline">{action.label}</button>}
      </div>
      {children}
    </section>
  );
}

function QuickAction({ icon, label, onClick, primary }) {
  return (
    <button onClick={onClick}
      className={`flex flex-col items-center justify-center gap-2 rounded-2xl border p-3.5 transition active:scale-95 ${primary ? "bg-[var(--accent)] border-[var(--accent)] text-white" : "bg-[var(--surface)] border-[var(--border)] text-[var(--text)] hover:border-[var(--border-strong)]"}`}>
      <Icon name={icon} size={20} />
      <span className="text-[12px] font-semibold text-center leading-tight">{label}</span>
    </button>
  );
}

Object.assign(window, { HomeScreen });
