// Alerts — price targets and ex-dividend reminders
// Stored in localStorage as jastocks-alerts
// Delivered via browser Notification API when tab is open

// ── Alert storage helpers ────────────────────────────────────────────────────
window.AlertsStore = (() => {
  const KEY = 'jastocks-alerts';
  function load() {
    try { return JSON.parse(localStorage.getItem(KEY) || '[]'); } catch { return []; }
  }
  function save(alerts) {
    localStorage.setItem(KEY, JSON.stringify(alerts));
    window.dispatchEvent(new Event('jastocks-alerts-changed'));
  }
  function add(alert) {
    const all = load();
    const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    const next = [...all, { ...alert, id, triggered: false, createdAt: new Date().toISOString() }];
    save(next);
    return id;
  }
  function remove(id) { save(load().filter(a => a.id !== id)); }
  function markTriggered(id) {
    save(load().map(a => a.id === id ? { ...a, triggered: true, triggeredAt: new Date().toISOString() } : a));
  }
  function reset(id) {
    save(load().map(a => a.id === id ? { ...a, triggered: false, triggeredAt: null } : a));
  }
  return { load, add, remove, markTriggered, reset };
})();

// ── Request notification permission ─────────────────────────────────────────
window.requestNotifPermission = async () => {
  if (!('Notification' in window)) return 'unsupported';
  if (Notification.permission === 'granted') return 'granted';
  return await Notification.requestPermission();
};

// ── Fire a browser notification ──────────────────────────────────────────────
window.fireNotif = (title, body, tag) => {
  if (Notification.permission !== 'granted') return;
  try { new Notification(title, { body, tag, icon: '/favicon.ico', badge: '/favicon.ico' }); }
  catch (_) {}
};

// ── Check price alerts against a live price update ───────────────────────────
window.checkPriceAlerts = (sym, price) => {
  const alerts = AlertsStore.load().filter(a => a.sym === sym && a.type === 'price' && !a.triggered);
  alerts.forEach(a => {
    const crossed = a.direction === 'above' ? price >= a.targetPrice : price <= a.targetPrice;
    if (crossed) {
      AlertsStore.markTriggered(a.id);
      fireNotif(
        `${sym} price alert`,
        `${sym} is now J$${price.toFixed(2)} — ${a.direction === 'above' ? 'above' : 'below'} your J$${a.targetPrice.toFixed(2)} target`,
        `price-${a.id}`
      );
    }
  });
};

// ── Check ex-dividend alerts on startup ─────────────────────────────────────
window.checkExDivAlerts = () => {
  if (!window.JASTOCKS_DATA) return;
  const today = JASTOCKS_DATA.today;
  const alerts = AlertsStore.load().filter(a => a.type === 'exdate' && !a.triggered);
  alerts.forEach(a => {
    const div = JASTOCKS_DATA.dividends.find(d => d.sym === a.sym && d.exDateStr === a.exDateStr);
    if (!div) return;
    const daysTo = Math.ceil((div.exDate - today) / 86400000);
    if (daysTo >= 0 && daysTo <= (a.daysBefore || 3)) {
      AlertsStore.markTriggered(a.id);
      fireNotif(
        `${a.sym} ex-dividend in ${daysTo === 0 ? 'today!' : daysTo + (daysTo === 1 ? ' day' : ' days')}`,
        `${a.sym} ex-dividend date is ${div.exDateStr} · J$${div.amount.toFixed(4)}/share`,
        `exdate-${a.id}`
      );
    }
  });
};

