const { useState } = React;

function SettingsToggle({ label, checked, onChange, description }) {
  return (
    <label className="row gap-16" style={{ alignItems: 'flex-start', cursor: 'pointer', padding: '12px 0' }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 16 }}>{label}</div>
        {description && <div className="muted" style={{ fontSize: 14, marginTop: 4 }}>{description}</div>}
      </div>
      <div style={{ 
        position: 'relative', width: 44, height: 24, borderRadius: 12, 
        background: checked ? 'var(--lime)' : 'var(--bg-2)',
        border: checked ? 'none' : '1px solid var(--border-strong)',
        transition: 'background .2s', flexShrink: 0
      }}>
        <div style={{
          position: 'absolute', top: checked ? 2 : 1, left: checked ? 22 : 1,
          width: 20, height: 20, borderRadius: '50%', background: '#fff',
          boxShadow: '0 2px 4px rgba(0,0,0,0.2)', transition: 'left .2s cubic-bezier(0.16, 1, 0.3, 1)'
        }} />
      </div>
      {/* Hidden checkbox for accessibility */}
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} style={{ position: 'absolute', opacity: 0, pointerEvents: 'none' }} />
    </label>
  );
}

function SettingsPage({ t, setTweak }) {
  const [activeTab, setActiveTab] = useState('profile');
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState('');
  
  // Local state for profile form
  const [fullName, setFullName] = useState(window.EDSTUTIA?.learner?.name || '');
  const [firstName, setFirstName] = useState(window.EDSTUTIA?.learner?.first || '');
  const [avatar, setAvatar] = useState(window.EDSTUTIA?.learner?.avatar || '');
  
  const handleSaveProfile = async (e) => {
    e.preventDefault();
    setLoading(true); setMsg('');
    
    // Update local immediately for snappy UI
    window.EDSTUTIA.learner.name = fullName;
    window.EDSTUTIA.learner.first = firstName;
    window.EDSTUTIA.learner.avatar = avatar;
    
    if (window.supabaseClient && window.ME_UUID) {
      const { error } = await window.supabaseClient.from('profiles').update({
        name: fullName,
        first_name: firstName,
        avatar: avatar
      }).eq('id', window.ME_UUID);
      
      if (error) {
        setMsg('Error saving profile: ' + error.message);
      } else {
        setMsg('Profile updated successfully!');
        setTimeout(() => setMsg(''), 3000);
      }
    } else {
      setMsg('Profile updated locally.');
      setTimeout(() => setMsg(''), 3000);
    }
    setLoading(false);
  };
  
  return (
    <div className="page" style={{ maxWidth: 900, margin: '0 auto', padding: '40px 20px' }}>
      <h1 style={{ fontSize: 32, marginBottom: 8 }}>Settings</h1>
      <p className="muted" style={{ marginBottom: 32 }}>Manage your account and customize your learning experience.</p>
      
      <div className="row gap-32" style={{ alignItems: 'flex-start' }}>
        <div className="col gap-6" style={{ width: 220, flexShrink: 0, position: 'sticky', top: 100 }}>
          <button className={'nav-item' + (activeTab === 'profile' ? ' active' : '')} onClick={() => setActiveTab('profile')}>
            <Icon name="users" size={20} /> Public Profile
          </button>
          <button className={'nav-item' + (activeTab === 'appearance' ? ' active' : '')} onClick={() => setActiveTab('appearance')}>
            <Icon name="sun" size={20} /> Appearance
          </button>
          <button className={'nav-item' + (activeTab === 'accessibility' ? ' active' : '')} onClick={() => setActiveTab('accessibility')}>
            <Icon name="eye" size={20} /> Accessibility
          </button>
        </div>
        
        <div className="card" style={{ flex: 1, padding: 32 }}>
          {activeTab === 'profile' && (
            <div className="col gap-24 fade-in">
              <h2 style={{ fontSize: 20, margin: 0, paddingBottom: 16, borderBottom: '1px solid var(--border)' }}>Public Profile</h2>
              {msg && (
                <div style={{ padding: 12, borderRadius: 8, background: msg.includes('Error') ? '#fee2e2' : 'var(--lime-soft)', color: msg.includes('Error') ? '#b91c1c' : 'var(--lime-strong)', fontWeight: 600 }}>
                  {msg}
                </div>
              )}
              
              <form onSubmit={handleSaveProfile} className="col gap-20">
                <div className="form-group">
                  <label style={{ fontWeight: 600, display: 'block', marginBottom: 8 }}>Full Name</label>
                  <input type="text" className="login-input" value={fullName} onChange={e => setFullName(e.target.value)} required />
                  <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>Used for certificates and official records.</div>
                </div>
                <div className="form-group">
                  <label style={{ fontWeight: 600, display: 'block', marginBottom: 8 }}>First Name</label>
                  <input type="text" className="login-input" value={firstName} onChange={e => setFirstName(e.target.value)} required />
                  <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>Used for friendly greetings on your dashboard.</div>
                </div>
                <div className="form-group">
                  <label style={{ fontWeight: 600, display: 'block', marginBottom: 8 }}>Avatar Initials</label>
                  <input type="text" className="login-input" value={avatar} maxLength={2} onChange={e => setAvatar(e.target.value.toUpperCase())} required style={{ width: 100, textAlign: 'center', fontSize: 20, letterSpacing: 2 }} />
                </div>
                <div className="row" style={{ marginTop: 12 }}>
                  <button type="submit" className="btn btn-primary btn-lg" disabled={loading}>
                    {loading ? 'Saving...' : 'Save Changes'}
                  </button>
                </div>
              </form>
            </div>
          )}
          
          {activeTab === 'appearance' && (
            <div className="col gap-24 fade-in">
              <h2 style={{ fontSize: 20, margin: 0, paddingBottom: 16, borderBottom: '1px solid var(--border)' }}>Appearance & Layout</h2>
              
              <div className="form-group">
                <label style={{ fontWeight: 600, display: 'block', marginBottom: 12 }}>Theme</label>
                <div className="row gap-12 p-1" style={{ background: 'var(--bg-2)', borderRadius: 12, padding: 6 }}>
                  <button className={'btn ' + (!t.dark ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: !t.dark ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('dark', false)}>Light Mode</button>
                  <button className={'btn ' + (t.dark ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: t.dark ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('dark', true)}>Dark Mode</button>
                </div>
              </div>
              
              <div className="form-group" style={{ marginTop: 16 }}>
                <label style={{ fontWeight: 600, display: 'block', marginBottom: 12 }}>Accent Color</label>
                <div className="row gap-16">
                  {ACCENTS.map((a, i) => (
                    <button key={i} onClick={() => setTweak('accent', a.lime)} 
                      style={{ 
                        width: 48, height: 48, borderRadius: '50%', background: a.lime, 
                        border: t.accent === a.lime ? '3px solid var(--surface)' : '3px solid transparent', 
                        outline: t.accent === a.lime ? `2px solid ${a.lime}` : 'none',
                        cursor: 'pointer', transition: 'transform .2s' 
                      }} 
                    />
                  ))}
                </div>
              </div>
              
              <div className="form-group" style={{ marginTop: 16 }}>
                <label style={{ fontWeight: 600, display: 'block', marginBottom: 12 }}>Navigation Layout</label>
                <div className="row gap-12 p-1" style={{ background: 'var(--bg-2)', borderRadius: 12, padding: 6 }}>
                  <button className={'btn ' + (t.nav === 'sidebar' ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: t.nav === 'sidebar' ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('nav', 'sidebar')}>Sidebar</button>
                  <button className={'btn ' + (t.nav === 'top' ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: t.nav === 'top' ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('nav', 'top')}>Top Navigation</button>
                </div>
              </div>
              
              <div className="form-group" style={{ marginTop: 16 }}>
                <label style={{ fontWeight: 600, display: 'block', marginBottom: 12 }}>Lesson Page Layout</label>
                <div className="row gap-12 p-1" style={{ background: 'var(--bg-2)', borderRadius: 12, padding: 6 }}>
                  <button className={'btn ' + (t.lessonLayout === 'guided' ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: t.lessonLayout === 'guided' ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('lessonLayout', 'guided')}>Guided</button>
                  <button className={'btn ' + (t.lessonLayout === 'focused' ? 'btn-primary' : 'btn-ghost')} style={{ flex: 1, border: 'none', boxShadow: t.lessonLayout === 'focused' ? '0 2px 8px rgba(0,0,0,0.1)' : 'none' }} onClick={() => setTweak('lessonLayout', 'focused')}>Focused</button>
                </div>
              </div>
            </div>
          )}
          
          {activeTab === 'accessibility' && (
            <div className="col gap-24 fade-in">
              <h2 style={{ fontSize: 20, margin: 0, paddingBottom: 16, borderBottom: '1px solid var(--border)' }}>Accessibility & Visuals</h2>
              
              <div className="form-group">
                <label style={{ fontWeight: 600, display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
                  <span>Text Scale ({Math.round(t.textSize * 100)}%)</span>
                </label>
                <input type="range" min={0.85} max={1.4} step={0.05} value={t.textSize} onChange={e => setTweak('textSize', Number(e.target.value))} style={{ width: '100%', cursor: 'pointer', height: 6, borderRadius: 3, appearance: 'none', background: 'var(--bg-2)', outline: 'none' }} />
                <div className="row" style={{ justifyContent: 'space-between', marginTop: 8, fontSize: 13, color: 'var(--text-muted)' }}>
                  <span>Small</span>
                  <span>Default</span>
                  <span>Large</span>
                </div>
              </div>
              
              <div className="form-group" style={{ marginTop: 16 }}>
                <label style={{ fontWeight: 600, display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
                  <span>Corner Roundness ({t.roundness}px)</span>
                </label>
                <input type="range" min={4} max={26} step={2} value={t.roundness} onChange={e => setTweak('roundness', Number(e.target.value))} style={{ width: '100%', cursor: 'pointer', height: 6, borderRadius: 3, appearance: 'none', background: 'var(--bg-2)', outline: 'none' }} />
              </div>
              
              <div className="form-group" style={{ marginTop: 24, borderTop: '1px solid var(--border)', paddingTop: 16 }}>
                <SettingsToggle 
                  label="High Contrast Mode" 
                  description="Increases contrast of text and borders to make UI elements easier to distinguish."
                  checked={t.highContrast} 
                  onChange={v => setTweak('highContrast', v)} 
                />
                <SettingsToggle 
                  label="Reduce Motion" 
                  description="Disables parallax effects, sliding animations, and transitions across the interface."
                  checked={t.reduceMotion} 
                  onChange={v => setTweak('reduceMotion', v)} 
                />
              </div>
            </div>
          )}
        </div>
      </div>
      <style>{`
        .fade-in { animation: fadeIn .3s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        
        /* Custom range slider thumb styling */
        input[type=range]::-webkit-slider-thumb {
          appearance: none;
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: var(--lime);
          cursor: pointer;
          border: 2px solid var(--surface);
          box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
      `}</style>
    </div>
  );
}

window.SettingsPage = SettingsPage;
