// Notification System — 3-tier alternative to backend email
// Tier 1: In-app notification center (always works)
// Tier 2: Browser Notification API (free, requires permission)
// Tier 3: LINE Notify / Discord Webhook (free, user configures URL in settings)

window.NotificationManager = (function () {
  const STORAGE_KEY = 'syk-notifications';
  const SETTINGS_KEY = 'syk-notif-settings';
  const MAX_KEEP = 50;
  const listeners = new Set();

  function load() {
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); } catch { return []; }
  }
  function save(list) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(list.slice(0, MAX_KEEP)));
    listeners.forEach(fn => { try { fn(list); } catch {} });
  }
  function settings() {
    try { return JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); } catch { return {}; }
  }
  function saveSettings(s) {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
  }

  return {
    // Add notification: { severity, title, body, link, category }
    push(notif) {
      const list = load();
      const item = {
        id: 'n_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7),
        ts: new Date().toISOString(),
        read: false,
        severity: 'info',
        ...notif,
      };
      list.unshift(item);
      save(list);

      // Tier 2: Browser Notification (if permitted)
      const s = settings();
      if (s.browser_enabled && typeof Notification !== 'undefined' && Notification.permission === 'granted') {
        try {
          new Notification('SYK: ' + (notif.title || ''), {
            body: notif.body || '',
            icon: '/favicon.ico',
            tag: notif.category || 'syk',
          });
        } catch {}
      }

      // Tier 3: LINE Notify / Discord Webhook (fire-and-forget)
      if (s.webhook_url) {
        this._sendWebhook(s.webhook_url, item).catch(() => {});
      }

      return item;
    },

    async _sendWebhook(url, item) {
      const text = `[${item.severity.toUpperCase()}] ${item.title}\n${item.body || ''}`;
      // LINE Notify pattern
      if (url.includes('notify-api.line.me')) {
        // Note: LINE Notify uses token, would normally need OAuth — most users set this server-side
        // For client-side: use generic webhook (Discord/Slack) instead
        return;
      }
      // Generic webhook (Discord-compatible: { content: "..." })
      try {
        await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ content: text, text }), // works for both Discord & Slack
        });
      } catch {}
    },

    list() { return load(); },
    unreadCount() { return load().filter(n => !n.read).length; },

    markRead(id) {
      const list = load().map(n => n.id === id ? { ...n, read: true } : n);
      save(list);
    },
    markAllRead() {
      const list = load().map(n => ({ ...n, read: true }));
      save(list);
    },
    remove(id) {
      const list = load().filter(n => n.id !== id);
      save(list);
    },
    clear() {
      save([]);
    },

    subscribe(fn) {
      listeners.add(fn);
      return () => listeners.delete(fn);
    },

    settings,
    saveSettings,

    // Request browser notification permission
    async requestBrowserPermission() {
      if (typeof Notification === 'undefined') return false;
      if (Notification.permission === 'granted') return true;
      if (Notification.permission === 'denied') return false;
      const result = await Notification.requestPermission();
      return result === 'granted';
    },

    // Convenience trigger from EVM/Risk events
    autoCheck(metrics, projectName) {
      if (!metrics) return;
      const { spi = 1, cpi = 1 } = metrics;
      if (spi < 0.85) {
        this.push({
          severity: 'critical', category: 'progress',
          title: `🔴 ${projectName}: SPI ${spi.toFixed(2)} — ล่าช้าวิกฤต`,
          body: 'โครงการช้ากว่าแผนมาก ควรจัดประชุม Recovery Plan'
        });
      }
      if (cpi < 0.85) {
        this.push({
          severity: 'critical', category: 'cost',
          title: `🔴 ${projectName}: CPI ${cpi.toFixed(2)} — ใช้งบเกิน`,
          body: 'ต้องทบทวน Cost Codes ที่ใช้เกินทันที'
        });
      }
    },
  };
})();

