import { useEffect, useState } from 'react';
import { SettingsApi } from '../api/client.js';

export default function DigestToggle() {
  const [enabled, setEnabled] = useState(null);

  useEffect(() => {
    SettingsApi.getDigest().then((d) => setEnabled(d.enabled)).catch(() => setEnabled(false));
  }, []);

  const toggle = async () => {
    const next = !enabled;
    setEnabled(next);
    try { await SettingsApi.setDigest(next); } catch { setEnabled(!next); }
  };

  if (enabled === null) return null;

  return (
    <button
      className="ghost digest-toggle"
      title={enabled ? 'Weekly digest emails: on' : 'Weekly digest emails: off'}
      onClick={toggle}
    >
      {enabled ? '🔔' : '🔕'}
    </button>
  );
}
