// ============ Notification Panel ============
const NOTIFS_SEED = [
  { id:'n1', group:'today', sev:'red',   title:'Daily loss alert — Apex Funded', body:"You're at -$420, 84% of max daily ($500)", time:'12m ago' },
  { id:'n2', group:'today', sev:'amber', title:'Challenge progress — FTMO 100k',  body:'You crossed 75% of profit target ($7,500/$10,000)', time:'2h ago' },
  { id:'n3', group:'today', sev:'green', title:'Win streak',                      body:'5 winning trades in a row', time:'3h ago' },
  { id:'n4', group:'yesterday', sev:'blue', title:'Journal reminder',             body:"You didn't write yesterday's reflection", time:'1d ago' },
  { id:'n5', group:'yesterday', sev:'gray', title:'New month',                    body:'April 2026 calendar started', time:'1d ago' },
  { id:'n6', group:'yesterday', sev:'green', title:'Best day this month',         body:'+$1,878 from TSLA short', time:'1d ago' },
  { id:'n7', group:'week', sev:'green', title:'Strategy insight',                 body:'ORB Breakout win rate hit 60% (last 20 trades)', time:'3d ago' },
  { id:'n8', group:'week', sev:'amber', title:'Habit streak',                     body:'7 days of journaling', time:'4d ago' },
  { id:'n9', group:'week', sev:'red',   title:'Rule violation',                   body:'Risk per trade exceeded 1.5% on AMZN long', time:'5d ago' },
  { id:'n10', group:'earlier', sev:'gray', title:'Account created',               body:'Apex Funded account added', time:'12d ago' },
  { id:'n11', group:'earlier', sev:'gray', title:'Welcome',                       body:'Welcome to Edgebook, Sam', time:'90d ago' },
];
const GROUP_LABELS = { today:'Today', yesterday:'Yesterday', week:'This week', earlier:'Earlier' };
const SEV_COLOR = { red:'#ef4444', amber:'#f59e0b', green:'#10b981', blue:'#3b82f6', gray:'#737373' };

const NotificationPanel = ({ onClose, setRoute }) => {
  const { t } = useI18n();
  const [tab, setTab] = useState('all');
  const [readIds, setReadIds] = useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem('edgebook:notif_read') || '["n4","n5","n6","n7","n8","n9","n10","n11"]')); }
    catch { return new Set(); }
  });
  const persist = (s) => { try { localStorage.setItem('edgebook:notif_read', JSON.stringify([...s])); } catch {} };

  const markAllRead = () => { const s = new Set(NOTIFS_SEED.map(n=>n.id)); setReadIds(s); persist(s); };
  const markRead = (id) => { const s = new Set(readIds); s.add(id); setReadIds(s); persist(s); };

  const list = tab === 'unread' ? NOTIFS_SEED.filter(n => !readIds.has(n.id)) : NOTIFS_SEED;
  const unreadCount = NOTIFS_SEED.filter(n => !readIds.has(n.id)).length;

  const byGroup = {};
  list.forEach(n => { (byGroup[n.group] = byGroup[n.group] || []).push(n); });
  const groupOrder = ['today','yesterday','week','earlier'];

  const goToSettings = () => {
    try { localStorage.setItem('edgebook:settings_tab', 'notifications'); } catch {}
    setRoute('settings'); onClose();
  };

  return (
    <div className="notif-panel" onClick={e=>e.stopPropagation()}>
      <div className="notif-head">
        <div style={{fontWeight:600,fontSize:14}}>{t('nav_notifications') || 'Notifications'}</div>
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <span style={{fontSize:12,color:'var(--accent)',cursor:'pointer',fontWeight:500}} onClick={markAllRead}>{t('mark_all_read') || 'Mark all read'}</span>
          <button className="icon-btn" style={{width:26,height:26}} onClick={goToSettings} title="Settings"><Icon name="settings" size={13}/></button>
        </div>
      </div>
      <div className="notif-tabs">
        <div className={'notif-tab ' + (tab==='all'?'on':'')} onClick={()=>setTab('all')}>{t('all') || 'All'}</div>
        <div className={'notif-tab ' + (tab==='unread'?'on':'')} onClick={()=>setTab('unread')}>{t('unread') || 'Unread'} {unreadCount > 0 && <span style={{marginLeft:4,opacity:.7}}>({unreadCount})</span>}</div>
      </div>
      <div className="notif-list">
        {list.length === 0 ? (
          <div className="notif-empty">{t('notif_empty') || "You're all caught up ✨"}</div>
        ) : groupOrder.map(g => byGroup[g] && (
          <div key={g}>
            <div className="notif-group-label">{t('group_'+g) || GROUP_LABELS[g]}</div>
            {byGroup[g].map(n => {
              const unread = !readIds.has(n.id);
              return (
                <div key={n.id} className={'notif-item ' + (unread?'unread':'')} onClick={()=>{ markRead(n.id); }}>
                  <div className="notif-dot" style={{background: SEV_COLOR[n.sev]}}/>
                  <div className="notif-body">
                    <div className="notif-title">{n.title}</div>
                    <div className="notif-sub">{n.body}</div>
                  </div>
                  <div className="notif-time">{n.time}</div>
                </div>
              );
            })}
          </div>
        ))}
      </div>
      <div className="notif-foot" onClick={goToSettings}>{t('notif_settings') || 'Notification settings'}</div>
    </div>
  );
};

window.NotificationPanel = NotificationPanel;