// ─── Notification Center Component (bell dropdown) ──────────
window.NotificationCenter = function NotificationCenter({ lang }) {
  const [open, setOpen] = React.useState(false);
  const [items, setItems] = React.useState(() => window.NotificationManager.list());
  const [tab, setTab] = React.useState('inbox'); // inbox | settings

  React.useEffect(() => {
    const unsub = window.NotificationManager.subscribe(setItems);
    return unsub;
  }, []);

  const unread = items.filter(n => !n.read).length;

  return (
    <div style={{ position: 'relative' }}>
      <button className="btn btn-sm btn-ghost" onClick={() => setOpen(!open)} title={lang === 'th' ? 'การแจ้งเตือน' : 'Notifications'}
        style={{ position: 'relative', padding: '6px 8px' }}>
        <I.bell />
        {unread > 0 && (
          <span style={{
            position: 'absolute', top: 2, right: 2,
            minWidth: 16, height: 16, padding: '0 4px', borderRadius: 8,
            background: 'var(--rose)', color: 'white', fontSize: 9, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{unread > 9 ? '9+' : unread}</span>
        )}
      </button>

      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 998 }} />
          <div className="card" style={{
            position: 'absolute', top: '110%', right: 0, zIndex: 999,
            width: 380, maxHeight: 500, overflow: 'hidden', padding: 0,
            display: 'flex', flexDirection: 'column',
            boxShadow: '0 20px 60px -10px rgba(0,0,0,0.5)',
          }}>
            {/* Header */}
            <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <strong style={{ flex: 1, fontSize: 14 }}>{lang === 'th' ? 'การแจ้งเตือน' : 'Notifications'}</strong>
              {tab === 'inbox' && items.length > 0 && (
                <>
                  <button className="btn btn-sm btn-ghost" onClick={() => window.NotificationManager.markAllRead()} style={{ fontSize: 11 }}>
                    {lang === 'th' ? 'อ่านทั้งหมด' : 'Mark all'}
                  </button>
                  <button className="btn btn-sm btn-ghost" onClick={() => { if (confirm(lang === 'th' ? 'ล้างทั้งหมด?' : 'Clear all?')) window.NotificationManager.clear(); }} style={{ fontSize: 11, color: 'var(--rose)' }}>
                    <I.trash />
                  </button>
                </>
              )}
            </div>

            {/* Tabs */}
            <div style={{ display: 'flex', borderBottom: '1px solid var(--line)' }}>
              {[
                { id: 'inbox', label: lang === 'th' ? `📥 กล่องข้อความ (${items.length})` : `📥 Inbox (${items.length})` },
                { id: 'settings', label: lang === 'th' ? '⚙️ ตั้งค่า' : '⚙️ Settings' },
              ].map(t => (
                <button key={t.id} onClick={() => setTab(t.id)}
                  style={{
                    flex: 1, padding: '8px 12px', fontSize: 12, fontWeight: 500,
                    background: tab === t.id ? 'var(--glass-2)' : 'transparent',
                    color: tab === t.id ? 'var(--ink)' : 'var(--ink-soft)',
                    border: 0, borderBottom: tab === t.id ? '2px solid var(--syk-blue-soft)' : '2px solid transparent',
                    cursor: 'pointer', transition: '.15s',
                  }}>{t.label}</button>
              ))}
            </div>

            {/* Content */}
            <div style={{ flex: 1, overflowY: 'auto' }}>
              {tab === 'inbox' && (
                items.length === 0 ? (
                  <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>
                    <div style={{ fontSize: 32, marginBottom: 8 }}>📭</div>
                    <div style={{ fontSize: 12 }}>{lang === 'th' ? 'ยังไม่มีการแจ้งเตือน' : 'No notifications'}</div>
                  </div>
                ) : (
                  items.map(n => (
                    <div key={n.id} onClick={() => window.NotificationManager.markRead(n.id)}
                      style={{
                        padding: '10px 14px', borderBottom: '1px solid var(--line)',
                        background: n.read ? 'transparent' : 'rgba(40,72,255,0.05)',
                        cursor: 'pointer', position: 'relative',
                      }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 4 }}>
                        <strong style={{ fontSize: 12.5, color: severityColor(n.severity), flex: 1 }}>{n.title}</strong>
                        <button onClick={(e) => { e.stopPropagation(); window.NotificationManager.remove(n.id); }}
                          style={{ background: 'transparent', border: 0, color: 'var(--ink-mute)', cursor: 'pointer', fontSize: 14, padding: 0, marginLeft: 6 }}>×</button>
                      </div>
                      {n.body && <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', lineHeight: 1.4 }}>{n.body}</div>}
                      <div style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 4 }}>{relTime(n.ts, lang)}</div>
                    </div>
                  ))
                )
              )}

              {tab === 'settings' && <NotifSettings lang={lang} />}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