// ── Alerts page ──────────────────────────────────────────────────────────────
window.AlertsPage = ({ currency, setPage, setSelectedStock }) => {
  const [alerts, setAlerts] = React.useState(() => AlertsStore.load());
  const [sym, setSym] = React.useState('');
  const [type, setType] = React.useState('price');
  const [targetPrice, setTargetPrice] = React.useState('');
  const [direction, setDirection] = React.useState('above');
  const [daysBefore, setDaysBefore] = React.useState('3');
  const [notifPerm, setNotifPerm] = React.useState(
    'Notification' in window ? Notification.permission : 'unsupported'
  );
  const [adding, setAdding] = React.useState(false);
  const [error, setError] = React.useState('');

  // Reload when storage changes
  React.useEffect(() => {
    const handler = () => setAlerts(AlertsStore.load());
    window.addEventListener('jastocks-alerts-changed', handler);
    return () => window.removeEventListener('jastocks-alerts-changed', handler);
  }, []);

  const requestPerm = async () => {
    const result = await requestNotifPermission();
    setNotifPerm(result);
  };

  const addAlert = async () => {
    const symUp = sym.trim().toUpperCase();
    if (!symUp) { setError('Enter a stock symbol'); return; }
    const stock = JASTOCKS_DATA?.bySym?.[symUp];
    if (!stock) { setError(`${symUp} not found`); return; }

    if (type === 'price') {
      const tp = parseFloat(targetPrice);
      if (!tp || tp <= 0) { setError('Enter a valid target price'); return; }
      AlertsStore.add({ sym: symUp, name: stock.name, type: 'price', targetPrice: tp, direction });
    } else {
      // ex-dividend alert — find next upcoming div
      const nextDiv = JASTOCKS_DATA.dividends
        .filter(d => d.sym === symUp && d.exDate >= JASTOCKS_DATA.today)
        .sort((a, b) => a.exDate - b.exDate)[0];
      if (!nextDiv) { setError(`No upcoming dividend found for ${symUp}`); return; }
      AlertsStore.add({ sym: symUp, name: stock.name, type: 'exdate', exDateStr: nextDiv.exDateStr, daysBefore: parseInt(daysBefore) || 3, exDate: nextDiv.exDateStr });
    }

    setSym(''); setTargetPrice(''); setError(''); setAdding(false);
    setAlerts(AlertsStore.load());
    if (notifPerm !== 'granted') await requestPerm();
  };

  const active = alerts.filter(a => !a.triggered);
  const triggered = alerts.filter(a => a.triggered);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Alerts</h1>
          <div className="page-subtitle">Price targets and ex-dividend reminders · Delivered as browser notifications</div>
        </div>
        <button className="btn primary" onClick={() => setAdding(true)}><Icons.Plus/> New alert</button>
      </div>

      {/* Notification permission banner */}
      {notifPerm !== 'granted' && (
        <div style={{
          background: 'var(--accent-3-dim)', border: '1px solid var(--accent-3)',
          borderRadius: 10, padding: '12px 16px', marginBottom: 20,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
        }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--accent-3)' }}>
              {notifPerm === 'unsupported' ? 'Browser notifications not supported' : 'Browser notifications are off'}
            </div>
            <div className="text-3" style={{ fontSize: 12, marginTop: 2 }}>
              {notifPerm === 'denied'
                ? 'Notifications are blocked — enable them in your browser settings to receive alerts'
                : 'Enable notifications so JaStocks can alert you when prices hit your targets'}
            </div>
          </div>
          {notifPerm !== 'denied' && notifPerm !== 'unsupported' && (
            <button className="btn primary" style={{ whiteSpace: 'nowrap' }} onClick={requestPerm}>Enable</button>
          )}
        </div>
      )}

      {/* Add alert form */}
      {adding && (
        <div className="card mb-4" style={{ padding: 20 }}>
          <div style={{ fontWeight: 600, marginBottom: 16 }}>New alert</div>
          <div className="flex gap-3" style={{ flexWrap: 'wrap', alignItems: 'flex-end' }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Symbol</div>
              <input
                value={sym} onChange={e => { setSym(e.target.value); setError(''); }}
                placeholder="e.g. GK"
                style={{ width: 100, padding: '7px 10px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--text)', fontSize: 13, fontFamily: 'Geist Mono, monospace', textTransform: 'uppercase' }}
              />
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Alert type</div>
              <div className="seg">
                <button className={type === 'price' ? 'active' : ''} onClick={() => setType('price')}>Price target</button>
                <button className={type === 'exdate' ? 'active' : ''} onClick={() => setType('exdate')}>Ex-dividend</button>
              </div>
            </div>

            {type === 'price' && <>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Direction</div>
                <div className="seg">
                  <button className={direction === 'above' ? 'active' : ''} onClick={() => setDirection('above')}>Above</button>
                  <button className={direction === 'below' ? 'active' : ''} onClick={() => setDirection('below')}>Below</button>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Target price (J$)</div>
                <input
                  type="number" min="0" step="0.01"
                  value={targetPrice} onChange={e => setTargetPrice(e.target.value)}
                  placeholder="e.g. 85.00"
                  style={{ width: 130, padding: '7px 10px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--text)', fontSize: 13, fontFamily: 'Geist Mono, monospace' }}
                />
              </div>
            </>}

            {type === 'exdate' && (
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Notify me</div>
                <div className="seg">
                  {['1', '3', '5', '7'].map(d => (
                    <button key={d} className={daysBefore === d ? 'active' : ''} onClick={() => setDaysBefore(d)}>{d}d before</button>
                  ))}
                </div>
              </div>
            )}

            <div className="flex gap-2">
              <button className="btn primary" onClick={addAlert}>Add</button>
              <button className="btn ghost" onClick={() => { setAdding(false); setError(''); }}>Cancel</button>
            </div>
          </div>
          {error && <div style={{ color: 'var(--down)', fontSize: 12, marginTop: 10 }}>{error}</div>}
        </div>
      )}

      {/* Active alerts */}
      {active.length === 0 && !adding ? (
        <div className="card" style={{ padding: '60px 24px', textAlign: 'center' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>🔔</div>
          <div style={{ fontWeight: 600, marginBottom: 6 }}>No active alerts</div>
          <div className="text-3" style={{ fontSize: 13, maxWidth: 340, margin: '0 auto 20px' }}>
            Set price targets or ex-dividend reminders. Alerts fire as browser notifications while this tab is open.
          </div>
          <button className="btn primary" onClick={() => setAdding(true)}><Icons.Plus/> Create your first alert</button>
        </div>
      ) : active.length > 0 && (
        <div className="card mb-4">
          <div className="card-header">
            <div className="card-title">Active alerts <span className="hint">{active.length} watching</span></div>
          </div>
          {active.map(a => (
            <AlertRow key={a.id} alert={a} onDelete={() => { AlertsStore.remove(a.id); setAlerts(AlertsStore.load()); }}
              onStock={() => { setSelectedStock(a.sym); setPage('stock'); }} currency={currency}/>
          ))}
        </div>
      )}

      {/* Triggered alerts */}
      {triggered.length > 0 && (
        <div className="card">
          <div className="card-header">
            <div className="card-title">Triggered <span className="hint">{triggered.length} fired</span></div>
            <button className="btn sm ghost" onClick={() => { triggered.forEach(a => AlertsStore.remove(a.id)); setAlerts(AlertsStore.load()); }}>Clear all</button>
          </div>
          {triggered.map(a => (
            <AlertRow key={a.id} alert={a} triggered
              onDelete={() => { AlertsStore.remove(a.id); setAlerts(AlertsStore.load()); }}
              onReset={() => { AlertsStore.reset(a.id); setAlerts(AlertsStore.load()); }}
              onStock={() => { setSelectedStock(a.sym); setPage('stock'); }} currency={currency}/>
          ))}
        </div>
      )}
    </div>
  );
};

function AlertRow({ alert: a, triggered, onDelete, onReset, onStock, currency }) {
  const stock = JASTOCKS_DATA?.bySym?.[a.sym];
  const currentPrice = stock?.price || 0;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '13px 16px',
      borderBottom: '1px solid var(--border)',
      opacity: triggered ? 0.6 : 1,
    }}>
      <SymBadge sym={a.sym} size={34} onClick={onStock} style={{ cursor: 'pointer' }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13 }}>{a.sym}
          {triggered && <span className="tag" style={{ marginLeft: 8, background: 'var(--up-dim)', color: 'var(--up)' }}>Triggered</span>}
        </div>
        <div className="text-3" style={{ fontSize: 11.5, marginTop: 2 }}>
          {a.type === 'price'
            ? `Price ${a.direction} J$${a.targetPrice.toFixed(2)} · Current J$${currentPrice.toFixed(2)}`
            : `Ex-dividend ${a.exDateStr} · ${a.daysBefore}d notice`}
        </div>
        {triggered && a.triggeredAt && (
          <div className="text-3" style={{ fontSize: 11, marginTop: 2 }}>
            Fired {new Date(a.triggeredAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
          </div>
        )}
      </div>
      {/* Progress bar for price alerts */}
      {a.type === 'price' && !triggered && currentPrice > 0 && (() => {
        const refPrice = currentPrice;
        const target = a.targetPrice;
        const pct = a.direction === 'above'
          ? Math.min(100, (refPrice / target) * 100)
          : Math.min(100, (target / refPrice) * 100);
        const remaining = Math.abs(((target - refPrice) / refPrice) * 100).toFixed(1);
        return (
          <div style={{ width: 120, textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>{remaining}% away</div>
            <div style={{ height: 4, background: 'var(--bg-3)', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ width: `${pct}%`, height: '100%', background: 'var(--accent)', borderRadius: 2, transition: 'width 0.4s' }}/>
            </div>
          </div>
        );
      })()}
      <div className="flex gap-2">
        {triggered && onReset && (
          <button className="btn sm ghost" onClick={onReset} title="Reset alert">↺</button>
        )}
        <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={onDelete} title="Remove alert">
          <Icons.X/>
        </button>
      </div>
    </div>
  );
}

// ── Quick "Set alert" modal (used from stock detail page) ────────────────────
window.SetAlertModal = ({ sym, stock, onClose }) => {
  const [type, setType] = React.useState('price');
  const [direction, setDirection] = React.useState('above');
  const [targetPrice, setTargetPrice] = React.useState(stock?.price?.toFixed(2) || '');
  const [daysBefore, setDaysBefore] = React.useState('3');
  const [done, setDone] = React.useState(false);
  const [error, setError] = React.useState('');

  const nextDiv = JASTOCKS_DATA?.dividends
    ?.filter(d => d.sym === sym && d.exDate >= JASTOCKS_DATA.today)
    ?.sort((a, b) => a.exDate - b.exDate)?.[0];

  const save = async () => {
    if (type === 'price') {
      const tp = parseFloat(targetPrice);
      if (!tp || tp <= 0) { setError('Enter a valid price'); return; }
      AlertsStore.add({ sym, name: stock?.name || sym, type: 'price', targetPrice: tp, direction });
    } else {
      if (!nextDiv) { setError('No upcoming dividend found'); return; }
      AlertsStore.add({ sym, name: stock?.name || sym, type: 'exdate', exDateStr: nextDiv.exDateStr, daysBefore: parseInt(daysBefore) || 3 });
    }
    if (Notification.permission !== 'granted') await requestNotifPermission();
    setDone(true);
    setTimeout(onClose, 1200);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 300,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }} onClick={onClose}>
      <div style={{
        background: 'var(--bg-elev)', border: '1px solid var(--border-strong)',
        borderRadius: 14, padding: 24, width: '100%', maxWidth: 400,
        boxShadow: 'var(--shadow)',
      }} onClick={e => e.stopPropagation()}>
        {done ? (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>✓</div>
            <div style={{ fontWeight: 600 }}>Alert set for {sym}</div>
          </div>
        ) : <>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 16 }}>Set alert — {sym}</div>
          <div className="seg" style={{ marginBottom: 16 }}>
            <button className={type === 'price' ? 'active' : ''} onClick={() => setType('price')}>Price target</button>
            <button className={type === 'exdate' ? 'active' : ''} onClick={() => setType('exdate')} disabled={!nextDiv}>
              Ex-dividend{!nextDiv ? ' (none)' : ''}
            </button>
          </div>

          {type === 'price' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="seg">
                <button className={direction === 'above' ? 'active' : ''} onClick={() => setDirection('above')}>Above</button>
                <button className={direction === 'below' ? 'active' : ''} onClick={() => setDirection('below')}>Below</button>
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Target price (J$) · Current: J${stock?.price?.toFixed(2)}</div>
                <input
                  type="number" min="0" step="0.01" value={targetPrice}
                  onChange={e => setTargetPrice(e.target.value)}
                  style={{ width: '100%', padding: '9px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text)', fontSize: 14, fontFamily: 'Geist Mono, monospace' }}
                />
              </div>
            </div>
          )}

          {type === 'exdate' && nextDiv && (
            <div>
              <div style={{ fontSize: 13, marginBottom: 12 }}>
                Next ex-date: <span className="mono" style={{ color: 'var(--accent-2)' }}>{nextDiv.exDateStr}</span>
                {' · '}J${nextDiv.amount.toFixed(4)}/share
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 8 }}>Notify me</div>
              <div className="seg">
                {['1', '3', '5', '7'].map(d => (
                  <button key={d} className={daysBefore === d ? 'active' : ''} onClick={() => setDaysBefore(d)}>{d}d before</button>
                ))}
              </div>
            </div>
          )}

          {error && <div style={{ color: 'var(--down)', fontSize: 12, marginTop: 10 }}>{error}</div>}

          <div className="flex gap-2" style={{ marginTop: 20 }}>
            <button className="btn primary" style={{ flex: 1 }} onClick={save}>Set alert</button>
            <button className="btn ghost" onClick={onClose}>Cancel</button>
          </div>
        </>}
      </div>
    </div>
  );
};
