// ============ Settings page ============

const HABIT_LABELS = ['Pre-market plan','Post-session review','Screenshot every trade','Journal emotion','Read playbook','Max 5 trades/day'];

const ProfileHabits = () => {
  const { t } = useI18n();
  const [sel, setSel] = useState(() => {
    try { return JSON.parse(localStorage.getItem('edgebook:habits') || 'null') || HABIT_LABELS.slice(0,4); } catch { return HABIT_LABELS.slice(0,4); }
  });
  const toggle = (h) => {
    const next = sel.includes(h) ? sel.filter(x=>x!==h) : [...sel, h];
    setSel(next);
    try { localStorage.setItem('edgebook:habits', JSON.stringify(next)); } catch {}
  };
  return (
    <div style={{marginTop:22}}>
      <div style={{fontWeight:600,fontSize:14,marginBottom:10}}>{t('habits_section')||'Trading habits'}</div>
      <div className="chips">
        {HABIT_LABELS.map(h => (
          <span key={h} className={'chip '+(sel.includes(h)?'on':'')} onClick={()=>toggle(h)}>{h}</span>
        ))}
      </div>
    </div>
  );
};

const ProfileBlockAfterN = () => {
  const { t } = useI18n();
  const [state, setState] = useState(() => {
    try { return JSON.parse(localStorage.getItem('edgebook:block_after_n') || 'null') || { enabled: false, n: 3 }; } catch { return { enabled: false, n: 3 }; }
  });
  const update = (patch) => {
    const next = { ...state, ...patch };
    setState(next);
    try { localStorage.setItem('edgebook:block_after_n', JSON.stringify(next)); } catch {}
  };
  return (
    <div style={{marginTop:22,padding:'14px 16px',background:'var(--card-2)',border:'1px solid var(--border)',borderRadius:10,display:'flex',alignItems:'center',gap:12,flexWrap:'wrap'}}>
      <div style={{flex:1,minWidth:220}}>
        <div style={{fontWeight:500,fontSize:13.5}}>{t('block_after_n')||'Auto-disable trading after N losses'}</div>
        <div className="muted tiny" style={{marginTop:3}}>{t('block_after_n_sub')||'Pauses logging after consecutive losing trades.'}</div>
      </div>
      <div style={{display:'flex',alignItems:'center',gap:10}}>
        <input className="input mono" type="number" min={1} max={10} value={state.n} disabled={!state.enabled} onChange={e=>update({n:Math.max(1,+e.target.value||1)})} style={{width:68,opacity:state.enabled?1:0.5}} title={t('threshold_losses')||'Threshold (losses)'}/>
        <div className={'disc-sw '+(state.enabled?'on':'')} onClick={()=>update({enabled:!state.enabled})}/>
      </div>
    </div>
  );
};

