// Profile panel — slides in from the right when clicking name or email

const AVATAR_COLORS = [
  '#1f2733','#2f8c70','#e05c3a','#6b5dd3','#c4922a',
  '#1a6b9e','#b54f8c','#3a7d44','#7c4b1f','#4a6fa5',
];

const CURRENCIES = [
  { code:'ZAR', symbol:'R',    name:'South African Rand' },
  { code:'USD', symbol:'$',    name:'US Dollar' },
  { code:'EUR', symbol:'€',    name:'Euro' },
  { code:'GBP', symbol:'£',    name:'British Pound' },
  { code:'AUD', symbol:'A$',   name:'Australian Dollar' },
  { code:'CAD', symbol:'C$',   name:'Canadian Dollar' },
  { code:'NGN', symbol:'₦',    name:'Nigerian Naira' },
  { code:'KES', symbol:'KSh',  name:'Kenyan Shilling' },
  { code:'GHS', symbol:'GH₵',  name:'Ghanaian Cedi' },
];

const PAGES = [
  { id:'dashboard',    label:'Dashboard' },
  { id:'transactions', label:'Transactions' },
  { id:'insights',     label:'Insights' },
  { id:'savings',      label:'Savings goals' },
  { id:'debt',         label:'Debt tracker' },
];

// ── Apply theme to document ────────────────────────────────────────────────────
const applyTheme = (theme) => {
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  const dark = theme === 'dark' || (theme === 'system' && prefersDark);
  document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
};
window.applyTheme = applyTheme;

// ── Small helpers ──────────────────────────────────────────────────────────────
const PField = ({ label, children }) => (
  <div>
    <label style={{ display:'block', fontSize:12, fontWeight:500, color:'var(--ink-2)', marginBottom:6 }}>{label}</label>
    {children}
  </div>
);

const PSection = ({ label, children }) => (
  <div style={{ marginBottom:28 }}>
    <div style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', marginBottom:14, paddingBottom:8, borderBottom:'1px solid var(--line-2)' }}>
      {label}
    </div>
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>{children}</div>
  </div>
);

const iStyle = {
  width:'100%', padding:'10px 12px', borderRadius:8,
  border:'1.5px solid var(--line)', background:'var(--surface)',
  fontSize:14, color:'var(--ink)', outline:'none',
  boxSizing:'border-box', transition:'border-color 0.15s',
};

