// Notification settings panel — lets signed-in users pick their own
// notification channels. Registers as window.SettingsPanel (no-build pattern,
// consistent with login-page.jsx / main.jsx).
const { useState: useSPState, useEffect: useSPEffect } = React;

const CHANNEL_OPTIONS = [
  { label: 'Email', id: 'email' },
  { label: 'Teams notification', id: 'teams-activity' },
  { label: 'Teams message', id: 'teams-chat' },
];

function SettingsPanel({ onClose }) {
  const [channels, setChannels] = useSPState(null); // null = loading
  const [saveState, setSaveState] = useSPState('idle'); // 'idle' | 'saving' | 'saved' | 'error'
  const [errorMsg, setErrorMsg] = useSPState(null);

  useSPEffect(() => {
    fetch('/prefs', { credentials: 'same-origin' })
      .then((r) => r.json())
      .then((data) => setChannels(data.channels ?? []))
      .catch(() => setChannels([]));
  }, []);

  async function toggle(channelId) {
    const next = channels.includes(channelId)
      ? channels.filter((c) => c !== channelId)
      : [...channels, channelId];

    // Optimistic update
    setChannels(next);
    setSaveState('saving');
    setErrorMsg(null);

    try {
      const res = await fetch('/prefs', {
        method: 'PUT',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ channels: next }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `HTTP ${res.status}`);
      }
      setSaveState('saved');
      setTimeout(() => setSaveState('idle'), 2000);
    } catch (e) {
      // Revert optimistic update
      setChannels(channels);
      setSaveState('error');
      setErrorMsg(String(e.message || e));
      setTimeout(() => setSaveState('idle'), 3000);
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="bg-white rounded-2xl border border-neutral-200 shadow-xl w-full max-w-sm mx-4 p-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-lg font-semibold text-neutral-800">Notifications</h2>
          <button
            onClick={onClose}
            className="text-neutral-400 hover:text-neutral-700 transition-colors rounded-lg p-1 hover:bg-neutral-100"
            aria-label="Close settings"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>

        <p className="text-sm text-neutral-500 mb-5">Choose how you want to be notified when tasks reach you.</p>

        {/* Channel toggles */}
        {channels === null ? (
          <p className="text-sm text-neutral-400 py-4 text-center">Loading…</p>
        ) : (
          <div className="space-y-3">
            {CHANNEL_OPTIONS.map(({ label, id }) => {
              const enabled = channels.includes(id);
              return (
                <label key={id} className="flex items-center justify-between cursor-pointer group">
                  <span className="text-sm font-medium text-neutral-700 group-hover:text-neutral-900">{label}</span>
                  <button
                    role="switch"
                    aria-checked={enabled}
                    onClick={() => toggle(id)}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 ${
                      enabled ? 'bg-indigo-600' : 'bg-neutral-200'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                        enabled ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </label>
              );
            })}
          </div>
        )}

        {/* Save status */}
        <div className="mt-5 h-5 flex items-center justify-end">
          {saveState === 'saving' && (
            <span className="text-xs text-neutral-400">Saving…</span>
          )}
          {saveState === 'saved' && (
            <span className="text-xs text-emerald-600 font-medium">Saved ✓</span>
          )}
          {saveState === 'error' && (
            <span className="text-xs text-red-600">{errorMsg || 'Save failed — please try again.'}</span>
          )}
        </div>
      </div>
    </div>
  );
}

window.SettingsPanel = SettingsPanel;