const SettingsPage = () => {
  const { t, fmtCurShort } = useI18n();
  const { accounts, statsFor, deleteAccount } = useAccounts();
  const { user, signOut, deleteAccount: wipeAccount } = useAuth();
  const { mode, setMode, accent, setAccent } = useTheme();
  const [tab, setTab] = useState(() => {
    try { const s = localStorage.getItem('edgebook:settings_tab'); if (s) { localStorage.removeItem('edgebook:settings_tab'); return s; } } catch {}
    return 'profile';
  });
  const [editAcct, setEditAcct] = useState(null);
  const [showNewAcct, setShowNewAcct] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleteText, setDeleteText] = useState('');
  return (
    <div className="page">
      <PageHead title={t('nav_settings')} sub={t('settings_sub')} />

      <div className="subtabs">
        {[['profile',t('st_profile')],['accounts',t('st_accounts')],['appearance',t('st_appearance')||'Appearance'],['notifications',t('st_notifications')||'Notifications'],['security',t('st_security')],['account',t('st_account')]].map(([id,label])=>(
          <button key={id} className={'subtab ' + (tab===id?'active':'')} onClick={()=>setTab(id)}>{label}</button>
        ))}
      </div>

      {tab==='accounts' && (
        <>
          <div className="card">
            <div className="card-head">
              <div>
                <div className="card-title">{t('st_accounts')}</div>
                <div className="card-sub">{t('accounts_sub')}</div>
              </div>
              <button className="btn btn-primary" onClick={()=>setShowNewAcct(true)}><Icon name="plus" size={13}/> {t('new_account')}</button>
            </div>
            <div style={{overflowX:'auto'}}>
            <table className="table" style={{display:'table'}}>
              <thead>
                <tr>
                  <th>{t('th_name')}</th><th>{t('th_broker')}</th><th>{t('th_type')}</th>
                  <th style={{textAlign:'right'}}>{t('th_starting')}</th>
                  <th style={{textAlign:'right'}}>{t('th_balance')}</th>
                  <th style={{textAlign:'right'}}>{t('th_pnl')}</th>
                  <th style={{textAlign:'right'}}>{t('th_open')}</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {accounts.map(a => {
                  const s = statsFor(a.id);
                  return (
                    <tr key={a.id} style={{cursor:'pointer'}} onClick={()=>setEditAcct(a)}>
                      <td>
                        <div style={{display:'flex',alignItems:'center',gap:10}}>
                          <div className="acct-avatar" style={{background:a.color}}>{a.name.slice(0,1).toUpperCase()}</div>
                          <div style={{fontWeight:500}}>{a.name}</div>
                        </div>
                      </td>
                      <td className="muted">{a.broker}</td>
                      <td>
                        <span className="acct-type-badge" style={{background:`color-mix(in srgb, ${accountTypeColor(a.type)} 18%, transparent)`, color: accountTypeColor(a.type)}}>
                          {accountTypeLabel(a.type)}
                        </span>
                      </td>
                      <td className="mono" style={{textAlign:'right'}}>{fmtCurShort(a.startingCapital)}</td>
                      <td className="mono" style={{textAlign:'right',fontWeight:600}}>{fmtCurShort(a.startingCapital + s.netPnl)}</td>
                      <td className={'mono ' + (s.netPnl>=0?'up':'dn')} style={{textAlign:'right',fontWeight:600}}>{fmtCurShort(s.netPnl)}</td>
                      <td className="mono muted" style={{textAlign:'right'}}>{s.openTrades}</td>
                      <td style={{textAlign:'right'}} onClick={e=>e.stopPropagation()}>
                        <button className="icon-btn" onClick={()=>setEditAcct(a)}><Icon name="edit" size={14}/></button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            </div>
          </div>
          {editAcct && <AccountModal initial={editAcct} onClose={()=>setEditAcct(null)} onDelete={deleteAccount}/>}
          {showNewAcct && <AccountModal onClose={()=>setShowNewAcct(false)}/>}
        </>
      )}

      {tab==='profile' && (
        <div className="card card-pad" style={{padding:24, maxWidth:720}}>
          <div style={{display:'flex',alignItems:'center',gap:16,marginBottom:20,flexWrap:'wrap'}}>
            <div className="avatar" style={{width:56,height:56,fontSize:18}}>{(user?.name||'??').slice(0,2).toUpperCase()}</div>
            <div>
              <div style={{fontWeight:600,fontSize:15}}>{user?.name}</div>
              <div className="muted tiny">{user?.email} · {t('member_since')}</div>
            </div>
            <button className="btn" style={{marginLeft:'auto'}}><Icon name="image" size={13}/> {t('upload')}</button>
          </div>
          <div className="g-2">
            <div><label className="label">{t('display_name')}</label><input className="input" defaultValue={user?.name||''} style={{width:'100%'}}/></div>
            <div><label className="label">{t('email')}</label><input className="input" defaultValue={user?.email||''} style={{width:'100%'}}/></div>
            <div><label className="label">{t('time_zone')}</label><select className="select" style={{width:'100%'}}><option>America / New York (ET)</option><option>Asia / Ulaanbaatar</option><option>Europe / London</option></select></div>
            <div><label className="label">{t('language')||'Language'}</label><select className="select" style={{width:'100%'}}><option>English</option><option>Монгол</option></select></div>
          </div>

          <ProfileHabits/>
          <ProfileBlockAfterN/>

          <div className="muted tiny" style={{marginTop:16,padding:'10px 12px',background:'var(--card-2)',border:'1px solid var(--border)',borderRadius:8,textWrap:'pretty'}}>{t('profile_risk_moved')||'Risk rules and goals are set per-account — open any account from the Accounts tab to configure them.'}</div>
          <div style={{display:'flex',gap:8,marginTop:20,justifyContent:'flex-end'}}>
            <button className="btn">{t('cancel')}</button>
            <button className="btn btn-primary">{t('save_changes')}</button>
          </div>
        </div>
      )}

      {tab==='security' && (
        <div className="card card-pad" style={{padding:24, maxWidth:720}}>
          <div style={{fontWeight:500,marginBottom:6}}>{t('password')}</div>
          <div className="muted tiny" style={{marginBottom:10}}>{t('last_changed')}</div>
          <button className="btn">{t('change_password')}</button>
          <div className="hsep"/>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',flexWrap:'wrap',gap:12}}>
            <div><div style={{fontWeight:500}}>{t('two_factor')}</div><div className="muted tiny">{t('authenticator_on')}</div></div>
            <div className="toggle"><button className="on long">On</button><button>Off</button></div>
          </div>
          <div className="hsep"/>
          <div style={{fontWeight:500,marginBottom:10}}>{t('active_sessions')}</div>
          <div style={{display:'flex',flexDirection:'column',gap:8}}>
            {[['MacBook Pro · Chrome','New York, NY','Active now'],['iPhone 15 · Safari','New York, NY','2 hours ago']].map(([a,b,c],i)=>(
              <div key={i} style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 12px',background:'#0f0f0f',border:'1px solid #222',borderRadius:8,flexWrap:'wrap',gap:8}}>
                <div><div style={{fontWeight:500}}>{a}</div><div className="muted tiny">{b} · {c}</div></div>
                {i===0 ? <span className="badge badge-win">{t('current_session')}</span> : <button className="btn btn-ghost">{t('revoke')}</button>}
              </div>
            ))}
          </div>
        </div>
      )}
      {tab==='appearance' && (
        <div className="card card-pad" style={{padding:24, maxWidth:720}}>
          <div style={{fontWeight:500,marginBottom:12}}>{t('theme_mode')||'Theme'}</div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:10,marginBottom:20}}>
            {[
              ['system','Auto','System preference'],
              ['dark','Dark','Default'],
              ['light','Light','Bright'],
            ].map(([id,label,sub])=>(
              <div key={id} onClick={()=>setMode(id)} style={{
                padding:14,borderRadius:10,cursor:'pointer',
                border:'1px solid ' + (mode===id?'var(--accent)':'var(--border)'),
                background:mode===id?'var(--accent-dim)':'var(--card-2)',
                position:'relative',
              }}>
                <div style={{height:42,borderRadius:6,marginBottom:10,background:
                  id==='dark' ? 'linear-gradient(135deg,#0a0a0a,#1a1a1a)' :
                  id==='light'? 'linear-gradient(135deg,#fff,#e5e5e5)' :
                  'linear-gradient(135deg,#0a0a0a 0%,#0a0a0a 50%,#fff 50%,#fff 100%)',
                  border:'1px solid var(--border)',
                }}/>
                <div style={{fontWeight:500,fontSize:13}}>{label}</div>
                <div className="muted tiny">{sub}</div>
              </div>
            ))}
          </div>

          <div style={{fontWeight:500,marginBottom:12}}>{t('accent_color')||'Accent color'}</div>
          <div style={{display:'flex',gap:12,flexWrap:'wrap'}}>
            {Object.entries(ACCENTS).map(([id,a])=>(
              <div key={id} className={'accent-dot ' + (accent===id?'on':'')} onClick={()=>setAccent(id)} style={{background:a.bg,title:id}} title={id}/>
            ))}
          </div>
          <div className="muted tiny" style={{marginTop:10}}>{t('accent_sub')||'Used for primary buttons, links and chart highlights.'}</div>
        </div>
      )}

      {tab==='notifications' && (
        <div className="card card-pad" style={{padding:24, maxWidth:720}}>
          <div style={{fontWeight:500,marginBottom:4}}>{t('notif_channels')||'Delivery channels'}</div>
          <div className="muted tiny" style={{marginBottom:14}}>{t('notif_channels_sub')||'Where should we reach you?'}</div>
          {[
            ['in_app','In-app',true],
            ['email','Email',true],
            ['push','Browser push',false],
          ].map(([id,label,on])=>(
            <div key={id} className="disc-row">
              <div className="disc-label">{label}</div>
              <div className={'disc-sw ' + (on?'on':'')}/>
            </div>
          ))}
          <div className="hsep"/>
          <div style={{fontWeight:500,marginBottom:4}}>{t('notif_events')||'Which events'}</div>
          <div className="muted tiny" style={{marginBottom:14}}>{t('notif_events_sub')||'Turn specific triggers on or off'}</div>
          {[
            ['risk','Daily loss / risk rule hit',true,'#ef4444'],
            ['challenge','Prop challenge progress',true,'#f59e0b'],
            ['streak','Win/loss streaks',true,'#10b981'],
            ['journal',"Journal reminder (if you didn't write yesterday)",true,'#3b82f6'],
            ['insight','Strategy insights',false,'#8b5cf6'],
            ['product','Product updates',false,'#6b6b6b'],
          ].map(([id,label,on,color])=>(
            <div key={id} className="disc-row">
              <div className="disc-label">
                <span style={{width:8,height:8,borderRadius:999,background:color}}/>
                {label}
              </div>
              <div className={'disc-sw ' + (on?'on':'')}/>
            </div>
          ))}
          <div className="hsep"/>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',flexWrap:'wrap',gap:12}}>
            <div>
              <div style={{fontWeight:500}}>{t('quiet_hours')||'Quiet hours'}</div>
              <div className="muted tiny">{t('quiet_hours_sub')||'No alerts during these times'}</div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <input className="input mono" defaultValue="22:00" style={{width:90}}/>
              <span className="muted">→</span>
              <input className="input mono" defaultValue="07:00" style={{width:90}}/>
            </div>
          </div>
        </div>
      )}

      {tab==='account' && (
        <div style={{maxWidth:720, display:'flex', flexDirection:'column', gap:16}}>
          <div className="card card-pad" style={{padding:24}}>
            <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:18}}>
              <div className="avatar" style={{width:48,height:48,fontSize:16,background:'#10b981',color:'#042f1c',fontWeight:700}}>
                {(user?.name||'?').slice(0,2).toUpperCase()}
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontWeight:600,fontSize:15}}>{user?.name}</div>
                <div className="muted tiny" style={{wordBreak:'break-all'}}>{t('signed_in_as')} {user?.email}</div>
              </div>
              <button className="btn" onClick={signOut}><Icon name="log-out" size={13}/> {t('sign_out')}</button>
            </div>
          </div>

          <div className="card card-pad" style={{padding:24, border:'1px solid rgba(239,68,68,.3)'}}>
            <div style={{fontWeight:600,marginBottom:6,color:'#ef4444'}}>{t('delete_account_title')}</div>
            <div className="muted tiny" style={{marginBottom:14,textWrap:'pretty'}}>{t('delete_account_desc')}</div>
            <button className="btn" style={{color:'#ef4444',borderColor:'rgba(239,68,68,.3)'}} onClick={()=>{setShowDeleteConfirm(true);setDeleteText('')}}>
              <Icon name="trash" size={13}/> {t('delete_account_btn')}
            </button>
          </div>

          {showDeleteConfirm && (
            <div className="modal-scrim" onClick={()=>setShowDeleteConfirm(false)}>
              <div className="modal" onClick={e=>e.stopPropagation()} style={{width:'min(480px,100%)'}}>
                <div className="modal-head">
                  <div>
                    <div style={{fontWeight:600,fontSize:15,color:'#ef4444'}}>{t('confirm_delete_title')}</div>
                  </div>
                  <button className="icon-btn" onClick={()=>setShowDeleteConfirm(false)}><Icon name="x" size={16}/></button>
                </div>
                <div className="modal-body">
                  <div className="muted" style={{marginBottom:14,textWrap:'pretty',fontSize:13.5}}>{t('confirm_delete_body')}</div>
                  <input
                    className="input mono"
                    value={deleteText}
                    onChange={e=>setDeleteText(e.target.value)}
                    placeholder={t('type_delete')}
                    style={{width:'100%',letterSpacing:'0.15em'}}
                    autoFocus
                  />
                </div>
                <div className="modal-foot">
                  <button className="btn" onClick={()=>setShowDeleteConfirm(false)}>{t('keep_account')}</button>
                  <button
                    className="btn"
                    disabled={deleteText !== 'DELETE'}
                    style={{
                      background: deleteText==='DELETE' ? '#ef4444' : '#2a0f0f',
                      color: deleteText==='DELETE' ? '#fff' : '#6b6b6b',
                      borderColor: 'transparent',
                      cursor: deleteText==='DELETE' ? 'pointer' : 'not-allowed',
                    }}
                    onClick={()=>{ if (deleteText==='DELETE') wipeAccount(); }}
                  >
                    <Icon name="trash" size={13}/> {t('delete_account_btn')}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

window.SettingsPage = SettingsPage;