function NotifSettings({ lang }) {
  const [settings, setSettings] = React.useState(() => window.NotificationManager.settings());
  const [browserStatus, setBrowserStatus] = React.useState(typeof Notification !== 'undefined' ? Notification.permission : 'unsupported');
  const [testing, setTesting] = React.useState(false);

  const save = (patch) => {
    const next = { ...settings, ...patch };
    setSettings(next);
    window.NotificationManager.saveSettings(next);
  };

  const enableBrowser = async () => {
    const ok = await window.NotificationManager.requestBrowserPermission();
    setBrowserStatus(typeof Notification !== 'undefined' ? Notification.permission : 'unsupported');
    save({ browser_enabled: ok });
  };

  const sendTest = () => {
    setTesting(true);
    window.NotificationManager.push({
      severity: 'info', category: 'test',
      title: '🧪 ' + (lang === 'th' ? 'ทดสอบการแจ้งเตือน' : 'Test notification'),
      body: lang === 'th' ? 'ระบบทำงานได้ปกติ' : 'System working',
    });
    setTimeout(() => setTesting(false), 1200);
  };

  return (
    <div style={{ padding: 14 }}>
      {/* Browser */}
      <div style={{ padding: 12, background: 'var(--glass-2)', borderRadius: 10, marginBottom: 10 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <strong style={{ fontSize: 12 }}>🌐 {lang === 'th' ? 'แจ้งเตือนบนเบราว์เซอร์' : 'Browser Notification'}</strong>
          {browserStatus === 'granted' ? <span className="chip success">{lang === 'th' ? 'อนุญาตแล้ว' : 'Granted'}</span>
            : browserStatus === 'denied' ? <span className="chip danger">{lang === 'th' ? 'ปฏิเสธ' : 'Denied'}</span>
            : browserStatus === 'unsupported' ? <span className="chip">N/A</span>
            : <button className="btn btn-sm btn-primary" onClick={enableBrowser}>{lang === 'th' ? 'เปิดใช้งาน' : 'Enable'}</button>}
        </div>
        <div className="micro">{lang === 'th' ? 'แสดงแจ้งเตือนบนเดสก์ท็อปแม้จะไม่ได้เปิดเบราว์เซอร์' : 'Show desktop notifications even when browser is minimized'}</div>
        {browserStatus === 'granted' && (
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, fontSize: 11.5, cursor: 'pointer' }}>
            <input type="checkbox" checked={!!settings.browser_enabled} onChange={(e) => save({ browser_enabled: e.target.checked })} />
            {lang === 'th' ? 'เปิดใช้งานแจ้งเตือน' : 'Enable notifications'}
          </label>
        )}
      </div>

      {/* Webhook */}
      <div style={{ padding: 12, background: 'var(--glass-2)', borderRadius: 10, marginBottom: 10 }}>
        <strong style={{ fontSize: 12 }}>🔗 {lang === 'th' ? 'Webhook (Discord/Slack)' : 'Webhook (Discord/Slack)'}</strong>
        <div className="micro" style={{ marginTop: 4, marginBottom: 8 }}>
          {lang === 'th' ? 'แทนอีเมล: ใช้ Discord/Slack Webhook (ฟรี ไม่ต้อง backend)' : 'Replaces email: Use Discord/Slack Webhook (free, no backend needed)'}
        </div>
        <input type="text" placeholder="https://discord.com/api/webhooks/..."
          value={settings.webhook_url || ''} onChange={(e) => save({ webhook_url: e.target.value })}
          style={{ width: '100%', padding: '8px 10px', background: 'var(--glass-3)', border: '1px solid var(--line)', borderRadius: 6, color: 'var(--ink)', fontSize: 11.5, fontFamily: 'var(--font-mono)' }} />
        <details style={{ marginTop: 6 }}>
          <summary style={{ fontSize: 11, color: 'var(--syk-blue-soft)', cursor: 'pointer' }}>{lang === 'th' ? '📖 วิธีสร้าง webhook' : '📖 How to create webhook'}</summary>
          <ol style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 6, paddingLeft: 20, lineHeight: 1.6 }}>
            <li><strong>Discord:</strong> {lang === 'th' ? 'Server Settings → Integrations → Webhooks → New' : 'Server Settings → Integrations → Webhooks → New'}</li>
            <li><strong>Slack:</strong> api.slack.com/messaging/webhooks</li>
            <li>{lang === 'th' ? 'คัดลอก URL มาวางที่ช่องด้านบน' : 'Copy URL and paste above'}</li>
          </ol>
        </details>
      </div>

      <button className="btn btn-sm" style={{ width: '100%', justifyContent: 'center' }} onClick={sendTest} disabled={testing}>
        {testing ? '✓ ' + (lang === 'th' ? 'ส่งแล้ว' : 'Sent') : '🧪 ' + (lang === 'th' ? 'ส่งทดสอบ' : 'Send test')}
      </button>

      <div style={{ marginTop: 10, padding: 8, background: 'rgba(74,222,128,0.06)', borderRadius: 8, fontSize: 10.5, color: 'var(--emerald)' }}>
        💡 {lang === 'th'
          ? 'ทำไมไม่ใช้อีเมล? — Email service ต้องตั้ง SendGrid/Mailgun ($$$) Webhook ฟรีและส่งเร็วกว่า'
          : 'Why not email? — Email needs SendGrid/Mailgun ($$$); Webhook is free + faster'}
      </div>
    </div>
  );
}

function severityColor(sev) {
  switch (sev) {
    case 'critical': return 'var(--rose)';
    case 'warning': return 'var(--amber)';
    case 'success': return 'var(--emerald)';
    default: return 'var(--ink)';
  }
}

function relTime(iso, lang) {
  const diff = (Date.now() - new Date(iso).getTime()) / 1000;
  if (diff < 60) return lang === 'th' ? 'เมื่อสักครู่' : 'just now';
  if (diff < 3600) return Math.floor(diff / 60) + (lang === 'th' ? ' นาทีที่แล้ว' : 'm ago');
  if (diff < 86400) return Math.floor(diff / 3600) + (lang === 'th' ? ' ชั่วโมงที่แล้ว' : 'h ago');
  return Math.floor(diff / 86400) + (lang === 'th' ? ' วันที่แล้ว' : 'd ago');
}
