// Shared · Account Settings — members edit their own profile. Used as the
// "Account" tab in BOTH the student and admin/coach portals.
// Exposes window.AccountSettings and window.cgDisplayName.
//
// LOCKED: registered name + email. They are identity of record, tied to
// payments and account recovery; only the main admin can change a name.
//
// All writes go through update_my_profile() / update_my_coach_profile().
// There is deliberately NO RLS policy letting a member UPDATE their own row —
// one would also expose tier, vip and status, and RLS cannot be scoped to a
// single column. The RPCs write exactly the fields below and nothing else.
//
// birthdate lives in member_private, a table whose only policy is
// "member reads own". Staff `select *` on students cannot reach it.
(function(){
const { useState, useEffect } = React;

function displayName(fullName, nickname){
  const n=(nickname||'').trim(), f=(fullName||'').trim();
  if(!n) return f; if(!f) return n; return f+' ('+n+')';
}
window.cgDisplayName = displayName;

// Zones our members actually live in, so nobody scrolls a 400-entry list.
const ZONES = [
  ['Asia/Manila','Philippines (PHT)'], ['Asia/Dubai','UAE (GST)'],
  ['Asia/Singapore','Singapore'], ['Asia/Hong_Kong','Hong Kong'],
  ['Asia/Tokyo','Japan'], ['Asia/Seoul','South Korea'],
  ['Asia/Qatar','Qatar'], ['Asia/Riyadh','Saudi Arabia'], ['Asia/Kuwait','Kuwait'],
  ['Asia/Almaty','Kazakhstan'], ['Europe/London','United Kingdom'],
  ['Europe/Rome','Italy'], ['Europe/Madrid','Spain'], ['Europe/Berlin','Germany'],
  ['America/Toronto','Canada (Eastern)'], ['America/Vancouver','Canada (Pacific)'],
  ['America/New_York','USA (Eastern)'], ['America/Los_Angeles','USA (Pacific)'],
  ['Australia/Sydney','Australia (Sydney)'], ['Pacific/Auckland','New Zealand'],
];

// 7:00 AM PH shown in the member's own zone — the whole point of storing it.
function localEquivalent(tz){
  if(!tz) return null;
  try{
    const now = new Date();
    const ph  = new Date(now.toLocaleString('en-US',{timeZone:'Asia/Manila'}));
    const d   = new Date(ph); d.setHours(7,0,0,0);
    const shift = d.getTime() - ph.getTime() + now.getTime();
    return new Date(shift).toLocaleTimeString('en-US',
      {timeZone:tz, hour:'numeric', minute:'2-digit'});
  }catch(e){ return null; }
}

const Row = ({label, hint, children}) => <div className="field">
  <label>{label}</label>{children}
  {hint && <span style={{fontSize:'.75rem',color:'var(--ink-faint)',marginTop:4,display:'block',lineHeight:1.45}}>{hint}</span>}
</div>;

function AccountSettings({ client, role, profile, email, onSaved }){
  const isCoach = role === 'coach';
  const [f,setF] = useState({ nickname:'', phone:'', country:'', birthdate:'', telegram:'', timezone:'' });
  const [start,setStart] = useState(f);
  const [busy,setBusy]=useState(false); const [msg,setMsg]=useState(''); const [err,setErr]=useState('');

  useEffect(()=>{
    if(!profile) return;
    const next = {
      nickname: profile.nickname||'', phone: profile.phone||'',
      country: profile.country||'', birthdate: profile.birthdate||'',
      telegram: profile.telegram_username||'', timezone: profile.timezone||'',
    };
    setF(next); setStart(next);
  },[profile]);

  const set = k => e => { setF(s=>({...s,[k]:e.target.value})); setErr(''); setMsg(''); };
  const dirty = JSON.stringify(f) !== JSON.stringify(start);
  const fullName = isCoach ? (profile&&profile.name) : (profile&&profile.full_name);

  async function save(){
    setBusy(true); setErr(''); setMsg('');
    const args = isCoach
      ? { p_nickname:f.nickname, p_phone:f.phone, p_birthdate:f.birthdate||null,
          p_telegram:f.telegram, p_timezone:f.timezone }
      : { p_nickname:f.nickname, p_phone:f.phone, p_country:f.country,
          p_birthdate:f.birthdate||null, p_telegram:f.telegram, p_timezone:f.timezone };
    const { data, error } = await client.rpc(isCoach?'update_my_coach_profile':'update_my_profile', args);
    setBusy(false);
    if(error){ setErr(error.message||'Could not save your changes.'); return; }
    setStart(f); setMsg('Saved'); setTimeout(()=>setMsg(''),2400);
    if(onSaved) onSaved(data||{});
  }

  const ro = { width:'100%', padding:'11px 13px', borderRadius:'var(--radius-sm)',
    background:'var(--surface-2)', border:'1px dashed var(--border)',
    color:'var(--ink-dim)', fontSize:'.92rem' };
  const local = localEquivalent(f.timezone);

  return <div style={{maxWidth:760}}>
    <div style={{marginBottom:22}}>
      <span className="eyebrow">Account</span>
      <h2 style={{fontSize:'1.55rem',margin:'12px 0 6px'}}>Your profile</h2>
      <p style={{color:'var(--ink-dim)',fontSize:'.92rem',margin:0,lineHeight:1.6}}>
        Keep your details current so your coach can reach you and your session times are right.
      </p>
    </div>

    {/* locked identity */}
    <div style={{border:'1px solid var(--border)',borderRadius:'var(--radius)',
        background:'var(--surface)',padding:'18px 20px',marginBottom:18}}>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}} className="form-2">
        <div>
          <label style={{display:'block',fontSize:'.8rem',color:'var(--ink-faint)',marginBottom:6}}>Registered name</label>
          <div style={ro}>{fullName || '—'}</div>
        </div>
        <div>
          <label style={{display:'block',fontSize:'.8rem',color:'var(--ink-faint)',marginBottom:6}}>Email</label>
          <div style={{...ro,fontFamily:'var(--font-mono)',fontSize:'.84rem',wordBreak:'break-all'}}>{email||'—'}</div>
        </div>
      </div>
      <p style={{fontSize:'.78rem',color:'var(--ink-faint)',margin:'12px 0 0',lineHeight:1.55}}>
        🔒 These are locked. They're tied to your membership record, payments and account
        recovery. If either is wrong, message the admin and they'll correct it for you.
      </p>
    </div>

    {/* editable */}
    <div style={{border:'1px solid var(--border-gold)',borderRadius:'var(--radius)',
        background:'linear-gradient(165deg,var(--surface-2),var(--surface))',padding:'22px 22px 24px',display:'grid',gap:16}}>

      <Row label="Nickname"
           hint={f.nickname ? 'Shown as: '+displayName(fullName,f.nickname) : 'Optional. Up to 30 characters — shown next to your registered name.'}>
        <input value={f.nickname} maxLength={30} placeholder="e.g. JD" onChange={set('nickname')}/>
      </Row>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}} className="form-2">
        <Row label="Contact number" hint="Include your country code.">
          <input value={f.phone} maxLength={32} placeholder="+63 912 345 6789"
                 inputMode="tel" onChange={set('phone')}/>
        </Row>
        <Row label="Telegram username" hint="So your coach can send you the channel invite.">
          <input value={f.telegram} maxLength={32} placeholder="@yourhandle" onChange={set('telegram')}/>
        </Row>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}} className="form-2">
        {!isCoach && <Row label="Country" hint="Update this if you move contracts.">
          <input value={f.country} maxLength={60} placeholder="e.g. United Arab Emirates" onChange={set('country')}/>
        </Row>}
        <Row label="Your timezone"
             hint={local ? 'The 7:00 AM PH session starts at '+local+' your time.' : 'Lets us show session times in your local time.'}>
          <select value={f.timezone} onChange={set('timezone')}>
            <option value="">Select…</option>
            {ZONES.map(([v,l])=><option key={v} value={v}>{l}</option>)}
          </select>
        </Row>
      </div>

      <Row label="Date of birth" hint="🔒 Private — only you can see this. It is never shown to coaches or admins.">
        <input type="date" value={f.birthdate} max={new Date().toISOString().slice(0,10)}
               onChange={set('birthdate')}/>
      </Row>

      {err && <div style={{color:'var(--red)',fontSize:'.85rem',fontFamily:'var(--font-mono)'}}>{err}</div>}

      <div style={{display:'flex',alignItems:'center',gap:13,flexWrap:'wrap'}}>
        <button className="btn btn-primary" style={{width:'auto',opacity:(!dirty||busy)?.55:1}}
                disabled={!dirty||busy} onClick={save}>
          {busy ? <React.Fragment><span className="cg-spin"></span> Saving…</React.Fragment> : 'Save changes'}
        </button>
        {dirty && !busy && <button className="btn btn-ghost" style={{width:'auto'}}
          onClick={()=>{ setF(start); setErr(''); }}>Discard</button>}
        {msg && <span style={{color:'var(--green)',fontSize:'.86rem',fontFamily:'var(--font-mono)'}}>✓ {msg}</span>}
      </div>
    </div>

    <p style={{fontSize:'.78rem',color:'var(--ink-faint)',marginTop:16,lineHeight:1.55}}>
      Need to change your password? Log out and use <b>Forgot password</b> on the sign-in page —
      we'll email you a secure reset link.
    </p>
  </div>;
}
window.AccountSettings = AccountSettings;
})();