// ── Main panel ────────────────────────────────────────────────────────────────
const ProfilePanel = ({ open, onClose }) => {
  const { user, signOut, updatePassword, updateEmail } = useAuth();
  const { profile, updateProfile } = useAppState();

  const [displayName,    setDisplayName]    = React.useState('');
  const [avatarColor,    setAvatarColor]    = React.useState('#1f2733');
  const [theme,          setTheme]          = React.useState('system');
  const [currency,       setCurrency]       = React.useState('ZAR');
  const [defaultPage,    setDefaultPage]    = React.useState('dashboard');
  const [saving,         setSaving]         = React.useState(false);
  const [saved,          setSaved]          = React.useState(false);

  const [newPassword,    setNewPassword]    = React.useState('');
  const [confirmPw,      setConfirmPw]      = React.useState('');
  const [pwMsg,          setPwMsg]          = React.useState(null);
  const [pwSaving,       setPwSaving]       = React.useState(false);

  const [newEmail,       setNewEmail]       = React.useState('');
  const [emailMsg,       setEmailMsg]       = React.useState(null);
  const [emailSaving,    setEmailSaving]    = React.useState(false);

  const [deleteText,     setDeleteText]     = React.useState('');
  const [deleting,       setDeleting]       = React.useState(false);

  // Sync from profile context when panel opens
  React.useEffect(() => {
    if (!open) return;
    setDisplayName(profile?.displayName || '');
    setAvatarColor(profile?.avatarColor || '#1f2733');
    setTheme(profile?.theme       || 'system');
    setCurrency(profile?.currency  || 'ZAR');
    setDefaultPage(profile?.defaultPage || 'dashboard');
    setPwMsg(null); setEmailMsg(null); setDeleteText('');
  }, [open, profile]);

  // Live preview of theme while panel is open
  React.useEffect(() => { if (open) applyTheme(theme); }, [theme]);

  const handleSave = async () => {
    setSaving(true);
    await updateProfile({ displayName, avatarColor, theme, currency, defaultPage });
    setSaving(false); setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const handlePasswordChange = async () => {
    setPwMsg(null);
    if (newPassword.length < 6) { setPwMsg({ ok:false, text:'At least 6 characters required' }); return; }
    if (newPassword !== confirmPw) { setPwMsg({ ok:false, text:'Passwords do not match' }); return; }
    setPwSaving(true);
    const { error } = await updatePassword(newPassword);
    setPwSaving(false);
    if (error) { setPwMsg({ ok:false, text:error.message }); return; }
    setPwMsg({ ok:true, text:'Password updated successfully' });
    setNewPassword(''); setConfirmPw('');
  };

  const handleEmailChange = async () => {
    setEmailMsg(null);
    if (!newEmail.includes('@')) { setEmailMsg({ ok:false, text:'Enter a valid email address' }); return; }
    setEmailSaving(true);
    const { error } = await updateEmail(newEmail);
    setEmailSaving(false);
    if (error) { setEmailMsg({ ok:false, text:error.message }); return; }
    setEmailMsg({ ok:true, text:'Confirmation sent to your new email' });
    setNewEmail('');
  };

  const handleDelete = async () => {
    if (deleteText !== 'DELETE') return;
    setDeleting(true);
    try {
      await window._supabase.rpc('delete_my_data');
      await signOut();
    } catch { setDeleting(false); }
  };

  const isGoogle = user?.app_metadata?.provider === 'google';
  const previewInitial = (displayName || user?.email || '?')[0].toUpperCase();

  if (!open) return null;

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position:'fixed', inset:0, background:'rgba(0,0,0,0.35)', zIndex:300,
      }}/>

      {/* Slide-over panel */}
      <div style={{
        position:'fixed', top:0, right:0, bottom:0,
        width: Math.min(420, window.innerWidth),
        background:'var(--card)', borderLeft:'1px solid var(--line)',
        zIndex:301, display:'flex', flexDirection:'column',
        boxShadow:'-8px 0 32px rgba(0,0,0,0.15)',
        animation:'slideInRight 0.25s cubic-bezier(0.4,0,0.2,1)',
        paddingTop:'env(safe-area-inset-top, 0px)',
        paddingBottom:'env(safe-area-inset-bottom, 0px)',
      }}>

        {/* Header */}
        <div style={{ padding:'20px 24px 16px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0 }}>
          <div style={{ fontWeight:600, fontSize:16, color:'var(--ink)' }}>Profile & Settings</div>
          <button onClick={onClose} style={{ background:'none', border:'none', cursor:'pointer', color:'var(--ink-3)', padding:4, borderRadius:6, display:'flex', alignItems:'center' }}>
            <IClose size={18}/>
          </button>
        </div>

        {/* Scrollable body */}
        <div style={{ flex:1, overflowY:'auto', padding:'24px' }}>

          {/* Avatar preview */}
          <div style={{ display:'flex', alignItems:'center', gap:14, padding:'16px', background:'var(--surface-2)', borderRadius:12, marginBottom:28 }}>
            <div style={{ width:52, height:52, borderRadius:'50%', background:avatarColor, color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, fontWeight:600, flexShrink:0, transition:'background 0.2s' }}>
              {previewInitial}
            </div>
            <div>
              <div style={{ fontWeight:500, fontSize:15, color:'var(--ink)' }}>{displayName || 'Your name'}</div>
              <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{user?.email}</div>
            </div>
          </div>

          {/* ── Identity ─────────────────────────────────── */}
          <PSection label="Identity">
            <PField label="Display name">
              <input type="text" value={displayName} onChange={e => setDisplayName(e.target.value)}
                placeholder="e.g. Rudolph"
                style={iStyle}
                onFocus={e => e.target.style.borderColor='var(--ink)'}
                onBlur={e => e.target.style.borderColor='var(--line)'}
              />
            </PField>
            <PField label="Avatar colour">
              <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
                {AVATAR_COLORS.map(c => (
                  <button key={c} onClick={() => setAvatarColor(c)} style={{
                    width:32, height:32, borderRadius:'50%', background:c, border:'none',
                    cursor:'pointer', padding:0, transition:'transform 0.15s, box-shadow 0.15s',
                    boxShadow: avatarColor === c ? `0 0 0 3px var(--card), 0 0 0 5px ${c}` : 'none',
                    transform: avatarColor === c ? 'scale(1.15)' : 'scale(1)',
                  }}/>
                ))}
              </div>
            </PField>
          </PSection>

          {/* ── Preferences ──────────────────────────────── */}
          <PSection label="Preferences">
            <PField label="Theme">
              <div style={{ display:'flex', background:'var(--surface-2)', borderRadius:8, padding:3, gap:3 }}>
                {[['light','☀️ Light'],['dark','🌙 Dark'],['system','💻 System']].map(([val,label]) => (
                  <button key={val} onClick={() => setTheme(val)} style={{
                    flex:1, padding:'7px 0', borderRadius:6, border:'none', cursor:'pointer',
                    fontSize:12.5, fontWeight:500,
                    background: theme===val ? 'var(--card)' : 'transparent',
                    color:      theme===val ? 'var(--ink)' : 'var(--ink-3)',
                    boxShadow:  theme===val ? 'var(--shadow-sm)' : 'none',
                    transition:'all 0.15s',
                  }}>{label}</button>
                ))}
              </div>
            </PField>
            <PField label="Currency">
              <select value={currency} onChange={e => setCurrency(e.target.value)} style={iStyle}>
                {CURRENCIES.map(c => <option key={c.code} value={c.code}>{c.symbol} — {c.name}</option>)}
              </select>
            </PField>
            <PField label="Default page on open">
              <select value={defaultPage} onChange={e => setDefaultPage(e.target.value)} style={iStyle}>
                {PAGES.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
              </select>
            </PField>
          </PSection>

          {/* Save */}
          <button className="btn btn-primary" onClick={handleSave} disabled={saving}
            style={{ width:'100%', marginBottom:28, display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
            {saving ? 'Saving…' : saved ? <><ICheck size={14}/> Saved</> : 'Save changes'}
          </button>

          {/* ── Account ──────────────────────────────────── */}
          <PSection label="Account">
            {!isGoogle && (
              <PField label="Change password">
                <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                  <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)}
                    placeholder="New password" style={iStyle}
                    onFocus={e => e.target.style.borderColor='var(--ink)'}
                    onBlur={e => e.target.style.borderColor='var(--line)'}/>
                  <input type="password" value={confirmPw} onChange={e => setConfirmPw(e.target.value)}
                    placeholder="Confirm new password" style={iStyle}
                    onFocus={e => e.target.style.borderColor='var(--ink)'}
                    onBlur={e => e.target.style.borderColor='var(--line)'}/>
                  {pwMsg && <div style={{ fontSize:12.5, color: pwMsg.ok ? 'var(--mint-deep)' : 'var(--coral)' }}>{pwMsg.text}</div>}
                  <button className="btn btn-ghost btn-sm" onClick={handlePasswordChange} disabled={pwSaving} style={{ alignSelf:'flex-start' }}>
                    {pwSaving ? 'Updating…' : 'Update password'}
                  </button>
                </div>
              </PField>
            )}
            <PField label="Change email">
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                <input type="email" value={newEmail} onChange={e => setNewEmail(e.target.value)}
                  placeholder="New email address" style={iStyle}
                  onFocus={e => e.target.style.borderColor='var(--ink)'}
                  onBlur={e => e.target.style.borderColor='var(--line)'}/>
                {emailMsg && <div style={{ fontSize:12.5, color: emailMsg.ok ? 'var(--mint-deep)' : 'var(--coral)' }}>{emailMsg.text}</div>}
                <button className="btn btn-ghost btn-sm" onClick={handleEmailChange} disabled={emailSaving} style={{ alignSelf:'flex-start' }}>
                  {emailSaving ? 'Updating…' : 'Update email'}
                </button>
              </div>
            </PField>
          </PSection>

          {/* Sign out */}
          <button className="btn btn-ghost" onClick={() => { signOut(); onClose(); }}
            style={{ width:'100%', marginBottom:28, display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
            Sign out
          </button>

          {/* ── Danger zone ──────────────────────────────── */}
          <PSection label="Danger zone">
            <div style={{ fontSize:13, color:'var(--ink-3)', lineHeight:1.6 }}>
              Permanently deletes all your transactions, debts, goals, and bills. Type <strong style={{ color:'var(--ink)' }}>DELETE</strong> to confirm.
            </div>
            <input type="text" value={deleteText} onChange={e => setDeleteText(e.target.value)}
              placeholder="Type DELETE to confirm" style={iStyle}
              onFocus={e => e.target.style.borderColor='var(--coral)'}
              onBlur={e => e.target.style.borderColor='var(--line)'}/>
            <button onClick={handleDelete} disabled={deleteText !== 'DELETE' || deleting} style={{
              width:'100%', padding:'11px', borderRadius:8,
              border:`1px solid var(--coral)`,
              background: deleteText === 'DELETE' ? 'var(--coral)' : 'transparent',
              color:       deleteText === 'DELETE' ? 'white' : 'var(--coral)',
              cursor:      deleteText === 'DELETE' ? 'pointer' : 'not-allowed',
              fontSize:14, fontWeight:500, transition:'all 0.15s', opacity: deleteText === 'DELETE' ? 1 : 0.6,
            }}>
              {deleting ? 'Deleting…' : 'Delete my account'}
            </button>
          </PSection>

        </div>
      </div>
    </>
  );
};

Object.assign(window, { ProfilePanel, applyTheme });
